source: src/SymTab/Validate.cc @ f621a148

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

compute and store array length when missing and known at compile-time

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