source: src/CodeGen/CodeGenerator.cc@ d6c464d

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