source: src/CodeGen/CodeGenerator.cc@ fa2c005

ADT
Last change on this file since fa2c005 was fa2c005, checked in by JiadaL <j82liang@…>, 3 years ago

Finish Adt POC

  • Property mode set to 100644
File size: 40.4 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// CodeGenerator.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Wed Jun 29 14:34:00 2022
13// Update Count : 542
14//
15#include "CodeGenerator.h"
16
17#include <cassert> // for assert, assertf
18#include <list> // for _List_iterator, list, list<>::it...
19#include <sstream> // for stringstream
20
21#include "AST/Decl.hpp" // for DeclWithType
22#include "Common/UniqueName.h" // for UniqueName
23#include "GenType.h" // for genType
24#include "InitTweak/InitTweak.h" // for getPointerBase
25#include "OperatorTable.h" // for OperatorInfo, operatorLookup
26#include "SynTree/LinkageSpec.h" // for Spec, Intrinsic
27#include "SynTree/Attribute.h" // for Attribute
28#include "SynTree/BaseSyntaxNode.h" // for BaseSyntaxNode
29#include "SynTree/Constant.h" // for Constant
30#include "SynTree/Declaration.h" // for DeclarationWithType, TypeDecl
31#include "SynTree/Expression.h" // for Expression, UntypedExpr, Applica...
32#include "SynTree/Initializer.h" // for Initializer, ListInit, Designation
33#include "SynTree/Label.h" // for Label, operator<<
34#include "SynTree/Statement.h" // for Statement, AsmStmt, BranchStmt
35#include "SynTree/Type.h" // for Type, Type::StorageClasses, Func...
36
37using namespace std;
38
39namespace CodeGen {
40 int CodeGenerator::tabsize = 4;
41
42 // The kinds of statements that would ideally be followed by whitespace.
43 bool wantSpacing( Statement * stmt) {
44 return dynamic_cast< IfStmt * >( stmt ) || dynamic_cast< CompoundStmt * >( stmt ) ||
45 dynamic_cast< WhileDoStmt * >( stmt ) || dynamic_cast< ForStmt * >( stmt ) || dynamic_cast< SwitchStmt *>( stmt );
46 }
47
48 void CodeGenerator::extension( Expression * expr ) {
49 if ( expr->get_extension() ) {
50 output << "__extension__ ";
51 } // if
52 } // extension
53
54 void CodeGenerator::extension( Declaration * decl ) {
55 if ( decl->get_extension() ) {
56 output << "__extension__ ";
57 } // if
58 } // extension
59
60 void CodeGenerator::asmName( DeclarationWithType * decl ) {
61 if ( ConstantExpr * asmName = dynamic_cast<ConstantExpr *>(decl->get_asmName()) ) {
62 output << " asm ( " << asmName->get_constant()->get_value() << " )";
63 } // if
64 } // extension
65
66 CodeGenerator::LabelPrinter & CodeGenerator::LabelPrinter::operator()( std::list< Label > & l ) {
67 labels = &l;
68 return *this;
69 }
70
71 ostream & operator<<( ostream & output, CodeGenerator::LabelPrinter & printLabels ) {
72 std::list< Label > & labs = *printLabels.labels;
73 // l.unique(); // assumes a sorted list. Why not use set? Does order matter?
74 for ( Label & l : labs ) {
75 output << l.get_name() + ": ";
76 printLabels.cg.genAttributes( l.get_attributes() );
77 } // for
78 return output;
79 }
80
81 // Using updateLocation at the beginning of a node and endl within a node should become the method of formating.
82 void CodeGenerator::updateLocation( CodeLocation const & to ) {
83 // skip if linemarks shouldn't appear or if codelocation is unset
84 if ( !options.lineMarks || to.isUnset() ) return;
85
86 if ( currentLocation.followedBy( to, 0 ) ) {
87 return;
88 } else if ( currentLocation.followedBy( to, 1 ) ) {
89 output << "\n" << indent;
90 currentLocation.first_line += 1;
91 } else if ( currentLocation.followedBy( to, 2 ) ) {
92 output << "\n\n" << indent;
93 currentLocation.first_line += 2;
94 } else {
95 output << "\n# " << to.first_line << " \"" << to.filename
96 << "\"\n" << indent;
97 currentLocation = to;
98 }
99 output << std::flush;
100 }
101
102 void CodeGenerator::updateLocation( BaseSyntaxNode const * to ) {
103 updateLocation( to->location );
104 }
105
106 // replace endl
107 ostream & CodeGenerator::LineEnder::operator()( ostream & os ) const {
108 // if ( !cg.lineMarks ) {
109 // os << "\n" << cg.indent << std::flush;
110 // }
111 os << "\n" << std::flush;
112 cg.currentLocation.first_line++;
113 // os << "/* did endl; current loc is: " << cg.currentLocation.first_line << "*/";
114 return os;
115 }
116
117 CodeGenerator::CodeGenerator( std::ostream & os, bool pretty, bool genC, bool lineMarks, bool printExprTypes ) : indent( 0, CodeGenerator::tabsize ), output( os ), printLabels( *this ), options( pretty, genC, lineMarks, printExprTypes ), endl( *this ) {}
118 CodeGenerator::CodeGenerator( std::ostream & os, const Options &options ) : indent( 0, CodeGenerator::tabsize ), output( os ), printLabels( *this ), options(options), endl( *this ) {}
119
120 string CodeGenerator::mangleName( DeclarationWithType * decl ) {
121 // GCC builtins should always be printed unmangled
122 if ( options.pretty || decl->linkage.is_gcc_builtin ) return decl->name;
123 if ( LinkageSpec::isMangled(decl->linkage) && decl->mangleName != "" ) {
124 // need to incorporate scope level in order to differentiate names for destructors
125 return decl->get_scopedMangleName();
126 } else {
127 return decl->name;
128 } // if
129 }
130
131 void CodeGenerator::genAttributes( list< Attribute * > & attributes ) {
132 if ( attributes.empty() ) return;
133 output << "__attribute__ ((";
134 for ( list< Attribute * >::iterator attr( attributes.begin() );; ) {
135 output << (*attr)->name;
136 if ( ! (*attr)->parameters.empty() ) {
137 output << "(";
138 genCommaList( (*attr)->parameters.begin(), (*attr)->parameters.end() );
139 output << ")";
140 } // if
141 if ( ++attr == attributes.end() ) break;
142 output << ","; // separator
143 } // for
144 output << ")) ";
145 } // CodeGenerator::genAttributes
146
147 // *** BaseSyntaxNode
148 void CodeGenerator::previsit( BaseSyntaxNode * node ) {
149 // turn off automatic recursion for all nodes, to allow each visitor to
150 // precisely control the order in which its children are visited.
151 visit_children = false;
152 updateLocation( node );
153 }
154
155 // *** BaseSyntaxNode
156 void CodeGenerator::postvisit( BaseSyntaxNode * node ) {
157 std::stringstream ss;
158 node->print( ss );
159 assertf( false, "Unhandled node reached in CodeGenerator: %s", ss.str().c_str() );
160 }
161
162 // *** Expression
163 void CodeGenerator::previsit( Expression * node ) {
164 previsit( (BaseSyntaxNode *)node );
165 GuardAction( [this, node](){
166 if ( options.printExprTypes && node->result ) {
167 output << " /* " << genType( node->result, "", options ) << " */ ";
168 }
169 } );
170 }
171
172 // *** Declarations
173 void CodeGenerator::postvisit( FunctionDecl * functionDecl ) {
174 // deleted decls should never be used, so don't print them
175 if ( functionDecl->isDeleted && options.genC ) return;
176 extension( functionDecl );
177 genAttributes( functionDecl->get_attributes() );
178
179 handleStorageClass( functionDecl );
180 functionDecl->get_funcSpec().print( output );
181
182 Options subOptions = options;
183 subOptions.anonymousUnused = functionDecl->has_body();
184 output << genType( functionDecl->get_functionType(), mangleName( functionDecl ), subOptions );
185
186 asmName( functionDecl );
187
188 if ( functionDecl->get_statements() ) {
189 functionDecl->get_statements()->accept( *visitor );
190 } // if
191 if ( functionDecl->isDeleted ) {
192 output << " = void";
193 }
194 }
195
196 void CodeGenerator::postvisit( ObjectDecl * objectDecl ) {
197 // deleted decls should never be used, so don't print them
198 if ( objectDecl->isDeleted && options.genC ) return;
199
200 // gcc allows an empty declarator (no name) for bit-fields and C states: 6.7.2.1 Structure and union specifiers,
201 // point 4, page 113: If the (bit field) value is zero, the declaration shall have no declarator. For anything
202 // else, the anonymous name refers to the anonymous object for plan9 inheritance.
203 if ( objectDecl->get_name().empty() && options.genC && ! objectDecl->get_bitfieldWidth() ) {
204 // only generate an anonymous name when generating C code, otherwise it clutters the output too much
205 static UniqueName name = { "__anonymous_object" };
206 objectDecl->set_name( name.newName() );
207 // Stops unused parameter warnings.
208 if ( options.anonymousUnused ) {
209 objectDecl->attributes.push_back( new Attribute( "unused" ) );
210 }
211 }
212
213 extension( objectDecl );
214 genAttributes( objectDecl->get_attributes() );
215
216 handleStorageClass( objectDecl );
217 output << genType( objectDecl->get_type(), mangleName( objectDecl ), options.pretty, options.genC );
218
219 asmName( objectDecl );
220
221 if ( objectDecl->get_init() ) {
222 output << " = ";
223 objectDecl->get_init()->accept( *visitor );
224 } // if
225 if ( objectDecl->isDeleted ) {
226 output << " = void";
227 }
228
229 if ( objectDecl->get_bitfieldWidth() ) {
230 output << ":";
231 objectDecl->get_bitfieldWidth()->accept( *visitor );
232 } // if
233 }
234
235 void CodeGenerator::handleAggregate( AggregateDecl * aggDecl, const std::string & kind ) {
236 if( ! aggDecl->parameters.empty() && ! options.genC ) {
237 // assertf( ! genC, "Aggregate type parameters should not reach code generation." );
238 output << "forall(";
239 genCommaList( aggDecl->parameters.begin(), aggDecl->parameters.end() );
240 output << ")" << endl;
241 output << indent;
242 }
243
244 output << kind;
245 genAttributes( aggDecl->attributes );
246 output << aggDecl->name;
247
248 if ( aggDecl->has_body() ) {
249 std::list< Declaration * > & memb = aggDecl->members;
250 output << " {" << endl;
251
252 ++indent;
253 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++ ) {
254 output << indent;
255 (*i)->accept( *visitor );
256 output << ";" << endl;
257 } // for
258
259 --indent;
260
261 output << indent << "}";
262 } // if
263 }
264
265 void CodeGenerator::postvisit( StructDecl * structDecl ) {
266 extension( structDecl );
267 handleAggregate( structDecl, "struct " );
268 }
269
270 void CodeGenerator::postvisit( UnionDecl * unionDecl ) {
271 extension( unionDecl );
272 handleAggregate( unionDecl, "union " );
273 }
274
275 template<typename pass_type>
276 inline void genEnumInitializer( PassVisitor<pass_type> * visitor, Type * baseType, std::ostream & output,
277 Initializer * init, long long * cur_val, Options options) {
278 auto baseTypeAsBasic = baseType ? dynamic_cast<BasicType *>( baseType ) : nullptr;
279 if ( init ) { // If value has an explicit initiazatior
280 output << " = ";
281 output << "(" << genType(baseType, "", options) << ")";
282 init->accept( *visitor );
283 if ( baseTypeAsBasic && baseTypeAsBasic->isInteger() ) { // if it is an integral type and initilizer offered,
284 // need to update the cur_val
285 Expression* expr = ((SingleInit *)(init))->value;
286 while ( auto temp = dynamic_cast<CastExpr *>(expr) ) { // unwrap introduced cast
287 expr = temp->arg;
288 }
289 *cur_val = ((ConstantExpr *)expr)->constant.get_ival()+1;
290 }
291 } else if ( baseTypeAsBasic && baseTypeAsBasic->isInteger() ) { // integral implicitly init to cur_val + 1
292 output << " = " << "(" << genType(baseType, "", options) << ")";
293 output << (*cur_val)++;
294 }
295 }
296
297 void CodeGenerator::handleData( EnumDecl * ) {
298 assert(false);
299 }
300
301 void CodeGenerator::postvisit( EnumDecl * enumDecl ) {
302 extension( enumDecl );
303 std::list< Declaration* > &memb = enumDecl->get_members();
304 if (enumDecl->base && ! memb.empty()) {
305 long long cur_val = 0;
306 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++) {
307 ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
308 assert( obj );
309 output << "static ";
310 output << genType(enumDecl->base, mangleName( obj ), options);
311 genEnumInitializer( visitor, enumDecl->base, output, obj->get_init(), &cur_val, options);
312 output << ";" << endl;
313 } // for
314 } else {
315 output << "enum ";
316 genAttributes( enumDecl->get_attributes() );
317
318 output << enumDecl->get_name();
319
320 if ( ! memb.empty() ) {
321 output << " {" << endl;
322
323 ++indent;
324 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++) {
325 ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
326 assert( obj );
327 output << indent << mangleName( obj );
328 if ( obj->get_init() ) {
329 output << " = ";
330 obj->get_init()->accept( *visitor );
331 } // if
332 output << "," << endl;
333 } // for
334 --indent;
335 output << indent << "}";
336 } // if
337 } // if
338 }
339
340 // Temporary fix, But visitor should be able to handle this
341 void CodeGenerator::postvisit( AdtDecl * adtDecl ) {
342 output << endl << "/* AdtDecl Code Section */" << endl;
343 postvisit( adtDecl->tag );
344 output << ";" << endl;
345 postvisit( adtDecl->data_union );
346 output << ";" << endl;
347 postvisit( adtDecl->tag_union );
348 }
349
350 void CodeGenerator::postvisit( TraitDecl * traitDecl ) {
351 assertf( ! options.genC, "TraitDecls should not reach code generation." );
352 extension( traitDecl );
353 handleAggregate( traitDecl, "trait " );
354 }
355
356 void CodeGenerator::postvisit( TypedefDecl * typeDecl ) {
357 assertf( ! options.genC, "Typedefs are removed and substituted in earlier passes." );
358 output << "typedef ";
359 output << genType( typeDecl->get_base(), typeDecl->get_name(), options ) << endl;
360 }
361
362 void CodeGenerator::postvisit( TypeDecl * typeDecl ) {
363 assertf( ! options.genC, "TypeDecls should not reach code generation." );
364 output << typeDecl->genTypeString() << " " << typeDecl->name;
365 if ( typeDecl->sized ) {
366 output << " | sized(" << typeDecl->name << ")";
367 }
368 if ( ! typeDecl->assertions.empty() ) {
369 output << " | { ";
370 for ( DeclarationWithType * assert : typeDecl->assertions ) {
371 assert->accept( *visitor );
372 output << "; ";
373 }
374 output << " }";
375 }
376 }
377
378 void CodeGenerator::postvisit( StaticAssertDecl * assertDecl ) {
379 output << "_Static_assert(";
380 assertDecl->condition->accept( *visitor );
381 output << ", ";
382 assertDecl->message->accept( *visitor );
383 output << ")";
384 }
385
386 void CodeGenerator::postvisit( Designation * designation ) {
387 std::list< Expression * > designators = designation->get_designators();
388 if ( designators.size() == 0 ) return;
389 for ( Expression * des : designators ) {
390 if ( dynamic_cast< NameExpr * >( des ) || dynamic_cast< VariableExpr * >( des ) ) {
391 // if expression is a NameExpr or VariableExpr, then initializing aggregate member
392 output << ".";
393 des->accept( *visitor );
394 } else {
395 // otherwise, it has to be a ConstantExpr or CastExpr, initializing array element
396 output << "[";
397 des->accept( *visitor );
398 output << "]";
399 } // if
400 } // for
401 output << " = ";
402 }
403
404 void CodeGenerator::postvisit( SingleInit * init ) {
405 init->get_value()->accept( *visitor );
406 }
407
408 void CodeGenerator::postvisit( ListInit * init ) {
409 auto initBegin = init->begin();
410 auto initEnd = init->end();
411 auto desigBegin = init->get_designations().begin();
412 auto desigEnd = init->get_designations().end();
413
414 output << "{ ";
415 for ( ; initBegin != initEnd && desigBegin != desigEnd; ) {
416 (*desigBegin)->accept( *visitor );
417 (*initBegin)->accept( *visitor );
418 ++initBegin, ++desigBegin;
419 if ( initBegin != initEnd ) {
420 output << ", ";
421 }
422 }
423 output << " }";
424 assertf( initBegin == initEnd && desigBegin == desigEnd, "Initializers and designators not the same length. %s", toString( init ).c_str() );
425 }
426
427 void CodeGenerator::postvisit( ConstructorInit * init ){
428 assertf( ! options.genC, "ConstructorInit nodes should not reach code generation." );
429 // pseudo-output for constructor/destructor pairs
430 output << "<ctorinit>{" << endl << ++indent << "ctor: ";
431 maybeAccept( init->get_ctor(), *visitor );
432 output << ", " << endl << indent << "dtor: ";
433 maybeAccept( init->get_dtor(), *visitor );
434 output << endl << --indent << "}";
435 }
436
437 void CodeGenerator::postvisit( Constant * constant ) {
438 output << constant->get_value();
439 }
440
441 // *** Expressions
442 void CodeGenerator::postvisit( ApplicationExpr * applicationExpr ) {
443 extension( applicationExpr );
444 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
445 const OperatorInfo * opInfo;
446 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && ( opInfo = operatorLookup( varExpr->get_var()->get_name() ) ) ) {
447 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
448 switch ( opInfo->type ) {
449 case OT_INDEX:
450 assert( applicationExpr->get_args().size() == 2 );
451 (*arg++)->accept( *visitor );
452 output << "[";
453 (*arg)->accept( *visitor );
454 output << "]";
455 break;
456
457 case OT_CALL:
458 // there are no intrinsic definitions of the function call operator
459 assert( false );
460 break;
461
462 case OT_CTOR:
463 case OT_DTOR:
464 if ( applicationExpr->get_args().size() == 1 ) {
465 // the expression fed into a single parameter constructor or destructor may contain side
466 // effects, so must still output this expression
467 output << "(";
468 (*arg++)->accept( *visitor );
469 output << ") /* " << opInfo->inputName << " */";
470 } else if ( applicationExpr->get_args().size() == 2 ) {
471 // intrinsic two parameter constructors are essentially bitwise assignment
472 output << "(";
473 (*arg++)->accept( *visitor );
474 output << opInfo->symbol;
475 (*arg)->accept( *visitor );
476 output << ") /* " << opInfo->inputName << " */";
477 } else {
478 // no constructors with 0 or more than 2 parameters
479 assert( false );
480 } // if
481 break;
482
483 case OT_PREFIX:
484 case OT_PREFIXASSIGN:
485 assert( applicationExpr->get_args().size() == 1 );
486 output << "(";
487 output << opInfo->symbol;
488 (*arg)->accept( *visitor );
489 output << ")";
490 break;
491
492 case OT_POSTFIX:
493 case OT_POSTFIXASSIGN:
494 assert( applicationExpr->get_args().size() == 1 );
495 (*arg)->accept( *visitor );
496 output << opInfo->symbol;
497 break;
498
499
500 case OT_INFIX:
501 case OT_INFIXASSIGN:
502 assert( applicationExpr->get_args().size() == 2 );
503 output << "(";
504 (*arg++)->accept( *visitor );
505 output << opInfo->symbol;
506 (*arg)->accept( *visitor );
507 output << ")";
508 break;
509
510 case OT_CONSTANT:
511 case OT_LABELADDRESS:
512 // there are no intrinsic definitions of 0/1 or label addresses as functions
513 assert( false );
514 } // switch
515 } else if( varExpr->get_var()->get_linkage() == LinkageSpec::BuiltinCFA && varExpr->get_var()->get_name() == "intptr" ) {
516 // THIS is a hack to make it a constant until a proper constexpr solution is created
517 output << "((void*)";
518 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
519 (*arg++)->accept( *visitor );
520 output << ")";
521 } else {
522 varExpr->accept( *visitor );
523 output << "(";
524 genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
525 output << ")";
526 } // if
527 } else {
528 applicationExpr->get_function()->accept( *visitor );
529 output << "(";
530 genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
531 output << ")";
532 } // if
533 }
534
535 void CodeGenerator::postvisit( UntypedExpr * untypedExpr ) {
536 extension( untypedExpr );
537 if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->function ) ) {
538 const OperatorInfo * opInfo = operatorLookup( nameExpr->name );
539 if ( opInfo ) {
540 std::list< Expression* >::iterator arg = untypedExpr->args.begin();
541 switch ( opInfo->type ) {
542 case OT_INDEX:
543 assert( untypedExpr->args.size() == 2 );
544 (*arg++)->accept( *visitor );
545 output << "[";
546 (*arg)->accept( *visitor );
547 output << "]";
548 break;
549
550 case OT_CALL:
551 assert( false );
552
553 case OT_CTOR:
554 case OT_DTOR:
555 if ( untypedExpr->args.size() == 1 ) {
556 // the expression fed into a single parameter constructor or destructor may contain side
557 // effects, so must still output this expression
558 output << "(";
559 (*arg++)->accept( *visitor );
560 output << ") /* " << opInfo->inputName << " */";
561 } else if ( untypedExpr->get_args().size() == 2 ) {
562 // intrinsic two parameter constructors are essentially bitwise assignment
563 output << "(";
564 (*arg++)->accept( *visitor );
565 output << opInfo->symbol;
566 (*arg)->accept( *visitor );
567 output << ") /* " << opInfo->inputName << " */";
568 } else {
569 // no constructors with 0 or more than 2 parameters
570 assertf( ! options.genC, "UntypedExpr constructor/destructor with 0 or more than 2 parameters." );
571 output << "(";
572 (*arg++)->accept( *visitor );
573 output << opInfo->symbol << "{ ";
574 genCommaList( arg, untypedExpr->args.end() );
575 output << "}) /* " << opInfo->inputName << " */";
576 } // if
577 break;
578
579 case OT_PREFIX:
580 case OT_PREFIXASSIGN:
581 case OT_LABELADDRESS:
582 assert( untypedExpr->args.size() == 1 );
583 output << "(";
584 output << opInfo->symbol;
585 (*arg)->accept( *visitor );
586 output << ")";
587 break;
588
589 case OT_POSTFIX:
590 case OT_POSTFIXASSIGN:
591 assert( untypedExpr->args.size() == 1 );
592 (*arg)->accept( *visitor );
593 output << opInfo->symbol;
594 break;
595
596 case OT_INFIX:
597 case OT_INFIXASSIGN:
598 assert( untypedExpr->args.size() == 2 );
599 output << "(";
600 (*arg++)->accept( *visitor );
601 output << opInfo->symbol;
602 (*arg)->accept( *visitor );
603 output << ")";
604 break;
605
606 case OT_CONSTANT:
607 // there are no intrinsic definitions of 0 or 1 as functions
608 assert( false );
609 } // switch
610 } else {
611 // builtin routines
612 nameExpr->accept( *visitor );
613 output << "(";
614 genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
615 output << ")";
616 } // if
617 } else {
618 untypedExpr->function->accept( *visitor );
619 output << "(";
620 genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
621 output << ")";
622 } // if
623 }
624
625 void CodeGenerator::postvisit( RangeExpr * rangeExpr ) {
626 rangeExpr->low->accept( *visitor );
627 output << " ... ";
628 rangeExpr->high->accept( *visitor );
629 }
630
631 void CodeGenerator::postvisit( NameExpr * nameExpr ) {
632 extension( nameExpr );
633 const OperatorInfo * opInfo = operatorLookup( nameExpr->name );
634 if ( opInfo ) {
635 if ( opInfo->type == OT_CONSTANT ) {
636 output << opInfo->symbol;
637 } else {
638 output << opInfo->outputName;
639 }
640 } else {
641 output << nameExpr->get_name();
642 } // if
643 }
644
645 void CodeGenerator::postvisit( DimensionExpr * dimensionExpr ) {
646 extension( dimensionExpr );
647 output << "/*non-type*/" << dimensionExpr->get_name();
648 }
649
650 void CodeGenerator::postvisit( AddressExpr * addressExpr ) {
651 extension( addressExpr );
652 output << "(&";
653 addressExpr->arg->accept( *visitor );
654 output << ")";
655 }
656
657 void CodeGenerator::postvisit( LabelAddressExpr *addressExpr ) {
658 extension( addressExpr );
659 output << "(&&" << addressExpr->arg << ")";
660 }
661
662 void CodeGenerator::postvisit( CastExpr * castExpr ) {
663 extension( castExpr );
664 output << "(";
665 if ( castExpr->get_result()->isVoid() ) {
666 output << "(void)";
667 } else {
668 // at least one result type of cast.
669 // Note: previously, lvalue casts were skipped. Since it's now impossible for the user to write
670 // an lvalue cast, this has been taken out.
671 output << "(";
672 output << genType( castExpr->get_result(), "", options );
673 output << ")";
674 } // if
675 castExpr->arg->accept( *visitor );
676 output << ")";
677 }
678
679 void CodeGenerator::postvisit( KeywordCastExpr * castExpr ) {
680 assertf( ! options.genC, "KeywordCast should not reach code generation." );
681 extension( castExpr );
682 output << "((" << castExpr->targetString() << " &)";
683 castExpr->arg->accept( *visitor );
684 output << ")";
685 }
686
687 void CodeGenerator::postvisit( VirtualCastExpr * castExpr ) {
688 assertf( ! options.genC, "VirtualCastExpr should not reach code generation." );
689 extension( castExpr );
690 output << "(virtual ";
691 castExpr->get_arg()->accept( *visitor );
692 output << ")";
693 }
694
695 void CodeGenerator::postvisit( UntypedMemberExpr * memberExpr ) {
696 assertf( ! options.genC, "UntypedMemberExpr should not reach code generation." );
697 extension( memberExpr );
698 memberExpr->get_aggregate()->accept( *visitor );
699 output << ".";
700 memberExpr->get_member()->accept( *visitor );
701 }
702
703 void CodeGenerator::postvisit( MemberExpr * memberExpr ) {
704 extension( memberExpr );
705 memberExpr->get_aggregate()->accept( *visitor );
706 output << "." << mangleName( memberExpr->get_member() );
707 }
708
709 void CodeGenerator::postvisit( VariableExpr * variableExpr ) {
710 extension( variableExpr );
711 const OperatorInfo * opInfo;
712 if( dynamic_cast<ZeroType*>( variableExpr->get_var()->get_type() ) ) {
713 output << "0";
714 } else if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && (opInfo = operatorLookup( variableExpr->get_var()->get_name() )) && opInfo->type == OT_CONSTANT ) {
715 output << opInfo->symbol;
716 } else {
717 output << mangleName( variableExpr->get_var() );
718 } // if
719 }
720
721 void CodeGenerator::postvisit( ConstantExpr * constantExpr ) {
722 assert( constantExpr->get_constant() );
723 extension( constantExpr );
724 constantExpr->get_constant()->accept( *visitor );
725 }
726
727 void CodeGenerator::postvisit( SizeofExpr * sizeofExpr ) {
728 extension( sizeofExpr );
729 output << "sizeof(";
730 if ( sizeofExpr->get_isType() ) {
731 output << genType( sizeofExpr->get_type(), "", options );
732 } else {
733 sizeofExpr->get_expr()->accept( *visitor );
734 } // if
735 output << ")";
736 }
737
738 void CodeGenerator::postvisit( AlignofExpr * alignofExpr ) {
739 // use GCC extension to avoid bumping std to C11
740 extension( alignofExpr );
741 output << "__alignof__(";
742 if ( alignofExpr->get_isType() ) {
743 output << genType( alignofExpr->get_type(), "", options );
744 } else {
745 alignofExpr->get_expr()->accept( *visitor );
746 } // if
747 output << ")";
748 }
749
750 void CodeGenerator::postvisit( UntypedOffsetofExpr * offsetofExpr ) {
751 assertf( ! options.genC, "UntypedOffsetofExpr should not reach code generation." );
752 output << "offsetof(";
753 output << genType( offsetofExpr->get_type(), "", options );
754 output << ", " << offsetofExpr->get_member();
755 output << ")";
756 }
757
758 void CodeGenerator::postvisit( OffsetofExpr * offsetofExpr ) {
759 // use GCC builtin
760 output << "__builtin_offsetof(";
761 output << genType( offsetofExpr->get_type(), "", options );
762 output << ", " << mangleName( offsetofExpr->get_member() );
763 output << ")";
764 }
765
766 void CodeGenerator::postvisit( OffsetPackExpr * offsetPackExpr ) {
767 assertf( ! options.genC, "OffsetPackExpr should not reach code generation." );
768 output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", options ) << ")";
769 }
770
771 void CodeGenerator::postvisit( LogicalExpr * logicalExpr ) {
772 extension( logicalExpr );
773 output << "(";
774 logicalExpr->get_arg1()->accept( *visitor );
775 if ( logicalExpr->get_isAnd() ) {
776 output << " && ";
777 } else {
778 output << " || ";
779 } // if
780 logicalExpr->get_arg2()->accept( *visitor );
781 output << ")";
782 }
783
784 void CodeGenerator::postvisit( ConditionalExpr * conditionalExpr ) {
785 extension( conditionalExpr );
786 output << "(";
787 conditionalExpr->get_arg1()->accept( *visitor );
788 output << " ? ";
789 conditionalExpr->get_arg2()->accept( *visitor );
790 output << " : ";
791 conditionalExpr->get_arg3()->accept( *visitor );
792 output << ")";
793 }
794
795 void CodeGenerator::postvisit( CommaExpr * commaExpr ) {
796 extension( commaExpr );
797 output << "(";
798 if ( options.genC ) {
799 // arg1 of a CommaExpr is never used, so it can be safely cast to void to reduce gcc warnings.
800 commaExpr->set_arg1( new CastExpr( commaExpr->get_arg1() ) );
801 }
802 commaExpr->get_arg1()->accept( *visitor );
803 output << " , ";
804 commaExpr->get_arg2()->accept( *visitor );
805 output << ")";
806 }
807
808 void CodeGenerator::postvisit( TupleAssignExpr * tupleExpr ) {
809 assertf( ! options.genC, "TupleAssignExpr should not reach code generation." );
810 tupleExpr->stmtExpr->accept( *visitor );
811 }
812
813 void CodeGenerator::postvisit( UntypedTupleExpr * tupleExpr ) {
814 assertf( ! options.genC, "UntypedTupleExpr should not reach code generation." );
815 extension( tupleExpr );
816 output << "[";
817 genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
818 output << "]";
819 }
820
821 void CodeGenerator::postvisit( TupleExpr * tupleExpr ) {
822 assertf( ! options.genC, "TupleExpr should not reach code generation." );
823 extension( tupleExpr );
824 output << "[";
825 genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
826 output << "]";
827 }
828
829 void CodeGenerator::postvisit( TupleIndexExpr * tupleExpr ) {
830 assertf( ! options.genC, "TupleIndexExpr should not reach code generation." );
831 extension( tupleExpr );
832 tupleExpr->get_tuple()->accept( *visitor );
833 output << "." << tupleExpr->get_index();
834 }
835
836 void CodeGenerator::postvisit( TypeExpr * typeExpr ) {
837 // if ( options.genC ) std::cerr << "typeexpr still exists: " << typeExpr << std::endl;
838 // assertf( ! options.genC, "TypeExpr should not reach code generation." );
839 if ( ! options.genC ) {
840 output << genType( typeExpr->get_type(), "", options );
841 }
842 }
843
844 void CodeGenerator::postvisit( AsmExpr * asmExpr ) {
845 if ( !asmExpr->inout.empty() ) {
846 output << "[ ";
847 output << asmExpr->inout;
848 output << " ] ";
849 } // if
850 asmExpr->constraint->accept( *visitor );
851 output << " ( ";
852 asmExpr->operand->accept( *visitor );
853 output << " )";
854 }
855
856 void CodeGenerator::postvisit( CompoundLiteralExpr *compLitExpr ) {
857 assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
858 output << "(" << genType( compLitExpr->get_result(), "", options ) << ")";
859 compLitExpr->get_initializer()->accept( *visitor );
860 }
861
862 void CodeGenerator::postvisit( UniqueExpr * unqExpr ) {
863 assertf( ! options.genC, "Unique expressions should not reach code generation." );
864 output << "unq<" << unqExpr->get_id() << ">{ ";
865 unqExpr->get_expr()->accept( *visitor );
866 output << " }";
867 }
868
869 void CodeGenerator::postvisit( StmtExpr * stmtExpr ) {
870 std::list< Statement * > & stmts = stmtExpr->statements->kids;
871 output << "({" << endl;
872 ++indent;
873 unsigned int numStmts = stmts.size();
874 unsigned int i = 0;
875 for ( Statement * stmt : stmts ) {
876 output << indent << printLabels( stmt->get_labels() );
877 if ( i+1 == numStmts ) {
878 // last statement in a statement expression needs to be handled specially -
879 // cannot cast to void, otherwise the expression statement has no value
880 if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
881 exprStmt->expr->accept( *visitor );
882 output << ";" << endl;
883 ++i;
884 break;
885 }
886 }
887 stmt->accept( *visitor );
888 output << endl;
889 if ( wantSpacing( stmt ) ) {
890 output << endl;
891 } // if
892 ++i;
893 }
894 --indent;
895 output << indent << "})";
896 }
897
898 void CodeGenerator::postvisit( ConstructorExpr * expr ) {
899 assertf( ! options.genC, "Unique expressions should not reach code generation." );
900 expr->callExpr->accept( *visitor );
901 }
902
903 void CodeGenerator::postvisit( DeletedExpr * expr ) {
904 assertf( ! options.genC, "Deleted expressions should not reach code generation." );
905 expr->expr->accept( *visitor );
906 }
907
908 void CodeGenerator::postvisit( DefaultArgExpr * arg ) {
909 assertf( ! options.genC, "Default argument expressions should not reach code generation." );
910 arg->expr->accept( *visitor );
911 }
912
913 void CodeGenerator::postvisit( GenericExpr * expr ) {
914 assertf( ! options.genC, "C11 _Generic expressions should not reach code generation." );
915 output << "_Generic(";
916 expr->control->accept( *visitor );
917 output << ", ";
918 unsigned int numAssocs = expr->associations.size();
919 unsigned int i = 0;
920 for ( GenericExpr::Association & assoc : expr->associations ) {
921 if (assoc.isDefault) {
922 output << "default: ";
923 } else {
924 output << genType( assoc.type, "", options ) << ": ";
925 }
926 assoc.expr->accept( *visitor );
927 if ( i+1 != numAssocs ) {
928 output << ", ";
929 }
930 i++;
931 }
932 output << ")";
933 }
934
935 // *** Statements
936 void CodeGenerator::postvisit( CompoundStmt * compoundStmt ) {
937 std::list<Statement*> ks = compoundStmt->get_kids();
938 output << "{" << endl;
939
940 ++indent;
941
942 for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end(); i++ ) {
943 output << indent << printLabels( (*i)->get_labels() );
944 (*i)->accept( *visitor );
945
946 output << endl;
947 if ( wantSpacing( *i ) ) {
948 output << endl;
949 } // if
950 } // for
951 --indent;
952
953 output << indent << "}";
954 }
955
956 void CodeGenerator::postvisit( ExprStmt * exprStmt ) {
957 assert( exprStmt );
958 if ( options.genC ) {
959 // cast the top-level expression to void to reduce gcc warnings.
960 exprStmt->set_expr( new CastExpr( exprStmt->get_expr() ) );
961 }
962 exprStmt->get_expr()->accept( *visitor );
963 output << ";";
964 }
965
966 void CodeGenerator::postvisit( AsmStmt * asmStmt ) {
967 output << "asm ";
968 if ( asmStmt->get_voltile() ) output << "volatile ";
969 if ( ! asmStmt->get_gotolabels().empty() ) output << "goto ";
970 output << "( ";
971 if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *visitor );
972 output << " : ";
973 genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
974 output << " : ";
975 genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
976 output << " : ";
977 genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
978 if ( ! asmStmt->get_gotolabels().empty() ) {
979 output << " : ";
980 for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
981 output << *begin++;
982 if ( begin == asmStmt->get_gotolabels().end() ) break;
983 output << ", ";
984 } // for
985 } // if
986 output << " );";
987 }
988
989 void CodeGenerator::postvisit( AsmDecl * asmDecl ) {
990 output << "asm ";
991 AsmStmt * asmStmt = asmDecl->get_stmt();
992 output << "( ";
993 if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *visitor );
994 output << " )";
995 }
996
997 void CodeGenerator::postvisit( DirectiveDecl * directiveDecl ) {
998 output << endl << directiveDecl->get_stmt()->directive; // endl prevents spaces before directive
999 }
1000
1001 void CodeGenerator::postvisit( DirectiveStmt * dirStmt ) {
1002 output << endl << dirStmt->directive; // endl prevents spaces before directive
1003 }
1004
1005 void CodeGenerator::postvisit( IfStmt * ifStmt ) {
1006 output << "if ( ";
1007 ifStmt->get_condition()->accept( *visitor );
1008 output << " ) ";
1009
1010 ifStmt->get_then()->accept( *visitor );
1011
1012 if ( ifStmt->get_else() != 0) {
1013 output << " else ";
1014 ifStmt->get_else()->accept( *visitor );
1015 } // if
1016 }
1017
1018 void CodeGenerator::postvisit( SwitchStmt * switchStmt ) {
1019 output << "switch ( ";
1020 switchStmt->get_condition()->accept( *visitor );
1021 output << " ) ";
1022
1023 output << "{" << endl;
1024 ++indent;
1025 acceptAll( switchStmt->get_statements(), *visitor );
1026 --indent;
1027 output << indent << "}";
1028 }
1029
1030 void CodeGenerator::postvisit( CaseStmt * caseStmt ) {
1031 updateLocation( caseStmt );
1032 output << indent;
1033 if ( caseStmt->isDefault()) {
1034 output << "default";
1035 } else {
1036 output << "case ";
1037 caseStmt->get_condition()->accept( *visitor );
1038 } // if
1039 output << ":" << endl;
1040
1041 std::list<Statement *> sts = caseStmt->get_statements();
1042
1043 ++indent;
1044 for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end(); i++) {
1045 output << indent << printLabels( (*i)->get_labels() ) ;
1046 (*i)->accept( *visitor );
1047 output << endl;
1048 } // for
1049 --indent;
1050 }
1051
1052 void CodeGenerator::postvisit( BranchStmt * branchStmt ) {
1053 switch ( branchStmt->get_type()) {
1054 case BranchStmt::Goto:
1055 if ( ! branchStmt->get_target().empty() )
1056 output << "goto " << branchStmt->get_target();
1057 else {
1058 if ( branchStmt->get_computedTarget() != 0 ) {
1059 output << "goto *";
1060 branchStmt->get_computedTarget()->accept( *visitor );
1061 } // if
1062 } // if
1063 break;
1064 case BranchStmt::Break:
1065 output << "break";
1066 break;
1067 case BranchStmt::Continue:
1068 output << "continue";
1069 break;
1070 case BranchStmt::FallThrough:
1071 case BranchStmt::FallThroughDefault:
1072 assertf( ! options.genC, "fallthru should not reach code generation." );
1073 output << "fallthru";
1074 break;
1075 default: ; // prevent warning
1076 } // switch
1077 // print branch target for labelled break/continue/fallthru in debug mode
1078 if ( ! options.genC && branchStmt->get_type() != BranchStmt::Goto ) {
1079 if ( ! branchStmt->get_target().empty() ) {
1080 output << " " << branchStmt->get_target();
1081 } else if ( branchStmt->get_type() == BranchStmt::FallThrough ) {
1082 output << " default";
1083 }
1084 }
1085 output << ";";
1086 }
1087
1088 void CodeGenerator::postvisit( ReturnStmt * returnStmt ) {
1089 output << "return ";
1090 maybeAccept( returnStmt->get_expr(), *visitor );
1091 output << ";";
1092 }
1093
1094 void CodeGenerator::postvisit( ThrowStmt * throwStmt ) {
1095 assertf( ! options.genC, "Throw statements should not reach code generation." );
1096
1097 output << ((throwStmt->get_kind() == ThrowStmt::Terminate) ?
1098 "throw" : "throwResume");
1099 if (throwStmt->get_expr()) {
1100 output << " ";
1101 throwStmt->get_expr()->accept( *visitor );
1102 }
1103 if (throwStmt->get_target()) {
1104 output << " _At ";
1105 throwStmt->get_target()->accept( *visitor );
1106 }
1107 output << ";";
1108 }
1109 void CodeGenerator::postvisit( CatchStmt * stmt ) {
1110 assertf( ! options.genC, "Catch statements should not reach code generation." );
1111
1112 output << ((stmt->get_kind() == CatchStmt::Terminate) ?
1113 "catch" : "catchResume");
1114 output << "( ";
1115 stmt->decl->accept( *visitor );
1116 output << " ) ";
1117
1118 if( stmt->cond ) {
1119 output << "if/when(?) (";
1120 stmt->cond->accept( *visitor );
1121 output << ") ";
1122 }
1123 stmt->body->accept( *visitor );
1124 }
1125
1126 void CodeGenerator::postvisit( WaitForStmt * stmt ) {
1127 assertf( ! options.genC, "Waitfor statements should not reach code generation." );
1128
1129 bool first = true;
1130 for( auto & clause : stmt->clauses ) {
1131 if(first) { output << "or "; first = false; }
1132 if( clause.condition ) {
1133 output << "when(";
1134 stmt->timeout.condition->accept( *visitor );
1135 output << ") ";
1136 }
1137 output << "waitfor(";
1138 clause.target.function->accept( *visitor );
1139 for( Expression * expr : clause.target.arguments ) {
1140 output << ",";
1141 expr->accept( *visitor );
1142 }
1143 output << ") ";
1144 clause.statement->accept( *visitor );
1145 }
1146
1147 if( stmt->timeout.statement ) {
1148 output << "or ";
1149 if( stmt->timeout.condition ) {
1150 output << "when(";
1151 stmt->timeout.condition->accept( *visitor );
1152 output << ") ";
1153 }
1154 output << "timeout(";
1155 stmt->timeout.time->accept( *visitor );
1156 output << ") ";
1157 stmt->timeout.statement->accept( *visitor );
1158 }
1159
1160 if( stmt->orelse.statement ) {
1161 output << "or ";
1162 if( stmt->orelse.condition ) {
1163 output << "when(";
1164 stmt->orelse.condition->accept( *visitor );
1165 output << ")";
1166 }
1167 output << "else ";
1168 stmt->orelse.statement->accept( *visitor );
1169 }
1170 }
1171
1172 void CodeGenerator::postvisit( WithStmt * with ) {
1173 if ( ! options.genC ) {
1174 output << "with ( ";
1175 genCommaList( with->exprs.begin(), with->exprs.end() );
1176 output << " ) ";
1177 }
1178 with->stmt->accept( *visitor );
1179 }
1180
1181 void CodeGenerator::postvisit( WhileDoStmt * whileDoStmt ) {
1182 if ( whileDoStmt->get_isDoWhile() ) {
1183 output << "do";
1184 } else {
1185 output << "while (";
1186 whileDoStmt->get_condition()->accept( *visitor );
1187 output << ")";
1188 } // if
1189 output << " ";
1190
1191 output << CodeGenerator::printLabels( whileDoStmt->get_body()->get_labels() );
1192 whileDoStmt->get_body()->accept( *visitor );
1193
1194 output << indent;
1195
1196 if ( whileDoStmt->get_isDoWhile() ) {
1197 output << " while (";
1198 whileDoStmt->get_condition()->accept( *visitor );
1199 output << ");";
1200 } // if
1201 }
1202
1203 void CodeGenerator::postvisit( ForStmt * forStmt ) {
1204 // initialization is always hoisted, so don't bother doing anything with that
1205 output << "for (;";
1206
1207 if ( forStmt->get_condition() != 0 ) {
1208 forStmt->get_condition()->accept( *visitor );
1209 } // if
1210 output << ";";
1211
1212 if ( forStmt->get_increment() != 0 ) {
1213 // cast the top-level expression to void to reduce gcc warnings.
1214 Expression * expr = new CastExpr( forStmt->get_increment() );
1215 expr->accept( *visitor );
1216 } // if
1217 output << ") ";
1218
1219 if ( forStmt->get_body() != 0 ) {
1220 output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
1221 forStmt->get_body()->accept( *visitor );
1222 } // if
1223 }
1224
1225 void CodeGenerator::postvisit( __attribute__((unused)) NullStmt * nullStmt ) {
1226 //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
1227 output << "/* null statement */ ;";
1228 }
1229
1230 void CodeGenerator::postvisit( DeclStmt * declStmt ) {
1231 declStmt->get_decl()->accept( *visitor );
1232
1233 if ( doSemicolon( declStmt->get_decl() ) ) {
1234 output << ";";
1235 } // if
1236 }
1237
1238 void CodeGenerator::postvisit( ImplicitCtorDtorStmt * stmt ) {
1239 assertf( ! options.genC, "ImplicitCtorDtorStmts should not reach code generation." );
1240 stmt->callStmt->accept( *visitor );
1241 }
1242
1243 void CodeGenerator::postvisit( MutexStmt * stmt ) {
1244 assertf( ! options.genC, "ImplicitCtorDtorStmts should not reach code generation." );
1245 stmt->stmt->accept( *visitor );
1246 }
1247
1248 void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
1249 if ( decl->get_storageClasses().any() ) {
1250 decl->get_storageClasses().print( output );
1251 } // if
1252 } // CodeGenerator::handleStorageClass
1253
1254 std::string genName( DeclarationWithType * decl ) {
1255 const OperatorInfo * opInfo = operatorLookup( decl->get_name() );
1256 if ( opInfo ) {
1257 return opInfo->outputName;
1258 } else {
1259 return decl->get_name();
1260 } // if
1261 }
1262
1263std::string genName( ast::DeclWithType const * decl ) {
1264 if ( const OperatorInfo * opInfo = operatorLookup( decl->name ) ) {
1265 return opInfo->outputName;
1266 } else {
1267 return decl->name;
1268 }
1269}
1270
1271} // namespace CodeGen
1272
1273// Local Variables: //
1274// tab-width: 4 //
1275// mode: c++ //
1276// compile-command: "make install" //
1277// End: //
Note: See TracBrowser for help on using the repository browser.