source: translator/SymTab/Validate.cc @ 42dcae7

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 42dcae7 was 42dcae7, checked in by Peter A. Buhr <pabuhr@…>, 9 years ago

re-inserted remove and reorder hoisted aggregate, fixed example programs

  • Property mode set to 100644
File size: 28.8 KB
Line 
1/*
2  The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
3  as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
4  complete, including:
5
6  - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
7    union.
8
9  - All enumeration constants have type EnumInstType.
10
11  - The type "void" never occurs in lists of function parameter or return types; neither do tuple types.  A function
12    taking no arguments has no argument types, and tuples are flattened.
13
14  - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
15    by the particular set of type arguments.
16
17  - Every declaration is assigned a unique id.
18
19  - No typedef declarations or instances exist; the actual type is substituted for each instance.
20
21  - Each type, struct, and union definition is followed by an appropriate assignment operator.
22
23  - Each use of a struct or union is connected to a complete definition of that struct or union, even if that definition
24    occurs later in the input.
25*/
26
27#include <list>
28#include <iterator>
29#include "Validate.h"
30#include "SynTree/Visitor.h"
31#include "SynTree/Mutator.h"
32#include "SynTree/Type.h"
33#include "SynTree/Statement.h"
34#include "Indexer.h"
35#include "SynTree/TypeSubstitution.h"
36#include "FixFunction.h"
37#include "ImplementationType.h"
38#include "utility.h"
39#include "UniqueName.h"
40#include "AddVisit.h"
41
42
43#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
44
45namespace SymTab {
46    class HoistStruct : public Visitor {
47      public:
48        static void hoistStruct( std::list< Declaration * > &translationUnit );
49 
50        std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
51 
52        virtual void visit( StructDecl *aggregateDecl );
53        virtual void visit( UnionDecl *aggregateDecl );
54
55        virtual void visit( CompoundStmt *compoundStmt );
56        virtual void visit( IfStmt *ifStmt );
57        virtual void visit( WhileStmt *whileStmt );
58        virtual void visit( ForStmt *forStmt );
59        virtual void visit( SwitchStmt *switchStmt );
60        virtual void visit( ChooseStmt *chooseStmt );
61        virtual void visit( CaseStmt *caseStmt );
62        virtual void visit( CatchStmt *catchStmt );
63      private:
64        HoistStruct();
65
66        template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
67
68        std::list< Declaration * > declsToAdd;
69        bool inStruct;
70    };
71
72    class Pass1 : public Visitor {
73        typedef Visitor Parent;
74        virtual void visit( EnumDecl *aggregateDecl );
75        virtual void visit( FunctionType *func );
76    };
77 
78    class Pass2 : public Indexer {
79        typedef Indexer Parent;
80      public:
81        Pass2( bool doDebug, const Indexer *indexer );
82      private:
83        virtual void visit( StructInstType *structInst );
84        virtual void visit( UnionInstType *unionInst );
85        virtual void visit( ContextInstType *contextInst );
86        virtual void visit( StructDecl *structDecl );
87        virtual void visit( UnionDecl *unionDecl );
88        virtual void visit( TypeInstType *typeInst );
89
90        const Indexer *indexer;
91 
92        typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
93        typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
94        ForwardStructsType forwardStructs;
95        ForwardUnionsType forwardUnions;
96    };
97
98    class Pass3 : public Indexer {
99        typedef Indexer Parent;
100      public:
101        Pass3( const Indexer *indexer );
102      private:
103        virtual void visit( ObjectDecl *object );
104        virtual void visit( FunctionDecl *func );
105
106        const Indexer *indexer;
107    };
108
109    class AddStructAssignment : public Visitor {
110      public:
111        static void addStructAssignment( std::list< Declaration * > &translationUnit );
112
113        std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
114 
115        virtual void visit( StructDecl *structDecl );
116        virtual void visit( UnionDecl *structDecl );
117        virtual void visit( TypeDecl *typeDecl );
118        virtual void visit( ContextDecl *ctxDecl );
119        virtual void visit( FunctionDecl *functionDecl );
120
121        virtual void visit( FunctionType *ftype );
122        virtual void visit( PointerType *ftype );
123 
124        virtual void visit( CompoundStmt *compoundStmt );
125        virtual void visit( IfStmt *ifStmt );
126        virtual void visit( WhileStmt *whileStmt );
127        virtual void visit( ForStmt *forStmt );
128        virtual void visit( SwitchStmt *switchStmt );
129        virtual void visit( ChooseStmt *chooseStmt );
130        virtual void visit( CaseStmt *caseStmt );
131        virtual void visit( CatchStmt *catchStmt );
132
133        AddStructAssignment() : functionNesting( 0 ) {}
134      private:
135        template< typename StmtClass > void visitStatement( StmtClass *stmt );
136 
137        std::list< Declaration * > declsToAdd;
138        std::set< std::string > structsDone;
139        unsigned int functionNesting;                   // current level of nested functions
140    };
141
142    class EliminateTypedef : public Mutator {
143      public:
144        static void eliminateTypedef( std::list< Declaration * > &translationUnit );
145      private:
146        virtual Declaration *mutate( TypedefDecl *typeDecl );
147        virtual TypeDecl *mutate( TypeDecl *typeDecl );
148        virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
149        virtual ObjectDecl *mutate( ObjectDecl *objDecl );
150        virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
151        virtual Type *mutate( TypeInstType *aggregateUseType );
152        virtual Expression *mutate( CastExpr *castExpr );
153 
154        std::map< std::string, TypedefDecl * > typedefNames;
155    };
156
157    void validate( std::list< Declaration * > &translationUnit, bool doDebug, const Indexer *indexer ) {
158        Pass1 pass1;
159        Pass2 pass2( doDebug, indexer );
160        Pass3 pass3( indexer );
161        EliminateTypedef::eliminateTypedef( translationUnit );
162        HoistStruct::hoistStruct( translationUnit );
163        acceptAll( translationUnit, pass1 );
164        acceptAll( translationUnit, pass2 );
165        AddStructAssignment::addStructAssignment( translationUnit );
166        acceptAll( translationUnit, pass3 );
167    }
168
169    void validateType( Type *type, const Indexer *indexer ) {
170        Pass1 pass1;
171        Pass2 pass2( false, indexer );
172        Pass3 pass3( indexer );
173        type->accept( pass1 );
174        type->accept( pass2 );
175        type->accept( pass3 );
176    }
177
178    template< typename Visitor >
179    void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor, bool addBefore ) {
180        std::list< Declaration * >::iterator i = translationUnit.begin();
181        while ( i != translationUnit.end() ) {
182            (*i)->accept( visitor );
183            std::list< Declaration * >::iterator next = i;
184            next++;
185            if ( ! visitor.get_declsToAdd().empty() ) {
186                translationUnit.splice( addBefore ? i : next, visitor.get_declsToAdd() );
187            }
188            i = next;
189        }
190    }
191
192    void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
193        HoistStruct hoister;
194        acceptAndAdd( translationUnit, hoister, true );
195    }
196
197    HoistStruct::HoistStruct() :  inStruct( false ) {
198    }
199
200    void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
201        std::list< Declaration * >::iterator i = declList.begin();
202        while ( i != declList.end() ) {
203            std::list< Declaration * >::iterator next = i;
204            ++next;
205            if ( pred( *i ) ) {
206                if ( doDelete ) {
207                    delete *i;
208                }
209                declList.erase( i );
210            }
211            i = next;
212        }
213    }
214
215    bool isStructOrUnion( Declaration *decl ) {
216        return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
217    }
218
219    template< typename AggDecl >
220    void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
221        if ( inStruct ) {
222            // Add elements in stack order corresponding to nesting structure.
223            declsToAdd.push_front( aggregateDecl );
224            Visitor::visit( aggregateDecl );
225        } else {
226            inStruct = true;
227            Visitor::visit( aggregateDecl );
228            inStruct = false;
229        }
230        // Always remove the hoisted aggregate from the inner structure.
231        filter( aggregateDecl->get_members(), isStructOrUnion, false );
232    }
233
234    void HoistStruct::visit( StructDecl *aggregateDecl ) {
235        handleAggregate( aggregateDecl );
236    }
237
238    void HoistStruct::visit( UnionDecl *aggregateDecl ) {
239        handleAggregate( aggregateDecl );
240    }
241
242    void HoistStruct::visit( CompoundStmt *compoundStmt ) {
243        addVisit( compoundStmt, *this );
244    }
245
246    void HoistStruct::visit( IfStmt *ifStmt ) {
247        addVisit( ifStmt, *this );
248    }
249
250    void HoistStruct::visit( WhileStmt *whileStmt ) {
251        addVisit( whileStmt, *this );
252    }
253
254    void HoistStruct::visit( ForStmt *forStmt ) {
255        addVisit( forStmt, *this );
256    }
257
258    void HoistStruct::visit( SwitchStmt *switchStmt ) {
259        addVisit( switchStmt, *this );
260    }
261
262    void HoistStruct::visit( ChooseStmt *switchStmt ) {
263        addVisit( switchStmt, *this );
264    }
265
266    void HoistStruct::visit( CaseStmt *caseStmt ) {
267        addVisit( caseStmt, *this );
268    }
269
270    void HoistStruct::visit( CatchStmt *cathStmt ) {
271        addVisit( cathStmt, *this );
272    }
273
274    void Pass1::visit( EnumDecl *enumDecl ) {
275        // Set the type of each member of the enumeration to be EnumConstant
276 
277        for( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
278            ObjectDecl *obj = dynamic_cast< ObjectDecl * >( *i );
279            assert( obj );
280            obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false ), enumDecl->get_name() ) );
281        }
282        Parent::visit( enumDecl );
283    }
284
285    namespace {
286        template< typename DWTIterator >
287        void
288        fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func ) {
289            // the only case in which "void" is valid is where it is the only one in the list; then
290            // it should be removed entirely
291            // other fix ups are handled by the FixFunction class
292            if ( begin == end ) return;
293            FixFunction fixer;
294            DWTIterator i = begin;
295            *i = (*i )->acceptMutator( fixer );
296            if ( fixer.get_isVoid() ) {
297                DWTIterator j = i;
298                ++i;
299                func->get_parameters().erase( j );
300                if ( i != end ) { 
301                    throw SemanticError( "invalid type void in function type ", func );
302                }
303            } else {
304                ++i;
305                for( ; i != end; ++i ) {
306                    FixFunction fixer;
307                    *i = (*i )->acceptMutator( fixer );
308                    if ( fixer.get_isVoid() ) {
309                        throw SemanticError( "invalid type void in function type ", func );
310                    }
311                }
312            }
313        }
314    }
315
316    void Pass1::visit( FunctionType *func ) {
317        // Fix up parameters and return types
318        fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func );
319        fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func );
320        Visitor::visit( func );
321    }
322
323    Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
324        if ( other_indexer ) {
325            indexer = other_indexer;
326        } else {
327            indexer = this;
328        }
329    }
330
331    void Pass2::visit( StructInstType *structInst ) {
332        Parent::visit( structInst );
333        StructDecl *st = indexer->lookupStruct( structInst->get_name() );
334        // it's not a semantic error if the struct is not found, just an implicit forward declaration
335        if ( st ) {
336            assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
337            structInst->set_baseStruct( st );
338        }
339        if ( ! st || st->get_members().empty() ) {
340            // use of forward declaration
341            forwardStructs[ structInst->get_name() ].push_back( structInst );
342        }
343    }
344
345    void Pass2::visit( UnionInstType *unionInst ) {
346        Parent::visit( unionInst );
347        UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
348        // it's not a semantic error if the union is not found, just an implicit forward declaration
349        if ( un ) {
350            unionInst->set_baseUnion( un );
351        }
352        if ( ! un || un->get_members().empty() ) {
353            // use of forward declaration
354            forwardUnions[ unionInst->get_name() ].push_back( unionInst );
355        }
356    }
357
358    void Pass2::visit( ContextInstType *contextInst ) {
359        Parent::visit( contextInst );
360        ContextDecl *ctx = indexer->lookupContext( contextInst->get_name() );
361        if ( ! ctx ) {
362            throw SemanticError( "use of undeclared context " + contextInst->get_name() );
363        }
364        for( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
365            for( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
366                if ( ContextInstType *otherCtx = dynamic_cast< ContextInstType * >(*assert ) ) {
367                    cloneAll( otherCtx->get_members(), contextInst->get_members() );
368                } else {
369                    contextInst->get_members().push_back( (*assert )->clone() );
370                }
371            }
372        }
373        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() ) );
374    }
375
376    void Pass2::visit( StructDecl *structDecl ) {
377        if ( ! structDecl->get_members().empty() ) {
378            ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
379            if ( fwds != forwardStructs.end() ) {
380                for( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
381                    (*inst )->set_baseStruct( structDecl );
382                }
383                forwardStructs.erase( fwds );
384            }
385        }
386        Indexer::visit( structDecl );
387    }
388
389    void Pass2::visit( UnionDecl *unionDecl ) {
390        if ( ! unionDecl->get_members().empty() ) {
391            ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
392            if ( fwds != forwardUnions.end() ) {
393                for( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
394                    (*inst )->set_baseUnion( unionDecl );
395                }
396                forwardUnions.erase( fwds );
397            }
398        }
399        Indexer::visit( unionDecl );
400    }
401
402    void Pass2::visit( TypeInstType *typeInst ) {
403        if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
404            if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
405                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
406            }
407        }
408    }
409
410    Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
411        if ( other_indexer ) {
412            indexer = other_indexer;
413        } else {
414            indexer = this;
415        }
416    }
417
418    void forallFixer( Type *func ) {
419        // Fix up assertions
420        for( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
421            std::list< DeclarationWithType * > toBeDone, nextRound;
422            toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
423            while ( ! toBeDone.empty() ) {
424                for( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
425                    if ( ContextInstType *ctx = dynamic_cast< ContextInstType * >( (*assertion )->get_type() ) ) {
426                        for( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
427                            DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
428                            assert( dwt );
429                            nextRound.push_back( dwt->clone() );
430                        }
431                        delete ctx;
432                    } else {
433                        FixFunction fixer;
434                        *assertion = (*assertion )->acceptMutator( fixer );
435                        if ( fixer.get_isVoid() ) {
436                            throw SemanticError( "invalid type void in assertion of function ", func );
437                        }
438                        (*type )->get_assertions().push_back( *assertion );
439                    }
440                }
441                toBeDone.clear();
442                toBeDone.splice( toBeDone.end(), nextRound );
443            }
444        }
445    }
446
447    void Pass3::visit( ObjectDecl *object ) {
448        forallFixer( object->get_type() );
449        if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
450            forallFixer( pointer->get_base() );
451        }
452        Parent::visit( object );
453        object->fixUniqueId();
454    }
455
456    void Pass3::visit( FunctionDecl *func ) {
457        forallFixer( func->get_type() );
458        Parent::visit( func );
459        func->fixUniqueId();
460    }
461
462    static const std::list< std::string > noLabels;
463
464    void AddStructAssignment::addStructAssignment( std::list< Declaration * > &translationUnit ) {
465        AddStructAssignment visitor;
466        acceptAndAdd( translationUnit, visitor, false );
467    }
468
469    template< typename OutputIterator >
470    void makeScalarAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, OutputIterator out ) {
471        ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member ); // PAB: unnamed bit fields are not copied
472        if ( obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL ) return;
473
474        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
475 
476        UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
477        derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
478 
479        // do something special for unnamed members
480        Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
481        assignExpr->get_args().push_back( dstselect );
482 
483        Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
484        assignExpr->get_args().push_back( srcselect );
485 
486        *out++ = new ExprStmt( noLabels, assignExpr );
487    }
488
489    template< typename OutputIterator >
490    void makeArrayAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, ArrayType *array, OutputIterator out ) {
491        static UniqueName indexName( "_index" );
492 
493        // for a flexible array member nothing is done -- user must define own assignment
494        if ( ! array->get_dimension() ) return;
495 
496        ObjectDecl *index = new ObjectDecl( indexName.newName(), Declaration::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), 0 );
497        *out++ = new DeclStmt( noLabels, index );
498 
499        UntypedExpr *init = new UntypedExpr( new NameExpr( "?=?" ) );
500        init->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
501        init->get_args().push_back( new NameExpr( "0" ) );
502        Statement *initStmt = new ExprStmt( noLabels, init );
503 
504        UntypedExpr *cond = new UntypedExpr( new NameExpr( "?<?" ) );
505        cond->get_args().push_back( new VariableExpr( index ) );
506        cond->get_args().push_back( array->get_dimension()->clone() );
507 
508        UntypedExpr *inc = new UntypedExpr( new NameExpr( "++?" ) );
509        inc->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
510 
511        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
512 
513        UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
514        derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
515 
516        Expression *dstselect = new MemberExpr( member, derefExpr );
517        UntypedExpr *dstIndex = new UntypedExpr( new NameExpr( "?+?" ) );
518        dstIndex->get_args().push_back( dstselect );
519        dstIndex->get_args().push_back( new VariableExpr( index ) );
520        assignExpr->get_args().push_back( dstIndex );
521 
522        Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
523        UntypedExpr *srcIndex = new UntypedExpr( new NameExpr( "?[?]" ) );
524        srcIndex->get_args().push_back( srcselect );
525        srcIndex->get_args().push_back( new VariableExpr( index ) );
526        assignExpr->get_args().push_back( srcIndex );
527 
528        *out++ = new ForStmt( noLabels, initStmt, cond, inc, new ExprStmt( noLabels, assignExpr ) );
529    }
530
531    Declaration *makeStructAssignment( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting ) {
532        FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
533 
534        ObjectDecl *returnVal = new ObjectDecl( "", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
535        assignType->get_returnVals().push_back( returnVal );
536 
537        ObjectDecl *dstParam = new ObjectDecl( "_dst", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType->clone() ), 0 );
538        assignType->get_parameters().push_back( dstParam );
539 
540        ObjectDecl *srcParam = new ObjectDecl( "_src", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType, 0 );
541        assignType->get_parameters().push_back( srcParam );
542
543        // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
544        // because each unit generates copies of the default routines for each aggregate.
545        FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? Declaration::NoStorageClass : Declaration::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true );
546        assignDecl->fixUniqueId();
547 
548        for( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) {
549            if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) {
550                if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) {
551                    makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
552                } else {
553                    makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
554                }
555            }
556        }
557        assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
558 
559        return assignDecl;
560    }
561
562    Declaration *makeUnionAssignment( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting ) {
563        FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
564 
565        ObjectDecl *returnVal = new ObjectDecl( "", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
566        assignType->get_returnVals().push_back( returnVal );
567 
568        ObjectDecl *dstParam = new ObjectDecl( "_dst", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType->clone() ), 0 );
569        assignType->get_parameters().push_back( dstParam );
570 
571        ObjectDecl *srcParam = new ObjectDecl( "_src", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType, 0 );
572        assignType->get_parameters().push_back( srcParam );
573 
574        // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
575        // because each unit generates copies of the default routines for each aggregate.
576        FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? Declaration::NoStorageClass : Declaration::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true );
577        assignDecl->fixUniqueId();
578 
579        UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
580        copy->get_args().push_back( new VariableExpr( dstParam ) );
581        copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
582        copy->get_args().push_back( new SizeofExpr( refType->clone() ) );
583
584        assignDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, copy ) );
585        assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
586 
587        return assignDecl;
588    }
589
590    void AddStructAssignment::visit( StructDecl *structDecl ) {
591        if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
592            StructInstType *structInst = new StructInstType( Type::Qualifiers(), structDecl->get_name() );
593            structInst->set_baseStruct( structDecl );
594            declsToAdd.push_back( makeStructAssignment( structDecl, structInst, functionNesting ) );
595            structsDone.insert( structDecl->get_name() );
596        }
597    }
598
599    void AddStructAssignment::visit( UnionDecl *unionDecl ) {
600        if ( ! unionDecl->get_members().empty() ) {
601            UnionInstType *unionInst = new UnionInstType( Type::Qualifiers(), unionDecl->get_name() );
602            unionInst->set_baseUnion( unionDecl );
603            declsToAdd.push_back( makeUnionAssignment( unionDecl, unionInst, functionNesting ) );
604        }
605    }
606
607    void AddStructAssignment::visit( TypeDecl *typeDecl ) {
608        CompoundStmt *stmts = 0;
609        TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
610        typeInst->set_baseType( typeDecl );
611        ObjectDecl *src = new ObjectDecl( "_src", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
612        ObjectDecl *dst = new ObjectDecl( "_dst", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
613        if ( typeDecl->get_base() ) {
614            stmts = new CompoundStmt( std::list< Label >() );
615            UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
616            assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
617            assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
618            stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
619        }
620        FunctionType *type = new FunctionType( Type::Qualifiers(), false );
621        type->get_returnVals().push_back( new ObjectDecl( "", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
622        type->get_parameters().push_back( dst );
623        type->get_parameters().push_back( src );
624        FunctionDecl *func = new FunctionDecl( "?=?", Declaration::NoStorageClass, LinkageSpec::AutoGen, type, stmts, false );
625        declsToAdd.push_back( func );
626    }
627
628    void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
629        if ( ! declsToAdd.empty() ) {
630            for( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
631                statements.insert( i, new DeclStmt( noLabels, *decl ) );
632            }
633            declsToAdd.clear();
634        }
635    }
636
637    void AddStructAssignment::visit( FunctionType *) {
638        // ensure that we don't add assignment ops for types defined
639        // as part of the function
640    }
641
642    void AddStructAssignment::visit( PointerType *) {
643        // ensure that we don't add assignment ops for types defined
644        // as part of the pointer
645    }
646
647    void AddStructAssignment::visit( ContextDecl *) {
648        // ensure that we don't add assignment ops for types defined
649        // as part of the context
650    }
651
652    template< typename StmtClass >
653    inline void AddStructAssignment::visitStatement( StmtClass *stmt ) {
654        std::set< std::string > oldStructs = structsDone;
655        addVisit( stmt, *this );
656        structsDone = oldStructs;
657    }
658
659    void AddStructAssignment::visit( FunctionDecl *functionDecl ) {
660        maybeAccept( functionDecl->get_functionType(), *this );
661        acceptAll( functionDecl->get_oldDecls(), *this );
662        functionNesting += 1;
663        maybeAccept( functionDecl->get_statements(), *this );
664        functionNesting -= 1;
665    }
666
667    void AddStructAssignment::visit( CompoundStmt *compoundStmt ) {
668        visitStatement( compoundStmt );
669    }
670
671    void AddStructAssignment::visit( IfStmt *ifStmt ) {
672        visitStatement( ifStmt );
673    }
674
675    void AddStructAssignment::visit( WhileStmt *whileStmt ) {
676        visitStatement( whileStmt );
677    }
678
679    void AddStructAssignment::visit( ForStmt *forStmt ) {
680        visitStatement( forStmt );
681    }
682
683    void AddStructAssignment::visit( SwitchStmt *switchStmt ) {
684        visitStatement( switchStmt );
685    }
686
687    void AddStructAssignment::visit( ChooseStmt *switchStmt ) {
688        visitStatement( switchStmt );
689    }
690
691    void AddStructAssignment::visit( CaseStmt *caseStmt ) {
692        visitStatement( caseStmt );
693    }
694
695    void AddStructAssignment::visit( CatchStmt *cathStmt ) {
696        visitStatement( cathStmt );
697    }
698
699    bool isTypedef( Declaration *decl ) {
700        return dynamic_cast< TypedefDecl * >( decl );
701    }
702
703    void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
704        EliminateTypedef eliminator;
705        mutateAll( translationUnit, eliminator );
706        filter( translationUnit, isTypedef, true );
707    }
708
709    Type *EliminateTypedef::mutate( TypeInstType *typeInst ) {
710        std::map< std::string, TypedefDecl * >::const_iterator def = typedefNames.find( typeInst->get_name() );
711        if ( def != typedefNames.end() ) {
712            Type *ret = def->second->get_base()->clone();
713            ret->get_qualifiers() += typeInst->get_qualifiers();
714            delete typeInst;
715            return ret;
716        }
717        return typeInst;
718    }
719
720    Declaration *EliminateTypedef::mutate( TypedefDecl *tyDecl ) {
721        Declaration *ret = Mutator::mutate( tyDecl );
722        typedefNames[ tyDecl->get_name() ] = tyDecl;
723        if ( AggregateDecl *aggDecl = dynamic_cast< AggregateDecl * >( tyDecl->get_base() ) ) {
724            tyDecl->set_base( 0 );
725            delete tyDecl;
726            return aggDecl;
727        } else {
728            return ret;
729        }
730    }
731
732    TypeDecl *EliminateTypedef::mutate( TypeDecl *typeDecl ) {
733        std::map< std::string, TypedefDecl * >::iterator i = typedefNames.find( typeDecl->get_name() );
734        if ( i != typedefNames.end() ) {
735            typedefNames.erase( i ) ;
736        }
737        return typeDecl;
738    }
739
740    DeclarationWithType *EliminateTypedef::mutate( FunctionDecl *funcDecl ) {
741        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
742        DeclarationWithType *ret = Mutator::mutate( funcDecl );
743        typedefNames = oldNames;
744        return ret;
745    }
746
747    ObjectDecl *EliminateTypedef::mutate( ObjectDecl *objDecl ) {
748        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
749        ObjectDecl *ret = Mutator::mutate( objDecl );
750        typedefNames = oldNames;
751        return ret;
752    }
753
754    Expression *EliminateTypedef::mutate( CastExpr *castExpr ) {
755        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
756        Expression *ret = Mutator::mutate( castExpr );
757        typedefNames = oldNames;
758        return ret;
759    }
760
761    CompoundStmt *EliminateTypedef::mutate( CompoundStmt *compoundStmt ) {
762        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
763        CompoundStmt *ret = Mutator::mutate( compoundStmt );
764        std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
765        while ( i != compoundStmt->get_kids().end() ) {
766            std::list< Statement * >::iterator next = i;
767            ++next;
768            if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
769                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
770                    delete *i;
771                    compoundStmt->get_kids().erase( i );
772                }
773            }
774            i = next;
775        }
776        typedefNames = oldNames;
777        return ret;
778    }
779} // namespace SymTab
Note: See TracBrowser for help on using the repository browser.