source: src/SymTab/Validate.cc @ a172972

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since a172972 was a172972, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Merge branch 'master' into ctor

Conflicts:

src/ResolvExpr/Resolver.cc

  • Property mode set to 100644
File size: 49.1 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
[f066321]11// Last Modified By : Rob Schluntz
[7528ba1]12// Last Modified On : Mon Feb 22 12:26:37 2016
13// Update Count     : 297
[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//
25// - The type "void" never occurs in lists of function parameter or return types; neither do tuple types.  A function
26//   taking no arguments has no argument types, and tuples are flattened.
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>
42#include "Validate.h"
43#include "SynTree/Visitor.h"
44#include "SynTree/Mutator.h"
45#include "SynTree/Type.h"
46#include "SynTree/Statement.h"
47#include "SynTree/TypeSubstitution.h"
[68cd1ce]48#include "Indexer.h"
[51b7345]49#include "FixFunction.h"
[cc79d97]50// #include "ImplementationType.h"
[d3b7937]51#include "Common/utility.h"
52#include "Common/UniqueName.h"
[51b7345]53#include "AddVisit.h"
[f6d7e0f]54#include "MakeLibCfa.h"
[cc79d97]55#include "TypeEquality.h"
[1cbca6e]56#include "ResolvExpr/typeops.h"
[51b7345]57
[c8ffe20b]58#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
[51b7345]59
60namespace SymTab {
[a08ba92]61        class HoistStruct : public Visitor {
62          public:
[82dd287]63                /// Flattens nested struct types
[0dd3a2f]64                static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]65
[0dd3a2f]66                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
[9cb8e88d]67
[0dd3a2f]68                virtual void visit( StructDecl *aggregateDecl );
69                virtual void visit( UnionDecl *aggregateDecl );
[c8ffe20b]70
[0dd3a2f]71                virtual void visit( CompoundStmt *compoundStmt );
72                virtual void visit( IfStmt *ifStmt );
73                virtual void visit( WhileStmt *whileStmt );
74                virtual void visit( ForStmt *forStmt );
75                virtual void visit( SwitchStmt *switchStmt );
76                virtual void visit( ChooseStmt *chooseStmt );
77                virtual void visit( CaseStmt *caseStmt );
78                virtual void visit( CatchStmt *catchStmt );
[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
[de91427b]88        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
[a08ba92]89        class Pass1 : public Visitor {
[0dd3a2f]90                typedef Visitor Parent;
91                virtual void visit( EnumDecl *aggregateDecl );
92                virtual void visit( FunctionType *func );
[a08ba92]93        };
[82dd287]94
95        /// Associates forward declarations of aggregates with their definitions
[a08ba92]96        class Pass2 : public Indexer {
[0dd3a2f]97                typedef Indexer Parent;
[a08ba92]98          public:
[0dd3a2f]99                Pass2( bool doDebug, const Indexer *indexer );
[a08ba92]100          private:
[0dd3a2f]101                virtual void visit( StructInstType *structInst );
102                virtual void visit( UnionInstType *unionInst );
103                virtual void visit( ContextInstType *contextInst );
104                virtual void visit( StructDecl *structDecl );
105                virtual void visit( UnionDecl *unionDecl );
106                virtual void visit( TypeInstType *typeInst );
107
108                const Indexer *indexer;
[9cb8e88d]109
[0dd3a2f]110                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
111                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
112                ForwardStructsType forwardStructs;
113                ForwardUnionsType forwardUnions;
[a08ba92]114        };
[c8ffe20b]115
[82dd287]116        /// Replaces array and function types in forall lists by appropriate pointer type
[a08ba92]117        class Pass3 : public Indexer {
[0dd3a2f]118                typedef Indexer Parent;
[a08ba92]119          public:
[0dd3a2f]120                Pass3( const Indexer *indexer );
[a08ba92]121          private:
[0dd3a2f]122                virtual void visit( ObjectDecl *object );
123                virtual void visit( FunctionDecl *func );
[c8ffe20b]124
[0dd3a2f]125                const Indexer *indexer;
[a08ba92]126        };
[c8ffe20b]127
[f066321]128        class AutogenerateRoutines : public Visitor {
[a08ba92]129          public:
[82dd287]130                /// Generates assignment operators for aggregate types as required
[f066321]131                static void autogenerateRoutines( std::list< Declaration * > &translationUnit );
[c8ffe20b]132
[0dd3a2f]133                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
[9cb8e88d]134
[28a8cf9]135                virtual void visit( EnumDecl *enumDecl );
[0dd3a2f]136                virtual void visit( StructDecl *structDecl );
137                virtual void visit( UnionDecl *structDecl );
138                virtual void visit( TypeDecl *typeDecl );
139                virtual void visit( ContextDecl *ctxDecl );
140                virtual void visit( FunctionDecl *functionDecl );
[c8ffe20b]141
[0dd3a2f]142                virtual void visit( FunctionType *ftype );
143                virtual void visit( PointerType *ftype );
[9cb8e88d]144
[0dd3a2f]145                virtual void visit( CompoundStmt *compoundStmt );
146                virtual void visit( IfStmt *ifStmt );
147                virtual void visit( WhileStmt *whileStmt );
148                virtual void visit( ForStmt *forStmt );
149                virtual void visit( SwitchStmt *switchStmt );
150                virtual void visit( ChooseStmt *chooseStmt );
151                virtual void visit( CaseStmt *caseStmt );
152                virtual void visit( CatchStmt *catchStmt );
[3c70d38]153
[f066321]154                AutogenerateRoutines() : functionNesting( 0 ) {}
[a08ba92]155          private:
[0dd3a2f]156                template< typename StmtClass > void visitStatement( StmtClass *stmt );
[9cb8e88d]157
[0dd3a2f]158                std::list< Declaration * > declsToAdd;
159                std::set< std::string > structsDone;
160                unsigned int functionNesting;                   // current level of nested functions
[a08ba92]161        };
[c8ffe20b]162
[de91427b]163        class ReturnChecker : public Visitor {
164          public:
165                /// Checks that return statements return nothing if their return type is void
166                /// and return something if the return type is non-void.
167                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
168
169          private:
170                virtual void visit( FunctionDecl * functionDecl );
171
172                virtual void visit( ReturnStmt * returnStmt );
173
174                std::list< DeclarationWithType * > returnVals;
175        };
176
[a08ba92]177        class EliminateTypedef : public Mutator {
178          public:
[de91427b]179                EliminateTypedef() : scopeLevel( 0 ) {}
180                /// Replaces typedefs by forward declarations
[0dd3a2f]181                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
[a08ba92]182          private:
[0dd3a2f]183                virtual Declaration *mutate( TypedefDecl *typeDecl );
184                virtual TypeDecl *mutate( TypeDecl *typeDecl );
185                virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
[1db21619]186                virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
[0dd3a2f]187                virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
188                virtual Type *mutate( TypeInstType *aggregateUseType );
189                virtual Expression *mutate( CastExpr *castExpr );
[cc79d97]190
[85c4ef0]191                virtual Declaration *mutate( StructDecl * structDecl );
192                virtual Declaration *mutate( UnionDecl * unionDecl );
193                virtual Declaration *mutate( EnumDecl * enumDecl );
194                virtual Declaration *mutate( ContextDecl * contextDecl );
195
196                template<typename AggDecl>
197                AggDecl *handleAggregate( AggDecl * aggDecl );
198
[cc79d97]199                typedef std::map< std::string, std::pair< TypedefDecl *, int > > TypedefMap;
200                TypedefMap typedefNames;
201                int scopeLevel;
[a08ba92]202        };
[c8ffe20b]203
[9cb8e88d]204        class VerifyCtorDtor : public Visitor {
205        public:
206                /// ensure that constructors and destructors have at least one
207                /// parameter, the first of which must be a pointer, and no
208                /// return values.
209                static void verify( std::list< Declaration * > &translationUnit );
210
211                // VerifyCtorDtor() {}
212
213                virtual void visit( FunctionDecl *funcDecl );
214        private:
215        };
216
[a08ba92]217        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
[0dd3a2f]218                Pass1 pass1;
219                Pass2 pass2( doDebug, 0 );
220                Pass3 pass3( 0 );
221                EliminateTypedef::eliminateTypedef( translationUnit );
222                HoistStruct::hoistStruct( translationUnit );
223                acceptAll( translationUnit, pass1 );
224                acceptAll( translationUnit, pass2 );
[de91427b]225                ReturnChecker::checkFunctionReturns( translationUnit );
[f066321]226                AutogenerateRoutines::autogenerateRoutines( translationUnit );
[0dd3a2f]227                acceptAll( translationUnit, pass3 );
[9cb8e88d]228                VerifyCtorDtor::verify( translationUnit );
[a08ba92]229        }
[9cb8e88d]230
[a08ba92]231        void validateType( Type *type, const Indexer *indexer ) {
[0dd3a2f]232                Pass1 pass1;
233                Pass2 pass2( false, indexer );
234                Pass3 pass3( indexer );
235                type->accept( pass1 );
236                type->accept( pass2 );
237                type->accept( pass3 );
[a08ba92]238        }
[c8ffe20b]239
[a08ba92]240        template< typename Visitor >
241        void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor, bool addBefore ) {
[0dd3a2f]242                std::list< Declaration * >::iterator i = translationUnit.begin();
243                while ( i != translationUnit.end() ) {
244                        (*i)->accept( visitor );
245                        std::list< Declaration * >::iterator next = i;
246                        next++;
247                        if ( ! visitor.get_declsToAdd().empty() ) {
248                                translationUnit.splice( addBefore ? i : next, visitor.get_declsToAdd() );
249                        } // if
250                        i = next;
251                } // while
[a08ba92]252        }
[c8ffe20b]253
[a08ba92]254        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]255                HoistStruct hoister;
256                acceptAndAdd( translationUnit, hoister, true );
[a08ba92]257        }
[c8ffe20b]258
[a08ba92]259        HoistStruct::HoistStruct() : inStruct( false ) {
260        }
[c8ffe20b]261
[a08ba92]262        void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
[0dd3a2f]263                std::list< Declaration * >::iterator i = declList.begin();
264                while ( i != declList.end() ) {
265                        std::list< Declaration * >::iterator next = i;
266                        ++next;
267                        if ( pred( *i ) ) {
268                                if ( doDelete ) {
269                                        delete *i;
270                                } // if
271                                declList.erase( i );
272                        } // if
273                        i = next;
274                } // while
[a08ba92]275        }
[c8ffe20b]276
[a08ba92]277        bool isStructOrUnion( Declaration *decl ) {
[0dd3a2f]278                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
[a08ba92]279        }
[51b7345]280
[a08ba92]281        template< typename AggDecl >
282        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[0dd3a2f]283                if ( inStruct ) {
284                        // Add elements in stack order corresponding to nesting structure.
285                        declsToAdd.push_front( aggregateDecl );
286                        Visitor::visit( aggregateDecl );
287                } else {
288                        inStruct = true;
289                        Visitor::visit( aggregateDecl );
290                        inStruct = false;
291                } // if
292                // Always remove the hoisted aggregate from the inner structure.
293                filter( aggregateDecl->get_members(), isStructOrUnion, false );
[a08ba92]294        }
[c8ffe20b]295
[a08ba92]296        void HoistStruct::visit( StructDecl *aggregateDecl ) {
[0dd3a2f]297                handleAggregate( aggregateDecl );
[a08ba92]298        }
[c8ffe20b]299
[a08ba92]300        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
[0dd3a2f]301                handleAggregate( aggregateDecl );
[a08ba92]302        }
[c8ffe20b]303
[a08ba92]304        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]305                addVisit( compoundStmt, *this );
[a08ba92]306        }
[c8ffe20b]307
[a08ba92]308        void HoistStruct::visit( IfStmt *ifStmt ) {
[0dd3a2f]309                addVisit( ifStmt, *this );
[a08ba92]310        }
[c8ffe20b]311
[a08ba92]312        void HoistStruct::visit( WhileStmt *whileStmt ) {
[0dd3a2f]313                addVisit( whileStmt, *this );
[a08ba92]314        }
[c8ffe20b]315
[a08ba92]316        void HoistStruct::visit( ForStmt *forStmt ) {
[0dd3a2f]317                addVisit( forStmt, *this );
[a08ba92]318        }
[c8ffe20b]319
[a08ba92]320        void HoistStruct::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]321                addVisit( switchStmt, *this );
[a08ba92]322        }
[c8ffe20b]323
[a08ba92]324        void HoistStruct::visit( ChooseStmt *switchStmt ) {
[0dd3a2f]325                addVisit( switchStmt, *this );
[a08ba92]326        }
[c8ffe20b]327
[a08ba92]328        void HoistStruct::visit( CaseStmt *caseStmt ) {
[0dd3a2f]329                addVisit( caseStmt, *this );
[a08ba92]330        }
[c8ffe20b]331
[a08ba92]332        void HoistStruct::visit( CatchStmt *cathStmt ) {
[0dd3a2f]333                addVisit( cathStmt, *this );
[a08ba92]334        }
[c8ffe20b]335
[a08ba92]336        void Pass1::visit( EnumDecl *enumDecl ) {
[0dd3a2f]337                // Set the type of each member of the enumeration to be EnumConstant
[9cb8e88d]338
[0dd3a2f]339                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
[f6d7e0f]340                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]341                        assert( obj );
[f6d7e0f]342                        // obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
343                        BasicType * enumType = new BasicType( Type::Qualifiers(), BasicType::SignedInt );
344                        obj->set_type( enumType ) ;
[0dd3a2f]345                } // for
346                Parent::visit( enumDecl );
[a08ba92]347        }
[51b7345]348
[a08ba92]349        namespace {
[0dd3a2f]350                template< typename DWTIterator >
351                void fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func ) {
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
354                        if ( begin == end ) return;
355                        FixFunction fixer;
356                        DWTIterator i = begin;
357                        *i = (*i )->acceptMutator( fixer );
358                        if ( fixer.get_isVoid() ) {
359                                DWTIterator j = i;
360                                ++i;
361                                func->get_parameters().erase( j );
[9cb8e88d]362                                if ( i != end ) {
[0dd3a2f]363                                        throw SemanticError( "invalid type void in function type ", func );
364                                } // if
365                        } else {
366                                ++i;
367                                for ( ; i != end; ++i ) {
368                                        FixFunction fixer;
369                                        *i = (*i )->acceptMutator( fixer );
370                                        if ( fixer.get_isVoid() ) {
371                                                throw SemanticError( "invalid type void in function type ", func );
372                                        } // if
373                                } // for
374                        } // if
375                }
[a08ba92]376        }
[c8ffe20b]377
[a08ba92]378        void Pass1::visit( FunctionType *func ) {
[0dd3a2f]379                // Fix up parameters and return types
380                fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func );
381                fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func );
382                Visitor::visit( func );
[a08ba92]383        }
[c8ffe20b]384
[a08ba92]385        Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
[0dd3a2f]386                if ( other_indexer ) {
387                        indexer = other_indexer;
388                } else {
389                        indexer = this;
390                } // if
[a08ba92]391        }
[c8ffe20b]392
[a08ba92]393        void Pass2::visit( StructInstType *structInst ) {
[0dd3a2f]394                Parent::visit( structInst );
395                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
396                // it's not a semantic error if the struct is not found, just an implicit forward declaration
397                if ( st ) {
[98735ef]398                        //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
[0dd3a2f]399                        structInst->set_baseStruct( st );
400                } // if
401                if ( ! st || st->get_members().empty() ) {
402                        // use of forward declaration
403                        forwardStructs[ structInst->get_name() ].push_back( structInst );
404                } // if
[a08ba92]405        }
[c8ffe20b]406
[a08ba92]407        void Pass2::visit( UnionInstType *unionInst ) {
[0dd3a2f]408                Parent::visit( unionInst );
409                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
410                // it's not a semantic error if the union is not found, just an implicit forward declaration
411                if ( un ) {
412                        unionInst->set_baseUnion( un );
413                } // if
414                if ( ! un || un->get_members().empty() ) {
415                        // use of forward declaration
416                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
417                } // if
[a08ba92]418        }
[c8ffe20b]419
[a08ba92]420        void Pass2::visit( ContextInstType *contextInst ) {
[0dd3a2f]421                Parent::visit( contextInst );
422                ContextDecl *ctx = indexer->lookupContext( contextInst->get_name() );
423                if ( ! ctx ) {
424                        throw SemanticError( "use of undeclared context " + contextInst->get_name() );
[17cd4eb]425                } // if
[0dd3a2f]426                for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
427                        for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
428                                if ( ContextInstType *otherCtx = dynamic_cast< ContextInstType * >(*assert ) ) {
429                                        cloneAll( otherCtx->get_members(), contextInst->get_members() );
430                                } else {
431                                        contextInst->get_members().push_back( (*assert )->clone() );
432                                } // if
433                        } // for
434                } // for
[51b986f]435
436                if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
437                        throw SemanticError( "incorrect number of context parameters: ", contextInst );
438                } // if
439
[0dd3a2f]440                applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), ctx->get_members().begin(), ctx->get_members().end(), back_inserter( contextInst->get_members() ) );
[a08ba92]441        }
[c8ffe20b]442
[a08ba92]443        void Pass2::visit( StructDecl *structDecl ) {
[0dd3a2f]444                if ( ! structDecl->get_members().empty() ) {
445                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
446                        if ( fwds != forwardStructs.end() ) {
447                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
448                                        (*inst )->set_baseStruct( structDecl );
449                                } // for
450                                forwardStructs.erase( fwds );
451                        } // if
452                } // if
453                Indexer::visit( structDecl );
[a08ba92]454        }
[c8ffe20b]455
[a08ba92]456        void Pass2::visit( UnionDecl *unionDecl ) {
[0dd3a2f]457                if ( ! unionDecl->get_members().empty() ) {
458                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
459                        if ( fwds != forwardUnions.end() ) {
460                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
461                                        (*inst )->set_baseUnion( unionDecl );
462                                } // for
463                                forwardUnions.erase( fwds );
464                        } // if
465                } // if
466                Indexer::visit( unionDecl );
[a08ba92]467        }
[c8ffe20b]468
[a08ba92]469        void Pass2::visit( TypeInstType *typeInst ) {
[0dd3a2f]470                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
471                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
472                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
473                        } // if
474                } // if
[a08ba92]475        }
[c8ffe20b]476
[a08ba92]477        Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
[0dd3a2f]478                if ( other_indexer ) {
479                        indexer = other_indexer;
480                } else {
481                        indexer = this;
482                } // if
[a08ba92]483        }
[c8ffe20b]484
[82dd287]485        /// Fix up assertions
[a08ba92]486        void forallFixer( Type *func ) {
[0dd3a2f]487                for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
488                        std::list< DeclarationWithType * > toBeDone, nextRound;
489                        toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
490                        while ( ! toBeDone.empty() ) {
491                                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
492                                        if ( ContextInstType *ctx = dynamic_cast< ContextInstType * >( (*assertion )->get_type() ) ) {
493                                                for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
494                                                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
495                                                        assert( dwt );
496                                                        nextRound.push_back( dwt->clone() );
497                                                }
498                                                delete ctx;
499                                        } else {
500                                                FixFunction fixer;
501                                                *assertion = (*assertion )->acceptMutator( fixer );
502                                                if ( fixer.get_isVoid() ) {
503                                                        throw SemanticError( "invalid type void in assertion of function ", func );
504                                                }
505                                                (*type )->get_assertions().push_back( *assertion );
506                                        } // if
507                                } // for
508                                toBeDone.clear();
509                                toBeDone.splice( toBeDone.end(), nextRound );
510                        } // while
511                } // for
[a08ba92]512        }
[c8ffe20b]513
[a08ba92]514        void Pass3::visit( ObjectDecl *object ) {
[0dd3a2f]515                forallFixer( object->get_type() );
516                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
517                        forallFixer( pointer->get_base() );
518                } // if
519                Parent::visit( object );
520                object->fixUniqueId();
[a08ba92]521        }
[c8ffe20b]522
[a08ba92]523        void Pass3::visit( FunctionDecl *func ) {
[0dd3a2f]524                forallFixer( func->get_type() );
525                Parent::visit( func );
526                func->fixUniqueId();
[a08ba92]527        }
[c8ffe20b]528
[a08ba92]529        static const std::list< std::string > noLabels;
[c8ffe20b]530
[f066321]531        void AutogenerateRoutines::autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
532                AutogenerateRoutines visitor;
[0dd3a2f]533                acceptAndAdd( translationUnit, visitor, false );
[a08ba92]534        }
[c8ffe20b]535
[a08ba92]536        template< typename OutputIterator >
537        void makeScalarAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, OutputIterator out ) {
[0dd3a2f]538                ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member );
539                // unnamed bit fields are not copied as they cannot be accessed
540                if ( obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL ) return;
[c8ffe20b]541
[0dd3a2f]542                UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
[9cb8e88d]543
[0dd3a2f]544                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
545                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
[9cb8e88d]546
[0dd3a2f]547                // do something special for unnamed members
548                Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
549                assignExpr->get_args().push_back( dstselect );
[9cb8e88d]550
[0dd3a2f]551                Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
552                assignExpr->get_args().push_back( srcselect );
[9cb8e88d]553
[0dd3a2f]554                *out++ = new ExprStmt( noLabels, assignExpr );
[a08ba92]555        }
[c8ffe20b]556
[a08ba92]557        template< typename OutputIterator >
558        void makeArrayAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, ArrayType *array, OutputIterator out ) {
[0dd3a2f]559                static UniqueName indexName( "_index" );
[9cb8e88d]560
[0dd3a2f]561                // for a flexible array member nothing is done -- user must define own assignment
562                if ( ! array->get_dimension() ) return;
[9cb8e88d]563
[68cd1ce]564                ObjectDecl *index = new ObjectDecl( indexName.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), 0 );
[0dd3a2f]565                *out++ = new DeclStmt( noLabels, index );
[9cb8e88d]566
[0dd3a2f]567                UntypedExpr *init = new UntypedExpr( new NameExpr( "?=?" ) );
568                init->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
569                init->get_args().push_back( new NameExpr( "0" ) );
570                Statement *initStmt = new ExprStmt( noLabels, init );
[145f1fc]571                std::list<Statement *> initList;
572                initList.push_back( initStmt );
[9cb8e88d]573
[0dd3a2f]574                UntypedExpr *cond = new UntypedExpr( new NameExpr( "?<?" ) );
575                cond->get_args().push_back( new VariableExpr( index ) );
576                cond->get_args().push_back( array->get_dimension()->clone() );
[9cb8e88d]577
[0dd3a2f]578                UntypedExpr *inc = new UntypedExpr( new NameExpr( "++?" ) );
579                inc->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
[9cb8e88d]580
[0dd3a2f]581                UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
[9cb8e88d]582
[0dd3a2f]583                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
584                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
[9cb8e88d]585
[0dd3a2f]586                Expression *dstselect = new MemberExpr( member, derefExpr );
587                UntypedExpr *dstIndex = new UntypedExpr( new NameExpr( "?+?" ) );
588                dstIndex->get_args().push_back( dstselect );
589                dstIndex->get_args().push_back( new VariableExpr( index ) );
590                assignExpr->get_args().push_back( dstIndex );
[9cb8e88d]591
[0dd3a2f]592                Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
593                UntypedExpr *srcIndex = new UntypedExpr( new NameExpr( "?[?]" ) );
594                srcIndex->get_args().push_back( srcselect );
595                srcIndex->get_args().push_back( new VariableExpr( index ) );
596                assignExpr->get_args().push_back( srcIndex );
[9cb8e88d]597
[145f1fc]598                *out++ = new ForStmt( noLabels, initList, cond, inc, new ExprStmt( noLabels, assignExpr ) );
[a08ba92]599        }
[c8ffe20b]600
[4ef7506]601        template< typename OutputIterator >
602        void makeUnionFieldsAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, UnionInstType *unionType, OutputIterator out ) {
603                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
604                copy->get_args().push_back( new VariableExpr( dstParam ) );
605                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
606                copy->get_args().push_back( new SizeofExpr( unionType ) );
607
608                *out++ = new ExprStmt( noLabels, copy );
609        }
610
[9cb8e88d]611        //E ?=?(E volatile*, int),
[f6d7e0f]612        //  ?=?(E _Atomic volatile*, int);
613        void makeEnumAssignment( EnumDecl *enumDecl, EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
614                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
[9cb8e88d]615
[f6d7e0f]616                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
617                assignType->get_returnVals().push_back( returnVal );
618
619                // need two assignment operators with different types
620                FunctionType * assignType2 = assignType->clone();
621
622                // E ?=?(E volatile *, E)
623                Type *etype = refType->clone();
[8686f31]624                // etype->get_qualifiers() += Type::Qualifiers(false, true, false, false, false, false);
[f6d7e0f]625
626                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), etype ), 0 );
627                assignType->get_parameters().push_back( dstParam );
628
629                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, etype->clone(), 0 );
630                assignType->get_parameters().push_back( srcParam );
631
632                // E ?=?(E volatile *, int)
633                assignType2->get_parameters().push_back( dstParam->clone() );
[9cb8e88d]634                BasicType * paramType = new BasicType(Type::Qualifiers(), BasicType::SignedInt);
[f6d7e0f]635                ObjectDecl *srcParam2 = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, paramType, 0 );
636                assignType2->get_parameters().push_back( srcParam2 );
637
638                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
639                // because each unit generates copies of the default routines for each aggregate.
640
641                // since there is no definition, these should not be inline
642                // make these intrinsic so that the code generator does not make use of them
643                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType, 0, false, false );
644                assignDecl->fixUniqueId();
645                FunctionDecl *assignDecl2 = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType2, 0, false, false );
646                assignDecl2->fixUniqueId();
647
[cc79d97]648                // these should be built in the same way that the prelude
649                // functions are, so build a list containing the prototypes
650                // and allow MakeLibCfa to autogenerate the bodies.
[f6d7e0f]651                std::list< Declaration * > assigns;
652                assigns.push_back( assignDecl );
653                assigns.push_back( assignDecl2 );
654
655                LibCfa::makeLibCfa( assigns );
656
[cc79d97]657                // need to remove the prototypes, since this may be nested in a routine
[8686f31]658                for (int start = 0, end = assigns.size()/2; start < end; start++) {
659                        delete assigns.front();
660                        assigns.pop_front();
[1db21619]661                } // for
[8686f31]662
[f6d7e0f]663                declsToAdd.insert( declsToAdd.begin(), assigns.begin(), assigns.end() );
664        }
665
[32d281d]666        /// Clones a reference type, replacing any parameters it may have with a clone of the provided list
667        template< typename GenericInstType >
668        GenericInstType *cloneWithParams( GenericInstType *refType, const std::list< Expression* >& params ) {
669                GenericInstType *clone = refType->clone();
670                clone->get_parameters().clear();
671                cloneAll( params, clone->get_parameters() );
672                return clone;
673        }
[f6d7e0f]674
[98735ef]675        /// Creates a new type decl that's the same as src, but renamed and with only the ?=? assertion (for complete types only)
676        TypeDecl *cloneAndRename( TypeDecl *src, const std::string &name ) {
677                TypeDecl *dst = new TypeDecl( name, src->get_storageClass(), 0, src->get_kind() );
678
679                if ( src->get_kind() == TypeDecl::Any ) {
680                        // just include assignment operator assertion
681                        TypeInstType *assignParamType = new TypeInstType( Type::Qualifiers(), name, dst );
682                        FunctionType *assignFunctionType = new FunctionType( Type::Qualifiers(), false );
683                        assignFunctionType->get_returnVals().push_back(
684                                new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, assignParamType->clone(), 0 ) );
685                        assignFunctionType->get_parameters().push_back(
686                                new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), assignParamType->clone() ), 0 ) );
687                        assignFunctionType->get_parameters().push_back(
688                                new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, assignParamType, 0 ) );
689                        FunctionDecl *assignAssert = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, assignFunctionType, 0, false, false );
690                        dst->get_assertions().push_back( assignAssert );
691                }
692
693                return dst;
694        }
695
[a08ba92]696        Declaration *makeStructAssignment( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting ) {
[0dd3a2f]697                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
[37a3b8f9]698
699                // Make function polymorphic in same parameters as generic struct, if applicable
[4ef7506]700                bool isGeneric = false;  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
[37a3b8f9]701                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
[32d281d]702                std::list< Expression* > structParams;  // List of matching parameters to put on types
[98735ef]703                TypeSubstitution genericSubs; // Substitutions to make to member types of struct
[37a3b8f9]704                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
[4ef7506]705                        isGeneric = true;
[98735ef]706                        TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() );
[32d281d]707                        assignType->get_forall().push_back( typeParam );
[98735ef]708                        TypeInstType *newParamType = new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam );
709                        genericSubs.add( (*param)->get_name(), newParamType );
710                        structParams.push_back( new TypeExpr( newParamType ) );
[37a3b8f9]711                }
[9cb8e88d]712
[4ef7506]713                ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
[0dd3a2f]714                assignType->get_returnVals().push_back( returnVal );
[9cb8e88d]715
[32d281d]716                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, structParams ) ), 0 );
[0dd3a2f]717                assignType->get_parameters().push_back( dstParam );
[9cb8e88d]718
[32d281d]719                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
[0dd3a2f]720                assignType->get_parameters().push_back( srcParam );
721
722                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
723                // because each unit generates copies of the default routines for each aggregate.
[de62360d]724                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
[0dd3a2f]725                assignDecl->fixUniqueId();
[9cb8e88d]726
[0dd3a2f]727                for ( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) {
728                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) {
[9cb8e88d]729                                // query the type qualifiers of this field and skip assigning it if it is marked const.
[367e082]730                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
731                                Type * type = dwt->get_type();
732                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
733                                        type = at->get_base();
734                                }
735
736                                if ( type->get_qualifiers().isConst ) {
[53a2e97]737                                        // don't assign const members
738                                        continue;
739                                }
740
[98735ef]741                                if ( isGeneric ) {
742                                        // rewrite member type in terms of the type variables on this operator
743                                        DeclarationWithType *fixedMember = dwt->clone();
744                                        genericSubs.apply( fixedMember );
745
746                                        // assign to both destination and return value
747                                        if ( ArrayType *array = dynamic_cast< ArrayType * >( fixedMember->get_type() ) ) {
748                                                makeArrayAssignment( srcParam, dstParam, fixedMember, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
749                                                makeArrayAssignment( srcParam, returnVal, fixedMember, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
750                                        } else {
751                                                makeScalarAssignment( srcParam, dstParam, fixedMember, back_inserter( assignDecl->get_statements()->get_kids() ) );
752                                                makeScalarAssignment( srcParam, returnVal, fixedMember, back_inserter( assignDecl->get_statements()->get_kids() ) );
753                                        } // if
[0dd3a2f]754                                } else {
[98735ef]755                                        // assign to destination
756                                        if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) {
757                                                makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
758                                        } else {
759                                                makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
760                                        } // if
[0dd3a2f]761                                } // if
762                        } // if
763                } // for
[4ef7506]764                if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
[9cb8e88d]765
[0dd3a2f]766                return assignDecl;
[a08ba92]767        }
[c8ffe20b]768
[7528ba1]769
770        void makeStructCtorDtor( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
771                FunctionType *ctorType = new FunctionType( Type::Qualifiers(), false );
772
773                // Make function polymorphic in same parameters as generic struct, if applicable
774                bool isGeneric = false;  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
775                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
776                std::list< Expression* > structParams;  // List of matching parameters to put on types
777                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
778                        isGeneric = true;
779                        TypeDecl *typeParam = (*param)->clone();
780                        ctorType->get_forall().push_back( typeParam );
781                        structParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) );
782                }
783
784                ObjectDecl *thisParam = new ObjectDecl( "_this", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, structParams ) ), 0 );
785                ctorType->get_parameters().push_back( thisParam );
786
787                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
788                // because each unit generates copies of the default routines for each aggregate.
789                FunctionDecl *ctorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, ctorType, 0, true, false );
790                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, ctorType, 0, true, false );
791                ctorDecl->fixUniqueId();
792                dtorDecl->fixUniqueId();
793
794                // add definitions
795                // TODO: add in calls to default constructors and destructors for fields
796                ctorDecl->set_statements( new CompoundStmt( noLabels ) );
797                dtorDecl->set_statements( new CompoundStmt( noLabels ) );
798                declsToAdd.push_back( ctorDecl );
799                declsToAdd.push_back( dtorDecl );
800
801
802                // for ( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) {
803                //      if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) {
804                //              // query the type qualifiers of this field and skip assigning it if it is marked const.
805                //              // If it is an array type, we need to strip off the array layers to find its qualifiers.
806                //              Type * type = dwt->get_type();
807                //              while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
808                //                      type = at->get_base();
809                //              }
810
811                //              if ( type->get_qualifiers().isConst ) {
812                //                      // don't assign const members
813                //                      continue;
814                //              }
815
816                //              if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) {
817                //                      makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
818                //                      if ( isGeneric ) makeArrayAssignment( srcParam, returnVal, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
819                //              } else {
820                //                      makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
821                //                      if ( isGeneric ) makeScalarAssignment( srcParam, returnVal, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
822                //              } // if
823                //      } // if
824                // } // for
825                // if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
826
827                // return assignDecl;
828        }
829
[a08ba92]830        Declaration *makeUnionAssignment( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting ) {
[0dd3a2f]831                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
[32d281d]832
833                // Make function polymorphic in same parameters as generic union, if applicable
[4ef7506]834                bool isGeneric = false;  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for struct)
[32d281d]835                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
836                std::list< Expression* > unionParams;  // List of matching parameters to put on types
837                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
[4ef7506]838                        isGeneric = true;
[98735ef]839                        TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() );
[32d281d]840                        assignType->get_forall().push_back( typeParam );
841                        unionParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) );
842                }
[9cb8e88d]843
[4ef7506]844                ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
[0dd3a2f]845                assignType->get_returnVals().push_back( returnVal );
[9cb8e88d]846
[32d281d]847                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, unionParams ) ), 0 );
[0dd3a2f]848                assignType->get_parameters().push_back( dstParam );
[9cb8e88d]849
[32d281d]850                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
[0dd3a2f]851                assignType->get_parameters().push_back( srcParam );
[9cb8e88d]852
[0dd3a2f]853                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
854                // because each unit generates copies of the default routines for each aggregate.
[de62360d]855                FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
[0dd3a2f]856                assignDecl->fixUniqueId();
[9cb8e88d]857
[4ef7506]858                makeUnionFieldsAssignment( srcParam, dstParam, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) );
859                if ( isGeneric ) makeUnionFieldsAssignment( srcParam, returnVal, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) );
[c8ffe20b]860
[4ef7506]861                if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
[9cb8e88d]862
[0dd3a2f]863                return assignDecl;
[a08ba92]864        }
[c8ffe20b]865
[f066321]866        void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
[f6d7e0f]867                if ( ! enumDecl->get_members().empty() ) {
868                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
869                        // enumInst->set_baseEnum( enumDecl );
[9cb8e88d]870                        // declsToAdd.push_back(
[f6d7e0f]871                        makeEnumAssignment( enumDecl, enumInst, functionNesting, declsToAdd );
872                }
873        }
874
[f066321]875        void AutogenerateRoutines::visit( StructDecl *structDecl ) {
[0dd3a2f]876                if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
[32d281d]877                        StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
878                        structInst.set_baseStruct( structDecl );
[7528ba1]879
[32d281d]880                        declsToAdd.push_back( makeStructAssignment( structDecl, &structInst, functionNesting ) );
[7528ba1]881                        makeStructCtorDtor( structDecl, &structInst, functionNesting, declsToAdd );
[0dd3a2f]882                        structsDone.insert( structDecl->get_name() );
883                } // if
[a08ba92]884        }
[c8ffe20b]885
[f066321]886        void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
[0dd3a2f]887                if ( ! unionDecl->get_members().empty() ) {
[32d281d]888                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
889                        unionInst.set_baseUnion( unionDecl );
890                        declsToAdd.push_back( makeUnionAssignment( unionDecl, &unionInst, functionNesting ) );
[0dd3a2f]891                } // if
[a08ba92]892        }
[c8ffe20b]893
[f066321]894        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
[0dd3a2f]895                CompoundStmt *stmts = 0;
896                TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
897                typeInst->set_baseType( typeDecl );
[68cd1ce]898                ObjectDecl *src = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
899                ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
[0dd3a2f]900                if ( typeDecl->get_base() ) {
901                        stmts = new CompoundStmt( std::list< Label >() );
902                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
903                        assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
904                        assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
905                        stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
906                } // if
907                FunctionType *type = new FunctionType( Type::Qualifiers(), false );
[68cd1ce]908                type->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
[0dd3a2f]909                type->get_parameters().push_back( dst );
910                type->get_parameters().push_back( src );
[de62360d]911                FunctionDecl *func = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::AutoGen, type, stmts, false, false );
[0dd3a2f]912                declsToAdd.push_back( func );
[a08ba92]913        }
[c8ffe20b]914
[a08ba92]915        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
[5f2f2d7]916                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
917                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
918                } // for
919                declsToAdd.clear();
[a08ba92]920        }
[c8ffe20b]921
[f066321]922        void AutogenerateRoutines::visit( FunctionType *) {
[0dd3a2f]923                // ensure that we don't add assignment ops for types defined as part of the function
[a08ba92]924        }
[c8ffe20b]925
[f066321]926        void AutogenerateRoutines::visit( PointerType *) {
[0dd3a2f]927                // ensure that we don't add assignment ops for types defined as part of the pointer
[a08ba92]928        }
[c8ffe20b]929
[f066321]930        void AutogenerateRoutines::visit( ContextDecl *) {
[0dd3a2f]931                // ensure that we don't add assignment ops for types defined as part of the context
[a08ba92]932        }
[c8ffe20b]933
[a08ba92]934        template< typename StmtClass >
[f066321]935        inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
[0dd3a2f]936                std::set< std::string > oldStructs = structsDone;
937                addVisit( stmt, *this );
938                structsDone = oldStructs;
[a08ba92]939        }
[c8ffe20b]940
[f066321]941        void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
[0dd3a2f]942                maybeAccept( functionDecl->get_functionType(), *this );
943                acceptAll( functionDecl->get_oldDecls(), *this );
944                functionNesting += 1;
945                maybeAccept( functionDecl->get_statements(), *this );
946                functionNesting -= 1;
[a08ba92]947        }
[3c70d38]948
[f066321]949        void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]950                visitStatement( compoundStmt );
[a08ba92]951        }
[c8ffe20b]952
[f066321]953        void AutogenerateRoutines::visit( IfStmt *ifStmt ) {
[0dd3a2f]954                visitStatement( ifStmt );
[a08ba92]955        }
[c8ffe20b]956
[f066321]957        void AutogenerateRoutines::visit( WhileStmt *whileStmt ) {
[0dd3a2f]958                visitStatement( whileStmt );
[a08ba92]959        }
[c8ffe20b]960
[f066321]961        void AutogenerateRoutines::visit( ForStmt *forStmt ) {
[0dd3a2f]962                visitStatement( forStmt );
[a08ba92]963        }
[c8ffe20b]964
[f066321]965        void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]966                visitStatement( switchStmt );
[a08ba92]967        }
[c8ffe20b]968
[f066321]969        void AutogenerateRoutines::visit( ChooseStmt *switchStmt ) {
[0dd3a2f]970                visitStatement( switchStmt );
[a08ba92]971        }
[c8ffe20b]972
[f066321]973        void AutogenerateRoutines::visit( CaseStmt *caseStmt ) {
[0dd3a2f]974                visitStatement( caseStmt );
[a08ba92]975        }
[c8ffe20b]976
[f066321]977        void AutogenerateRoutines::visit( CatchStmt *cathStmt ) {
[0dd3a2f]978                visitStatement( cathStmt );
[a08ba92]979        }
[c8ffe20b]980
[de91427b]981        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
982                ReturnChecker checker;
983                acceptAll( translationUnit, checker );
984        }
985
986        void ReturnChecker::visit( FunctionDecl * functionDecl ) {
987                std::list< DeclarationWithType * > oldReturnVals = returnVals;
988                returnVals = functionDecl->get_functionType()->get_returnVals();
989                Visitor::visit( functionDecl );
990                returnVals = oldReturnVals;
991        }
992
993        void ReturnChecker::visit( ReturnStmt * returnStmt ) {
994                if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) {
995                        throw SemanticError( "Non-void function returns no values: " , returnStmt );
996                } else if ( returnStmt->get_expr() != NULL && returnVals.size() == 0 ) {
997                        throw SemanticError( "void function returns values: " , returnStmt );
998                }
999        }
1000
1001
[a08ba92]1002        bool isTypedef( Declaration *decl ) {
[0dd3a2f]1003                return dynamic_cast< TypedefDecl * >( decl );
[a08ba92]1004        }
[c8ffe20b]1005
[a08ba92]1006        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]1007                EliminateTypedef eliminator;
1008                mutateAll( translationUnit, eliminator );
1009                filter( translationUnit, isTypedef, true );
[a08ba92]1010        }
[c8ffe20b]1011
[85c4ef0]1012        Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
[9cb8e88d]1013                // instances of typedef types will come here. If it is an instance
[cc79d97]1014                // of a typdef type, link the instance to its actual type.
1015                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
[0dd3a2f]1016                if ( def != typedefNames.end() ) {
[cc79d97]1017                        Type *ret = def->second.first->get_base()->clone();
[0dd3a2f]1018                        ret->get_qualifiers() += typeInst->get_qualifiers();
[0215a76f]1019                        // place instance parameters on the typedef'd type
1020                        if ( ! typeInst->get_parameters().empty() ) {
1021                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
1022                                if ( ! rtt ) {
1023                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
1024                                }
1025                                rtt->get_parameters().clear();
1026                                cloneAll(typeInst->get_parameters(), rtt->get_parameters());
[1db21619]1027                        } // if
[0dd3a2f]1028                        delete typeInst;
1029                        return ret;
1030                } // if
1031                return typeInst;
[a08ba92]1032        }
[c8ffe20b]1033
[85c4ef0]1034        Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
[0dd3a2f]1035                Declaration *ret = Mutator::mutate( tyDecl );
[cc79d97]1036                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
[9cb8e88d]1037                        // typedef to the same name from the same scope
[cc79d97]1038                        // must be from the same type
1039
1040                        Type * t1 = tyDecl->get_base();
1041                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
[1cbca6e]1042                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[cc79d97]1043                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
[85c4ef0]1044                        }
[cc79d97]1045                } else {
1046                        typedefNames[ tyDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
1047                } // if
1048
[0dd3a2f]1049                // When a typedef is a forward declaration:
1050                //    typedef struct screen SCREEN;
1051                // the declaration portion must be retained:
1052                //    struct screen;
1053                // because the expansion of the typedef is:
1054                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
1055                // hence the type-name "screen" must be defined.
1056                // Note, qualifiers on the typedef are superfluous for the forward declaration.
1057                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
1058                        return new StructDecl( aggDecl->get_name() );
1059                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
1060                        return new UnionDecl( aggDecl->get_name() );
1061                } else {
1062                        return ret;
1063                } // if
[a08ba92]1064        }
[c8ffe20b]1065
[85c4ef0]1066        TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
[cc79d97]1067                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
[0dd3a2f]1068                if ( i != typedefNames.end() ) {
1069                        typedefNames.erase( i ) ;
1070                } // if
1071                return typeDecl;
[a08ba92]1072        }
[c8ffe20b]1073
[85c4ef0]1074        DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
[cc79d97]1075                TypedefMap oldNames = typedefNames;
[0dd3a2f]1076                DeclarationWithType *ret = Mutator::mutate( funcDecl );
1077                typedefNames = oldNames;
1078                return ret;
[a08ba92]1079        }
[c8ffe20b]1080
[1db21619]1081        DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
[cc79d97]1082                TypedefMap oldNames = typedefNames;
[1db21619]1083                DeclarationWithType *ret = Mutator::mutate( objDecl );
[ae4c85a]1084                typedefNames = oldNames;
[02e5ab6]1085                // is the type a function?
[1db21619]1086                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
[02e5ab6]1087                        // replace the current object declaration with a function declaration
[1db21619]1088                        return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
1089                } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
1090                        throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
1091                } // if
[0dd3a2f]1092                return ret;
[a08ba92]1093        }
[c8ffe20b]1094
[85c4ef0]1095        Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
[cc79d97]1096                TypedefMap oldNames = typedefNames;
[0dd3a2f]1097                Expression *ret = Mutator::mutate( castExpr );
1098                typedefNames = oldNames;
1099                return ret;
[a08ba92]1100        }
[c8ffe20b]1101
[85c4ef0]1102        CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
[cc79d97]1103                TypedefMap oldNames = typedefNames;
1104                scopeLevel += 1;
[0dd3a2f]1105                CompoundStmt *ret = Mutator::mutate( compoundStmt );
[cc79d97]1106                scopeLevel -= 1;
[0dd3a2f]1107                std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
1108                while ( i != compoundStmt->get_kids().end() ) {
[85c4ef0]1109                        std::list< Statement * >::iterator next = i+1;
[0dd3a2f]1110                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
1111                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
1112                                        delete *i;
1113                                        compoundStmt->get_kids().erase( i );
1114                                } // if
1115                        } // if
1116                        i = next;
1117                } // while
1118                typedefNames = oldNames;
1119                return ret;
[a08ba92]1120        }
[85c4ef0]1121
1122        // there may be typedefs nested within aggregates
1123        // in order for everything to work properly, these
1124        // should be removed as well
1125        template<typename AggDecl>
1126        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
1127                std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
1128                for ( ; it != aggDecl->get_members().end(); ) {
1129                        std::list< Declaration * >::iterator next = it+1;
1130                        if ( dynamic_cast< TypedefDecl * >( *it ) ) {
1131                                delete *it;
1132                                aggDecl->get_members().erase( it );
1133                        } // if
1134                        it = next;
1135                }
1136                return aggDecl;
1137        }
1138
1139        Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
1140                Mutator::mutate( structDecl );
1141                return handleAggregate( structDecl );
1142        }
1143
1144        Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
1145                Mutator::mutate( unionDecl );
1146                return handleAggregate( unionDecl );
1147        }
1148
1149        Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
1150                Mutator::mutate( enumDecl );
1151                return handleAggregate( enumDecl );
1152        }
1153
1154                Declaration *EliminateTypedef::mutate( ContextDecl * contextDecl ) {
1155                Mutator::mutate( contextDecl );
1156                return handleAggregate( contextDecl );
1157        }
1158
[9cb8e88d]1159        void VerifyCtorDtor::verify( std::list< Declaration * > & translationUnit ) {
1160                VerifyCtorDtor verifier;
1161                acceptAll( translationUnit, verifier );
1162        }
1163
1164        void VerifyCtorDtor::visit( FunctionDecl * funcDecl ) {
1165                FunctionType * funcType = funcDecl->get_functionType();
1166                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1167                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1168
1169                if ( funcDecl->get_name() == "?{}" || funcDecl->get_name() == "^?{}" ) {
1170                        if ( params.size() == 0 ) {
1171                                throw SemanticError( "Constructors and destructors require at least one parameter ", funcDecl );
1172                        }
1173                        if ( ! dynamic_cast< PointerType * >( params.front()->get_type() ) ) {
1174                                throw SemanticError( "First parameter of a constructor or destructor must be a pointer ", funcDecl );
1175                        }
1176                        if ( returnVals.size() != 0 ) {
1177                                throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
1178                        }
1179                }
1180
1181                Visitor::visit( funcDecl );
1182                // original idea: modify signature of ctor/dtors and insert appropriate return statements
1183                // to cause desired behaviour
1184                // new idea: add comma exprs to every ctor call to produce first parameter.
1185                // this requires some memoization of the first parameter, because it can be a
1186                // complicated expression with side effects (see: malloc). idea: add temporary variable
1187                // that is assigned address of constructed object in ctor argument position and
1188                // return the temporary. It should also be done after all implicit ctors are
1189                // added, so not in this pass!
1190        }
[51b7345]1191} // namespace SymTab
[0dd3a2f]1192
1193// Local Variables: //
1194// tab-width: 4 //
1195// mode: c++ //
1196// compile-command: "make install" //
1197// End: //
Note: See TracBrowser for help on using the repository browser.