source: src/CodeGen/CodeGenerator.cc@ 12df6fe

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since 12df6fe was 12df6fe, checked in by JiadaL <j82liang@…>, 3 years ago

Fix an enumerator value bug; add basic tests for new features; save the current progress before merge

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