source: src/SymTab/Validate.cc @ d24d4e1

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

convert more passes to PassVisitor?, fix PassVisitor? constructor bug, add WithDeclsToAdd? parent class

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