source: src/CodeGen/CodeGenerator.cc @ 8ebbfc4

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since 8ebbfc4 was 13073be, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Fix atomic builtins in libcfa and prelude

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