source: src/CodeGen/CodeGenerator.cc@ 9749d2fa

ADT ast-experimental
Last change on this file since 9749d2fa was 9749d2fa, checked in by JiadaL <j82liang@…>, 3 years ago

Fix CodeGen for function type enum

  • Property mode set to 100644
File size: 39.7 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
20#include "AST/Decl.hpp" // for DeclWithType
21#include "Common/UniqueName.h" // for UniqueName
22#include "Common/utility.h" // for CodeLocation, toString
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 void CodeGenerator::postvisit( EnumDecl * enumDecl ) {
276 extension( enumDecl );
277 std::list< Declaration* > &memb = enumDecl->get_members();
278 if (enumDecl->base && ! memb.empty()) {
279 unsigned long long last_val = -1; // if the first enum value has no explicit initializer,
280 // as other
281 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++) {
282 ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
283 assert( obj );
284 output << "static ";
285 output << genType(enumDecl->base, mangleName( obj ), options);
286 output << " = ";
287 output << "(" << genType(enumDecl->base, "", options) << ")";
288 if ( (BasicType *)(enumDecl->base) && ((BasicType *)(enumDecl->base))->isWholeNumber() ) {
289 if ( obj->get_init() ) {
290 obj->get_init()->accept( *visitor );
291 Expression* expr = ((SingleInit *)(obj->init))->value;
292 while ( auto temp = dynamic_cast<CastExpr *>(expr) ) {
293 expr = temp->arg;
294 }
295 last_val = ((ConstantExpr *)expr)->constant.get_ival();
296 } else {
297 output << ++last_val;
298 } // if
299 } else {
300 if ( obj->get_init() ) {
301 obj->get_init()->accept( *visitor );
302 } else {
303 // Should not reach here!
304 }
305 }
306 output << ";" << endl;
307 } // for
308 } else {
309 output << "enum ";
310 genAttributes( enumDecl->get_attributes() );
311
312 output << enumDecl->get_name();
313
314 if ( ! memb.empty() ) {
315 output << " {" << endl;
316
317 ++indent;
318 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++) {
319 ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
320 assert( obj );
321 output << indent << mangleName( obj );
322 if ( obj->get_init() ) {
323 output << " = ";
324 obj->get_init()->accept( *visitor );
325 } // if
326 output << "," << endl;
327 } // for
328 --indent;
329 output << indent << "}";
330 } // if
331 } // if
332 }
333
334 void CodeGenerator::postvisit( TraitDecl * traitDecl ) {
335 assertf( ! options.genC, "TraitDecls should not reach code generation." );
336 extension( traitDecl );
337 handleAggregate( traitDecl, "trait " );
338 }
339
340 void CodeGenerator::postvisit( TypedefDecl * typeDecl ) {
341 assertf( ! options.genC, "Typedefs are removed and substituted in earlier passes." );
342 output << "typedef ";
343 output << genType( typeDecl->get_base(), typeDecl->get_name(), options ) << endl;
344 }
345
346 void CodeGenerator::postvisit( TypeDecl * typeDecl ) {
347 assertf( ! options.genC, "TypeDecls should not reach code generation." );
348 output << typeDecl->genTypeString() << " " << typeDecl->name;
349 if ( typeDecl->sized ) {
350 output << " | sized(" << typeDecl->name << ")";
351 }
352 if ( ! typeDecl->assertions.empty() ) {
353 output << " | { ";
354 for ( DeclarationWithType * assert : typeDecl->assertions ) {
355 assert->accept( *visitor );
356 output << "; ";
357 }
358 output << " }";
359 }
360 }
361
362 void CodeGenerator::postvisit( StaticAssertDecl * assertDecl ) {
363 output << "_Static_assert(";
364 assertDecl->condition->accept( *visitor );
365 output << ", ";
366 assertDecl->message->accept( *visitor );
367 output << ")";
368 }
369
370 void CodeGenerator::postvisit( Designation * designation ) {
371 std::list< Expression * > designators = designation->get_designators();
372 if ( designators.size() == 0 ) return;
373 for ( Expression * des : designators ) {
374 if ( dynamic_cast< NameExpr * >( des ) || dynamic_cast< VariableExpr * >( des ) ) {
375 // if expression is a NameExpr or VariableExpr, then initializing aggregate member
376 output << ".";
377 des->accept( *visitor );
378 } else {
379 // otherwise, it has to be a ConstantExpr or CastExpr, initializing array element
380 output << "[";
381 des->accept( *visitor );
382 output << "]";
383 } // if
384 } // for
385 output << " = ";
386 }
387
388 void CodeGenerator::postvisit( SingleInit * init ) {
389 init->get_value()->accept( *visitor );
390 }
391
392 void CodeGenerator::postvisit( ListInit * init ) {
393 auto initBegin = init->begin();
394 auto initEnd = init->end();
395 auto desigBegin = init->get_designations().begin();
396 auto desigEnd = init->get_designations().end();
397
398 output << "{ ";
399 for ( ; initBegin != initEnd && desigBegin != desigEnd; ) {
400 (*desigBegin)->accept( *visitor );
401 (*initBegin)->accept( *visitor );
402 ++initBegin, ++desigBegin;
403 if ( initBegin != initEnd ) {
404 output << ", ";
405 }
406 }
407 output << " }";
408 assertf( initBegin == initEnd && desigBegin == desigEnd, "Initializers and designators not the same length. %s", toString( init ).c_str() );
409 }
410
411 void CodeGenerator::postvisit( ConstructorInit * init ){
412 assertf( ! options.genC, "ConstructorInit nodes should not reach code generation." );
413 // pseudo-output for constructor/destructor pairs
414 output << "<ctorinit>{" << endl << ++indent << "ctor: ";
415 maybeAccept( init->get_ctor(), *visitor );
416 output << ", " << endl << indent << "dtor: ";
417 maybeAccept( init->get_dtor(), *visitor );
418 output << endl << --indent << "}";
419 }
420
421 void CodeGenerator::postvisit( Constant * constant ) {
422 output << constant->get_value();
423 }
424
425 // *** Expressions
426 void CodeGenerator::postvisit( ApplicationExpr * applicationExpr ) {
427 extension( applicationExpr );
428 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
429 const OperatorInfo * opInfo;
430 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && ( opInfo = operatorLookup( varExpr->get_var()->get_name() ) ) ) {
431 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
432 switch ( opInfo->type ) {
433 case OT_INDEX:
434 assert( applicationExpr->get_args().size() == 2 );
435 (*arg++)->accept( *visitor );
436 output << "[";
437 (*arg)->accept( *visitor );
438 output << "]";
439 break;
440
441 case OT_CALL:
442 // there are no intrinsic definitions of the function call operator
443 assert( false );
444 break;
445
446 case OT_CTOR:
447 case OT_DTOR:
448 if ( applicationExpr->get_args().size() == 1 ) {
449 // the expression fed into a single parameter constructor or destructor may contain side
450 // effects, so must still output this expression
451 output << "(";
452 (*arg++)->accept( *visitor );
453 output << ") /* " << opInfo->inputName << " */";
454 } else if ( applicationExpr->get_args().size() == 2 ) {
455 // intrinsic two parameter constructors are essentially bitwise assignment
456 output << "(";
457 (*arg++)->accept( *visitor );
458 output << opInfo->symbol;
459 (*arg)->accept( *visitor );
460 output << ") /* " << opInfo->inputName << " */";
461 } else {
462 // no constructors with 0 or more than 2 parameters
463 assert( false );
464 } // if
465 break;
466
467 case OT_PREFIX:
468 case OT_PREFIXASSIGN:
469 assert( applicationExpr->get_args().size() == 1 );
470 output << "(";
471 output << opInfo->symbol;
472 (*arg)->accept( *visitor );
473 output << ")";
474 break;
475
476 case OT_POSTFIX:
477 case OT_POSTFIXASSIGN:
478 assert( applicationExpr->get_args().size() == 1 );
479 (*arg)->accept( *visitor );
480 output << opInfo->symbol;
481 break;
482
483
484 case OT_INFIX:
485 case OT_INFIXASSIGN:
486 assert( applicationExpr->get_args().size() == 2 );
487 output << "(";
488 (*arg++)->accept( *visitor );
489 output << opInfo->symbol;
490 (*arg)->accept( *visitor );
491 output << ")";
492 break;
493
494 case OT_CONSTANT:
495 case OT_LABELADDRESS:
496 // there are no intrinsic definitions of 0/1 or label addresses as functions
497 assert( false );
498 } // switch
499 } else if( varExpr->get_var()->get_linkage() == LinkageSpec::BuiltinCFA && varExpr->get_var()->get_name() == "intptr" ) {
500 // THIS is a hack to make it a constant until a proper constexpr solution is created
501 output << "((void*)";
502 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
503 (*arg++)->accept( *visitor );
504 output << ")";
505 } else {
506 varExpr->accept( *visitor );
507 output << "(";
508 genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
509 output << ")";
510 } // if
511 } else {
512 applicationExpr->get_function()->accept( *visitor );
513 output << "(";
514 genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
515 output << ")";
516 } // if
517 }
518
519 void CodeGenerator::postvisit( UntypedExpr * untypedExpr ) {
520 extension( untypedExpr );
521 if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->function ) ) {
522 const OperatorInfo * opInfo = operatorLookup( nameExpr->name );
523 if ( opInfo ) {
524 std::list< Expression* >::iterator arg = untypedExpr->args.begin();
525 switch ( opInfo->type ) {
526 case OT_INDEX:
527 assert( untypedExpr->args.size() == 2 );
528 (*arg++)->accept( *visitor );
529 output << "[";
530 (*arg)->accept( *visitor );
531 output << "]";
532 break;
533
534 case OT_CALL:
535 assert( false );
536
537 case OT_CTOR:
538 case OT_DTOR:
539 if ( untypedExpr->args.size() == 1 ) {
540 // the expression fed into a single parameter constructor or destructor may contain side
541 // effects, so must still output this expression
542 output << "(";
543 (*arg++)->accept( *visitor );
544 output << ") /* " << opInfo->inputName << " */";
545 } else if ( untypedExpr->get_args().size() == 2 ) {
546 // intrinsic two parameter constructors are essentially bitwise assignment
547 output << "(";
548 (*arg++)->accept( *visitor );
549 output << opInfo->symbol;
550 (*arg)->accept( *visitor );
551 output << ") /* " << opInfo->inputName << " */";
552 } else {
553 // no constructors with 0 or more than 2 parameters
554 assertf( ! options.genC, "UntypedExpr constructor/destructor with 0 or more than 2 parameters." );
555 output << "(";
556 (*arg++)->accept( *visitor );
557 output << opInfo->symbol << "{ ";
558 genCommaList( arg, untypedExpr->args.end() );
559 output << "}) /* " << opInfo->inputName << " */";
560 } // if
561 break;
562
563 case OT_PREFIX:
564 case OT_PREFIXASSIGN:
565 case OT_LABELADDRESS:
566 assert( untypedExpr->args.size() == 1 );
567 output << "(";
568 output << opInfo->symbol;
569 (*arg)->accept( *visitor );
570 output << ")";
571 break;
572
573 case OT_POSTFIX:
574 case OT_POSTFIXASSIGN:
575 assert( untypedExpr->args.size() == 1 );
576 (*arg)->accept( *visitor );
577 output << opInfo->symbol;
578 break;
579
580 case OT_INFIX:
581 case OT_INFIXASSIGN:
582 assert( untypedExpr->args.size() == 2 );
583 output << "(";
584 (*arg++)->accept( *visitor );
585 output << opInfo->symbol;
586 (*arg)->accept( *visitor );
587 output << ")";
588 break;
589
590 case OT_CONSTANT:
591 // there are no intrinsic definitions of 0 or 1 as functions
592 assert( false );
593 } // switch
594 } else {
595 // builtin routines
596 nameExpr->accept( *visitor );
597 output << "(";
598 genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
599 output << ")";
600 } // if
601 } else {
602 untypedExpr->function->accept( *visitor );
603 output << "(";
604 genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
605 output << ")";
606 } // if
607 }
608
609 void CodeGenerator::postvisit( RangeExpr * rangeExpr ) {
610 rangeExpr->low->accept( *visitor );
611 output << " ... ";
612 rangeExpr->high->accept( *visitor );
613 }
614
615 void CodeGenerator::postvisit( NameExpr * nameExpr ) {
616 extension( nameExpr );
617 const OperatorInfo * opInfo = operatorLookup( nameExpr->name );
618 if ( opInfo ) {
619 if ( opInfo->type == OT_CONSTANT ) {
620 output << opInfo->symbol;
621 } else {
622 output << opInfo->outputName;
623 }
624 } else {
625 output << nameExpr->get_name();
626 } // if
627 }
628
629 void CodeGenerator::postvisit( DimensionExpr * dimensionExpr ) {
630 extension( dimensionExpr );
631 output << "/*non-type*/" << dimensionExpr->get_name();
632 }
633
634 void CodeGenerator::postvisit( AddressExpr * addressExpr ) {
635 extension( addressExpr );
636 output << "(&";
637 addressExpr->arg->accept( *visitor );
638 output << ")";
639 }
640
641 void CodeGenerator::postvisit( LabelAddressExpr *addressExpr ) {
642 extension( addressExpr );
643 output << "(&&" << addressExpr->arg << ")";
644 }
645
646 void CodeGenerator::postvisit( CastExpr * castExpr ) {
647 extension( castExpr );
648 output << "(";
649 if ( castExpr->get_result()->isVoid() ) {
650 output << "(void)";
651 } else {
652 // at least one result type of cast.
653 // Note: previously, lvalue casts were skipped. Since it's now impossible for the user to write
654 // an lvalue cast, this has been taken out.
655 output << "(";
656 output << genType( castExpr->get_result(), "", options );
657 output << ")";
658 } // if
659 castExpr->arg->accept( *visitor );
660 output << ")";
661 }
662
663 void CodeGenerator::postvisit( KeywordCastExpr * castExpr ) {
664 assertf( ! options.genC, "KeywordCast should not reach code generation." );
665 extension( castExpr );
666 output << "((" << castExpr->targetString() << " &)";
667 castExpr->arg->accept( *visitor );
668 output << ")";
669 }
670
671 void CodeGenerator::postvisit( VirtualCastExpr * castExpr ) {
672 assertf( ! options.genC, "VirtualCastExpr should not reach code generation." );
673 extension( castExpr );
674 output << "(virtual ";
675 castExpr->get_arg()->accept( *visitor );
676 output << ")";
677 }
678
679 void CodeGenerator::postvisit( UntypedMemberExpr * memberExpr ) {
680 assertf( ! options.genC, "UntypedMemberExpr should not reach code generation." );
681 extension( memberExpr );
682 memberExpr->get_aggregate()->accept( *visitor );
683 output << ".";
684 memberExpr->get_member()->accept( *visitor );
685 }
686
687 void CodeGenerator::postvisit( MemberExpr * memberExpr ) {
688 extension( memberExpr );
689 memberExpr->get_aggregate()->accept( *visitor );
690 output << "." << mangleName( memberExpr->get_member() );
691 }
692
693 void CodeGenerator::postvisit( VariableExpr * variableExpr ) {
694 extension( variableExpr );
695 const OperatorInfo * opInfo;
696 if( dynamic_cast<ZeroType*>( variableExpr->get_var()->get_type() ) ) {
697 output << "0";
698 } else if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && (opInfo = operatorLookup( variableExpr->get_var()->get_name() )) && opInfo->type == OT_CONSTANT ) {
699 output << opInfo->symbol;
700 } else {
701 output << mangleName( variableExpr->get_var() );
702 } // if
703 }
704
705 void CodeGenerator::postvisit( ConstantExpr * constantExpr ) {
706 assert( constantExpr->get_constant() );
707 extension( constantExpr );
708 constantExpr->get_constant()->accept( *visitor );
709 }
710
711 void CodeGenerator::postvisit( SizeofExpr * sizeofExpr ) {
712 extension( sizeofExpr );
713 output << "sizeof(";
714 if ( sizeofExpr->get_isType() ) {
715 output << genType( sizeofExpr->get_type(), "", options );
716 } else {
717 sizeofExpr->get_expr()->accept( *visitor );
718 } // if
719 output << ")";
720 }
721
722 void CodeGenerator::postvisit( AlignofExpr * alignofExpr ) {
723 // use GCC extension to avoid bumping std to C11
724 extension( alignofExpr );
725 output << "__alignof__(";
726 if ( alignofExpr->get_isType() ) {
727 output << genType( alignofExpr->get_type(), "", options );
728 } else {
729 alignofExpr->get_expr()->accept( *visitor );
730 } // if
731 output << ")";
732 }
733
734 void CodeGenerator::postvisit( UntypedOffsetofExpr * offsetofExpr ) {
735 assertf( ! options.genC, "UntypedOffsetofExpr should not reach code generation." );
736 output << "offsetof(";
737 output << genType( offsetofExpr->get_type(), "", options );
738 output << ", " << offsetofExpr->get_member();
739 output << ")";
740 }
741
742 void CodeGenerator::postvisit( OffsetofExpr * offsetofExpr ) {
743 // use GCC builtin
744 output << "__builtin_offsetof(";
745 output << genType( offsetofExpr->get_type(), "", options );
746 output << ", " << mangleName( offsetofExpr->get_member() );
747 output << ")";
748 }
749
750 void CodeGenerator::postvisit( OffsetPackExpr * offsetPackExpr ) {
751 assertf( ! options.genC, "OffsetPackExpr should not reach code generation." );
752 output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", options ) << ")";
753 }
754
755 void CodeGenerator::postvisit( LogicalExpr * logicalExpr ) {
756 extension( logicalExpr );
757 output << "(";
758 logicalExpr->get_arg1()->accept( *visitor );
759 if ( logicalExpr->get_isAnd() ) {
760 output << " && ";
761 } else {
762 output << " || ";
763 } // if
764 logicalExpr->get_arg2()->accept( *visitor );
765 output << ")";
766 }
767
768 void CodeGenerator::postvisit( ConditionalExpr * conditionalExpr ) {
769 extension( conditionalExpr );
770 output << "(";
771 conditionalExpr->get_arg1()->accept( *visitor );
772 output << " ? ";
773 conditionalExpr->get_arg2()->accept( *visitor );
774 output << " : ";
775 conditionalExpr->get_arg3()->accept( *visitor );
776 output << ")";
777 }
778
779 void CodeGenerator::postvisit( CommaExpr * commaExpr ) {
780 extension( commaExpr );
781 output << "(";
782 if ( options.genC ) {
783 // arg1 of a CommaExpr is never used, so it can be safely cast to void to reduce gcc warnings.
784 commaExpr->set_arg1( new CastExpr( commaExpr->get_arg1() ) );
785 }
786 commaExpr->get_arg1()->accept( *visitor );
787 output << " , ";
788 commaExpr->get_arg2()->accept( *visitor );
789 output << ")";
790 }
791
792 void CodeGenerator::postvisit( TupleAssignExpr * tupleExpr ) {
793 assertf( ! options.genC, "TupleAssignExpr should not reach code generation." );
794 tupleExpr->stmtExpr->accept( *visitor );
795 }
796
797 void CodeGenerator::postvisit( UntypedTupleExpr * tupleExpr ) {
798 assertf( ! options.genC, "UntypedTupleExpr should not reach code generation." );
799 extension( tupleExpr );
800 output << "[";
801 genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
802 output << "]";
803 }
804
805 void CodeGenerator::postvisit( TupleExpr * tupleExpr ) {
806 assertf( ! options.genC, "TupleExpr should not reach code generation." );
807 extension( tupleExpr );
808 output << "[";
809 genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
810 output << "]";
811 }
812
813 void CodeGenerator::postvisit( TupleIndexExpr * tupleExpr ) {
814 assertf( ! options.genC, "TupleIndexExpr should not reach code generation." );
815 extension( tupleExpr );
816 tupleExpr->get_tuple()->accept( *visitor );
817 output << "." << tupleExpr->get_index();
818 }
819
820 void CodeGenerator::postvisit( TypeExpr * typeExpr ) {
821 // if ( options.genC ) std::cerr << "typeexpr still exists: " << typeExpr << std::endl;
822 // assertf( ! options.genC, "TypeExpr should not reach code generation." );
823 if ( ! options.genC ) {
824 output << genType( typeExpr->get_type(), "", options );
825 }
826 }
827
828 void CodeGenerator::postvisit( AsmExpr * asmExpr ) {
829 if ( !asmExpr->inout.empty() ) {
830 output << "[ ";
831 output << asmExpr->inout;
832 output << " ] ";
833 } // if
834 asmExpr->constraint->accept( *visitor );
835 output << " ( ";
836 asmExpr->operand->accept( *visitor );
837 output << " )";
838 }
839
840 void CodeGenerator::postvisit( CompoundLiteralExpr *compLitExpr ) {
841 assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
842 output << "(" << genType( compLitExpr->get_result(), "", options ) << ")";
843 compLitExpr->get_initializer()->accept( *visitor );
844 }
845
846 void CodeGenerator::postvisit( UniqueExpr * unqExpr ) {
847 assertf( ! options.genC, "Unique expressions should not reach code generation." );
848 output << "unq<" << unqExpr->get_id() << ">{ ";
849 unqExpr->get_expr()->accept( *visitor );
850 output << " }";
851 }
852
853 void CodeGenerator::postvisit( StmtExpr * stmtExpr ) {
854 std::list< Statement * > & stmts = stmtExpr->statements->kids;
855 output << "({" << endl;
856 ++indent;
857 unsigned int numStmts = stmts.size();
858 unsigned int i = 0;
859 for ( Statement * stmt : stmts ) {
860 output << indent << printLabels( stmt->get_labels() );
861 if ( i+1 == numStmts ) {
862 // last statement in a statement expression needs to be handled specially -
863 // cannot cast to void, otherwise the expression statement has no value
864 if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
865 exprStmt->expr->accept( *visitor );
866 output << ";" << endl;
867 ++i;
868 break;
869 }
870 }
871 stmt->accept( *visitor );
872 output << endl;
873 if ( wantSpacing( stmt ) ) {
874 output << endl;
875 } // if
876 ++i;
877 }
878 --indent;
879 output << indent << "})";
880 }
881
882 void CodeGenerator::postvisit( ConstructorExpr * expr ) {
883 assertf( ! options.genC, "Unique expressions should not reach code generation." );
884 expr->callExpr->accept( *visitor );
885 }
886
887 void CodeGenerator::postvisit( DeletedExpr * expr ) {
888 assertf( ! options.genC, "Deleted expressions should not reach code generation." );
889 expr->expr->accept( *visitor );
890 }
891
892 void CodeGenerator::postvisit( DefaultArgExpr * arg ) {
893 assertf( ! options.genC, "Default argument expressions should not reach code generation." );
894 arg->expr->accept( *visitor );
895 }
896
897 void CodeGenerator::postvisit( GenericExpr * expr ) {
898 assertf( ! options.genC, "C11 _Generic expressions should not reach code generation." );
899 output << "_Generic(";
900 expr->control->accept( *visitor );
901 output << ", ";
902 unsigned int numAssocs = expr->associations.size();
903 unsigned int i = 0;
904 for ( GenericExpr::Association & assoc : expr->associations ) {
905 if (assoc.isDefault) {
906 output << "default: ";
907 } else {
908 output << genType( assoc.type, "", options ) << ": ";
909 }
910 assoc.expr->accept( *visitor );
911 if ( i+1 != numAssocs ) {
912 output << ", ";
913 }
914 i++;
915 }
916 output << ")";
917 }
918
919 // *** Statements
920 void CodeGenerator::postvisit( CompoundStmt * compoundStmt ) {
921 std::list<Statement*> ks = compoundStmt->get_kids();
922 output << "{" << endl;
923
924 ++indent;
925
926 for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end(); i++ ) {
927 output << indent << printLabels( (*i)->get_labels() );
928 (*i)->accept( *visitor );
929
930 output << endl;
931 if ( wantSpacing( *i ) ) {
932 output << endl;
933 } // if
934 } // for
935 --indent;
936
937 output << indent << "}";
938 }
939
940 void CodeGenerator::postvisit( ExprStmt * exprStmt ) {
941 assert( exprStmt );
942 if ( options.genC ) {
943 // cast the top-level expression to void to reduce gcc warnings.
944 exprStmt->set_expr( new CastExpr( exprStmt->get_expr() ) );
945 }
946 exprStmt->get_expr()->accept( *visitor );
947 output << ";";
948 }
949
950 void CodeGenerator::postvisit( AsmStmt * asmStmt ) {
951 output << "asm ";
952 if ( asmStmt->get_voltile() ) output << "volatile ";
953 if ( ! asmStmt->get_gotolabels().empty() ) output << "goto ";
954 output << "( ";
955 if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *visitor );
956 output << " : ";
957 genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
958 output << " : ";
959 genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
960 output << " : ";
961 genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
962 if ( ! asmStmt->get_gotolabels().empty() ) {
963 output << " : ";
964 for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
965 output << *begin++;
966 if ( begin == asmStmt->get_gotolabels().end() ) break;
967 output << ", ";
968 } // for
969 } // if
970 output << " );";
971 }
972
973 void CodeGenerator::postvisit( AsmDecl * asmDecl ) {
974 output << "asm ";
975 AsmStmt * asmStmt = asmDecl->get_stmt();
976 output << "( ";
977 if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *visitor );
978 output << " )";
979 }
980
981 void CodeGenerator::postvisit( DirectiveDecl * directiveDecl ) {
982 output << endl << directiveDecl->get_stmt()->directive; // endl prevents spaces before directive
983 }
984
985 void CodeGenerator::postvisit( DirectiveStmt * dirStmt ) {
986 output << endl << dirStmt->directive; // endl prevents spaces before directive
987 }
988
989 void CodeGenerator::postvisit( IfStmt * ifStmt ) {
990 output << "if ( ";
991 ifStmt->get_condition()->accept( *visitor );
992 output << " ) ";
993
994 ifStmt->get_then()->accept( *visitor );
995
996 if ( ifStmt->get_else() != 0) {
997 output << " else ";
998 ifStmt->get_else()->accept( *visitor );
999 } // if
1000 }
1001
1002 void CodeGenerator::postvisit( SwitchStmt * switchStmt ) {
1003 output << "switch ( ";
1004 switchStmt->get_condition()->accept( *visitor );
1005 output << " ) ";
1006
1007 output << "{" << endl;
1008 ++indent;
1009 acceptAll( switchStmt->get_statements(), *visitor );
1010 --indent;
1011 output << indent << "}";
1012 }
1013
1014 void CodeGenerator::postvisit( CaseStmt * caseStmt ) {
1015 updateLocation( caseStmt );
1016 output << indent;
1017 if ( caseStmt->isDefault()) {
1018 output << "default";
1019 } else {
1020 output << "case ";
1021 caseStmt->get_condition()->accept( *visitor );
1022 } // if
1023 output << ":" << endl;
1024
1025 std::list<Statement *> sts = caseStmt->get_statements();
1026
1027 ++indent;
1028 for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end(); i++) {
1029 output << indent << printLabels( (*i)->get_labels() ) ;
1030 (*i)->accept( *visitor );
1031 output << endl;
1032 } // for
1033 --indent;
1034 }
1035
1036 void CodeGenerator::postvisit( BranchStmt * branchStmt ) {
1037 switch ( branchStmt->get_type()) {
1038 case BranchStmt::Goto:
1039 if ( ! branchStmt->get_target().empty() )
1040 output << "goto " << branchStmt->get_target();
1041 else {
1042 if ( branchStmt->get_computedTarget() != 0 ) {
1043 output << "goto *";
1044 branchStmt->get_computedTarget()->accept( *visitor );
1045 } // if
1046 } // if
1047 break;
1048 case BranchStmt::Break:
1049 output << "break";
1050 break;
1051 case BranchStmt::Continue:
1052 output << "continue";
1053 break;
1054 case BranchStmt::FallThrough:
1055 case BranchStmt::FallThroughDefault:
1056 assertf( ! options.genC, "fallthru should not reach code generation." );
1057 output << "fallthru";
1058 break;
1059 default: ; // prevent warning
1060 } // switch
1061 // print branch target for labelled break/continue/fallthru in debug mode
1062 if ( ! options.genC && branchStmt->get_type() != BranchStmt::Goto ) {
1063 if ( ! branchStmt->get_target().empty() ) {
1064 output << " " << branchStmt->get_target();
1065 } else if ( branchStmt->get_type() == BranchStmt::FallThrough ) {
1066 output << " default";
1067 }
1068 }
1069 output << ";";
1070 }
1071
1072 void CodeGenerator::postvisit( ReturnStmt * returnStmt ) {
1073 output << "return ";
1074 maybeAccept( returnStmt->get_expr(), *visitor );
1075 output << ";";
1076 }
1077
1078 void CodeGenerator::postvisit( ThrowStmt * throwStmt ) {
1079 assertf( ! options.genC, "Throw statements should not reach code generation." );
1080
1081 output << ((throwStmt->get_kind() == ThrowStmt::Terminate) ?
1082 "throw" : "throwResume");
1083 if (throwStmt->get_expr()) {
1084 output << " ";
1085 throwStmt->get_expr()->accept( *visitor );
1086 }
1087 if (throwStmt->get_target()) {
1088 output << " _At ";
1089 throwStmt->get_target()->accept( *visitor );
1090 }
1091 output << ";";
1092 }
1093 void CodeGenerator::postvisit( CatchStmt * stmt ) {
1094 assertf( ! options.genC, "Catch statements should not reach code generation." );
1095
1096 output << ((stmt->get_kind() == CatchStmt::Terminate) ?
1097 "catch" : "catchResume");
1098 output << "( ";
1099 stmt->decl->accept( *visitor );
1100 output << " ) ";
1101
1102 if( stmt->cond ) {
1103 output << "if/when(?) (";
1104 stmt->cond->accept( *visitor );
1105 output << ") ";
1106 }
1107 stmt->body->accept( *visitor );
1108 }
1109
1110 void CodeGenerator::postvisit( WaitForStmt * stmt ) {
1111 assertf( ! options.genC, "Waitfor statements should not reach code generation." );
1112
1113 bool first = true;
1114 for( auto & clause : stmt->clauses ) {
1115 if(first) { output << "or "; first = false; }
1116 if( clause.condition ) {
1117 output << "when(";
1118 stmt->timeout.condition->accept( *visitor );
1119 output << ") ";
1120 }
1121 output << "waitfor(";
1122 clause.target.function->accept( *visitor );
1123 for( Expression * expr : clause.target.arguments ) {
1124 output << ",";
1125 expr->accept( *visitor );
1126 }
1127 output << ") ";
1128 clause.statement->accept( *visitor );
1129 }
1130
1131 if( stmt->timeout.statement ) {
1132 output << "or ";
1133 if( stmt->timeout.condition ) {
1134 output << "when(";
1135 stmt->timeout.condition->accept( *visitor );
1136 output << ") ";
1137 }
1138 output << "timeout(";
1139 stmt->timeout.time->accept( *visitor );
1140 output << ") ";
1141 stmt->timeout.statement->accept( *visitor );
1142 }
1143
1144 if( stmt->orelse.statement ) {
1145 output << "or ";
1146 if( stmt->orelse.condition ) {
1147 output << "when(";
1148 stmt->orelse.condition->accept( *visitor );
1149 output << ")";
1150 }
1151 output << "else ";
1152 stmt->orelse.statement->accept( *visitor );
1153 }
1154 }
1155
1156 void CodeGenerator::postvisit( WithStmt * with ) {
1157 if ( ! options.genC ) {
1158 output << "with ( ";
1159 genCommaList( with->exprs.begin(), with->exprs.end() );
1160 output << " ) ";
1161 }
1162 with->stmt->accept( *visitor );
1163 }
1164
1165 void CodeGenerator::postvisit( WhileDoStmt * whileDoStmt ) {
1166 if ( whileDoStmt->get_isDoWhile() ) {
1167 output << "do";
1168 } else {
1169 output << "while (";
1170 whileDoStmt->get_condition()->accept( *visitor );
1171 output << ")";
1172 } // if
1173 output << " ";
1174
1175 output << CodeGenerator::printLabels( whileDoStmt->get_body()->get_labels() );
1176 whileDoStmt->get_body()->accept( *visitor );
1177
1178 output << indent;
1179
1180 if ( whileDoStmt->get_isDoWhile() ) {
1181 output << " while (";
1182 whileDoStmt->get_condition()->accept( *visitor );
1183 output << ");";
1184 } // if
1185 }
1186
1187 void CodeGenerator::postvisit( ForStmt * forStmt ) {
1188 // initialization is always hoisted, so don't bother doing anything with that
1189 output << "for (;";
1190
1191 if ( forStmt->get_condition() != 0 ) {
1192 forStmt->get_condition()->accept( *visitor );
1193 } // if
1194 output << ";";
1195
1196 if ( forStmt->get_increment() != 0 ) {
1197 // cast the top-level expression to void to reduce gcc warnings.
1198 Expression * expr = new CastExpr( forStmt->get_increment() );
1199 expr->accept( *visitor );
1200 } // if
1201 output << ") ";
1202
1203 if ( forStmt->get_body() != 0 ) {
1204 output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
1205 forStmt->get_body()->accept( *visitor );
1206 } // if
1207 }
1208
1209 void CodeGenerator::postvisit( __attribute__((unused)) NullStmt * nullStmt ) {
1210 //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
1211 output << "/* null statement */ ;";
1212 }
1213
1214 void CodeGenerator::postvisit( DeclStmt * declStmt ) {
1215 declStmt->get_decl()->accept( *visitor );
1216
1217 if ( doSemicolon( declStmt->get_decl() ) ) {
1218 output << ";";
1219 } // if
1220 }
1221
1222 void CodeGenerator::postvisit( ImplicitCtorDtorStmt * stmt ) {
1223 assertf( ! options.genC, "ImplicitCtorDtorStmts should not reach code generation." );
1224 stmt->callStmt->accept( *visitor );
1225 }
1226
1227 void CodeGenerator::postvisit( MutexStmt * stmt ) {
1228 assertf( ! options.genC, "ImplicitCtorDtorStmts should not reach code generation." );
1229 stmt->stmt->accept( *visitor );
1230 }
1231
1232 void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
1233 if ( decl->get_storageClasses().any() ) {
1234 decl->get_storageClasses().print( output );
1235 } // if
1236 } // CodeGenerator::handleStorageClass
1237
1238 std::string genName( DeclarationWithType * decl ) {
1239 const OperatorInfo * opInfo = operatorLookup( decl->get_name() );
1240 if ( opInfo ) {
1241 return opInfo->outputName;
1242 } else {
1243 return decl->get_name();
1244 } // if
1245 }
1246
1247std::string genName( ast::DeclWithType const * decl ) {
1248 if ( const OperatorInfo * opInfo = operatorLookup( decl->name ) ) {
1249 return opInfo->outputName;
1250 } else {
1251 return decl->name;
1252 }
1253}
1254
1255} // namespace CodeGen
1256
1257// Local Variables: //
1258// tab-width: 4 //
1259// mode: c++ //
1260// compile-command: "make install" //
1261// End: //
Note: See TracBrowser for help on using the repository browser.