source: src/SymTab/Validate.cc @ ea6332d

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 ea6332d was d180746, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Big header cleaning pass - commit 2

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