source: src/SymTab/Validate.cc @ 1869adf

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

fix label name in label address expression

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