source: src/SymTab/Validate.cc @ ef3d798

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

Carry attributes through typedefs

  • Property mode set to 100644
File size: 43.0 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 28 13:47:23 2017
13// Update Count     : 359
14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21//   union.
22//
23// - All enumeration constants have type EnumInstType.
24//
25// - The type "void" never occurs in lists of function parameter or return types.  A function
26//   taking no arguments has no argument types.
27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29//   by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38//   definition occurs later in the input.
39
40#include "Validate.h"
41
42#include <cassert>                     // for assertf, assert
43#include <cstddef>                     // for size_t
44#include <list>                        // for list
45#include <string>                      // for string
46#include <utility>                     // for pair
47
48#include "CodeGen/CodeGenerator.h"     // for genName
49#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
50#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
51#include "Common/ScopedMap.h"          // for ScopedMap
52#include "Common/SemanticError.h"      // for SemanticError
53#include "Common/UniqueName.h"         // for UniqueName
54#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
55#include "Concurrency/Keywords.h"      // for applyKeywords
56#include "FixFunction.h"               // for FixFunction
57#include "Indexer.h"                   // for Indexer
58#include "InitTweak/GenInit.h"         // for fixReturnStatements
59#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
60#include "Parser/LinkageSpec.h"        // for C
61#include "ResolvExpr/typeops.h"        // for typesCompatible
62#include "SymTab/AddVisit.h"           // for addVisit
63#include "SymTab/Autogen.h"            // for SizeType
64#include "SynTree/Attribute.h"         // for noAttributes, Attribute
65#include "SynTree/Constant.h"          // for Constant
66#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
67#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
68#include "SynTree/Initializer.h"       // for ListInit, Initializer
69#include "SynTree/Label.h"             // for operator==, Label
70#include "SynTree/Mutator.h"           // for Mutator
71#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
72#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
73#include "SynTree/Visitor.h"           // for Visitor
74
75class CompoundStmt;
76class ReturnStmt;
77class SwitchStmt;
78
79
80#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
81
82namespace SymTab {
83        class HoistStruct final : public Visitor {
84                template< typename Visitor >
85                friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
86            template< typename Visitor >
87            friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
88          public:
89                /// Flattens nested struct types
90                static void hoistStruct( std::list< Declaration * > &translationUnit );
91
92                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
93
94                virtual void visit( EnumInstType *enumInstType );
95                virtual void visit( StructInstType *structInstType );
96                virtual void visit( UnionInstType *unionInstType );
97                virtual void visit( StructDecl *aggregateDecl );
98                virtual void visit( UnionDecl *aggregateDecl );
99
100                virtual void visit( CompoundStmt *compoundStmt );
101                virtual void visit( SwitchStmt *switchStmt );
102          private:
103                HoistStruct();
104
105                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
106
107                std::list< Declaration * > declsToAdd, declsToAddAfter;
108                bool inStruct;
109        };
110
111        /// Fix return types so that every function returns exactly one value
112        struct ReturnTypeFixer {
113                static void fix( std::list< Declaration * > &translationUnit );
114
115                void postvisit( FunctionDecl * functionDecl );
116                void postvisit( FunctionType * ftype );
117        };
118
119        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
120        struct EnumAndPointerDecay {
121                void previsit( EnumDecl *aggregateDecl );
122                void previsit( FunctionType *func );
123        };
124
125        /// Associates forward declarations of aggregates with their definitions
126        struct LinkReferenceToTypes final : public WithIndexer, public WithGuards {
127                LinkReferenceToTypes( const Indexer *indexer );
128                void postvisit( TypeInstType *typeInst );
129
130                void postvisit( EnumInstType *enumInst );
131                void postvisit( StructInstType *structInst );
132                void postvisit( UnionInstType *unionInst );
133                void postvisit( TraitInstType *traitInst );
134
135                void postvisit( EnumDecl *enumDecl );
136                void postvisit( StructDecl *structDecl );
137                void postvisit( UnionDecl *unionDecl );
138                void postvisit( TraitDecl * traitDecl );
139
140                void previsit( StructDecl *structDecl );
141                void previsit( UnionDecl *unionDecl );
142
143                void renameGenericParams( std::list< TypeDecl * > & params );
144
145          private:
146                const Indexer *local_indexer;
147
148                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
149                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
150                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
151                ForwardEnumsType forwardEnums;
152                ForwardStructsType forwardStructs;
153                ForwardUnionsType forwardUnions;
154                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
155                bool inGeneric = false;
156        };
157
158        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
159        struct ForallPointerDecay final {
160                void previsit( ObjectDecl * object );
161                void previsit( FunctionDecl * func );
162                void previsit( StructDecl * aggrDecl );
163                void previsit( UnionDecl * aggrDecl );
164        };
165
166        struct ReturnChecker : public WithGuards {
167                /// Checks that return statements return nothing if their return type is void
168                /// and return something if the return type is non-void.
169                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
170
171                void previsit( FunctionDecl * functionDecl );
172                void previsit( ReturnStmt * returnStmt );
173
174                typedef std::list< DeclarationWithType * > ReturnVals;
175                ReturnVals returnVals;
176        };
177
178        struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards {
179                EliminateTypedef() : scopeLevel( 0 ) {}
180                /// Replaces typedefs by forward declarations
181                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
182
183                Type * postmutate( TypeInstType * aggregateUseType );
184                Declaration * postmutate( TypedefDecl * typeDecl );
185                void premutate( TypeDecl * typeDecl );
186                void premutate( FunctionDecl * funcDecl );
187                void premutate( ObjectDecl * objDecl );
188                DeclarationWithType * postmutate( ObjectDecl * objDecl );
189
190                void premutate( CastExpr * castExpr );
191
192                void premutate( CompoundStmt * compoundStmt );
193                CompoundStmt * postmutate( CompoundStmt * compoundStmt );
194
195                void premutate( StructDecl * structDecl );
196                Declaration * postmutate( StructDecl * structDecl );
197                void premutate( UnionDecl * unionDecl );
198                Declaration * postmutate( UnionDecl * unionDecl );
199                void premutate( EnumDecl * enumDecl );
200                Declaration * postmutate( EnumDecl * enumDecl );
201                Declaration * postmutate( TraitDecl * contextDecl );
202
203                void premutate( FunctionType * ftype );
204
205          private:
206                template<typename AggDecl>
207                AggDecl *handleAggregate( AggDecl * aggDecl );
208
209                template<typename AggDecl>
210                void addImplicitTypedef( AggDecl * aggDecl );
211
212                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
213                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
214                typedef std::map< std::string, TypeDecl * > TypeDeclMap;
215                TypedefMap typedefNames;
216                TypeDeclMap typedeclNames;
217                int scopeLevel;
218                bool inFunctionType = false;
219        };
220
221        struct VerifyCtorDtorAssign {
222                /// ensure that constructors, destructors, and assignment have at least one
223                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
224                /// return values.
225                static void verify( std::list< Declaration * > &translationUnit );
226
227                void previsit( FunctionDecl *funcDecl );
228        };
229
230        /// ensure that generic types have the correct number of type arguments
231        struct ValidateGenericParameters {
232                void previsit( StructInstType * inst );
233                void previsit( UnionInstType * inst );
234        };
235
236        struct ArrayLength {
237                /// for array types without an explicit length, compute the length and store it so that it
238                /// is known to the rest of the phases. For example,
239                ///   int x[] = { 1, 2, 3 };
240                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
241                /// here x and y are known at compile-time to have length 3, so change this into
242                ///   int x[3] = { 1, 2, 3 };
243                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
244                static void computeLength( std::list< Declaration * > & translationUnit );
245
246                void previsit( ObjectDecl * objDecl );
247        };
248
249        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
250                Type::StorageClasses storageClasses;
251
252                void premutate( ObjectDecl *objectDecl );
253                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
254        };
255
256        struct LabelAddressFixer final : public WithGuards {
257                std::set< Label > labels;
258
259                void premutate( FunctionDecl * funcDecl );
260                Expression * postmutate( AddressExpr * addrExpr );
261        };
262
263        FunctionDecl * dereferenceOperator = nullptr;
264        struct FindSpecialDeclarations final {
265                void previsit( FunctionDecl * funcDecl );
266        };
267
268        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
269                PassVisitor<EnumAndPointerDecay> epc;
270                PassVisitor<LinkReferenceToTypes> lrt( nullptr );
271                PassVisitor<ForallPointerDecay> fpd;
272                PassVisitor<CompoundLiteral> compoundliteral;
273                PassVisitor<ValidateGenericParameters> genericParams;
274                PassVisitor<FindSpecialDeclarations> finder;
275                PassVisitor<LabelAddressFixer> labelAddrFixer;
276
277                EliminateTypedef::eliminateTypedef( translationUnit );
278                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
279                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
280                acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
281                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
282                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
283                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
284                ReturnChecker::checkFunctionReturns( translationUnit );
285                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
286                Concurrency::applyKeywords( translationUnit );
287                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
288                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
289                Concurrency::implementMutexFuncs( translationUnit );
290                Concurrency::implementThreadStarter( translationUnit );
291                mutateAll( translationUnit, compoundliteral );
292                ArrayLength::computeLength( translationUnit );
293                acceptAll( translationUnit, finder ); // xxx - remove this pass soon
294                mutateAll( translationUnit, labelAddrFixer );
295        }
296
297        void validateType( Type *type, const Indexer *indexer ) {
298                PassVisitor<EnumAndPointerDecay> epc;
299                PassVisitor<LinkReferenceToTypes> lrt( indexer );
300                PassVisitor<ForallPointerDecay> fpd;
301                type->accept( epc );
302                type->accept( lrt );
303                type->accept( fpd );
304        }
305
306        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
307                HoistStruct hoister;
308                acceptAndAdd( translationUnit, hoister );
309        }
310
311        HoistStruct::HoistStruct() : inStruct( false ) {
312        }
313
314        bool isStructOrUnion( Declaration *decl ) {
315                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
316        }
317
318        template< typename AggDecl >
319        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
320                if ( inStruct ) {
321                        // Add elements in stack order corresponding to nesting structure.
322                        declsToAdd.push_front( aggregateDecl );
323                        Visitor::visit( aggregateDecl );
324                } else {
325                        inStruct = true;
326                        Visitor::visit( aggregateDecl );
327                        inStruct = false;
328                } // if
329                // Always remove the hoisted aggregate from the inner structure.
330                filter( aggregateDecl->get_members(), isStructOrUnion, false );
331        }
332
333        void HoistStruct::visit( EnumInstType *structInstType ) {
334                if ( structInstType->get_baseEnum() ) {
335                        declsToAdd.push_front( structInstType->get_baseEnum() );
336                }
337        }
338
339        void HoistStruct::visit( StructInstType *structInstType ) {
340                if ( structInstType->get_baseStruct() ) {
341                        declsToAdd.push_front( structInstType->get_baseStruct() );
342                }
343        }
344
345        void HoistStruct::visit( UnionInstType *structInstType ) {
346                if ( structInstType->get_baseUnion() ) {
347                        declsToAdd.push_front( structInstType->get_baseUnion() );
348                }
349        }
350
351        void HoistStruct::visit( StructDecl *aggregateDecl ) {
352                handleAggregate( aggregateDecl );
353        }
354
355        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
356                handleAggregate( aggregateDecl );
357        }
358
359        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
360                addVisit( compoundStmt, *this );
361        }
362
363        void HoistStruct::visit( SwitchStmt *switchStmt ) {
364                addVisit( switchStmt, *this );
365        }
366
367        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
368                // Set the type of each member of the enumeration to be EnumConstant
369                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
370                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
371                        assert( obj );
372                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
373                } // for
374        }
375
376        namespace {
377                template< typename DWTList >
378                void fixFunctionList( DWTList & dwts, FunctionType * func ) {
379                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
380                        // entirely. other fix ups are handled by the FixFunction class
381                        typedef typename DWTList::iterator DWTIterator;
382                        DWTIterator begin( dwts.begin() ), end( dwts.end() );
383                        if ( begin == end ) return;
384                        PassVisitor<FixFunction> fixer;
385                        DWTIterator i = begin;
386                        *i = (*i)->acceptMutator( fixer );
387                        if ( fixer.pass.isVoid ) {
388                                DWTIterator j = i;
389                                ++i;
390                                delete *j;
391                                dwts.erase( j );
392                                if ( i != end ) {
393                                        throw SemanticError( "invalid type void in function type ", func );
394                                } // if
395                        } else {
396                                ++i;
397                                for ( ; i != end; ++i ) {
398                                        PassVisitor<FixFunction> fixer;
399                                        *i = (*i)->acceptMutator( fixer );
400                                        if ( fixer.pass.isVoid ) {
401                                                throw SemanticError( "invalid type void in function type ", func );
402                                        } // if
403                                } // for
404                        } // if
405                }
406        }
407
408        void EnumAndPointerDecay::previsit( FunctionType *func ) {
409                // Fix up parameters and return types
410                fixFunctionList( func->get_parameters(), func );
411                fixFunctionList( func->get_returnVals(), func );
412        }
413
414        LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
415                if ( other_indexer ) {
416                        local_indexer = other_indexer;
417                } else {
418                        local_indexer = &indexer;
419                } // if
420        }
421
422        void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
423                EnumDecl *st = local_indexer->lookupEnum( enumInst->get_name() );
424                // it's not a semantic error if the enum is not found, just an implicit forward declaration
425                if ( st ) {
426                        //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
427                        enumInst->set_baseEnum( st );
428                } // if
429                if ( ! st || st->get_members().empty() ) {
430                        // use of forward declaration
431                        forwardEnums[ enumInst->get_name() ].push_back( enumInst );
432                } // if
433        }
434
435        void checkGenericParameters( ReferenceToType * inst ) {
436                for ( Expression * param : inst->parameters ) {
437                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
438                                throw SemanticError( "Expression parameters for generic types are currently unsupported: ", inst );
439                        }
440                }
441        }
442
443        void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
444                StructDecl *st = local_indexer->lookupStruct( structInst->get_name() );
445                // it's not a semantic error if the struct is not found, just an implicit forward declaration
446                if ( st ) {
447                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
448                        structInst->set_baseStruct( st );
449                } // if
450                if ( ! st || st->get_members().empty() ) {
451                        // use of forward declaration
452                        forwardStructs[ structInst->get_name() ].push_back( structInst );
453                } // if
454                checkGenericParameters( structInst );
455        }
456
457        void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
458                UnionDecl *un = local_indexer->lookupUnion( unionInst->get_name() );
459                // it's not a semantic error if the union is not found, just an implicit forward declaration
460                if ( un ) {
461                        unionInst->set_baseUnion( un );
462                } // if
463                if ( ! un || un->get_members().empty() ) {
464                        // use of forward declaration
465                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
466                } // if
467                checkGenericParameters( unionInst );
468        }
469
470        template< typename Decl >
471        void normalizeAssertions( std::list< Decl * > & assertions ) {
472                // ensure no duplicate trait members after the clone
473                auto pred = [](Decl * d1, Decl * d2) {
474                        // only care if they're equal
475                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
476                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
477                        if ( dwt1 && dwt2 ) {
478                                if ( dwt1->get_name() == dwt2->get_name() && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
479                                        // std::cerr << "=========== equal:" << std::endl;
480                                        // std::cerr << "d1: " << d1 << std::endl;
481                                        // std::cerr << "d2: " << d2 << std::endl;
482                                        return false;
483                                }
484                        }
485                        return d1 < d2;
486                };
487                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
488                // if ( unique_members.size() != assertions.size() ) {
489                //      std::cerr << "============different" << std::endl;
490                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
491                // }
492
493                std::list< Decl * > order;
494                order.splice( order.end(), assertions );
495                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
496                        return unique_members.count( decl );
497                });
498        }
499
500        // expand assertions from trait instance, performing the appropriate type variable substitutions
501        template< typename Iterator >
502        void expandAssertions( TraitInstType * inst, Iterator out ) {
503                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toString( inst ).c_str() );
504                std::list< DeclarationWithType * > asserts;
505                for ( Declaration * decl : inst->baseTrait->members ) {
506                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
507                }
508                // substitute trait decl parameters for instance parameters
509                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
510        }
511
512        void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
513                if ( traitDecl->name == "sized" ) {
514                        // "sized" is a special trait - flick the sized status on for the type variable
515                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
516                        TypeDecl * td = traitDecl->parameters.front();
517                        td->set_sized( true );
518                }
519
520                // move assertions from type parameters into the body of the trait
521                for ( TypeDecl * td : traitDecl->parameters ) {
522                        for ( DeclarationWithType * assert : td->assertions ) {
523                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
524                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
525                                } else {
526                                        traitDecl->members.push_back( assert->clone() );
527                                }
528                        }
529                        deleteAll( td->assertions );
530                        td->assertions.clear();
531                } // for
532        }
533
534        void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
535                // handle other traits
536                TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
537                if ( ! traitDecl ) {
538                        throw SemanticError( "use of undeclared trait " + traitInst->name );
539                } // if
540                if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
541                        throw SemanticError( "incorrect number of trait parameters: ", traitInst );
542                } // if
543                traitInst->baseTrait = traitDecl;
544
545                // need to carry over the 'sized' status of each decl in the instance
546                for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
547                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
548                        if ( ! expr ) {
549                                throw SemanticError( "Expression parameters for trait instances are currently unsupported: ", std::get<1>(p) );
550                        }
551                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
552                                TypeDecl * formalDecl = std::get<0>(p);
553                                TypeDecl * instDecl = inst->get_baseType();
554                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
555                        }
556                }
557                // normalizeAssertions( traitInst->members );
558        }
559
560        void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
561                // visit enum members first so that the types of self-referencing members are updated properly
562                if ( ! enumDecl->get_members().empty() ) {
563                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
564                        if ( fwds != forwardEnums.end() ) {
565                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
566                                        (*inst )->set_baseEnum( enumDecl );
567                                } // for
568                                forwardEnums.erase( fwds );
569                        } // if
570                } // if
571        }
572
573        void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
574                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
575                //   forall(otype T)
576                //   struct Box {
577                //     T x;
578                //   };
579                //   forall(otype T)
580                //   void f(Box(T) b) {
581                //     ...
582                //   }
583                // The T in Box and the T in f are different, so internally the naming must reflect that.
584                GuardValue( inGeneric );
585                inGeneric = ! params.empty();
586                for ( TypeDecl * td : params ) {
587                        td->name = "__" + td->name + "_generic_";
588                }
589        }
590
591        void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
592                renameGenericParams( structDecl->parameters );
593        }
594
595        void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
596                renameGenericParams( unionDecl->parameters );
597        }
598
599        void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
600                // visit struct members first so that the types of self-referencing members are updated properly
601                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
602                if ( ! structDecl->get_members().empty() ) {
603                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
604                        if ( fwds != forwardStructs.end() ) {
605                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
606                                        (*inst )->set_baseStruct( structDecl );
607                                } // for
608                                forwardStructs.erase( fwds );
609                        } // if
610                } // if
611        }
612
613        void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
614                if ( ! unionDecl->get_members().empty() ) {
615                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
616                        if ( fwds != forwardUnions.end() ) {
617                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
618                                        (*inst )->set_baseUnion( unionDecl );
619                                } // for
620                                forwardUnions.erase( fwds );
621                        } // if
622                } // if
623        }
624
625        void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
626                // ensure generic parameter instances are renamed like the base type
627                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
628                if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->get_name() ) ) {
629                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
630                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
631                        } // if
632                } // if
633        }
634
635        /// Fix up assertions - flattens assertion lists, removing all trait instances
636        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
637                for ( TypeDecl * type : forall ) {
638                        std::list< DeclarationWithType * > asserts;
639                        asserts.splice( asserts.end(), type->assertions );
640                        // expand trait instances into their members
641                        for ( DeclarationWithType * assertion : asserts ) {
642                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
643                                        // expand trait instance into all of its members
644                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
645                                        delete traitInst;
646                                } else {
647                                        // pass other assertions through
648                                        type->assertions.push_back( assertion );
649                                } // if
650                        } // for
651                        // apply FixFunction to every assertion to check for invalid void type
652                        for ( DeclarationWithType *& assertion : type->assertions ) {
653                                PassVisitor<FixFunction> fixer;
654                                assertion = assertion->acceptMutator( fixer );
655                                if ( fixer.pass.isVoid ) {
656                                        throw SemanticError( "invalid type void in assertion of function ", node );
657                                } // if
658                        } // for
659                        // normalizeAssertions( type->assertions );
660                } // for
661        }
662
663        void ForallPointerDecay::previsit( ObjectDecl *object ) {
664                forallFixer( object->type->forall, object );
665                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->type ) ) {
666                        forallFixer( pointer->base->forall, object );
667                } // if
668                object->fixUniqueId();
669        }
670
671        void ForallPointerDecay::previsit( FunctionDecl *func ) {
672                forallFixer( func->type->forall, func );
673                func->fixUniqueId();
674        }
675
676        void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
677                forallFixer( aggrDecl->parameters, aggrDecl );
678        }
679
680        void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
681                forallFixer( aggrDecl->parameters, aggrDecl );
682        }
683
684        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
685                PassVisitor<ReturnChecker> checker;
686                acceptAll( translationUnit, checker );
687        }
688
689        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
690                GuardValue( returnVals );
691                returnVals = functionDecl->get_functionType()->get_returnVals();
692        }
693
694        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
695                // Previously this also checked for the existence of an expr paired with no return values on
696                // the  function return type. This is incorrect, since you can have an expression attached to
697                // a return statement in a void-returning function in C. The expression is treated as if it
698                // were cast to void.
699                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
700                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
701                }
702        }
703
704
705        bool isTypedef( Declaration *decl ) {
706                return dynamic_cast< TypedefDecl * >( decl );
707        }
708
709        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
710                PassVisitor<EliminateTypedef> eliminator;
711                mutateAll( translationUnit, eliminator );
712                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
713                        // grab and remember declaration of size_t
714                        SizeType = eliminator.pass.typedefNames["size_t"].first->get_base()->clone();
715                } else {
716                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
717                        // eventually should have a warning for this case.
718                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
719                }
720                filter( translationUnit, isTypedef, true );
721        }
722
723        Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) {
724                // instances of typedef types will come here. If it is an instance
725                // of a typdef type, link the instance to its actual type.
726                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
727                if ( def != typedefNames.end() ) {
728                        Type *ret = def->second.first->base->clone();
729                        ret->get_qualifiers() |= typeInst->get_qualifiers();
730                        // attributes are not carried over from typedef to function parameters/return values
731                        if ( ! inFunctionType ) {
732                                ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
733                        } else {
734                                deleteAll( ret->attributes );
735                                ret->attributes.clear();
736                        }
737                        // place instance parameters on the typedef'd type
738                        if ( ! typeInst->parameters.empty() ) {
739                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
740                                if ( ! rtt ) {
741                                        throw SemanticError("Cannot apply type parameters to base type of " + typeInst->name);
742                                }
743                                rtt->get_parameters().clear();
744                                cloneAll( typeInst->parameters, rtt->parameters );
745                                mutateAll( rtt->parameters, *visitor );  // recursively fix typedefs on parameters
746                        } // if
747                        delete typeInst;
748                        return ret;
749                } else {
750                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
751                        assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->name.c_str() );
752                        typeInst->set_baseType( base->second );
753                } // if
754                return typeInst;
755        }
756
757        struct VarLenChecker : WithShortCircuiting {
758                void previsit( FunctionType * ) { visit_children = false; }
759                void previsit( ArrayType * at ) {
760                        isVarLen |= at->isVarLen;
761                }
762                bool isVarLen = false;
763        };
764
765        bool isVariableLength( Type * t ) {
766                PassVisitor<VarLenChecker> varLenChecker;
767                maybeAccept( t, varLenChecker );
768                return varLenChecker.pass.isVarLen;
769        }
770
771        Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) {
772                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
773                        // typedef to the same name from the same scope
774                        // must be from the same type
775
776                        Type * t1 = tyDecl->get_base();
777                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
778                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
779                                throw SemanticError( "Cannot redefine typedef: " + tyDecl->name );
780                        }
781                        // cannot redefine VLA typedefs
782                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
783                                throw SemanticError( "Cannot redefine typedef: " + tyDecl->name );
784                        }
785                } else {
786                        typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
787                } // if
788
789                // When a typedef is a forward declaration:
790                //    typedef struct screen SCREEN;
791                // the declaration portion must be retained:
792                //    struct screen;
793                // because the expansion of the typedef is:
794                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
795                // hence the type-name "screen" must be defined.
796                // Note, qualifiers on the typedef are superfluous for the forward declaration.
797
798                Type *designatorType = tyDecl->get_base()->stripDeclarator();
799                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
800                        return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() );
801                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
802                        return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() );
803                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
804                        return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() );
805                } else {
806                        return tyDecl->clone();
807                } // if
808        }
809
810        void EliminateTypedef::premutate( TypeDecl * typeDecl ) {
811                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
812                if ( i != typedefNames.end() ) {
813                        typedefNames.erase( i ) ;
814                } // if
815
816                typedeclNames[ typeDecl->get_name() ] = typeDecl;
817        }
818
819        void EliminateTypedef::premutate( FunctionDecl * ) {
820                GuardScope( typedefNames );
821        }
822
823        void EliminateTypedef::premutate( ObjectDecl * ) {
824                GuardScope( typedefNames );
825        }
826
827        DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) {
828                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->get_type() ) ) { // function type?
829                        // replace the current object declaration with a function declaration
830                        FunctionDecl * newDecl = new FunctionDecl( objDecl->get_name(), objDecl->get_storageClasses(), objDecl->get_linkage(), funtype, 0, objDecl->get_attributes(), objDecl->get_funcSpec() );
831                        objDecl->get_attributes().clear();
832                        objDecl->set_type( nullptr );
833                        delete objDecl;
834                        return newDecl;
835                } // if
836                return objDecl;
837        }
838
839        void EliminateTypedef::premutate( CastExpr * ) {
840                GuardScope( typedefNames );
841        }
842
843        void EliminateTypedef::premutate( CompoundStmt * ) {
844                GuardScope( typedefNames );
845                scopeLevel += 1;
846                GuardAction( [this](){ scopeLevel -= 1; } );
847        }
848
849        CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) {
850                // remove and delete decl stmts
851                filter( compoundStmt->kids, [](Statement * stmt) {
852                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
853                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
854                                        return true;
855                                } // if
856                        } // if
857                        return false;
858                }, true);
859                return compoundStmt;
860        }
861
862        // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
863        // as well
864        template<typename AggDecl>
865        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
866                filter( aggDecl->members, isTypedef, true );
867                return aggDecl;
868        }
869
870        template<typename AggDecl>
871        void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
872                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
873                        Type *type = nullptr;
874                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
875                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
876                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
877                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
878                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
879                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
880                        } // if
881                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), Type::StorageClasses(), type, aggDecl->get_linkage() ) );
882                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
883                } // if
884        }
885
886        void EliminateTypedef::premutate( StructDecl * structDecl ) {
887                addImplicitTypedef( structDecl );
888        }
889
890
891        Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) {
892                return handleAggregate( structDecl );
893        }
894
895        void EliminateTypedef::premutate( UnionDecl * unionDecl ) {
896                addImplicitTypedef( unionDecl );
897        }
898
899        Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) {
900                return handleAggregate( unionDecl );
901        }
902
903        void EliminateTypedef::premutate( EnumDecl * enumDecl ) {
904                addImplicitTypedef( enumDecl );
905        }
906
907        Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) {
908                return handleAggregate( enumDecl );
909        }
910
911        Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) {
912                return handleAggregate( traitDecl );
913        }
914
915        void EliminateTypedef::premutate( FunctionType * ) {
916                GuardValue( inFunctionType );
917                inFunctionType = true;
918        }
919
920        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
921                PassVisitor<VerifyCtorDtorAssign> verifier;
922                acceptAll( translationUnit, verifier );
923        }
924
925        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
926                FunctionType * funcType = funcDecl->get_functionType();
927                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
928                std::list< DeclarationWithType * > &params = funcType->get_parameters();
929
930                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
931                        if ( params.size() == 0 ) {
932                                throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
933                        }
934                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
935                        if ( ! refType ) {
936                                throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a reference ", funcDecl );
937                        }
938                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
939                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
940                        }
941                }
942        }
943
944        template< typename Aggr >
945        void validateGeneric( Aggr * inst ) {
946                std::list< TypeDecl * > * params = inst->get_baseParameters();
947                if ( params ) {
948                        std::list< Expression * > & args = inst->get_parameters();
949
950                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
951                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
952                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
953                        //   vector(int) v;
954                        // after insertion of default values becomes
955                        //   vector(int, heap_allocator(T))
956                        // and the substitution is built with T=int so that after substitution, the result is
957                        //   vector(int, heap_allocator(int))
958                        TypeSubstitution sub;
959                        auto paramIter = params->begin();
960                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
961                                if ( i < args.size() ) {
962                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
963                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
964                                } else if ( i == args.size() ) {
965                                        Type * defaultType = (*paramIter)->get_init();
966                                        if ( defaultType ) {
967                                                args.push_back( new TypeExpr( defaultType->clone() ) );
968                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
969                                        }
970                                }
971                        }
972
973                        sub.apply( inst );
974                        if ( args.size() < params->size() ) throw SemanticError( "Too few type arguments in generic type ", inst );
975                        if ( args.size() > params->size() ) throw SemanticError( "Too many type arguments in generic type ", inst );
976                }
977        }
978
979        void ValidateGenericParameters::previsit( StructInstType * inst ) {
980                validateGeneric( inst );
981        }
982
983        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
984                validateGeneric( inst );
985        }
986
987        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
988                storageClasses = objectDecl->get_storageClasses();
989        }
990
991        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
992                // transform [storage_class] ... (struct S){ 3, ... };
993                // into [storage_class] struct S temp =  { 3, ... };
994                static UniqueName indexName( "_compLit" );
995
996                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
997                compLitExpr->set_result( nullptr );
998                compLitExpr->set_initializer( nullptr );
999                delete compLitExpr;
1000                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1001                return new VariableExpr( tempvar );
1002        }
1003
1004        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1005                PassVisitor<ReturnTypeFixer> fixer;
1006                acceptAll( translationUnit, fixer );
1007        }
1008
1009        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1010                FunctionType * ftype = functionDecl->get_functionType();
1011                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1012                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1013                if ( retVals.size() == 1 ) {
1014                        // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging).
1015                        // ensure other return values have a name.
1016                        DeclarationWithType * ret = retVals.front();
1017                        if ( ret->get_name() == "" ) {
1018                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1019                        }
1020                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1021                }
1022        }
1023
1024        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1025                // xxx - need to handle named return values - this information needs to be saved somehow
1026                // so that resolution has access to the names.
1027                // Note that this pass needs to happen early so that other passes which look for tuple types
1028                // find them in all of the right places, including function return types.
1029                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1030                if ( retVals.size() > 1 ) {
1031                        // generate a single return parameter which is the tuple of all of the return values
1032                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1033                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1034                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
1035                        deleteAll( retVals );
1036                        retVals.clear();
1037                        retVals.push_back( newRet );
1038                }
1039        }
1040
1041        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1042                PassVisitor<ArrayLength> len;
1043                acceptAll( translationUnit, len );
1044        }
1045
1046        void ArrayLength::previsit( ObjectDecl * objDecl ) {
1047                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
1048                        if ( at->get_dimension() ) return;
1049                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
1050                                at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
1051                        }
1052                }
1053        }
1054
1055        struct LabelFinder {
1056                std::set< Label > & labels;
1057                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1058                void previsit( Statement * stmt ) {
1059                        for ( Label & l : stmt->labels ) {
1060                                labels.insert( l );
1061                        }
1062                }
1063        };
1064
1065        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1066                GuardValue( labels );
1067                PassVisitor<LabelFinder> finder( labels );
1068                funcDecl->accept( finder );
1069        }
1070
1071        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1072                // convert &&label into label address
1073                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1074                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1075                                if ( labels.count( nameExpr->name ) ) {
1076                                        Label name = nameExpr->name;
1077                                        delete addrExpr;
1078                                        return new LabelAddressExpr( name );
1079                                }
1080                        }
1081                }
1082                return addrExpr;
1083        }
1084
1085        void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1086                if ( ! dereferenceOperator ) {
1087                        if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1088                                FunctionType * ftype = funcDecl->get_functionType();
1089                                if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1090                                        dereferenceOperator = funcDecl;
1091                                }
1092                        }
1093                }
1094        }
1095} // namespace SymTab
1096
1097// Local Variables: //
1098// tab-width: 4 //
1099// mode: c++ //
1100// compile-command: "make install" //
1101// End: //
Note: See TracBrowser for help on using the repository browser.