source: src/SymTab/Validate.cc @ 5bf4712

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since 5bf4712 was 32d281d, checked in by Aaron Moss <a3moss@…>, 9 years ago

Fixed generic struct assignment operator generation to generify parameters

  • Property mode set to 100644
File size: 39.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//
7// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
[f066321]11// Last Modified By : Rob Schluntz
[5189888]12// Last Modified On : Fri Nov 20 16:33:52 2015
13// Update Count     : 201
[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"
[51b7345]51#include "utility.h"
52#include "UniqueName.h"
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 );
[c8ffe20b]65 
[0dd3a2f]66                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
[c8ffe20b]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
[82dd287]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;
109 
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; }
[c8ffe20b]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 );
[c8ffe20b]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 );
[c8ffe20b]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
[a08ba92]163        class EliminateTypedef : public Mutator {
164          public:
[cc79d97]165          EliminateTypedef() : scopeLevel( 0 ) {}
[73737e5]166            /// Replaces typedefs by forward declarations
[0dd3a2f]167                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
[a08ba92]168          private:
[0dd3a2f]169                virtual Declaration *mutate( TypedefDecl *typeDecl );
170                virtual TypeDecl *mutate( TypeDecl *typeDecl );
171                virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
[1db21619]172                virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
[0dd3a2f]173                virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
174                virtual Type *mutate( TypeInstType *aggregateUseType );
175                virtual Expression *mutate( CastExpr *castExpr );
[cc79d97]176
[85c4ef0]177                virtual Declaration *mutate( StructDecl * structDecl );
178                virtual Declaration *mutate( UnionDecl * unionDecl );
179                virtual Declaration *mutate( EnumDecl * enumDecl );
180                virtual Declaration *mutate( ContextDecl * contextDecl );
181
182                template<typename AggDecl>
183                AggDecl *handleAggregate( AggDecl * aggDecl );
184
[cc79d97]185                typedef std::map< std::string, std::pair< TypedefDecl *, int > > TypedefMap;
186                TypedefMap typedefNames;
187                int scopeLevel;
[a08ba92]188        };
[c8ffe20b]189
[a08ba92]190        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
[0dd3a2f]191                Pass1 pass1;
192                Pass2 pass2( doDebug, 0 );
193                Pass3 pass3( 0 );
194                EliminateTypedef::eliminateTypedef( translationUnit );
195                HoistStruct::hoistStruct( translationUnit );
196                acceptAll( translationUnit, pass1 );
197                acceptAll( translationUnit, pass2 );
[f066321]198                AutogenerateRoutines::autogenerateRoutines( translationUnit );
[0dd3a2f]199                acceptAll( translationUnit, pass3 );
[a08ba92]200        }
201       
202        void validateType( Type *type, const Indexer *indexer ) {
[0dd3a2f]203                Pass1 pass1;
204                Pass2 pass2( false, indexer );
205                Pass3 pass3( indexer );
206                type->accept( pass1 );
207                type->accept( pass2 );
208                type->accept( pass3 );
[a08ba92]209        }
[c8ffe20b]210
[a08ba92]211        template< typename Visitor >
212        void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor, bool addBefore ) {
[0dd3a2f]213                std::list< Declaration * >::iterator i = translationUnit.begin();
214                while ( i != translationUnit.end() ) {
215                        (*i)->accept( visitor );
216                        std::list< Declaration * >::iterator next = i;
217                        next++;
218                        if ( ! visitor.get_declsToAdd().empty() ) {
219                                translationUnit.splice( addBefore ? i : next, visitor.get_declsToAdd() );
220                        } // if
221                        i = next;
222                } // while
[a08ba92]223        }
[c8ffe20b]224
[a08ba92]225        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]226                HoistStruct hoister;
227                acceptAndAdd( translationUnit, hoister, true );
[a08ba92]228        }
[c8ffe20b]229
[a08ba92]230        HoistStruct::HoistStruct() : inStruct( false ) {
231        }
[c8ffe20b]232
[a08ba92]233        void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
[0dd3a2f]234                std::list< Declaration * >::iterator i = declList.begin();
235                while ( i != declList.end() ) {
236                        std::list< Declaration * >::iterator next = i;
237                        ++next;
238                        if ( pred( *i ) ) {
239                                if ( doDelete ) {
240                                        delete *i;
241                                } // if
242                                declList.erase( i );
243                        } // if
244                        i = next;
245                } // while
[a08ba92]246        }
[c8ffe20b]247
[a08ba92]248        bool isStructOrUnion( Declaration *decl ) {
[0dd3a2f]249                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
[a08ba92]250        }
[51b7345]251
[a08ba92]252        template< typename AggDecl >
253        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[0dd3a2f]254                if ( inStruct ) {
255                        // Add elements in stack order corresponding to nesting structure.
256                        declsToAdd.push_front( aggregateDecl );
257                        Visitor::visit( aggregateDecl );
258                } else {
259                        inStruct = true;
260                        Visitor::visit( aggregateDecl );
261                        inStruct = false;
262                } // if
263                // Always remove the hoisted aggregate from the inner structure.
264                filter( aggregateDecl->get_members(), isStructOrUnion, false );
[a08ba92]265        }
[c8ffe20b]266
[a08ba92]267        void HoistStruct::visit( StructDecl *aggregateDecl ) {
[0dd3a2f]268                handleAggregate( aggregateDecl );
[a08ba92]269        }
[c8ffe20b]270
[a08ba92]271        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
[0dd3a2f]272                handleAggregate( aggregateDecl );
[a08ba92]273        }
[c8ffe20b]274
[a08ba92]275        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]276                addVisit( compoundStmt, *this );
[a08ba92]277        }
[c8ffe20b]278
[a08ba92]279        void HoistStruct::visit( IfStmt *ifStmt ) {
[0dd3a2f]280                addVisit( ifStmt, *this );
[a08ba92]281        }
[c8ffe20b]282
[a08ba92]283        void HoistStruct::visit( WhileStmt *whileStmt ) {
[0dd3a2f]284                addVisit( whileStmt, *this );
[a08ba92]285        }
[c8ffe20b]286
[a08ba92]287        void HoistStruct::visit( ForStmt *forStmt ) {
[0dd3a2f]288                addVisit( forStmt, *this );
[a08ba92]289        }
[c8ffe20b]290
[a08ba92]291        void HoistStruct::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]292                addVisit( switchStmt, *this );
[a08ba92]293        }
[c8ffe20b]294
[a08ba92]295        void HoistStruct::visit( ChooseStmt *switchStmt ) {
[0dd3a2f]296                addVisit( switchStmt, *this );
[a08ba92]297        }
[c8ffe20b]298
[a08ba92]299        void HoistStruct::visit( CaseStmt *caseStmt ) {
[0dd3a2f]300                addVisit( caseStmt, *this );
[a08ba92]301        }
[c8ffe20b]302
[a08ba92]303        void HoistStruct::visit( CatchStmt *cathStmt ) {
[0dd3a2f]304                addVisit( cathStmt, *this );
[a08ba92]305        }
[c8ffe20b]306
[a08ba92]307        void Pass1::visit( EnumDecl *enumDecl ) {
[0dd3a2f]308                // Set the type of each member of the enumeration to be EnumConstant
[c8ffe20b]309 
[0dd3a2f]310                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
[f6d7e0f]311                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]312                        assert( obj );
[f6d7e0f]313                        // obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
314                        BasicType * enumType = new BasicType( Type::Qualifiers(), BasicType::SignedInt );
315                        obj->set_type( enumType ) ;
[0dd3a2f]316                } // for
317                Parent::visit( enumDecl );
[a08ba92]318        }
[51b7345]319
[a08ba92]320        namespace {
[0dd3a2f]321                template< typename DWTIterator >
322                void fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func ) {
323                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
324                        // entirely other fix ups are handled by the FixFunction class
325                        if ( begin == end ) return;
326                        FixFunction fixer;
327                        DWTIterator i = begin;
328                        *i = (*i )->acceptMutator( fixer );
329                        if ( fixer.get_isVoid() ) {
330                                DWTIterator j = i;
331                                ++i;
332                                func->get_parameters().erase( j );
333                                if ( i != end ) { 
334                                        throw SemanticError( "invalid type void in function type ", func );
335                                } // if
336                        } else {
337                                ++i;
338                                for ( ; i != end; ++i ) {
339                                        FixFunction fixer;
340                                        *i = (*i )->acceptMutator( fixer );
341                                        if ( fixer.get_isVoid() ) {
342                                                throw SemanticError( "invalid type void in function type ", func );
343                                        } // if
344                                } // for
345                        } // if
346                }
[a08ba92]347        }
[c8ffe20b]348
[a08ba92]349        void Pass1::visit( FunctionType *func ) {
[0dd3a2f]350                // Fix up parameters and return types
351                fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func );
352                fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func );
353                Visitor::visit( func );
[a08ba92]354        }
[c8ffe20b]355
[a08ba92]356        Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
[0dd3a2f]357                if ( other_indexer ) {
358                        indexer = other_indexer;
359                } else {
360                        indexer = this;
361                } // if
[a08ba92]362        }
[c8ffe20b]363
[a08ba92]364        void Pass2::visit( StructInstType *structInst ) {
[0dd3a2f]365                Parent::visit( structInst );
366                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
367                // it's not a semantic error if the struct is not found, just an implicit forward declaration
368                if ( st ) {
369                        assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
370                        structInst->set_baseStruct( st );
371                } // if
372                if ( ! st || st->get_members().empty() ) {
373                        // use of forward declaration
374                        forwardStructs[ structInst->get_name() ].push_back( structInst );
375                } // if
[a08ba92]376        }
[c8ffe20b]377
[a08ba92]378        void Pass2::visit( UnionInstType *unionInst ) {
[0dd3a2f]379                Parent::visit( unionInst );
380                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
381                // it's not a semantic error if the union is not found, just an implicit forward declaration
382                if ( un ) {
383                        unionInst->set_baseUnion( un );
384                } // if
385                if ( ! un || un->get_members().empty() ) {
386                        // use of forward declaration
387                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
388                } // if
[a08ba92]389        }
[c8ffe20b]390
[a08ba92]391        void Pass2::visit( ContextInstType *contextInst ) {
[0dd3a2f]392                Parent::visit( contextInst );
393                ContextDecl *ctx = indexer->lookupContext( contextInst->get_name() );
394                if ( ! ctx ) {
395                        throw SemanticError( "use of undeclared context " + contextInst->get_name() );
[17cd4eb]396                } // if
[0dd3a2f]397                for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
398                        for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
399                                if ( ContextInstType *otherCtx = dynamic_cast< ContextInstType * >(*assert ) ) {
400                                        cloneAll( otherCtx->get_members(), contextInst->get_members() );
401                                } else {
402                                        contextInst->get_members().push_back( (*assert )->clone() );
403                                } // if
404                        } // for
405                } // for
[51b986f]406
407                if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
408                        throw SemanticError( "incorrect number of context parameters: ", contextInst );
409                } // if
410
[0dd3a2f]411                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]412        }
[c8ffe20b]413
[a08ba92]414        void Pass2::visit( StructDecl *structDecl ) {
[0dd3a2f]415                if ( ! structDecl->get_members().empty() ) {
416                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
417                        if ( fwds != forwardStructs.end() ) {
418                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
419                                        (*inst )->set_baseStruct( structDecl );
420                                } // for
421                                forwardStructs.erase( fwds );
422                        } // if
423                } // if
424                Indexer::visit( structDecl );
[a08ba92]425        }
[c8ffe20b]426
[a08ba92]427        void Pass2::visit( UnionDecl *unionDecl ) {
[0dd3a2f]428                if ( ! unionDecl->get_members().empty() ) {
429                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
430                        if ( fwds != forwardUnions.end() ) {
431                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
432                                        (*inst )->set_baseUnion( unionDecl );
433                                } // for
434                                forwardUnions.erase( fwds );
435                        } // if
436                } // if
437                Indexer::visit( unionDecl );
[a08ba92]438        }
[c8ffe20b]439
[a08ba92]440        void Pass2::visit( TypeInstType *typeInst ) {
[0dd3a2f]441                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
442                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
443                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
444                        } // if
445                } // if
[a08ba92]446        }
[c8ffe20b]447
[a08ba92]448        Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
[0dd3a2f]449                if ( other_indexer ) {
450                        indexer = other_indexer;
451                } else {
452                        indexer = this;
453                } // if
[a08ba92]454        }
[c8ffe20b]455
[82dd287]456        /// Fix up assertions
[a08ba92]457        void forallFixer( Type *func ) {
[0dd3a2f]458                for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
459                        std::list< DeclarationWithType * > toBeDone, nextRound;
460                        toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
461                        while ( ! toBeDone.empty() ) {
462                                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
463                                        if ( ContextInstType *ctx = dynamic_cast< ContextInstType * >( (*assertion )->get_type() ) ) {
464                                                for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
465                                                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
466                                                        assert( dwt );
467                                                        nextRound.push_back( dwt->clone() );
468                                                }
469                                                delete ctx;
470                                        } else {
471                                                FixFunction fixer;
472                                                *assertion = (*assertion )->acceptMutator( fixer );
473                                                if ( fixer.get_isVoid() ) {
474                                                        throw SemanticError( "invalid type void in assertion of function ", func );
475                                                }
476                                                (*type )->get_assertions().push_back( *assertion );
477                                        } // if
478                                } // for
479                                toBeDone.clear();
480                                toBeDone.splice( toBeDone.end(), nextRound );
481                        } // while
482                } // for
[a08ba92]483        }
[c8ffe20b]484
[a08ba92]485        void Pass3::visit( ObjectDecl *object ) {
[0dd3a2f]486                forallFixer( object->get_type() );
487                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
488                        forallFixer( pointer->get_base() );
489                } // if
490                Parent::visit( object );
491                object->fixUniqueId();
[a08ba92]492        }
[c8ffe20b]493
[a08ba92]494        void Pass3::visit( FunctionDecl *func ) {
[0dd3a2f]495                forallFixer( func->get_type() );
496                Parent::visit( func );
497                func->fixUniqueId();
[a08ba92]498        }
[c8ffe20b]499
[a08ba92]500        static const std::list< std::string > noLabels;
[c8ffe20b]501
[f066321]502        void AutogenerateRoutines::autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
503                AutogenerateRoutines visitor;
[0dd3a2f]504                acceptAndAdd( translationUnit, visitor, false );
[a08ba92]505        }
[c8ffe20b]506
[a08ba92]507        template< typename OutputIterator >
508        void makeScalarAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, OutputIterator out ) {
[0dd3a2f]509                ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member );
510                // unnamed bit fields are not copied as they cannot be accessed
511                if ( obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL ) return;
[c8ffe20b]512
[0dd3a2f]513                UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
[c8ffe20b]514 
[0dd3a2f]515                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
516                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
[c8ffe20b]517 
[0dd3a2f]518                // do something special for unnamed members
519                Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
520                assignExpr->get_args().push_back( dstselect );
[c8ffe20b]521 
[0dd3a2f]522                Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
523                assignExpr->get_args().push_back( srcselect );
[c8ffe20b]524 
[0dd3a2f]525                *out++ = new ExprStmt( noLabels, assignExpr );
[a08ba92]526        }
[c8ffe20b]527
[a08ba92]528        template< typename OutputIterator >
529        void makeArrayAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, ArrayType *array, OutputIterator out ) {
[0dd3a2f]530                static UniqueName indexName( "_index" );
[c8ffe20b]531 
[0dd3a2f]532                // for a flexible array member nothing is done -- user must define own assignment
533                if ( ! array->get_dimension() ) return;
[c8ffe20b]534 
[68cd1ce]535                ObjectDecl *index = new ObjectDecl( indexName.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), 0 );
[0dd3a2f]536                *out++ = new DeclStmt( noLabels, index );
[c8ffe20b]537 
[0dd3a2f]538                UntypedExpr *init = new UntypedExpr( new NameExpr( "?=?" ) );
539                init->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
540                init->get_args().push_back( new NameExpr( "0" ) );
541                Statement *initStmt = new ExprStmt( noLabels, init );
[145f1fc]542                std::list<Statement *> initList;
543                initList.push_back( initStmt );
[c8ffe20b]544 
[0dd3a2f]545                UntypedExpr *cond = new UntypedExpr( new NameExpr( "?<?" ) );
546                cond->get_args().push_back( new VariableExpr( index ) );
547                cond->get_args().push_back( array->get_dimension()->clone() );
[c8ffe20b]548 
[0dd3a2f]549                UntypedExpr *inc = new UntypedExpr( new NameExpr( "++?" ) );
550                inc->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
[c8ffe20b]551 
[0dd3a2f]552                UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
[c8ffe20b]553 
[0dd3a2f]554                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
555                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
[c8ffe20b]556 
[0dd3a2f]557                Expression *dstselect = new MemberExpr( member, derefExpr );
558                UntypedExpr *dstIndex = new UntypedExpr( new NameExpr( "?+?" ) );
559                dstIndex->get_args().push_back( dstselect );
560                dstIndex->get_args().push_back( new VariableExpr( index ) );
561                assignExpr->get_args().push_back( dstIndex );
[c8ffe20b]562 
[0dd3a2f]563                Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
564                UntypedExpr *srcIndex = new UntypedExpr( new NameExpr( "?[?]" ) );
565                srcIndex->get_args().push_back( srcselect );
566                srcIndex->get_args().push_back( new VariableExpr( index ) );
567                assignExpr->get_args().push_back( srcIndex );
[c8ffe20b]568 
[145f1fc]569                *out++ = new ForStmt( noLabels, initList, cond, inc, new ExprStmt( noLabels, assignExpr ) );
[a08ba92]570        }
[c8ffe20b]571
[f6d7e0f]572        //E ?=?(E volatile*, int),
573        //  ?=?(E _Atomic volatile*, int);
574        void makeEnumAssignment( EnumDecl *enumDecl, EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
575                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
576 
577                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
578                assignType->get_returnVals().push_back( returnVal );
579
580                // need two assignment operators with different types
581                FunctionType * assignType2 = assignType->clone();
582
583                // E ?=?(E volatile *, E)
584                Type *etype = refType->clone();
[8686f31]585                // etype->get_qualifiers() += Type::Qualifiers(false, true, false, false, false, false);
[f6d7e0f]586
587                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), etype ), 0 );
588                assignType->get_parameters().push_back( dstParam );
589
590                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, etype->clone(), 0 );
591                assignType->get_parameters().push_back( srcParam );
592
593                // E ?=?(E volatile *, int)
594                assignType2->get_parameters().push_back( dstParam->clone() );
595                BasicType * paramType = new BasicType(Type::Qualifiers(), BasicType::SignedInt); 
596                ObjectDecl *srcParam2 = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, paramType, 0 );
597                assignType2->get_parameters().push_back( srcParam2 );
598
599                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
600                // because each unit generates copies of the default routines for each aggregate.
601
602                // since there is no definition, these should not be inline
603                // make these intrinsic so that the code generator does not make use of them
604                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType, 0, false, false );
605                assignDecl->fixUniqueId();
606                FunctionDecl *assignDecl2 = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType2, 0, false, false );
607                assignDecl2->fixUniqueId();
608
[cc79d97]609                // these should be built in the same way that the prelude
610                // functions are, so build a list containing the prototypes
611                // and allow MakeLibCfa to autogenerate the bodies.
[f6d7e0f]612                std::list< Declaration * > assigns;
613                assigns.push_back( assignDecl );
614                assigns.push_back( assignDecl2 );
615
616                LibCfa::makeLibCfa( assigns );
617
[cc79d97]618                // need to remove the prototypes, since this may be nested in a routine
[8686f31]619                for (int start = 0, end = assigns.size()/2; start < end; start++) {
620                        delete assigns.front();
621                        assigns.pop_front();
[1db21619]622                } // for
[8686f31]623
[f6d7e0f]624                declsToAdd.insert( declsToAdd.begin(), assigns.begin(), assigns.end() );
625        }
626
[32d281d]627        /// Clones a reference type, replacing any parameters it may have with a clone of the provided list
628        template< typename GenericInstType >
629        GenericInstType *cloneWithParams( GenericInstType *refType, const std::list< Expression* >& params ) {
630                GenericInstType *clone = refType->clone();
631                clone->get_parameters().clear();
632                cloneAll( params, clone->get_parameters() );
633                return clone;
634        }
[f6d7e0f]635
[a08ba92]636        Declaration *makeStructAssignment( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting ) {
[0dd3a2f]637                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
[37a3b8f9]638
639                // Make function polymorphic in same parameters as generic struct, if applicable
640                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
[32d281d]641                std::list< Expression* > structParams;  // List of matching parameters to put on types
[37a3b8f9]642                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
[32d281d]643                        TypeDecl *typeParam = (*param)->clone();
644                        assignType->get_forall().push_back( typeParam );
645                        structParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) );
[37a3b8f9]646                }
[0dd3a2f]647 
[32d281d]648                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
[0dd3a2f]649                assignType->get_returnVals().push_back( returnVal );
650 
[32d281d]651                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, structParams ) ), 0 );
[0dd3a2f]652                assignType->get_parameters().push_back( dstParam );
653 
[32d281d]654                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
[0dd3a2f]655                assignType->get_parameters().push_back( srcParam );
656
657                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
658                // because each unit generates copies of the default routines for each aggregate.
[de62360d]659                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
[0dd3a2f]660                assignDecl->fixUniqueId();
661 
662                for ( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) {
663                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) {
[367e082]664                                // query the type qualifiers of this field and skip assigning it if it is marked const.
665                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
666                                Type * type = dwt->get_type();
667                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
668                                        type = at->get_base();
669                                }
670
671                                if ( type->get_qualifiers().isConst ) {
[53a2e97]672                                        // don't assign const members
673                                        continue;
674                                }
675
[0dd3a2f]676                                if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) {
677                                        makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
678                                } else {
679                                        makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
680                                } // if
681                        } // if
682                } // for
683                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
[c8ffe20b]684 
[0dd3a2f]685                return assignDecl;
[a08ba92]686        }
[c8ffe20b]687
[a08ba92]688        Declaration *makeUnionAssignment( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting ) {
[0dd3a2f]689                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
[32d281d]690
691                // Make function polymorphic in same parameters as generic union, if applicable
692                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
693                std::list< Expression* > unionParams;  // List of matching parameters to put on types
694                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
695                        TypeDecl *typeParam = (*param)->clone();
696                        assignType->get_forall().push_back( typeParam );
697                        unionParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) );
698                }
[c8ffe20b]699 
[32d281d]700                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
[0dd3a2f]701                assignType->get_returnVals().push_back( returnVal );
[c8ffe20b]702 
[32d281d]703                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, unionParams ) ), 0 );
[0dd3a2f]704                assignType->get_parameters().push_back( dstParam );
[c8ffe20b]705 
[32d281d]706                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
[0dd3a2f]707                assignType->get_parameters().push_back( srcParam );
[c8ffe20b]708 
[0dd3a2f]709                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
710                // because each unit generates copies of the default routines for each aggregate.
[de62360d]711                FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
[0dd3a2f]712                assignDecl->fixUniqueId();
[c8ffe20b]713 
[0dd3a2f]714                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
715                copy->get_args().push_back( new VariableExpr( dstParam ) );
716                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
[32d281d]717                copy->get_args().push_back( new SizeofExpr( cloneWithParams( refType, unionParams ) ) );
[c8ffe20b]718
[0dd3a2f]719                assignDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, copy ) );
720                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
[c8ffe20b]721 
[0dd3a2f]722                return assignDecl;
[a08ba92]723        }
[c8ffe20b]724
[f066321]725        void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
[f6d7e0f]726                if ( ! enumDecl->get_members().empty() ) {
727                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
728                        // enumInst->set_baseEnum( enumDecl );
729                        // declsToAdd.push_back(
730                        makeEnumAssignment( enumDecl, enumInst, functionNesting, declsToAdd );
731                }
732        }
733
[f066321]734        void AutogenerateRoutines::visit( StructDecl *structDecl ) {
[0dd3a2f]735                if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
[32d281d]736                        StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
737                        structInst.set_baseStruct( structDecl );
738                        declsToAdd.push_back( makeStructAssignment( structDecl, &structInst, functionNesting ) );
[0dd3a2f]739                        structsDone.insert( structDecl->get_name() );
740                } // if
[a08ba92]741        }
[c8ffe20b]742
[f066321]743        void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
[0dd3a2f]744                if ( ! unionDecl->get_members().empty() ) {
[32d281d]745                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
746                        unionInst.set_baseUnion( unionDecl );
747                        declsToAdd.push_back( makeUnionAssignment( unionDecl, &unionInst, functionNesting ) );
[0dd3a2f]748                } // if
[a08ba92]749        }
[c8ffe20b]750
[f066321]751        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
[0dd3a2f]752                CompoundStmt *stmts = 0;
753                TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
754                typeInst->set_baseType( typeDecl );
[68cd1ce]755                ObjectDecl *src = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
756                ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
[0dd3a2f]757                if ( typeDecl->get_base() ) {
758                        stmts = new CompoundStmt( std::list< Label >() );
759                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
760                        assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
761                        assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
762                        stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
763                } // if
764                FunctionType *type = new FunctionType( Type::Qualifiers(), false );
[68cd1ce]765                type->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
[0dd3a2f]766                type->get_parameters().push_back( dst );
767                type->get_parameters().push_back( src );
[de62360d]768                FunctionDecl *func = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::AutoGen, type, stmts, false, false );
[0dd3a2f]769                declsToAdd.push_back( func );
[a08ba92]770        }
[c8ffe20b]771
[a08ba92]772        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
[5f2f2d7]773                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
774                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
775                } // for
776                declsToAdd.clear();
[a08ba92]777        }
[c8ffe20b]778
[f066321]779        void AutogenerateRoutines::visit( FunctionType *) {
[0dd3a2f]780                // ensure that we don't add assignment ops for types defined as part of the function
[a08ba92]781        }
[c8ffe20b]782
[f066321]783        void AutogenerateRoutines::visit( PointerType *) {
[0dd3a2f]784                // ensure that we don't add assignment ops for types defined as part of the pointer
[a08ba92]785        }
[c8ffe20b]786
[f066321]787        void AutogenerateRoutines::visit( ContextDecl *) {
[0dd3a2f]788                // ensure that we don't add assignment ops for types defined as part of the context
[a08ba92]789        }
[c8ffe20b]790
[a08ba92]791        template< typename StmtClass >
[f066321]792        inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
[0dd3a2f]793                std::set< std::string > oldStructs = structsDone;
794                addVisit( stmt, *this );
795                structsDone = oldStructs;
[a08ba92]796        }
[c8ffe20b]797
[f066321]798        void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
[0dd3a2f]799                maybeAccept( functionDecl->get_functionType(), *this );
800                acceptAll( functionDecl->get_oldDecls(), *this );
801                functionNesting += 1;
802                maybeAccept( functionDecl->get_statements(), *this );
803                functionNesting -= 1;
[a08ba92]804        }
[3c70d38]805
[f066321]806        void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
[0dd3a2f]807                visitStatement( compoundStmt );
[a08ba92]808        }
[c8ffe20b]809
[f066321]810        void AutogenerateRoutines::visit( IfStmt *ifStmt ) {
[0dd3a2f]811                visitStatement( ifStmt );
[a08ba92]812        }
[c8ffe20b]813
[f066321]814        void AutogenerateRoutines::visit( WhileStmt *whileStmt ) {
[0dd3a2f]815                visitStatement( whileStmt );
[a08ba92]816        }
[c8ffe20b]817
[f066321]818        void AutogenerateRoutines::visit( ForStmt *forStmt ) {
[0dd3a2f]819                visitStatement( forStmt );
[a08ba92]820        }
[c8ffe20b]821
[f066321]822        void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
[0dd3a2f]823                visitStatement( switchStmt );
[a08ba92]824        }
[c8ffe20b]825
[f066321]826        void AutogenerateRoutines::visit( ChooseStmt *switchStmt ) {
[0dd3a2f]827                visitStatement( switchStmt );
[a08ba92]828        }
[c8ffe20b]829
[f066321]830        void AutogenerateRoutines::visit( CaseStmt *caseStmt ) {
[0dd3a2f]831                visitStatement( caseStmt );
[a08ba92]832        }
[c8ffe20b]833
[f066321]834        void AutogenerateRoutines::visit( CatchStmt *cathStmt ) {
[0dd3a2f]835                visitStatement( cathStmt );
[a08ba92]836        }
[c8ffe20b]837
[a08ba92]838        bool isTypedef( Declaration *decl ) {
[0dd3a2f]839                return dynamic_cast< TypedefDecl * >( decl );
[a08ba92]840        }
[c8ffe20b]841
[a08ba92]842        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
[0dd3a2f]843                EliminateTypedef eliminator;
844                mutateAll( translationUnit, eliminator );
845                filter( translationUnit, isTypedef, true );
[a08ba92]846        }
[c8ffe20b]847
[85c4ef0]848        Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
[cc79d97]849                // instances of typedef types will come here. If it is an instance
850                // of a typdef type, link the instance to its actual type.
851                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
[0dd3a2f]852                if ( def != typedefNames.end() ) {
[cc79d97]853                        Type *ret = def->second.first->get_base()->clone();
[0dd3a2f]854                        ret->get_qualifiers() += typeInst->get_qualifiers();
[0215a76f]855                        // place instance parameters on the typedef'd type
856                        if ( ! typeInst->get_parameters().empty() ) {
857                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
858                                if ( ! rtt ) {
859                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
860                                }
861                                rtt->get_parameters().clear();
862                                cloneAll(typeInst->get_parameters(), rtt->get_parameters());
[1db21619]863                        } // if
[0dd3a2f]864                        delete typeInst;
865                        return ret;
866                } // if
867                return typeInst;
[a08ba92]868        }
[c8ffe20b]869
[85c4ef0]870        Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
[0dd3a2f]871                Declaration *ret = Mutator::mutate( tyDecl );
[cc79d97]872                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
873                        // typedef to the same name from the same scope
874                        // must be from the same type
875
876                        Type * t1 = tyDecl->get_base();
877                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
[1cbca6e]878                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[cc79d97]879                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
[85c4ef0]880                        }
[cc79d97]881                } else {
882                        typedefNames[ tyDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
883                } // if
884
[0dd3a2f]885                // When a typedef is a forward declaration:
886                //    typedef struct screen SCREEN;
887                // the declaration portion must be retained:
888                //    struct screen;
889                // because the expansion of the typedef is:
890                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
891                // hence the type-name "screen" must be defined.
892                // Note, qualifiers on the typedef are superfluous for the forward declaration.
893                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
894                        return new StructDecl( aggDecl->get_name() );
895                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
896                        return new UnionDecl( aggDecl->get_name() );
897                } else {
898                        return ret;
899                } // if
[a08ba92]900        }
[c8ffe20b]901
[85c4ef0]902        TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
[cc79d97]903                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
[0dd3a2f]904                if ( i != typedefNames.end() ) {
905                        typedefNames.erase( i ) ;
906                } // if
907                return typeDecl;
[a08ba92]908        }
[c8ffe20b]909
[85c4ef0]910        DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
[cc79d97]911                TypedefMap oldNames = typedefNames;
[0dd3a2f]912                DeclarationWithType *ret = Mutator::mutate( funcDecl );
913                typedefNames = oldNames;
914                return ret;
[a08ba92]915        }
[c8ffe20b]916
[1db21619]917        DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
[cc79d97]918                TypedefMap oldNames = typedefNames;
[1db21619]919                DeclarationWithType *ret = Mutator::mutate( objDecl );
[ae4c85a]920                typedefNames = oldNames;
[02e5ab6]921                // is the type a function?
[1db21619]922                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
[02e5ab6]923                        // replace the current object declaration with a function declaration
[1db21619]924                        return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
925                } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
926                        throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
927                } // if
[0dd3a2f]928                return ret;
[a08ba92]929        }
[c8ffe20b]930
[85c4ef0]931        Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
[cc79d97]932                TypedefMap oldNames = typedefNames;
[0dd3a2f]933                Expression *ret = Mutator::mutate( castExpr );
934                typedefNames = oldNames;
935                return ret;
[a08ba92]936        }
[c8ffe20b]937
[85c4ef0]938        CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
[cc79d97]939                TypedefMap oldNames = typedefNames;
940                scopeLevel += 1;
[0dd3a2f]941                CompoundStmt *ret = Mutator::mutate( compoundStmt );
[cc79d97]942                scopeLevel -= 1;
[0dd3a2f]943                std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
944                while ( i != compoundStmt->get_kids().end() ) {
[85c4ef0]945                        std::list< Statement * >::iterator next = i+1;
[0dd3a2f]946                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
947                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
948                                        delete *i;
949                                        compoundStmt->get_kids().erase( i );
950                                } // if
951                        } // if
952                        i = next;
953                } // while
954                typedefNames = oldNames;
955                return ret;
[a08ba92]956        }
[85c4ef0]957
958        // there may be typedefs nested within aggregates
959        // in order for everything to work properly, these
960        // should be removed as well
961        template<typename AggDecl>
962        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
963                std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
964                for ( ; it != aggDecl->get_members().end(); ) {
965                        std::list< Declaration * >::iterator next = it+1;
966                        if ( dynamic_cast< TypedefDecl * >( *it ) ) {
967                                delete *it;
968                                aggDecl->get_members().erase( it );
969                        } // if
970                        it = next;
971                }
972                return aggDecl;
973        }
974
975        Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
976                Mutator::mutate( structDecl );
977                return handleAggregate( structDecl );
978        }
979
980        Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
981                Mutator::mutate( unionDecl );
982                return handleAggregate( unionDecl );
983        }
984
985        Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
986                Mutator::mutate( enumDecl );
987                return handleAggregate( enumDecl );
988        }
989
990                Declaration *EliminateTypedef::mutate( ContextDecl * contextDecl ) {
991                Mutator::mutate( contextDecl );
992                return handleAggregate( contextDecl );
993        }
994
[51b7345]995} // namespace SymTab
[0dd3a2f]996
997// Local Variables: //
998// tab-width: 4 //
999// mode: c++ //
1000// compile-command: "make install" //
1001// End: //
Note: See TracBrowser for help on using the repository browser.