source: src/SymTab/Validate.cc @ 1dcd9554

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

Fix PassVisitor? Indexer calls, aggregate top-level errors in PassVisitor?, convert ForallPointerDecay? and LinkReferenceToTypes? to PassVisitor?

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