source: src/CodeGen/CodeGenerator.cc@ 72d1118

ADT ast-experimental pthread-emulation
Last change on this file since 72d1118 was 9d55ff6, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Hack in code gen to make 0p a constant

  • Property mode set to 100644
File size: 39.8 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;
280 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++) {
281 ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
282 assert( obj );
283 output << "static const ";
284 output << genType(enumDecl->base, "", options) << " ";
285 output << mangleName( obj ) << " ";
286 output << " = ";
287 output << "(" << genType(enumDecl->base, "", options) << ")";
288 if ( (BasicType *)(enumDecl->base) && ((BasicType *)(enumDecl->base))->isWholeNumber() ) {
289 if ( obj->get_init() ) {
290 obj->get_init()->accept( *visitor );
291 last_val = ((ConstantExpr *)(((SingleInit *)(obj->init))->value))->constant.get_ival();
292 } else {
293 output << ++last_val;
294 } // if
295 } else {
296 if ( obj->get_init() ) {
297 obj->get_init()->accept( *visitor );
298 } else {
299 // Should not reach here!
300 }
301 }
302 output << ";" << endl;
303 } // for
304 } else {
305 output << "enum ";
306 genAttributes( enumDecl->get_attributes() );
307
308 output << enumDecl->get_name();
309
310 if ( ! memb.empty() ) {
311 output << " {" << endl;
312
313 ++indent;
314 for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++) {
315 ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
316 assert( obj );
317 output << indent << mangleName( obj );
318 if ( obj->get_init() ) {
319 output << " = ";
320 obj->get_init()->accept( *visitor );
321 } // if
322 output << "," << endl;
323 } // for
324 --indent;
325 output << indent << "}";
326 } // if
327 } // if
328 }
329
330 void CodeGenerator::postvisit( TraitDecl * traitDecl ) {
331 assertf( ! options.genC, "TraitDecls should not reach code generation." );
332 extension( traitDecl );
333 handleAggregate( traitDecl, "trait " );
334 }
335
336 void CodeGenerator::postvisit( TypedefDecl * typeDecl ) {
337 assertf( ! options.genC, "Typedefs are removed and substituted in earlier passes." );
338 output << "typedef ";
339 output << genType( typeDecl->get_base(), typeDecl->get_name(), options ) << endl;
340 }
341
342 void CodeGenerator::postvisit( TypeDecl * typeDecl ) {
343 assertf( ! options.genC, "TypeDecls should not reach code generation." );
344 output << typeDecl->genTypeString() << " " << typeDecl->name;
345 if ( typeDecl->sized ) {
346 output << " | sized(" << typeDecl->name << ")";
347 }
348 if ( ! typeDecl->assertions.empty() ) {
349 output << " | { ";
350 for ( DeclarationWithType * assert : typeDecl->assertions ) {
351 assert->accept( *visitor );
352 output << "; ";
353 }
354 output << " }";
355 }
356 }
357
358 void CodeGenerator::postvisit( StaticAssertDecl * assertDecl ) {
359 output << "_Static_assert(";
360 assertDecl->condition->accept( *visitor );
361 output << ", ";
362 assertDecl->message->accept( *visitor );
363 output << ")";
364 }
365
366 void CodeGenerator::postvisit( Designation * designation ) {
367 std::list< Expression * > designators = designation->get_designators();
368 if ( designators.size() == 0 ) return;
369 for ( Expression * des : designators ) {
370 if ( dynamic_cast< NameExpr * >( des ) || dynamic_cast< VariableExpr * >( des ) ) {
371 // if expression is a NameExpr or VariableExpr, then initializing aggregate member
372 output << ".";
373 des->accept( *visitor );
374 } else {
375 // otherwise, it has to be a ConstantExpr or CastExpr, initializing array element
376 output << "[";
377 des->accept( *visitor );
378 output << "]";
379 } // if
380 } // for
381 output << " = ";
382 }
383
384 void CodeGenerator::postvisit( SingleInit * init ) {
385 init->get_value()->accept( *visitor );
386 }
387
388 void CodeGenerator::postvisit( ListInit * init ) {
389 auto initBegin = init->begin();
390 auto initEnd = init->end();
391 auto desigBegin = init->get_designations().begin();
392 auto desigEnd = init->get_designations().end();
393
394 output << "{ ";
395 for ( ; initBegin != initEnd && desigBegin != desigEnd; ) {
396 (*desigBegin)->accept( *visitor );
397 (*initBegin)->accept( *visitor );
398 ++initBegin, ++desigBegin;
399 if ( initBegin != initEnd ) {
400 output << ", ";
401 }
402 }
403 output << " }";
404 assertf( initBegin == initEnd && desigBegin == desigEnd, "Initializers and designators not the same length. %s", toString( init ).c_str() );
405 }
406
407 void CodeGenerator::postvisit( ConstructorInit * init ){
408 assertf( ! options.genC, "ConstructorInit nodes should not reach code generation." );
409 // pseudo-output for constructor/destructor pairs
410 output << "<ctorinit>{" << endl << ++indent << "ctor: ";
411 maybeAccept( init->get_ctor(), *visitor );
412 output << ", " << endl << indent << "dtor: ";
413 maybeAccept( init->get_dtor(), *visitor );
414 output << endl << --indent << "}";
415 }
416
417 void CodeGenerator::postvisit( Constant * constant ) {
418 output << constant->get_value();
419 }
420
421 // *** Expressions
422 void CodeGenerator::postvisit( ApplicationExpr * applicationExpr ) {
423 extension( applicationExpr );
424 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
425 const OperatorInfo * opInfo;
426 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && ( opInfo = operatorLookup( varExpr->get_var()->get_name() ) ) ) {
427 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
428 switch ( opInfo->type ) {
429 case OT_INDEX:
430 assert( applicationExpr->get_args().size() == 2 );
431 (*arg++)->accept( *visitor );
432 output << "[";
433 (*arg)->accept( *visitor );
434 output << "]";
435 break;
436
437 case OT_CALL:
438 // there are no intrinsic definitions of the function call operator
439 assert( false );
440 break;
441
442 case OT_CTOR:
443 case OT_DTOR:
444 if ( applicationExpr->get_args().size() == 1 ) {
445 // the expression fed into a single parameter constructor or destructor may contain side
446 // effects, so must still output this expression
447 output << "(";
448 (*arg++)->accept( *visitor );
449 output << ") /* " << opInfo->inputName << " */";
450 } else if ( applicationExpr->get_args().size() == 2 ) {
451 // intrinsic two parameter constructors are essentially bitwise assignment
452 output << "(";
453 (*arg++)->accept( *visitor );
454 output << opInfo->symbol;
455 (*arg)->accept( *visitor );
456 output << ") /* " << opInfo->inputName << " */";
457 } else {
458 // no constructors with 0 or more than 2 parameters
459 assert( false );
460 } // if
461 break;
462
463 case OT_PREFIX:
464 case OT_PREFIXASSIGN:
465 assert( applicationExpr->get_args().size() == 1 );
466 output << "(";
467 output << opInfo->symbol;
468 (*arg)->accept( *visitor );
469 output << ")";
470 break;
471
472 case OT_POSTFIX:
473 case OT_POSTFIXASSIGN:
474 assert( applicationExpr->get_args().size() == 1 );
475 (*arg)->accept( *visitor );
476 output << opInfo->symbol;
477 break;
478
479
480 case OT_INFIX:
481 case OT_INFIXASSIGN:
482 assert( applicationExpr->get_args().size() == 2 );
483 output << "(";
484 (*arg++)->accept( *visitor );
485 output << opInfo->symbol;
486 (*arg)->accept( *visitor );
487 output << ")";
488 break;
489
490 case OT_CONSTANT:
491 case OT_LABELADDRESS:
492 // there are no intrinsic definitions of 0/1 or label addresses as functions
493 assert( false );
494 } // switch
495 } else if( varExpr->get_var()->get_linkage() == LinkageSpec::BuiltinCFA && varExpr->get_var()->get_name() == "intptr" ) {
496 // THIS is a hack to make it a constant until a proper constexpr solution is created
497 output << "((void*)";
498 std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
499 (*arg++)->accept( *visitor );
500 output << ")";
501 } else {
502 varExpr->accept( *visitor );
503 output << "(";
504 genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
505 output << ")";
506 } // if
507 } else {
508 applicationExpr->get_function()->accept( *visitor );
509 output << "(";
510 genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
511 output << ")";
512 } // if
513 }
514
515 void CodeGenerator::postvisit( UntypedExpr * untypedExpr ) {
516 extension( untypedExpr );
517 if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->function ) ) {
518 const OperatorInfo * opInfo = operatorLookup( nameExpr->name );
519 if ( opInfo ) {
520 std::list< Expression* >::iterator arg = untypedExpr->args.begin();
521 switch ( opInfo->type ) {
522 case OT_INDEX:
523 assert( untypedExpr->args.size() == 2 );
524 (*arg++)->accept( *visitor );
525 output << "[";
526 (*arg)->accept( *visitor );
527 output << "]";
528 break;
529
530 case OT_CALL:
531 assert( false );
532
533 case OT_CTOR:
534 case OT_DTOR:
535 if ( untypedExpr->args.size() == 1 ) {
536 // the expression fed into a single parameter constructor or destructor may contain side
537 // effects, so must still output this expression
538 output << "(";
539 (*arg++)->accept( *visitor );
540 output << ") /* " << opInfo->inputName << " */";
541 } else if ( untypedExpr->get_args().size() == 2 ) {
542 // intrinsic two parameter constructors are essentially bitwise assignment
543 output << "(";
544 (*arg++)->accept( *visitor );
545 output << opInfo->symbol;
546 (*arg)->accept( *visitor );
547 output << ") /* " << opInfo->inputName << " */";
548 } else {
549 // no constructors with 0 or more than 2 parameters
550 assertf( ! options.genC, "UntypedExpr constructor/destructor with 0 or more than 2 parameters." );
551 output << "(";
552 (*arg++)->accept( *visitor );
553 output << opInfo->symbol << "{ ";
554 genCommaList( arg, untypedExpr->args.end() );
555 output << "}) /* " << opInfo->inputName << " */";
556 } // if
557 break;
558
559 case OT_PREFIX:
560 case OT_PREFIXASSIGN:
561 case OT_LABELADDRESS:
562 assert( untypedExpr->args.size() == 1 );
563 output << "(";
564 output << opInfo->symbol;
565 (*arg)->accept( *visitor );
566 output << ")";
567 break;
568
569 case OT_POSTFIX:
570 case OT_POSTFIXASSIGN:
571 assert( untypedExpr->args.size() == 1 );
572 (*arg)->accept( *visitor );
573 output << opInfo->symbol;
574 break;
575
576 case OT_INFIX:
577 case OT_INFIXASSIGN:
578 assert( untypedExpr->args.size() == 2 );
579 output << "(";
580 (*arg++)->accept( *visitor );
581 output << opInfo->symbol;
582 (*arg)->accept( *visitor );
583 output << ")";
584 break;
585
586 case OT_CONSTANT:
587 // there are no intrinsic definitions of 0 or 1 as functions
588 assert( false );
589 } // switch
590 } else {
591 // builtin routines
592 nameExpr->accept( *visitor );
593 output << "(";
594 genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
595 output << ")";
596 } // if
597 } else {
598 untypedExpr->function->accept( *visitor );
599 output << "(";
600 genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
601 output << ")";
602 } // if
603 }
604
605 void CodeGenerator::postvisit( RangeExpr * rangeExpr ) {
606 rangeExpr->low->accept( *visitor );
607 output << " ... ";
608 rangeExpr->high->accept( *visitor );
609 }
610
611 void CodeGenerator::postvisit( NameExpr * nameExpr ) {
612 extension( nameExpr );
613 const OperatorInfo * opInfo = operatorLookup( nameExpr->name );
614 if ( opInfo ) {
615 if ( opInfo->type == OT_CONSTANT ) {
616 output << opInfo->symbol;
617 } else {
618 output << opInfo->outputName;
619 }
620 } else {
621 output << nameExpr->get_name();
622 } // if
623 }
624
625 void CodeGenerator::postvisit( DimensionExpr * dimensionExpr ) {
626 extension( dimensionExpr );
627 output << "/*non-type*/" << dimensionExpr->get_name();
628 }
629
630 void CodeGenerator::postvisit( AddressExpr * addressExpr ) {
631 extension( addressExpr );
632 output << "(&";
633 addressExpr->arg->accept( *visitor );
634 output << ")";
635 }
636
637 void CodeGenerator::postvisit( LabelAddressExpr *addressExpr ) {
638 extension( addressExpr );
639 output << "(&&" << addressExpr->arg << ")";
640 }
641
642 void CodeGenerator::postvisit( CastExpr * castExpr ) {
643 extension( castExpr );
644 output << "(";
645 if ( castExpr->get_result()->isVoid() ) {
646 output << "(void)";
647 } else {
648 // at least one result type of cast.
649 // Note: previously, lvalue casts were skipped. Since it's now impossible for the user to write
650 // an lvalue cast, this has been taken out.
651 output << "(";
652 output << genType( castExpr->get_result(), "", options );
653 output << ")";
654 } // if
655 castExpr->arg->accept( *visitor );
656 output << ")";
657 }
658
659 void CodeGenerator::postvisit( KeywordCastExpr * castExpr ) {
660 assertf( ! options.genC, "KeywordCast should not reach code generation." );
661 extension( castExpr );
662 output << "((" << castExpr->targetString() << " &)";
663 castExpr->arg->accept( *visitor );
664 output << ")";
665 }
666
667 void CodeGenerator::postvisit( VirtualCastExpr * castExpr ) {
668 assertf( ! options.genC, "VirtualCastExpr should not reach code generation." );
669 extension( castExpr );
670 output << "(virtual ";
671 castExpr->get_arg()->accept( *visitor );
672 output << ")";
673 }
674
675 void CodeGenerator::postvisit( UntypedMemberExpr * memberExpr ) {
676 assertf( ! options.genC, "UntypedMemberExpr should not reach code generation." );
677 extension( memberExpr );
678 memberExpr->get_aggregate()->accept( *visitor );
679 output << ".";
680 memberExpr->get_member()->accept( *visitor );
681 }
682
683 void CodeGenerator::postvisit( MemberExpr * memberExpr ) {
684 extension( memberExpr );
685 memberExpr->get_aggregate()->accept( *visitor );
686 output << "." << mangleName( memberExpr->get_member() );
687 }
688
689 void CodeGenerator::postvisit( VariableExpr * variableExpr ) {
690 extension( variableExpr );
691 const OperatorInfo * opInfo;
692 if( dynamic_cast<ZeroType*>( variableExpr->get_var()->get_type() ) ) {
693 output << "0";
694 } else if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && (opInfo = operatorLookup( variableExpr->get_var()->get_name() )) && opInfo->type == OT_CONSTANT ) {
695 output << opInfo->symbol;
696 } else {
697 // if (dynamic_cast<EnumInstType *>(variableExpr->get_var()->get_type())
698 // && dynamic_cast<EnumInstType *>(variableExpr->get_var()->get_type())->baseEnum->base) {
699 // output << '(' <<genType(dynamic_cast<EnumInstType *>(variableExpr->get_var()->get_type())->baseEnum->base, "", options) << ')';
700 // }
701 output << mangleName( variableExpr->get_var() );
702 } // if
703 }
704
705 void CodeGenerator::postvisit( ConstantExpr * constantExpr ) {
706 assert( constantExpr->get_constant() );
707 extension( constantExpr );
708 constantExpr->get_constant()->accept( *visitor );
709 }
710
711 void CodeGenerator::postvisit( SizeofExpr * sizeofExpr ) {
712 extension( sizeofExpr );
713 output << "sizeof(";
714 if ( sizeofExpr->get_isType() ) {
715 output << genType( sizeofExpr->get_type(), "", options );
716 } else {
717 sizeofExpr->get_expr()->accept( *visitor );
718 } // if
719 output << ")";
720 }
721
722 void CodeGenerator::postvisit( AlignofExpr * alignofExpr ) {
723 // use GCC extension to avoid bumping std to C11
724 extension( alignofExpr );
725 output << "__alignof__(";
726 if ( alignofExpr->get_isType() ) {
727 output << genType( alignofExpr->get_type(), "", options );
728 } else {
729 alignofExpr->get_expr()->accept( *visitor );
730 } // if
731 output << ")";
732 }
733
734 void CodeGenerator::postvisit( UntypedOffsetofExpr * offsetofExpr ) {
735 assertf( ! options.genC, "UntypedOffsetofExpr should not reach code generation." );
736 output << "offsetof(";
737 output << genType( offsetofExpr->get_type(), "", options );
738 output << ", " << offsetofExpr->get_member();
739 output << ")";
740 }
741
742 void CodeGenerator::postvisit( OffsetofExpr * offsetofExpr ) {
743 // use GCC builtin
744 output << "__builtin_offsetof(";
745 output << genType( offsetofExpr->get_type(), "", options );
746 output << ", " << mangleName( offsetofExpr->get_member() );
747 output << ")";
748 }
749
750 void CodeGenerator::postvisit( OffsetPackExpr * offsetPackExpr ) {
751 assertf( ! options.genC, "OffsetPackExpr should not reach code generation." );
752 output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", options ) << ")";
753 }
754
755 void CodeGenerator::postvisit( LogicalExpr * logicalExpr ) {
756 extension( logicalExpr );
757 output << "(";
758 logicalExpr->get_arg1()->accept( *visitor );
759 if ( logicalExpr->get_isAnd() ) {
760 output << " && ";
761 } else {
762 output << " || ";
763 } // if
764 logicalExpr->get_arg2()->accept( *visitor );
765 output << ")";
766 }
767
768 void CodeGenerator::postvisit( ConditionalExpr * conditionalExpr ) {
769 extension( conditionalExpr );
770 output << "(";
771 conditionalExpr->get_arg1()->accept( *visitor );
772 output << " ? ";
773 conditionalExpr->get_arg2()->accept( *visitor );
774 output << " : ";
775 conditionalExpr->get_arg3()->accept( *visitor );
776 output << ")";
777 }
778
779 void CodeGenerator::postvisit( CommaExpr * commaExpr ) {
780 extension( commaExpr );
781 output << "(";
782 if ( options.genC ) {
783 // arg1 of a CommaExpr is never used, so it can be safely cast to void to reduce gcc warnings.
784 commaExpr->set_arg1( new CastExpr( commaExpr->get_arg1() ) );
785 }
786 commaExpr->get_arg1()->accept( *visitor );
787 output << " , ";
788 commaExpr->get_arg2()->accept( *visitor );
789 output << ")";
790 }
791
792 void CodeGenerator::postvisit( TupleAssignExpr * tupleExpr ) {
793 assertf( ! options.genC, "TupleAssignExpr should not reach code generation." );
794 tupleExpr->stmtExpr->accept( *visitor );
795 }
796
797 void CodeGenerator::postvisit( UntypedTupleExpr * tupleExpr ) {
798 assertf( ! options.genC, "UntypedTupleExpr should not reach code generation." );
799 extension( tupleExpr );
800 output << "[";
801 genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
802 output << "]";
803 }
804
805 void CodeGenerator::postvisit( TupleExpr * tupleExpr ) {
806 assertf( ! options.genC, "TupleExpr should not reach code generation." );
807 extension( tupleExpr );
808 output << "[";
809 genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
810 output << "]";
811 }
812
813 void CodeGenerator::postvisit( TupleIndexExpr * tupleExpr ) {
814 assertf( ! options.genC, "TupleIndexExpr should not reach code generation." );
815 extension( tupleExpr );
816 tupleExpr->get_tuple()->accept( *visitor );
817 output << "." << tupleExpr->get_index();
818 }
819
820 void CodeGenerator::postvisit( TypeExpr * typeExpr ) {
821 // if ( options.genC ) std::cerr << "typeexpr still exists: " << typeExpr << std::endl;
822 // assertf( ! options.genC, "TypeExpr should not reach code generation." );
823 if ( ! options.genC ) {
824 output << genType( typeExpr->get_type(), "", options );
825 }
826 }
827
828 void CodeGenerator::postvisit( AsmExpr * asmExpr ) {
829 if ( !asmExpr->inout.empty() ) {
830 output << "[ ";
831 output << asmExpr->inout;
832 output << " ] ";
833 } // if
834 asmExpr->constraint->accept( *visitor );
835 output << " ( ";
836 asmExpr->operand->accept( *visitor );
837 output << " )";
838 }
839
840 void CodeGenerator::postvisit( CompoundLiteralExpr *compLitExpr ) {
841 assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
842 output << "(" << genType( compLitExpr->get_result(), "", options ) << ")";
843 compLitExpr->get_initializer()->accept( *visitor );
844 }
845
846 void CodeGenerator::postvisit( UniqueExpr * unqExpr ) {
847 assertf( ! options.genC, "Unique expressions should not reach code generation." );
848 output << "unq<" << unqExpr->get_id() << ">{ ";
849 unqExpr->get_expr()->accept( *visitor );
850 output << " }";
851 }
852
853 void CodeGenerator::postvisit( StmtExpr * stmtExpr ) {
854 std::list< Statement * > & stmts = stmtExpr->statements->kids;
855 output << "({" << endl;
856 ++indent;
857 unsigned int numStmts = stmts.size();
858 unsigned int i = 0;
859 for ( Statement * stmt : stmts ) {
860 output << indent << printLabels( stmt->get_labels() );
861 if ( i+1 == numStmts ) {
862 // last statement in a statement expression needs to be handled specially -
863 // cannot cast to void, otherwise the expression statement has no value
864 if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
865 exprStmt->expr->accept( *visitor );
866 output << ";" << endl;
867 ++i;
868 break;
869 }
870 }
871 stmt->accept( *visitor );
872 output << endl;
873 if ( wantSpacing( stmt ) ) {
874 output << endl;
875 } // if
876 ++i;
877 }
878 --indent;
879 output << indent << "})";
880 }
881
882 void CodeGenerator::postvisit( ConstructorExpr * expr ) {
883 assertf( ! options.genC, "Unique expressions should not reach code generation." );
884 expr->callExpr->accept( *visitor );
885 }
886
887 void CodeGenerator::postvisit( DeletedExpr * expr ) {
888 assertf( ! options.genC, "Deleted expressions should not reach code generation." );
889 expr->expr->accept( *visitor );
890 }
891
892 void CodeGenerator::postvisit( DefaultArgExpr * arg ) {
893 assertf( ! options.genC, "Default argument expressions should not reach code generation." );
894 arg->expr->accept( *visitor );
895 }
896
897 void CodeGenerator::postvisit( GenericExpr * expr ) {
898 assertf( ! options.genC, "C11 _Generic expressions should not reach code generation." );
899 output << "_Generic(";
900 expr->control->accept( *visitor );
901 output << ", ";
902 unsigned int numAssocs = expr->associations.size();
903 unsigned int i = 0;
904 for ( GenericExpr::Association & assoc : expr->associations ) {
905 if (assoc.isDefault) {
906 output << "default: ";
907 } else {
908 output << genType( assoc.type, "", options ) << ": ";
909 }
910 assoc.expr->accept( *visitor );
911 if ( i+1 != numAssocs ) {
912 output << ", ";
913 }
914 i++;
915 }
916 output << ")";
917 }
918
919
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.