source: src/SymTab/Validate.cc @ 29f9e20

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 29f9e20 was 29f9e20, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Reorganize validate passes and reduce scope of HoistStruct? pass

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