source: src/CodeGen/CodeGenerator.cc @ fcd17b2f

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 fcd17b2f was a5f0529, checked in by Andrew Beach <ajbeach@…>, 7 years ago

Virtual casts have been added. They still require a lot of hand coded support to work but for simple cases it should be enough.

  • Property mode set to 100644
File size: 31.8 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 : Tus Jul 25 15:29:00 2017
13// Update Count     : 486
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/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( VirtualCastExpr * castExpr ) {
597                assertf( ! genC, "VirtualCastExpr should not reach code generation." );
598                extension( castExpr );
599                output << "(virtual ";
600                castExpr->get_arg()->accept( *this );
601                output << ")";
602        }
603
604        void CodeGenerator::visit( UntypedMemberExpr * memberExpr ) {
605                assertf( ! genC, "UntypedMemberExpr should not reach code generation." );
606                extension( memberExpr );
607                memberExpr->get_aggregate()->accept( *this );
608                output << ".";
609                memberExpr->get_member()->accept( *this );
610        }
611
612        void CodeGenerator::visit( MemberExpr * memberExpr ) {
613                extension( memberExpr );
614                memberExpr->get_aggregate()->accept( *this );
615                output << "." << mangleName( memberExpr->get_member() );
616        }
617
618        void CodeGenerator::visit( VariableExpr * variableExpr ) {
619                extension( variableExpr );
620                OperatorInfo opInfo;
621                if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( variableExpr->get_var()->get_name(), opInfo ) && opInfo.type == OT_CONSTANT ) {
622                        output << opInfo.symbol;
623                } else {
624                        output << mangleName( variableExpr->get_var() );
625                } // if
626        }
627
628        void CodeGenerator::visit( ConstantExpr * constantExpr ) {
629                assert( constantExpr->get_constant() );
630                extension( constantExpr );
631                constantExpr->get_constant()->accept( *this );
632        }
633
634        void CodeGenerator::visit( SizeofExpr * sizeofExpr ) {
635                extension( sizeofExpr );
636                output << "sizeof(";
637                if ( sizeofExpr->get_isType() ) {
638                        output << genType( sizeofExpr->get_type(), "", pretty, genC );
639                } else {
640                        sizeofExpr->get_expr()->accept( *this );
641                } // if
642                output << ")";
643        }
644
645        void CodeGenerator::visit( AlignofExpr * alignofExpr ) {
646                // use GCC extension to avoid bumping std to C11
647                extension( alignofExpr );
648                output << "__alignof__(";
649                if ( alignofExpr->get_isType() ) {
650                        output << genType( alignofExpr->get_type(), "", pretty, genC );
651                } else {
652                        alignofExpr->get_expr()->accept( *this );
653                } // if
654                output << ")";
655        }
656
657        void CodeGenerator::visit( UntypedOffsetofExpr * offsetofExpr ) {
658                assertf( ! genC, "UntypedOffsetofExpr should not reach code generation." );
659                output << "offsetof(";
660                output << genType( offsetofExpr->get_type(), "", pretty, genC );
661                output << ", " << offsetofExpr->get_member();
662                output << ")";
663        }
664
665        void CodeGenerator::visit( OffsetofExpr * offsetofExpr ) {
666                // use GCC builtin
667                output << "__builtin_offsetof(";
668                output << genType( offsetofExpr->get_type(), "", pretty, genC );
669                output << ", " << mangleName( offsetofExpr->get_member() );
670                output << ")";
671        }
672
673        void CodeGenerator::visit( OffsetPackExpr * offsetPackExpr ) {
674                assertf( ! genC, "OffsetPackExpr should not reach code generation." );
675                output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", pretty, genC ) << ")";
676        }
677
678        void CodeGenerator::visit( LogicalExpr * logicalExpr ) {
679                extension( logicalExpr );
680                output << "(";
681                logicalExpr->get_arg1()->accept( *this );
682                if ( logicalExpr->get_isAnd() ) {
683                        output << " && ";
684                } else {
685                        output << " || ";
686                } // if
687                logicalExpr->get_arg2()->accept( *this );
688                output << ")";
689        }
690
691        void CodeGenerator::visit( ConditionalExpr * conditionalExpr ) {
692                extension( conditionalExpr );
693                output << "(";
694                conditionalExpr->get_arg1()->accept( *this );
695                output << " ? ";
696                conditionalExpr->get_arg2()->accept( *this );
697                output << " : ";
698                conditionalExpr->get_arg3()->accept( *this );
699                output << ")";
700        }
701
702        void CodeGenerator::visit( CommaExpr * commaExpr ) {
703                extension( commaExpr );
704                output << "(";
705                commaExpr->get_arg1()->accept( *this );
706                output << " , ";
707                commaExpr->get_arg2()->accept( *this );
708                output << ")";
709        }
710
711        void CodeGenerator::visit( UntypedTupleExpr * tupleExpr ) {
712                assertf( ! genC, "UntypedTupleExpr 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( TupleExpr * tupleExpr ) {
720                assertf( ! genC, "TupleExpr should not reach code generation." );
721                extension( tupleExpr );
722                output << "[";
723                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
724                output << "]";
725        }
726
727        void CodeGenerator::visit( TupleIndexExpr * tupleExpr ) {
728                assertf( ! genC, "TupleIndexExpr should not reach code generation." );
729                extension( tupleExpr );
730                tupleExpr->get_tuple()->accept( *this );
731                output << "." << tupleExpr->get_index();
732        }
733
734        void CodeGenerator::visit( TypeExpr * typeExpr ) {
735                // if ( genC ) std::cerr << "typeexpr still exists: " << typeExpr << std::endl;
736                // assertf( ! genC, "TypeExpr should not reach code generation." );
737                if ( ! genC ) {
738                        output<< genType( typeExpr->get_type(), "", pretty, genC );
739                }
740        }
741
742        void CodeGenerator::visit( AsmExpr * asmExpr ) {
743                if ( asmExpr->get_inout() ) {
744                        output << "[ ";
745                        asmExpr->get_inout()->accept( *this );
746                        output << " ] ";
747                } // if
748                asmExpr->get_constraint()->accept( *this );
749                output << " ( ";
750                asmExpr->get_operand()->accept( *this );
751                output << " )";
752        }
753
754        void CodeGenerator::visit( CompoundLiteralExpr *compLitExpr ) {
755                assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
756                output << "(" << genType( compLitExpr->get_result(), "", pretty, genC ) << ")";
757                compLitExpr->get_initializer()->accept( *this );
758        }
759
760        void CodeGenerator::visit( StmtExpr * stmtExpr ) {
761                std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
762                output << lineDirective( stmtExpr) << "({" << std::endl;
763                cur_indent += CodeGenerator::tabsize;
764                unsigned int numStmts = stmts.size();
765                unsigned int i = 0;
766                for ( Statement * stmt : stmts ) {
767                        output << lineDirective( stmt ) << indent;
768            output << printLabels( stmt->get_labels() );
769                        if ( i+1 == numStmts ) {
770                                // last statement in a statement expression needs to be handled specially -
771                                // cannot cast to void, otherwise the expression statement has no value
772                                if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
773                                        exprStmt->get_expr()->accept( *this );
774                                        output << ";" << endl;
775                                        ++i;
776                                        break;
777                                }
778                        }
779                        stmt->accept( *this );
780                        output << endl;
781                        if ( wantSpacing( stmt ) ) {
782                                output << endl;
783                        } // if
784                        ++i;
785                }
786                cur_indent -= CodeGenerator::tabsize;
787                output << indent << "})";
788        }
789
790        // *** Statements
791        void CodeGenerator::visit( CompoundStmt * compoundStmt ) {
792                std::list<Statement*> ks = compoundStmt->get_kids();
793                output << "{" << endl;
794
795                cur_indent += CodeGenerator::tabsize;
796
797                for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end();  i++ ) {
798                        output << indent << printLabels( (*i)->get_labels() );
799                        (*i)->accept( *this );
800
801                        output << endl;
802                        if ( wantSpacing( *i ) ) {
803                                output << endl;
804                        } // if
805                } // for
806                cur_indent -= CodeGenerator::tabsize;
807
808                output << indent << "}";
809        }
810
811        void CodeGenerator::visit( ExprStmt * exprStmt ) {
812                assert( exprStmt );
813                Expression * expr = exprStmt->get_expr();
814                if ( genC ) {
815                        // cast the top-level expression to void to reduce gcc warnings.
816                        expr = new CastExpr( expr );
817                }
818                expr->accept( *this );
819                output << ";";
820        }
821
822        void CodeGenerator::visit( AsmStmt * asmStmt ) {
823                output << "asm ";
824                if ( asmStmt->get_voltile() ) output << "volatile ";
825                if ( ! asmStmt->get_gotolabels().empty()  ) output << "goto ";
826                output << "( ";
827                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
828                output << " : ";
829                genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
830                output << " : ";
831                genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
832                output << " : ";
833                genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
834                if ( ! asmStmt->get_gotolabels().empty() ) {
835                        output << " : ";
836                        for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
837                                output << *begin++;
838                                if ( begin == asmStmt->get_gotolabels().end() ) break;
839                                output << ", ";
840                        } // for
841                } // if
842                output << " );" ;
843        }
844
845        void CodeGenerator::visit( AsmDecl * asmDecl ) {
846                output << "asm ";
847                AsmStmt * asmStmt = asmDecl->get_stmt();
848                output << "( ";
849                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
850                output << " )" ;
851        }
852
853        void CodeGenerator::visit( IfStmt * ifStmt ) {
854                output << lineDirective( ifStmt );
855                output << "if ( ";
856                ifStmt->get_condition()->accept( *this );
857                output << " ) ";
858
859                ifStmt->get_thenPart()->accept( *this );
860
861                if ( ifStmt->get_elsePart() != 0) {
862                        output << " else ";
863                        ifStmt->get_elsePart()->accept( *this );
864                } // if
865        }
866
867        void CodeGenerator::visit( SwitchStmt * switchStmt ) {
868                output << lineDirective( switchStmt );
869                output << "switch ( " ;
870                switchStmt->get_condition()->accept( *this );
871                output << " ) ";
872
873                output << "{" << std::endl;
874                cur_indent += CodeGenerator::tabsize;
875                acceptAll( switchStmt->get_statements(), *this );
876                cur_indent -= CodeGenerator::tabsize;
877                output << indent << "}";
878        }
879
880        void CodeGenerator::visit( CaseStmt * caseStmt ) {
881                output << lineDirective( caseStmt );
882                output << indent;
883                if ( caseStmt->isDefault()) {
884                        output << "default";
885                } else {
886                        output << "case ";
887                        caseStmt->get_condition()->accept( *this );
888                } // if
889                output << ":\n";
890
891                std::list<Statement *> sts = caseStmt->get_statements();
892
893                cur_indent += CodeGenerator::tabsize;
894                for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end();  i++) {
895                        output << indent << printLabels( (*i)->get_labels() )  ;
896                        (*i)->accept( *this );
897                        output << endl;
898                } // for
899                cur_indent -= CodeGenerator::tabsize;
900        }
901
902        void CodeGenerator::visit( BranchStmt * branchStmt ) {
903                switch ( branchStmt->get_type()) {
904                  case BranchStmt::Goto:
905                        if ( ! branchStmt->get_target().empty() )
906                                output << "goto " << branchStmt->get_target();
907                        else {
908                                if ( branchStmt->get_computedTarget() != 0 ) {
909                                        output << "goto *";
910                                        branchStmt->get_computedTarget()->accept( *this );
911                                } // if
912                        } // if
913                        break;
914                  case BranchStmt::Break:
915                        output << "break";
916                        break;
917                  case BranchStmt::Continue:
918                        output << "continue";
919                        break;
920                } // switch
921                output << ";";
922        }
923
924        void CodeGenerator::visit( ReturnStmt * returnStmt ) {
925                output << "return ";
926                maybeAccept( returnStmt->get_expr(), *this );
927                output << ";";
928        }
929
930        void CodeGenerator::visit( ThrowStmt * throwStmt ) {
931                assertf( ! genC, "Throw statements should not reach code generation." );
932
933                output << ((throwStmt->get_kind() == ThrowStmt::Terminate) ?
934                           "throw" : "throwResume");
935                if (throwStmt->get_expr()) {
936                        output << " ";
937                        throwStmt->get_expr()->accept( *this );
938                }
939                if (throwStmt->get_target()) {
940                        output << " _At ";
941                        throwStmt->get_target()->accept( *this );
942                }
943                output << ";";
944        }
945
946        void CodeGenerator::visit( WhileStmt * whileStmt ) {
947                if ( whileStmt->get_isDoWhile() ) {
948                        output << "do" ;
949                } else {
950                        output << "while (" ;
951                        whileStmt->get_condition()->accept( *this );
952                        output << ")";
953                } // if
954                output << " ";
955
956                output << CodeGenerator::printLabels( whileStmt->get_body()->get_labels() );
957                whileStmt->get_body()->accept( *this );
958
959                output << indent;
960
961                if ( whileStmt->get_isDoWhile() ) {
962                        output << " while (" ;
963                        whileStmt->get_condition()->accept( *this );
964                        output << ");";
965                } // if
966        }
967
968        void CodeGenerator::visit( ForStmt * forStmt ) {
969                // initialization is always hoisted, so don't bother doing anything with that
970                output << "for (;";
971
972                if ( forStmt->get_condition() != 0 ) {
973                        forStmt->get_condition()->accept( *this );
974                } // if
975                output << ";";
976
977                if ( forStmt->get_increment() != 0 ) {
978                        // cast the top-level expression to void to reduce gcc warnings.
979                        Expression * expr = new CastExpr( forStmt->get_increment() );
980                        expr->accept( *this );
981                } // if
982                output << ") ";
983
984                if ( forStmt->get_body() != 0 ) {
985                        output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
986                        forStmt->get_body()->accept( *this );
987                } // if
988        }
989
990        void CodeGenerator::visit( __attribute__((unused)) NullStmt * nullStmt ) {
991                //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
992                output << "/* null statement */ ;";
993        }
994
995        void CodeGenerator::visit( DeclStmt * declStmt ) {
996                declStmt->get_decl()->accept( *this );
997
998                if ( doSemicolon( declStmt->get_decl() ) ) {
999                        output << ";";
1000                } // if
1001        }
1002
1003        void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
1004                if ( decl->get_storageClasses().any() ) {
1005                        decl->get_storageClasses().print( output );
1006                } // if
1007        } // CodeGenerator::handleStorageClass
1008
1009        std::string genName( DeclarationWithType * decl ) {
1010                CodeGen::OperatorInfo opInfo;
1011                if ( operatorLookup( decl->get_name(), opInfo ) ) {
1012                        return opInfo.outputName;
1013                } else {
1014                        return decl->get_name();
1015                } // if
1016        }
1017} // namespace CodeGen
1018
1019// Local Variables: //
1020// tab-width: 4 //
1021// mode: c++ //
1022// compile-command: "make install" //
1023// End: //
Note: See TracBrowser for help on using the repository browser.