source: src/CodeGen/CodeGenerator.cc@ 28f8f15

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

Save progress

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