source: src/CodeGen/CodeGenerator.cc @ de52331

ADTast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since de52331 was 6cebfef, checked in by caparsons <caparson@…>, 3 years ago

added mutex stmt monitor

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