source: src/CodeGen/CodeGenerator.cc @ e4d829b

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 e4d829b was e4d829b, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

major effort on designations, works in many cases

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