source: src/CodeGen/CodeGenerator.cc @ 786c438

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

Remove Marker to pass tests

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