source: src/SymTab/Validate.cc @ 1486116

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

fix function return type in Validate and add single return decl, construct the return decl, fix polymorphic functions to use the return decl

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