source: src/CodeGen/CodeGenerator.cc @ ab5c0008

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since ab5c0008 was 665f432, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Fixed trac #149 where operand names in asm statements where incorrectly resolved (i.e., should not have been resolved)

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