source: src/CodeGen/CodeGenerator.cc@ 5c931e0

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

Fix casted enum init

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