source: src/CodeGen/CodeGenerator.cc @ e5f2a67

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since e5f2a67 was bf2438c, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Cleaned-up some headers using a tool called 'include-what-you-use'

  • Property mode set to 100644
File size: 31.5 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 : Andrew Beach
12// Last Modified On : Thu Jun  8 16:00:00 2017
13// Update Count     : 485
14//
15
16#include <cassert>                   // for assert, assertf
17#include <list>                      // for _List_iterator, list, list<>::it...
18
19#include "CodeGenerator.h"
20#include "Common/SemanticError.h"    // for SemanticError
21#include "Common/UniqueName.h"       // for UniqueName
22#include "Common/utility.h"          // for CodeLocation, toString
23#include "GenType.h"                 // for genType
24#include "InitTweak/InitTweak.h"     // for getPointerBase
25#include "OperatorTable.h"           // for OperatorInfo, operatorLookup
26#include "Parser/LinkageSpec.h"      // for Spec, Intrinsic
27#include "SynTree/Attribute.h"       // for Attribute
28#include "SynTree/BaseSyntaxNode.h"  // for BaseSyntaxNode
29#include "SynTree/Constant.h"        // for Constant
30#include "SynTree/Declaration.h"     // for DeclarationWithType, TypeDecl
31#include "SynTree/Expression.h"      // for Expression, UntypedExpr, Applica...
32#include "SynTree/Initializer.h"     // for Initializer, ListInit, Designation
33#include "SynTree/Label.h"           // for Label, operator<<
34#include "SynTree/Statement.h"       // for Statement, AsmStmt, BranchStmt
35#include "SynTree/Type.h"            // for Type, Type::StorageClasses, Func...
36
37using namespace std;
38
39namespace CodeGen {
40        int CodeGenerator::tabsize = 4;
41
42        // the kinds of statements that would ideally be followed by whitespace
43        bool wantSpacing( Statement * stmt) {
44                return dynamic_cast< IfStmt * >( stmt ) || dynamic_cast< CompoundStmt * >( stmt ) ||
45                        dynamic_cast< WhileStmt * >( stmt ) || dynamic_cast< ForStmt * >( stmt ) || dynamic_cast< SwitchStmt *>( stmt );
46        }
47
48        void CodeGenerator::extension( Expression * expr ) {
49                if ( expr->get_extension() ) {
50                        output << "__extension__ ";
51                } // if
52        } // extension
53
54        void CodeGenerator::extension( Declaration * decl ) {
55                if ( decl->get_extension() ) {
56                        output << "__extension__ ";
57                } // if
58        } // extension
59
60        void CodeGenerator::asmName( DeclarationWithType * decl ) {
61                if ( ConstantExpr * asmName = decl->get_asmName() ) {
62                        output << " asm ( " << asmName->get_constant()->get_value() << " )";
63                } // if
64        } // extension
65
66        ostream & CodeGenerator::Indenter::operator()( ostream & output ) const {
67          return output << string( cg.cur_indent, ' ' );
68        }
69
70        ostream & operator<<( ostream & output, const CodeGenerator::Indenter &indent ) {
71                return indent( output );
72        }
73
74        CodeGenerator::LabelPrinter & CodeGenerator::LabelPrinter::operator()( std::list< Label > & l ) {
75                labels = &l;
76                return *this;
77        }
78
79        ostream & operator<<( ostream & output, CodeGenerator::LabelPrinter & printLabels ) {
80                std::list< Label > & labs = *printLabels.labels;
81                // l.unique(); // assumes a sorted list. Why not use set? Does order matter?
82                for ( Label & l : labs ) {
83                        output << l.get_name() + ": ";
84                        printLabels.cg.genAttributes( l.get_attributes() );
85                } // for
86                return output;
87        }
88
89        CodeGenerator::LineMarker::LineMarker(
90                        CodeLocation const & loc, bool toPrint) :
91                loc(loc), toPrint(toPrint)
92        {}
93
94        CodeGenerator::LineMarker CodeGenerator::lineDirective(
95                        BaseSyntaxNode const * node) {
96                return LineMarker(node->location, lineMarks);
97        }
98
99        std::ostream & operator<<(std::ostream & out,
100                        CodeGenerator::LineMarker const & marker) {
101                if (marker.toPrint && marker.loc.isSet()) {
102                        return out << "\n# " << marker.loc.linenumber << " \""
103                                << marker.loc.filename << "\"\n";
104                } else if (marker.toPrint) {
105                        return out << "\n/* Missing CodeLocation */\n";
106                } else {
107                return out;
108                }
109        }
110
111        CodeGenerator::CodeGenerator( std::ostream & os, bool pretty, bool genC, bool lineMarks ) : indent( *this), cur_indent( 0 ), insideFunction( false ), output( os ), printLabels( *this ), pretty( pretty ), genC( genC ), lineMarks( lineMarks ) {}
112
113        string CodeGenerator::mangleName( DeclarationWithType * decl ) {
114                if ( pretty ) return decl->get_name();
115                if ( decl->get_mangleName() != "" ) {
116                        // need to incorporate scope level in order to differentiate names for destructors
117                        return decl->get_scopedMangleName();
118                } else {
119                        return decl->get_name();
120                } // if
121        }
122
123        void CodeGenerator::genAttributes( list< Attribute * > & attributes ) {
124          if ( attributes.empty() ) return;
125                output << "__attribute__ ((";
126                for ( list< Attribute * >::iterator attr( attributes.begin() );; ) {
127                        output << (*attr)->get_name();
128                        if ( ! (*attr)->get_parameters().empty() ) {
129                                output << "(";
130                                genCommaList( (*attr)->get_parameters().begin(), (*attr)->get_parameters().end() );
131                                output << ")";
132                        } // if
133                  if ( ++attr == attributes.end() ) break;
134                        output << ",";                                                          // separator
135                } // for
136                output << ")) ";
137        } // CodeGenerator::genAttributes
138
139
140        // *** Declarations
141        void CodeGenerator::visit( FunctionDecl * functionDecl ) {
142                extension( functionDecl );
143                genAttributes( functionDecl->get_attributes() );
144
145                handleStorageClass( functionDecl );
146                functionDecl->get_funcSpec().print( output );
147
148                output << genType( functionDecl->get_functionType(), mangleName( functionDecl ), pretty, genC );
149
150                asmName( functionDecl );
151
152                // acceptAll( functionDecl->get_oldDecls(), *this );
153                if ( functionDecl->get_statements() ) {
154                        functionDecl->get_statements()->accept( *this );
155                } // if
156        }
157
158        void CodeGenerator::visit( ObjectDecl * objectDecl ) {
159                if (objectDecl->get_name().empty() && genC ) {
160                        // only generate an anonymous name when generating C code, otherwise it clutters the output too much
161                        static UniqueName name = { "__anonymous_object" };
162                        objectDecl->set_name( name.newName() );
163                }
164
165                extension( objectDecl );
166                genAttributes( objectDecl->get_attributes() );
167
168                handleStorageClass( objectDecl );
169                output << genType( objectDecl->get_type(), mangleName( objectDecl ), pretty, genC );
170
171                asmName( objectDecl );
172
173                if ( objectDecl->get_init() ) {
174                        output << " = ";
175                        objectDecl->get_init()->accept( *this );
176                } // if
177
178                if ( objectDecl->get_bitfieldWidth() ) {
179                        output << ":";
180                        objectDecl->get_bitfieldWidth()->accept( *this );
181                } // if
182        }
183
184        void CodeGenerator::handleAggregate( AggregateDecl * aggDecl, const std::string & kind ) {
185                genAttributes( aggDecl->get_attributes() );
186
187                if( ! aggDecl->get_parameters().empty() && ! genC ) {
188                        // assertf( ! genC, "Aggregate type parameters should not reach code generation." );
189                        output << "forall(";
190                        genCommaList( aggDecl->get_parameters().begin(), aggDecl->get_parameters().end() );
191                        output << ")" << endl;
192                }
193
194                output << kind;
195                if ( aggDecl->get_name() != "" )
196                        output << aggDecl->get_name();
197
198                if ( aggDecl->has_body() ) {
199                        std::list< Declaration * > & memb = aggDecl->get_members();
200                        output << " {" << endl;
201
202                        cur_indent += CodeGenerator::tabsize;
203                        for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++ ) {
204                                output << lineDirective( *i ) << indent;
205                                (*i)->accept( *this );
206                                output << ";" << endl;
207                        } // for
208
209                        cur_indent -= CodeGenerator::tabsize;
210
211                        output << indent << "}";
212                } // if
213        }
214
215        void CodeGenerator::visit( StructDecl * structDecl ) {
216                extension( structDecl );
217                handleAggregate( structDecl, "struct " );
218        }
219
220        void CodeGenerator::visit( UnionDecl * unionDecl ) {
221                extension( unionDecl );
222                handleAggregate( unionDecl, "union " );
223        }
224
225        void CodeGenerator::visit( EnumDecl * enumDecl ) {
226                extension( enumDecl );
227                output << lineDirective ( enumDecl );
228                output << "enum ";
229                genAttributes( enumDecl->get_attributes() );
230
231                if ( enumDecl->get_name() != "" )
232                        output << enumDecl->get_name();
233
234                std::list< Declaration* > &memb = enumDecl->get_members();
235
236                if ( ! memb.empty() ) {
237                        output << " {" << endl;
238
239                        cur_indent += CodeGenerator::tabsize;
240                        for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end();  i++) {
241                                ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
242                                assert( obj );
243                                output << lineDirective( obj ) << indent << mangleName( obj );
244                                if ( obj->get_init() ) {
245                                        output << " = ";
246                                        obj->get_init()->accept( *this );
247                                } // if
248                                output << "," << endl;
249                        } // for
250
251                        cur_indent -= CodeGenerator::tabsize;
252
253                        output << indent << "}";
254                } // if
255        }
256
257        void CodeGenerator::visit( __attribute__((unused)) TraitDecl * traitDecl ) {}
258
259        void CodeGenerator::visit( TypedefDecl * typeDecl ) {
260                assertf( ! genC, "Typedefs are removed and substituted in earlier passes." );
261                output << lineDirective( typeDecl );
262                output << "typedef ";
263                output << genType( typeDecl->get_base(), typeDecl->get_name(), pretty, genC ) << endl;
264        }
265
266        void CodeGenerator::visit( TypeDecl * typeDecl ) {
267                if ( genC ) {
268                        // really, we should mutate this into something that isn't a TypeDecl but that requires large-scale changes,
269                        // still to be done
270                        extension( typeDecl );
271                        output << "extern unsigned long " << typeDecl->get_name();
272                        if ( typeDecl->get_base() ) {
273                                output << " = sizeof( " << genType( typeDecl->get_base(), "", pretty, genC ) << " )";
274                        } // if
275                } else {
276                        output << typeDecl->genTypeString() << " " << typeDecl->get_name();
277                        if ( typeDecl->get_kind() != TypeDecl::Any && typeDecl->get_sized() ) {
278                                output << " | sized(" << typeDecl->get_name() << ")";
279                        }
280                        if ( ! typeDecl->get_assertions().empty() ) {
281                                output << " | { ";
282                                genCommaList( typeDecl->get_assertions().begin(), typeDecl->get_assertions().end() );
283                                output << " }";
284                        }
285                }
286        }
287
288        void CodeGenerator::visit( Designation * designation ) {
289                std::list< Expression * > designators = designation->get_designators();
290                if ( designators.size() == 0 ) return;
291                for ( Expression * des : designators ) {
292                        if ( dynamic_cast< NameExpr * >( des ) || dynamic_cast< VariableExpr * >( des ) ) {
293                                // if expression is a NameExpr or VariableExpr, then initializing aggregate member
294                                output << ".";
295                                des->accept( *this );
296                        } else {
297                                // otherwise, it has to be a ConstantExpr or CastExpr, initializing array eleemnt
298                                output << "[";
299                                des->accept( *this );
300                                output << "]";
301                        } // if
302                } // for
303                output << " = ";
304        }
305
306        void CodeGenerator::visit( SingleInit * init ) {
307                init->get_value()->accept( *this );
308        }
309
310        void CodeGenerator::visit( ListInit * init ) {
311                auto initBegin = init->begin();
312                auto initEnd = init->end();
313                auto desigBegin = init->get_designations().begin();
314                auto desigEnd = init->get_designations().end();
315
316                output << "{ ";
317                for ( ; initBegin != initEnd && desigBegin != desigEnd; ) {
318                        (*desigBegin)->accept( *this );
319                        (*initBegin)->accept( *this );
320                        ++initBegin, ++desigBegin;
321                        if ( initBegin != initEnd ) {
322                                output << ", ";
323                        }
324                }
325                output << " }";
326                assertf( initBegin == initEnd && desigBegin == desigEnd, "Initializers and designators not the same length. %s", toString( init ).c_str() );
327        }
328
329        void CodeGenerator::visit( __attribute__((unused)) ConstructorInit * init ){
330                assertf( ! genC, "ConstructorInit nodes should not reach code generation." );
331                // xxx - generate something reasonable for constructor/destructor pairs
332                output << "<ctorinit>";
333        }
334
335        void CodeGenerator::visit( Constant * constant ) {
336                output << constant->get_value() ;
337        }
338
339        // *** Expressions
340        void CodeGenerator::visit( ApplicationExpr * applicationExpr ) {
341                extension( applicationExpr );
342                if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
343                        OperatorInfo opInfo;
344                        if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( varExpr->get_var()->get_name(), opInfo ) ) {
345                                std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
346                                switch ( opInfo.type ) {
347                                  case OT_PREFIXASSIGN:
348                                  case OT_POSTFIXASSIGN:
349                                  case OT_INFIXASSIGN:
350                                  case OT_CTOR:
351                                  case OT_DTOR:
352                                        {
353                                                assert( arg != applicationExpr->get_args().end() );
354                                                if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( *arg ) ) {
355                                                        // remove & from first assignment/ctor argument
356                                                        *arg = addrExpr->get_arg();
357                                                } else {
358                                                        // no address-of operator, so must be a pointer - add dereference
359                                                        // NOTE: if the assertion starts to trigger, check that the application expr isn't being shared.
360                                                        // Since its arguments are modified here, this assertion most commonly triggers when the application
361                                                        // is visited multiple times.
362                                                        UntypedExpr * newExpr = new UntypedExpr( new NameExpr( "*?" ) );
363                                                        newExpr->get_args().push_back( *arg );
364                                                        Type * type = InitTweak::getPointerBase( (*arg)->get_result() );
365                                                        assertf( type, "First argument to a derefence must be a pointer. Ensure that expressions are not being shared." );
366                                                        newExpr->set_result( type->clone() );
367                                                        *arg = newExpr;
368                                                } // if
369                                                break;
370                                        }
371
372                                  default:
373                                        // do nothing
374                                        ;
375                                } // switch
376
377                                switch ( opInfo.type ) {
378                                  case OT_INDEX:
379                                        assert( applicationExpr->get_args().size() == 2 );
380                                        (*arg++)->accept( *this );
381                                        output << "[";
382                                        (*arg)->accept( *this );
383                                        output << "]";
384                                        break;
385
386                                  case OT_CALL:
387                                        // there are no intrinsic definitions of the function call operator
388                                        assert( false );
389                                        break;
390
391                                  case OT_CTOR:
392                                  case OT_DTOR:
393                                        if ( applicationExpr->get_args().size() == 1 ) {
394                                                // the expression fed into a single parameter constructor or destructor may contain side
395                                                // effects, so must still output this expression
396                                                output << "(";
397                                                (*arg++)->accept( *this );
398                                                output << ") /* " << opInfo.inputName << " */";
399                                        } else if ( applicationExpr->get_args().size() == 2 ) {
400                                                // intrinsic two parameter constructors are essentially bitwise assignment
401                                                output << "(";
402                                                (*arg++)->accept( *this );
403                                                output << opInfo.symbol;
404                                                (*arg)->accept( *this );
405                                                output << ") /* " << opInfo.inputName << " */";
406                                        } else {
407                                                // no constructors with 0 or more than 2 parameters
408                                                assert( false );
409                                        } // if
410                                        break;
411
412                                  case OT_PREFIX:
413                                  case OT_PREFIXASSIGN:
414                                        assert( applicationExpr->get_args().size() == 1 );
415                                        output << "(";
416                                        output << opInfo.symbol;
417                                        (*arg)->accept( *this );
418                                        output << ")";
419                                        break;
420
421                                  case OT_POSTFIX:
422                                  case OT_POSTFIXASSIGN:
423                                        assert( applicationExpr->get_args().size() == 1 );
424                                        (*arg)->accept( *this );
425                                        output << opInfo.symbol;
426                                        break;
427
428
429                                  case OT_INFIX:
430                                  case OT_INFIXASSIGN:
431                                        assert( applicationExpr->get_args().size() == 2 );
432                                        output << "(";
433                                        (*arg++)->accept( *this );
434                                        output << opInfo.symbol;
435                                        (*arg)->accept( *this );
436                                        output << ")";
437                                        break;
438
439                                  case OT_CONSTANT:
440                                  case OT_LABELADDRESS:
441                                        // there are no intrinsic definitions of 0/1 or label addresses as functions
442                                        assert( false );
443                                } // switch
444                        } else {
445                                varExpr->accept( *this );
446                                output << "(";
447                                genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
448                                output << ")";
449                        } // if
450                } else {
451                        applicationExpr->get_function()->accept( *this );
452                        output << "(";
453                        genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
454                        output << ")";
455                } // if
456        }
457
458        void CodeGenerator::visit( UntypedExpr * untypedExpr ) {
459                extension( untypedExpr );
460                if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->get_function() ) ) {
461                        OperatorInfo opInfo;
462                        if ( operatorLookup( nameExpr->get_name(), opInfo ) ) {
463                                std::list< Expression* >::iterator arg = untypedExpr->get_args().begin();
464                                switch ( opInfo.type ) {
465                                  case OT_INDEX:
466                                        assert( untypedExpr->get_args().size() == 2 );
467                                        (*arg++)->accept( *this );
468                                        output << "[";
469                                        (*arg)->accept( *this );
470                                        output << "]";
471                                        break;
472
473                                  case OT_CALL:
474                                        assert( false );
475
476                                  case OT_CTOR:
477                                  case OT_DTOR:
478                                        if ( untypedExpr->get_args().size() == 1 ) {
479                                                // the expression fed into a single parameter constructor or destructor may contain side
480                                                // effects, so must still output this expression
481                                                output << "(";
482                                                (*arg++)->accept( *this );
483                                                output << ") /* " << opInfo.inputName << " */";
484                                        } else if ( untypedExpr->get_args().size() == 2 ) {
485                                                // intrinsic two parameter constructors are essentially bitwise assignment
486                                                output << "(";
487                                                (*arg++)->accept( *this );
488                                                output << opInfo.symbol;
489                                                (*arg)->accept( *this );
490                                                output << ") /* " << opInfo.inputName << " */";
491                                        } else {
492                                                // no constructors with 0 or more than 2 parameters
493                                                assert( false );
494                                        } // if
495                                        break;
496
497                                  case OT_PREFIX:
498                                  case OT_PREFIXASSIGN:
499                                  case OT_LABELADDRESS:
500                                        assert( untypedExpr->get_args().size() == 1 );
501                                        output << "(";
502                                        output << opInfo.symbol;
503                                        (*arg)->accept( *this );
504                                        output << ")";
505                                        break;
506
507                                  case OT_POSTFIX:
508                                  case OT_POSTFIXASSIGN:
509                                        assert( untypedExpr->get_args().size() == 1 );
510                                        (*arg)->accept( *this );
511                                        output << opInfo.symbol;
512                                        break;
513
514                                  case OT_INFIX:
515                                  case OT_INFIXASSIGN:
516                                        assert( untypedExpr->get_args().size() == 2 );
517                                        output << "(";
518                                        (*arg++)->accept( *this );
519                                        output << opInfo.symbol;
520                                        (*arg)->accept( *this );
521                                        output << ")";
522                                        break;
523
524                                  case OT_CONSTANT:
525                                        // there are no intrinsic definitions of 0 or 1 as functions
526                                        assert( false );
527                                } // switch
528                        } else {
529                                if ( nameExpr->get_name() == "..." ) { // case V1 ... V2 or case V1~V2
530                                        assert( untypedExpr->get_args().size() == 2 );
531                                        (*untypedExpr->get_args().begin())->accept( *this );
532                                        output << " ... ";
533                                        (*--untypedExpr->get_args().end())->accept( *this );
534                                } else {                                                                // builtin routines
535                                        nameExpr->accept( *this );
536                                        output << "(";
537                                        genCommaList( untypedExpr->get_args().begin(), untypedExpr->get_args().end() );
538                                        output << ")";
539                                } // if
540                        } // if
541                } else {
542                        untypedExpr->get_function()->accept( *this );
543                        output << "(";
544                        genCommaList( untypedExpr->get_args().begin(), untypedExpr->get_args().end() );
545                        output << ")";
546                } // if
547        }
548
549        void CodeGenerator::visit( RangeExpr * rangeExpr ) {
550                rangeExpr->get_low()->accept( *this );
551                output << " ... ";
552                rangeExpr->get_high()->accept( *this );
553        }
554
555        void CodeGenerator::visit( NameExpr * nameExpr ) {
556                extension( nameExpr );
557                OperatorInfo opInfo;
558                if ( operatorLookup( nameExpr->get_name(), opInfo ) ) {
559                        assert( opInfo.type == OT_CONSTANT );
560                        output << opInfo.symbol;
561                } else {
562                        output << nameExpr->get_name();
563                } // if
564        }
565
566        void CodeGenerator::visit( AddressExpr * addressExpr ) {
567                extension( addressExpr );
568                output << "(&";
569                // this hack makes sure that we don't convert "constant_zero" to "0" if we're taking its address
570                if ( VariableExpr * variableExpr = dynamic_cast< VariableExpr* >( addressExpr->get_arg() ) ) {
571                        output << mangleName( variableExpr->get_var() );
572                } else {
573                        addressExpr->get_arg()->accept( *this );
574                } // if
575                output << ")";
576        }
577
578        void CodeGenerator::visit( CastExpr * castExpr ) {
579                extension( castExpr );
580                output << "(";
581                if ( castExpr->get_result()->isVoid() ) {
582                        output << "(void)" ;
583                } else if ( ! castExpr->get_result()->get_lvalue() ) {
584                        // at least one result type of cast, but not an lvalue
585                        output << "(";
586                        output << genType( castExpr->get_result(), "", pretty, genC );
587                        output << ")";
588                } else {
589                        // otherwise, the cast is to an lvalue type, so the cast should be dropped, since the result of a cast is
590                        // never an lvalue in C
591                } // if
592                castExpr->get_arg()->accept( *this );
593                output << ")";
594        }
595
596        void CodeGenerator::visit( UntypedMemberExpr * memberExpr ) {
597                assertf( ! genC, "UntypedMemberExpr should not reach code generation." );
598                extension( memberExpr );
599                memberExpr->get_aggregate()->accept( *this );
600                output << ".";
601                memberExpr->get_member()->accept( *this );
602        }
603
604        void CodeGenerator::visit( MemberExpr * memberExpr ) {
605                extension( memberExpr );
606                memberExpr->get_aggregate()->accept( *this );
607                output << "." << mangleName( memberExpr->get_member() );
608        }
609
610        void CodeGenerator::visit( VariableExpr * variableExpr ) {
611                extension( variableExpr );
612                OperatorInfo opInfo;
613                if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( variableExpr->get_var()->get_name(), opInfo ) && opInfo.type == OT_CONSTANT ) {
614                        output << opInfo.symbol;
615                } else {
616                        output << mangleName( variableExpr->get_var() );
617                } // if
618        }
619
620        void CodeGenerator::visit( ConstantExpr * constantExpr ) {
621                assert( constantExpr->get_constant() );
622                extension( constantExpr );
623                constantExpr->get_constant()->accept( *this );
624        }
625
626        void CodeGenerator::visit( SizeofExpr * sizeofExpr ) {
627                extension( sizeofExpr );
628                output << "sizeof(";
629                if ( sizeofExpr->get_isType() ) {
630                        output << genType( sizeofExpr->get_type(), "", pretty, genC );
631                } else {
632                        sizeofExpr->get_expr()->accept( *this );
633                } // if
634                output << ")";
635        }
636
637        void CodeGenerator::visit( AlignofExpr * alignofExpr ) {
638                // use GCC extension to avoid bumping std to C11
639                extension( alignofExpr );
640                output << "__alignof__(";
641                if ( alignofExpr->get_isType() ) {
642                        output << genType( alignofExpr->get_type(), "", pretty, genC );
643                } else {
644                        alignofExpr->get_expr()->accept( *this );
645                } // if
646                output << ")";
647        }
648
649        void CodeGenerator::visit( UntypedOffsetofExpr * offsetofExpr ) {
650                assertf( ! genC, "UntypedOffsetofExpr should not reach code generation." );
651                output << "offsetof(";
652                output << genType( offsetofExpr->get_type(), "", pretty, genC );
653                output << ", " << offsetofExpr->get_member();
654                output << ")";
655        }
656
657        void CodeGenerator::visit( OffsetofExpr * offsetofExpr ) {
658                // use GCC builtin
659                output << "__builtin_offsetof(";
660                output << genType( offsetofExpr->get_type(), "", pretty, genC );
661                output << ", " << mangleName( offsetofExpr->get_member() );
662                output << ")";
663        }
664
665        void CodeGenerator::visit( OffsetPackExpr * offsetPackExpr ) {
666                assertf( ! genC, "OffsetPackExpr should not reach code generation." );
667                output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", pretty, genC ) << ")";
668        }
669
670        void CodeGenerator::visit( LogicalExpr * logicalExpr ) {
671                extension( logicalExpr );
672                output << "(";
673                logicalExpr->get_arg1()->accept( *this );
674                if ( logicalExpr->get_isAnd() ) {
675                        output << " && ";
676                } else {
677                        output << " || ";
678                } // if
679                logicalExpr->get_arg2()->accept( *this );
680                output << ")";
681        }
682
683        void CodeGenerator::visit( ConditionalExpr * conditionalExpr ) {
684                extension( conditionalExpr );
685                output << "(";
686                conditionalExpr->get_arg1()->accept( *this );
687                output << " ? ";
688                conditionalExpr->get_arg2()->accept( *this );
689                output << " : ";
690                conditionalExpr->get_arg3()->accept( *this );
691                output << ")";
692        }
693
694        void CodeGenerator::visit( CommaExpr * commaExpr ) {
695                extension( commaExpr );
696                output << "(";
697                commaExpr->get_arg1()->accept( *this );
698                output << " , ";
699                commaExpr->get_arg2()->accept( *this );
700                output << ")";
701        }
702
703        void CodeGenerator::visit( UntypedTupleExpr * tupleExpr ) {
704                assertf( ! genC, "UntypedTupleExpr should not reach code generation." );
705                extension( tupleExpr );
706                output << "[";
707                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
708                output << "]";
709        }
710
711        void CodeGenerator::visit( TupleExpr * tupleExpr ) {
712                assertf( ! genC, "TupleExpr should not reach code generation." );
713                extension( tupleExpr );
714                output << "[";
715                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
716                output << "]";
717        }
718
719        void CodeGenerator::visit( TupleIndexExpr * tupleExpr ) {
720                assertf( ! genC, "TupleIndexExpr should not reach code generation." );
721                extension( tupleExpr );
722                tupleExpr->get_tuple()->accept( *this );
723                output << "." << tupleExpr->get_index();
724        }
725
726        void CodeGenerator::visit( TypeExpr * typeExpr ) {
727                // if ( genC ) std::cerr << "typeexpr still exists: " << typeExpr << std::endl;
728                // assertf( ! genC, "TypeExpr should not reach code generation." );
729                if ( ! genC ) {
730                        output<< genType( typeExpr->get_type(), "", pretty, genC );
731                }
732        }
733
734        void CodeGenerator::visit( AsmExpr * asmExpr ) {
735                if ( asmExpr->get_inout() ) {
736                        output << "[ ";
737                        asmExpr->get_inout()->accept( *this );
738                        output << " ] ";
739                } // if
740                asmExpr->get_constraint()->accept( *this );
741                output << " ( ";
742                asmExpr->get_operand()->accept( *this );
743                output << " )";
744        }
745
746        void CodeGenerator::visit( CompoundLiteralExpr *compLitExpr ) {
747                assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
748                output << "(" << genType( compLitExpr->get_result(), "", pretty, genC ) << ")";
749                compLitExpr->get_initializer()->accept( *this );
750        }
751
752        void CodeGenerator::visit( StmtExpr * stmtExpr ) {
753                std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
754                output << lineDirective( stmtExpr) << "({" << std::endl;
755                cur_indent += CodeGenerator::tabsize;
756                unsigned int numStmts = stmts.size();
757                unsigned int i = 0;
758                for ( Statement * stmt : stmts ) {
759                        output << lineDirective( stmt ) << indent;
760            output << printLabels( stmt->get_labels() );
761                        if ( i+1 == numStmts ) {
762                                // last statement in a statement expression needs to be handled specially -
763                                // cannot cast to void, otherwise the expression statement has no value
764                                if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
765                                        exprStmt->get_expr()->accept( *this );
766                                        output << ";" << endl;
767                                        ++i;
768                                        break;
769                                }
770                        }
771                        stmt->accept( *this );
772                        output << endl;
773                        if ( wantSpacing( stmt ) ) {
774                                output << endl;
775                        } // if
776                        ++i;
777                }
778                cur_indent -= CodeGenerator::tabsize;
779                output << indent << "})";
780        }
781
782        // *** Statements
783        void CodeGenerator::visit( CompoundStmt * compoundStmt ) {
784                std::list<Statement*> ks = compoundStmt->get_kids();
785                output << "{" << endl;
786
787                cur_indent += CodeGenerator::tabsize;
788
789                for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end();  i++ ) {
790                        output << indent << printLabels( (*i)->get_labels() );
791                        (*i)->accept( *this );
792
793                        output << endl;
794                        if ( wantSpacing( *i ) ) {
795                                output << endl;
796                        } // if
797                } // for
798                cur_indent -= CodeGenerator::tabsize;
799
800                output << indent << "}";
801        }
802
803        void CodeGenerator::visit( ExprStmt * exprStmt ) {
804                assert( exprStmt );
805                Expression * expr = exprStmt->get_expr();
806                if ( genC ) {
807                        // cast the top-level expression to void to reduce gcc warnings.
808                        expr = new CastExpr( expr );
809                }
810                expr->accept( *this );
811                output << ";";
812        }
813
814        void CodeGenerator::visit( AsmStmt * asmStmt ) {
815                output << "asm ";
816                if ( asmStmt->get_voltile() ) output << "volatile ";
817                if ( ! asmStmt->get_gotolabels().empty()  ) output << "goto ";
818                output << "( ";
819                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
820                output << " : ";
821                genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
822                output << " : ";
823                genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
824                output << " : ";
825                genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
826                if ( ! asmStmt->get_gotolabels().empty() ) {
827                        output << " : ";
828                        for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
829                                output << *begin++;
830                                if ( begin == asmStmt->get_gotolabels().end() ) break;
831                                output << ", ";
832                        } // for
833                } // if
834                output << " );" ;
835        }
836
837        void CodeGenerator::visit( AsmDecl * asmDecl ) {
838                output << "asm ";
839                AsmStmt * asmStmt = asmDecl->get_stmt();
840                output << "( ";
841                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
842                output << " )" ;
843        }
844
845        void CodeGenerator::visit( IfStmt * ifStmt ) {
846                output << lineDirective( ifStmt );
847                output << "if ( ";
848                ifStmt->get_condition()->accept( *this );
849                output << " ) ";
850
851                ifStmt->get_thenPart()->accept( *this );
852
853                if ( ifStmt->get_elsePart() != 0) {
854                        output << " else ";
855                        ifStmt->get_elsePart()->accept( *this );
856                } // if
857        }
858
859        void CodeGenerator::visit( SwitchStmt * switchStmt ) {
860                output << lineDirective( switchStmt );
861                output << "switch ( " ;
862                switchStmt->get_condition()->accept( *this );
863                output << " ) ";
864
865                output << "{" << std::endl;
866                cur_indent += CodeGenerator::tabsize;
867                acceptAll( switchStmt->get_statements(), *this );
868                cur_indent -= CodeGenerator::tabsize;
869                output << indent << "}";
870        }
871
872        void CodeGenerator::visit( CaseStmt * caseStmt ) {
873                output << lineDirective( caseStmt );
874                output << indent;
875                if ( caseStmt->isDefault()) {
876                        output << "default";
877                } else {
878                        output << "case ";
879                        caseStmt->get_condition()->accept( *this );
880                } // if
881                output << ":\n";
882
883                std::list<Statement *> sts = caseStmt->get_statements();
884
885                cur_indent += CodeGenerator::tabsize;
886                for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end();  i++) {
887                        output << indent << printLabels( (*i)->get_labels() )  ;
888                        (*i)->accept( *this );
889                        output << endl;
890                } // for
891                cur_indent -= CodeGenerator::tabsize;
892        }
893
894        void CodeGenerator::visit( BranchStmt * branchStmt ) {
895                switch ( branchStmt->get_type()) {
896                  case BranchStmt::Goto:
897                        if ( ! branchStmt->get_target().empty() )
898                                output << "goto " << branchStmt->get_target();
899                        else {
900                                if ( branchStmt->get_computedTarget() != 0 ) {
901                                        output << "goto *";
902                                        branchStmt->get_computedTarget()->accept( *this );
903                                } // if
904                        } // if
905                        break;
906                  case BranchStmt::Break:
907                        output << "break";
908                        break;
909                  case BranchStmt::Continue:
910                        output << "continue";
911                        break;
912                } // switch
913                output << ";";
914        }
915
916        void CodeGenerator::visit( ReturnStmt * returnStmt ) {
917                output << "return ";
918                maybeAccept( returnStmt->get_expr(), *this );
919                output << ";";
920        }
921
922        void CodeGenerator::visit( ThrowStmt * throwStmt ) {
923                assertf( ! genC, "Throw statements should not reach code generation." );
924
925                output << ((throwStmt->get_kind() == ThrowStmt::Terminate) ?
926                           "throw" : "throwResume");
927                if (throwStmt->get_expr()) {
928                        output << " ";
929                        throwStmt->get_expr()->accept( *this );
930                }
931                if (throwStmt->get_target()) {
932                        output << " _At ";
933                        throwStmt->get_target()->accept( *this );
934                }
935                output << ";";
936        }
937
938        void CodeGenerator::visit( WhileStmt * whileStmt ) {
939                if ( whileStmt->get_isDoWhile() ) {
940                        output << "do" ;
941                } else {
942                        output << "while (" ;
943                        whileStmt->get_condition()->accept( *this );
944                        output << ")";
945                } // if
946                output << " ";
947
948                output << CodeGenerator::printLabels( whileStmt->get_body()->get_labels() );
949                whileStmt->get_body()->accept( *this );
950
951                output << indent;
952
953                if ( whileStmt->get_isDoWhile() ) {
954                        output << " while (" ;
955                        whileStmt->get_condition()->accept( *this );
956                        output << ");";
957                } // if
958        }
959
960        void CodeGenerator::visit( ForStmt * forStmt ) {
961                // initialization is always hoisted, so don't bother doing anything with that
962                output << "for (;";
963
964                if ( forStmt->get_condition() != 0 ) {
965                        forStmt->get_condition()->accept( *this );
966                } // if
967                output << ";";
968
969                if ( forStmt->get_increment() != 0 ) {
970                        // cast the top-level expression to void to reduce gcc warnings.
971                        Expression * expr = new CastExpr( forStmt->get_increment() );
972                        expr->accept( *this );
973                } // if
974                output << ") ";
975
976                if ( forStmt->get_body() != 0 ) {
977                        output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
978                        forStmt->get_body()->accept( *this );
979                } // if
980        }
981
982        void CodeGenerator::visit( __attribute__((unused)) NullStmt * nullStmt ) {
983                //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
984                output << "/* null statement */ ;";
985        }
986
987        void CodeGenerator::visit( DeclStmt * declStmt ) {
988                declStmt->get_decl()->accept( *this );
989
990                if ( doSemicolon( declStmt->get_decl() ) ) {
991                        output << ";";
992                } // if
993        }
994
995        void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
996                if ( decl->get_storageClasses().any() ) {
997                        decl->get_storageClasses().print( output );
998                } // if
999        } // CodeGenerator::handleStorageClass
1000
1001        std::string genName( DeclarationWithType * decl ) {
1002                CodeGen::OperatorInfo opInfo;
1003                if ( operatorLookup( decl->get_name(), opInfo ) ) {
1004                        return opInfo.outputName;
1005                } else {
1006                        return decl->get_name();
1007                } // if
1008        }
1009} // namespace CodeGen
1010
1011// Local Variables: //
1012// tab-width: 4 //
1013// mode: c++ //
1014// compile-command: "make install" //
1015// End: //
Note: See TracBrowser for help on using the repository browser.