source: src/SymTab/Validate.cc @ 8804701

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 8804701 was 0a86a30, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

fix dropping attributes in function pointer decay and function typedefs

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