source: src/SymTab/Validate.cc @ 1c273d0

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 1c273d0 was 06edda0, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

convert EnumAndPointerDecayPass? and ForallPointerDecay? to PassVisitor?

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