source: src/CodeGen/CodeGenerator.cc @ 3eb1653

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 3eb1653 was 3eb1653, checked in by JiadaL <j82liang@…>, 2 years ago

Remove development labels to pass the tests

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