source: src/SymTab/Validate.cc @ 4934ea3

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since 4934ea3 was 4934ea3, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Resolve array dimensions early to correctly evaluate whether a type is VLA

  • Property mode set to 100644
File size: 50.5 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 28 13:47:23 2017
13// Update Count     : 359
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 "CodeGen/CodeGenerator.h"     // for genName
49#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
50#include "ControlStruct/Mutate.h"      // for ForExprMutator
51#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
52#include "Common/ScopedMap.h"          // for ScopedMap
53#include "Common/SemanticError.h"      // for SemanticError
54#include "Common/UniqueName.h"         // for UniqueName
55#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
56#include "Concurrency/Keywords.h"      // for applyKeywords
57#include "FixFunction.h"               // for FixFunction
58#include "Indexer.h"                   // for Indexer
59#include "InitTweak/GenInit.h"         // for fixReturnStatements
60#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
61#include "Parser/LinkageSpec.h"        // for C
62#include "ResolvExpr/typeops.h"        // for typesCompatible
63#include "ResolvExpr/Resolver.h"       // for findSingleExpression
64#include "SymTab/Autogen.h"            // for SizeType
65#include "SynTree/Attribute.h"         // for noAttributes, Attribute
66#include "SynTree/Constant.h"          // for Constant
67#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
68#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
69#include "SynTree/Initializer.h"       // for ListInit, Initializer
70#include "SynTree/Label.h"             // for operator==, Label
71#include "SynTree/Mutator.h"           // for Mutator
72#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
73#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
74#include "SynTree/Visitor.h"           // for Visitor
75
76class CompoundStmt;
77class ReturnStmt;
78class SwitchStmt;
79
80#define debugPrint( x ) if ( doDebug ) x
81
82namespace SymTab {
83        /// hoists declarations that are difficult to hoist while parsing
84        struct HoistTypeDecls final : public WithDeclsToAdd {
85                void previsit( SizeofExpr * );
86                void previsit( AlignofExpr * );
87                void previsit( UntypedOffsetofExpr * );
88                void previsit( CompoundLiteralExpr * );
89                void handleType( Type * );
90        };
91
92        struct FixQualifiedTypes final : public WithIndexer {
93                Type * postmutate( QualifiedType * );
94        };
95
96        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
97                /// Flattens nested struct types
98                static void hoistStruct( std::list< Declaration * > &translationUnit );
99
100                void previsit( StructDecl * aggregateDecl );
101                void previsit( UnionDecl * aggregateDecl );
102                void previsit( StaticAssertDecl * assertDecl );
103                void previsit( StructInstType * type );
104                void previsit( UnionInstType * type );
105                void previsit( EnumInstType * type );
106
107          private:
108                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
109
110                AggregateDecl * parentAggr = nullptr;
111        };
112
113        /// Fix return types so that every function returns exactly one value
114        struct ReturnTypeFixer {
115                static void fix( std::list< Declaration * > &translationUnit );
116
117                void postvisit( FunctionDecl * functionDecl );
118                void postvisit( FunctionType * ftype );
119        };
120
121        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
122        struct EnumAndPointerDecay {
123                void previsit( EnumDecl *aggregateDecl );
124                void previsit( FunctionType *func );
125        };
126
127        /// Associates forward declarations of aggregates with their definitions
128        struct LinkReferenceToTypes final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes>, public WithShortCircuiting {
129                LinkReferenceToTypes( const Indexer *indexer );
130                void postvisit( TypeInstType *typeInst );
131
132                void postvisit( EnumInstType *enumInst );
133                void postvisit( StructInstType *structInst );
134                void postvisit( UnionInstType *unionInst );
135                void postvisit( TraitInstType *traitInst );
136                void previsit( QualifiedType * qualType );
137                void postvisit( QualifiedType * qualType );
138
139                void postvisit( EnumDecl *enumDecl );
140                void postvisit( StructDecl *structDecl );
141                void postvisit( UnionDecl *unionDecl );
142                void postvisit( TraitDecl * traitDecl );
143
144                void previsit( StructDecl *structDecl );
145                void previsit( UnionDecl *unionDecl );
146
147                void renameGenericParams( std::list< TypeDecl * > & params );
148
149          private:
150                const Indexer *local_indexer;
151
152                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
153                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
154                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
155                ForwardEnumsType forwardEnums;
156                ForwardStructsType forwardStructs;
157                ForwardUnionsType forwardUnions;
158                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
159                bool inGeneric = false;
160        };
161
162        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
163        struct ForallPointerDecay final {
164                void previsit( ObjectDecl * object );
165                void previsit( FunctionDecl * func );
166                void previsit( FunctionType * ftype );
167                void previsit( StructDecl * aggrDecl );
168                void previsit( UnionDecl * aggrDecl );
169        };
170
171        struct ReturnChecker : public WithGuards {
172                /// Checks that return statements return nothing if their return type is void
173                /// and return something if the return type is non-void.
174                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
175
176                void previsit( FunctionDecl * functionDecl );
177                void previsit( ReturnStmt * returnStmt );
178
179                typedef std::list< DeclarationWithType * > ReturnVals;
180                ReturnVals returnVals;
181        };
182
183        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
184                ReplaceTypedef() : scopeLevel( 0 ) {}
185                /// Replaces typedefs by forward declarations
186                static void replaceTypedef( std::list< Declaration * > &translationUnit );
187
188                void premutate( QualifiedType * );
189                Type * postmutate( QualifiedType * qualType );
190                Type * postmutate( TypeInstType * aggregateUseType );
191                Declaration * postmutate( TypedefDecl * typeDecl );
192                void premutate( TypeDecl * typeDecl );
193                void premutate( FunctionDecl * funcDecl );
194                void premutate( ObjectDecl * objDecl );
195                DeclarationWithType * postmutate( ObjectDecl * objDecl );
196
197                void premutate( CastExpr * castExpr );
198
199                void premutate( CompoundStmt * compoundStmt );
200
201                void premutate( StructDecl * structDecl );
202                void premutate( UnionDecl * unionDecl );
203                void premutate( EnumDecl * enumDecl );
204                void premutate( TraitDecl * );
205
206                void premutate( FunctionType * ftype );
207
208          private:
209                template<typename AggDecl>
210                void addImplicitTypedef( AggDecl * aggDecl );
211                template< typename AggDecl >
212                void handleAggregate( AggDecl * aggr );
213
214                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
215                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
216                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
217                TypedefMap typedefNames;
218                TypeDeclMap typedeclNames;
219                int scopeLevel;
220                bool inFunctionType = false;
221        };
222
223        struct EliminateTypedef {
224                /// removes TypedefDecls from the AST
225                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
226
227                template<typename AggDecl>
228                void handleAggregate( AggDecl *aggregateDecl );
229
230                void previsit( StructDecl * aggregateDecl );
231                void previsit( UnionDecl * aggregateDecl );
232                void previsit( CompoundStmt * compoundStmt );
233        };
234
235        struct VerifyCtorDtorAssign {
236                /// ensure that constructors, destructors, and assignment have at least one
237                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
238                /// return values.
239                static void verify( std::list< Declaration * > &translationUnit );
240
241                void previsit( FunctionDecl *funcDecl );
242        };
243
244        /// ensure that generic types have the correct number of type arguments
245        struct ValidateGenericParameters {
246                void previsit( StructInstType * inst );
247                void previsit( UnionInstType * inst );
248        };
249
250        struct ArrayLength : public WithIndexer {
251                /// for array types without an explicit length, compute the length and store it so that it
252                /// is known to the rest of the phases. For example,
253                ///   int x[] = { 1, 2, 3 };
254                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
255                /// here x and y are known at compile-time to have length 3, so change this into
256                ///   int x[3] = { 1, 2, 3 };
257                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
258                static void computeLength( std::list< Declaration * > & translationUnit );
259
260                void previsit( ObjectDecl * objDecl );
261                void previsit( ArrayType * arrayType );
262        };
263
264        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
265                Type::StorageClasses storageClasses;
266
267                void premutate( ObjectDecl *objectDecl );
268                Expression * postmutate( CompoundLiteralExpr *compLitExpr );
269        };
270
271        struct LabelAddressFixer final : public WithGuards {
272                std::set< Label > labels;
273
274                void premutate( FunctionDecl * funcDecl );
275                Expression * postmutate( AddressExpr * addrExpr );
276        };
277
278        FunctionDecl * dereferenceOperator = nullptr;
279        struct FindSpecialDeclarations final {
280                void previsit( FunctionDecl * funcDecl );
281        };
282
283        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
284                PassVisitor<EnumAndPointerDecay> epc;
285                PassVisitor<LinkReferenceToTypes> lrt( nullptr );
286                PassVisitor<ForallPointerDecay> fpd;
287                PassVisitor<CompoundLiteral> compoundliteral;
288                PassVisitor<ValidateGenericParameters> genericParams;
289                PassVisitor<FindSpecialDeclarations> finder;
290                PassVisitor<LabelAddressFixer> labelAddrFixer;
291                PassVisitor<HoistTypeDecls> hoistDecls;
292                PassVisitor<FixQualifiedTypes> fixQual;
293
294                acceptAll( translationUnit, hoistDecls );
295                ReplaceTypedef::replaceTypedef( translationUnit );
296                ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
297                acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
298                acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
299                mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes, because aggregate members are accessed
300                HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
301                EliminateTypedef::eliminateTypedef( translationUnit ); //
302                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes
303                VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
304                ReturnChecker::checkFunctionReturns( translationUnit );
305                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
306                Concurrency::applyKeywords( translationUnit );
307                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
308                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
309                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
310                Concurrency::implementMutexFuncs( translationUnit );
311                Concurrency::implementThreadStarter( translationUnit );
312                mutateAll( translationUnit, compoundliteral );
313                ArrayLength::computeLength( translationUnit );
314                acceptAll( translationUnit, finder ); // xxx - remove this pass soon
315                mutateAll( translationUnit, labelAddrFixer );
316        }
317
318        void validateType( Type *type, const Indexer *indexer ) {
319                PassVisitor<EnumAndPointerDecay> epc;
320                PassVisitor<LinkReferenceToTypes> lrt( indexer );
321                PassVisitor<ForallPointerDecay> fpd;
322                type->accept( epc );
323                type->accept( lrt );
324                type->accept( fpd );
325        }
326
327
328        void HoistTypeDecls::handleType( Type * type ) {
329                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
330                AggregateDecl * aggr = nullptr;
331                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
332                        aggr = inst->baseStruct;
333                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
334                        aggr = inst->baseUnion;
335                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
336                        aggr = inst->baseEnum;
337                }
338                if ( aggr && aggr->body ) {
339                        declsToAddBefore.push_front( aggr );
340                }
341        }
342
343        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
344                handleType( expr->type );
345        }
346
347        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
348                handleType( expr->type );
349        }
350
351        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
352                handleType( expr->type );
353        }
354
355        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
356                handleType( expr->result );
357        }
358
359
360        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
361                Type * parent = qualType->parent;
362                Type * child = qualType->child;
363                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
364                        // .T => lookup T at global scope
365                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
366                                auto td = indexer.globalLookupType( inst->name );
367                                if ( ! td ) {
368                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
369                                }
370                                auto base = td->base;
371                                assert( base );
372                                Type * ret = base->clone();
373                                ret->get_qualifiers() = qualType->get_qualifiers();
374                                return ret;
375                        } else {
376                                // .T => T is not a type name
377                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
378                        }
379                } else {
380                        // S.T => S must be an aggregate type, find the declaration for T in S.
381                        AggregateDecl * aggr = nullptr;
382                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
383                                aggr = inst->baseStruct;
384                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
385                                aggr = inst->baseUnion;
386                        } else {
387                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
388                        }
389                        assert( aggr ); // TODO: need to handle forward declarations
390                        for ( Declaration * member : aggr->members ) {
391                                if ( StructInstType * inst = dynamic_cast< StructInstType * >( child ) ) {
392                                        if ( StructDecl * aggr = dynamic_cast< StructDecl * >( member ) ) {
393                                                if ( aggr->name == inst->name ) {
394                                                        // TODO: is this case, and other non-TypeInstType cases, necessary?
395                                                        return new StructInstType( qualType->get_qualifiers(), aggr );
396                                                }
397                                        }
398                                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( child ) ) {
399                                        if ( UnionDecl * aggr = dynamic_cast< UnionDecl * > ( member ) ) {
400                                                if ( aggr->name == inst->name ) {
401                                                        return new UnionInstType( qualType->get_qualifiers(), aggr );
402                                                }
403                                        }
404                                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( child ) ) {
405                                        if ( EnumDecl * aggr = dynamic_cast< EnumDecl * > ( member ) ) {
406                                                if ( aggr->name == inst->name ) {
407                                                        return new EnumInstType( qualType->get_qualifiers(), aggr );
408                                                }
409                                        }
410                                } else if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
411                                        // name on the right is a typedef
412                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
413                                                if ( aggr->name == inst->name ) {
414                                                        assert( aggr->base );
415                                                        Type * ret = aggr->base->clone();
416                                                        ret->get_qualifiers() = qualType->get_qualifiers();
417                                                        return ret;
418                                                }
419                                        }
420                                } else {
421                                        // S.T - S is not an aggregate => error
422                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
423                                }
424                        }
425                        // failed to find a satisfying definition of type
426                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
427                }
428
429                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
430        }
431
432
433        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
434                PassVisitor<HoistStruct> hoister;
435                acceptAll( translationUnit, hoister );
436        }
437
438        bool shouldHoist( Declaration *decl ) {
439                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
440        }
441
442        namespace {
443                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
444                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
445                        ss << "__" << aggr->name;
446                }
447
448                // mangle nested type names using entire parent chain
449                std::string qualifiedName( AggregateDecl * aggr ) {
450                        std::ostringstream ss;
451                        qualifiedName( aggr, ss );
452                        return ss.str();
453                }
454        }
455
456        template< typename AggDecl >
457        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
458                if ( parentAggr ) {
459                        aggregateDecl->parent = parentAggr;
460                        aggregateDecl->name = qualifiedName( aggregateDecl );
461                        // Add elements in stack order corresponding to nesting structure.
462                        declsToAddBefore.push_front( aggregateDecl );
463                } else {
464                        GuardValue( parentAggr );
465                        parentAggr = aggregateDecl;
466                } // if
467                // Always remove the hoisted aggregate from the inner structure.
468                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
469        }
470
471        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
472                if ( parentAggr ) {
473                        declsToAddBefore.push_back( assertDecl );
474                }
475        }
476
477        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
478                handleAggregate( aggregateDecl );
479        }
480
481        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
482                handleAggregate( aggregateDecl );
483        }
484
485        void HoistStruct::previsit( StructInstType * type ) {
486                // need to reset type name after expanding to qualified name
487                assert( type->baseStruct );
488                type->name = type->baseStruct->name;
489        }
490
491        void HoistStruct::previsit( UnionInstType * type ) {
492                assert( type->baseUnion );
493                type->name = type->baseUnion->name;
494        }
495
496        void HoistStruct::previsit( EnumInstType * type ) {
497                assert( type->baseEnum );
498                type->name = type->baseEnum->name;
499        }
500
501
502        bool isTypedef( Declaration *decl ) {
503                return dynamic_cast< TypedefDecl * >( decl );
504        }
505
506        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
507                PassVisitor<EliminateTypedef> eliminator;
508                acceptAll( translationUnit, eliminator );
509                filter( translationUnit, isTypedef, true );
510        }
511
512        template< typename AggDecl >
513        void EliminateTypedef::handleAggregate( AggDecl *aggregateDecl ) {
514                filter( aggregateDecl->members, isTypedef, true );
515        }
516
517        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
518                handleAggregate( aggregateDecl );
519        }
520
521        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
522                handleAggregate( aggregateDecl );
523        }
524
525        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
526                // remove and delete decl stmts
527                filter( compoundStmt->kids, [](Statement * stmt) {
528                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
529                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
530                                        return true;
531                                } // if
532                        } // if
533                        return false;
534                }, true);
535        }
536
537        void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
538                // Set the type of each member of the enumeration to be EnumConstant
539                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
540                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
541                        assert( obj );
542                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
543                } // for
544        }
545
546        namespace {
547                template< typename DWTList >
548                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
549                        auto nvals = dwts.size();
550                        bool containsVoid = false;
551                        for ( auto & dwt : dwts ) {
552                                // fix each DWT and record whether a void was found
553                                containsVoid |= fixFunction( dwt );
554                        }
555
556                        // the only case in which "void" is valid is where it is the only one in the list
557                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
558                                SemanticError( func, "invalid type void in function type " );
559                        }
560
561                        // one void is the only thing in the list; remove it.
562                        if ( containsVoid ) {
563                                delete dwts.front();
564                                dwts.clear();
565                        }
566                }
567        }
568
569        void EnumAndPointerDecay::previsit( FunctionType *func ) {
570                // Fix up parameters and return types
571                fixFunctionList( func->parameters, func->isVarArgs, func );
572                fixFunctionList( func->returnVals, false, func );
573        }
574
575        LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
576                if ( other_indexer ) {
577                        local_indexer = other_indexer;
578                } else {
579                        local_indexer = &indexer;
580                } // if
581        }
582
583        void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
584                EnumDecl *st = local_indexer->lookupEnum( enumInst->name );
585                // it's not a semantic error if the enum is not found, just an implicit forward declaration
586                if ( st ) {
587                        enumInst->baseEnum = st;
588                } // if
589                if ( ! st || ! st->body ) {
590                        // use of forward declaration
591                        forwardEnums[ enumInst->name ].push_back( enumInst );
592                } // if
593        }
594
595        void checkGenericParameters( ReferenceToType * inst ) {
596                for ( Expression * param : inst->parameters ) {
597                        if ( ! dynamic_cast< TypeExpr * >( param ) ) {
598                                SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
599                        }
600                }
601        }
602
603        void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
604                StructDecl *st = local_indexer->lookupStruct( structInst->name );
605                // it's not a semantic error if the struct is not found, just an implicit forward declaration
606                if ( st ) {
607                        structInst->baseStruct = st;
608                } // if
609                if ( ! st || ! st->body ) {
610                        // use of forward declaration
611                        forwardStructs[ structInst->name ].push_back( structInst );
612                } // if
613                checkGenericParameters( structInst );
614        }
615
616        void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
617                UnionDecl *un = local_indexer->lookupUnion( unionInst->name );
618                // it's not a semantic error if the union is not found, just an implicit forward declaration
619                if ( un ) {
620                        unionInst->baseUnion = un;
621                } // if
622                if ( ! un || ! un->body ) {
623                        // use of forward declaration
624                        forwardUnions[ unionInst->name ].push_back( unionInst );
625                } // if
626                checkGenericParameters( unionInst );
627        }
628
629        void LinkReferenceToTypes::previsit( QualifiedType * ) {
630                visit_children = false;
631        }
632
633        void LinkReferenceToTypes::postvisit( QualifiedType * qualType ) {
634                // linking only makes sense for the 'oldest ancestor' of the qualified type
635                qualType->parent->accept( *visitor );
636        }
637
638        template< typename Decl >
639        void normalizeAssertions( std::list< Decl * > & assertions ) {
640                // ensure no duplicate trait members after the clone
641                auto pred = [](Decl * d1, Decl * d2) {
642                        // only care if they're equal
643                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
644                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
645                        if ( dwt1 && dwt2 ) {
646                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
647                                        // std::cerr << "=========== equal:" << std::endl;
648                                        // std::cerr << "d1: " << d1 << std::endl;
649                                        // std::cerr << "d2: " << d2 << std::endl;
650                                        return false;
651                                }
652                        }
653                        return d1 < d2;
654                };
655                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
656                // if ( unique_members.size() != assertions.size() ) {
657                //      std::cerr << "============different" << std::endl;
658                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
659                // }
660
661                std::list< Decl * > order;
662                order.splice( order.end(), assertions );
663                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
664                        return unique_members.count( decl );
665                });
666        }
667
668        // expand assertions from trait instance, performing the appropriate type variable substitutions
669        template< typename Iterator >
670        void expandAssertions( TraitInstType * inst, Iterator out ) {
671                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
672                std::list< DeclarationWithType * > asserts;
673                for ( Declaration * decl : inst->baseTrait->members ) {
674                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
675                }
676                // substitute trait decl parameters for instance parameters
677                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
678        }
679
680        void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
681                if ( traitDecl->name == "sized" ) {
682                        // "sized" is a special trait - flick the sized status on for the type variable
683                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
684                        TypeDecl * td = traitDecl->parameters.front();
685                        td->set_sized( true );
686                }
687
688                // move assertions from type parameters into the body of the trait
689                for ( TypeDecl * td : traitDecl->parameters ) {
690                        for ( DeclarationWithType * assert : td->assertions ) {
691                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
692                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
693                                } else {
694                                        traitDecl->members.push_back( assert->clone() );
695                                }
696                        }
697                        deleteAll( td->assertions );
698                        td->assertions.clear();
699                } // for
700        }
701
702        void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
703                // handle other traits
704                TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
705                if ( ! traitDecl ) {
706                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
707                } // if
708                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
709                        SemanticError( traitInst, "incorrect number of trait parameters: " );
710                } // if
711                traitInst->baseTrait = traitDecl;
712
713                // need to carry over the 'sized' status of each decl in the instance
714                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
715                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
716                        if ( ! expr ) {
717                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
718                        }
719                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
720                                TypeDecl * formalDecl = std::get<0>(p);
721                                TypeDecl * instDecl = inst->baseType;
722                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
723                        }
724                }
725                // normalizeAssertions( traitInst->members );
726        }
727
728        void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
729                // visit enum members first so that the types of self-referencing members are updated properly
730                if ( enumDecl->body ) {
731                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
732                        if ( fwds != forwardEnums.end() ) {
733                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
734                                        (*inst)->baseEnum = enumDecl;
735                                } // for
736                                forwardEnums.erase( fwds );
737                        } // if
738                } // if
739        }
740
741        void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
742                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
743                //   forall(otype T)
744                //   struct Box {
745                //     T x;
746                //   };
747                //   forall(otype T)
748                //   void f(Box(T) b) {
749                //     ...
750                //   }
751                // The T in Box and the T in f are different, so internally the naming must reflect that.
752                GuardValue( inGeneric );
753                inGeneric = ! params.empty();
754                for ( TypeDecl * td : params ) {
755                        td->name = "__" + td->name + "_generic_";
756                }
757        }
758
759        void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
760                renameGenericParams( structDecl->parameters );
761        }
762
763        void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
764                renameGenericParams( unionDecl->parameters );
765        }
766
767        void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
768                // visit struct members first so that the types of self-referencing members are updated properly
769                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
770                if ( structDecl->body ) {
771                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
772                        if ( fwds != forwardStructs.end() ) {
773                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
774                                        (*inst)->baseStruct = structDecl;
775                                } // for
776                                forwardStructs.erase( fwds );
777                        } // if
778                } // if
779        }
780
781        void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
782                if ( unionDecl->body ) {
783                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
784                        if ( fwds != forwardUnions.end() ) {
785                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
786                                        (*inst)->baseUnion = unionDecl;
787                                } // for
788                                forwardUnions.erase( fwds );
789                        } // if
790                } // if
791        }
792
793        void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
794                // ensure generic parameter instances are renamed like the base type
795                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
796                if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
797                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
798                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
799                        } // if
800                } // if
801        }
802
803        /// Fix up assertions - flattens assertion lists, removing all trait instances
804        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
805                for ( TypeDecl * type : forall ) {
806                        std::list< DeclarationWithType * > asserts;
807                        asserts.splice( asserts.end(), type->assertions );
808                        // expand trait instances into their members
809                        for ( DeclarationWithType * assertion : asserts ) {
810                                if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
811                                        // expand trait instance into all of its members
812                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
813                                        delete traitInst;
814                                } else {
815                                        // pass other assertions through
816                                        type->assertions.push_back( assertion );
817                                } // if
818                        } // for
819                        // apply FixFunction to every assertion to check for invalid void type
820                        for ( DeclarationWithType *& assertion : type->assertions ) {
821                                bool isVoid = fixFunction( assertion );
822                                if ( isVoid ) {
823                                        SemanticError( node, "invalid type void in assertion of function " );
824                                } // if
825                        } // for
826                        // normalizeAssertions( type->assertions );
827                } // for
828        }
829
830        void ForallPointerDecay::previsit( ObjectDecl *object ) {
831                // ensure that operator names only apply to functions or function pointers
832                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
833                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
834                }
835                object->fixUniqueId();
836        }
837
838        void ForallPointerDecay::previsit( FunctionDecl *func ) {
839                func->fixUniqueId();
840        }
841
842        void ForallPointerDecay::previsit( FunctionType * ftype ) {
843                forallFixer( ftype->forall, ftype );
844        }
845
846        void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
847                forallFixer( aggrDecl->parameters, aggrDecl );
848        }
849
850        void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
851                forallFixer( aggrDecl->parameters, aggrDecl );
852        }
853
854        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
855                PassVisitor<ReturnChecker> checker;
856                acceptAll( translationUnit, checker );
857        }
858
859        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
860                GuardValue( returnVals );
861                returnVals = functionDecl->get_functionType()->get_returnVals();
862        }
863
864        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
865                // Previously this also checked for the existence of an expr paired with no return values on
866                // the  function return type. This is incorrect, since you can have an expression attached to
867                // a return statement in a void-returning function in C. The expression is treated as if it
868                // were cast to void.
869                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
870                        SemanticError( returnStmt, "Non-void function returns no values: " );
871                }
872        }
873
874
875        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
876                PassVisitor<ReplaceTypedef> eliminator;
877                mutateAll( translationUnit, eliminator );
878                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
879                        // grab and remember declaration of size_t
880                        SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
881                } else {
882                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
883                        // eventually should have a warning for this case.
884                        SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
885                }
886        }
887
888        void ReplaceTypedef::premutate( QualifiedType * ) {
889                visit_children = false;
890        }
891
892        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
893                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
894                qualType->parent = qualType->parent->acceptMutator( *visitor );
895                return qualType;
896        }
897
898        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
899                // instances of typedef types will come here. If it is an instance
900                // of a typdef type, link the instance to its actual type.
901                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
902                if ( def != typedefNames.end() ) {
903                        Type *ret = def->second.first->base->clone();
904                        ret->location = typeInst->location;
905                        ret->get_qualifiers() |= typeInst->get_qualifiers();
906                        // attributes are not carried over from typedef to function parameters/return values
907                        if ( ! inFunctionType ) {
908                                ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
909                        } else {
910                                deleteAll( ret->attributes );
911                                ret->attributes.clear();
912                        }
913                        // place instance parameters on the typedef'd type
914                        if ( ! typeInst->parameters.empty() ) {
915                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
916                                if ( ! rtt ) {
917                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
918                                }
919                                rtt->parameters.clear();
920                                cloneAll( typeInst->parameters, rtt->parameters );
921                                mutateAll( rtt->parameters, *visitor );  // recursively fix typedefs on parameters
922                        } // if
923                        delete typeInst;
924                        return ret;
925                } else {
926                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
927                        if ( base == typedeclNames.end() ) {
928                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
929                        }
930                        typeInst->set_baseType( base->second );
931                        return typeInst;
932                } // if
933                assert( false );
934        }
935
936        struct VarLenChecker : WithShortCircuiting {
937                void previsit( FunctionType * ) { visit_children = false; }
938                void previsit( ArrayType * at ) {
939                        isVarLen |= at->isVarLen;
940                }
941                bool isVarLen = false;
942        };
943
944        bool isVariableLength( Type * t ) {
945                PassVisitor<VarLenChecker> varLenChecker;
946                maybeAccept( t, varLenChecker );
947                return varLenChecker.pass.isVarLen;
948        }
949
950        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
951                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
952                        // typedef to the same name from the same scope
953                        // must be from the same type
954
955                        Type * t1 = tyDecl->base;
956                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
957                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
958                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
959                        }
960                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
961                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
962                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
963                        // to fix this corner case likely outweighs the utility of allowing it.
964                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
965                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
966                        }
967                } else {
968                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
969                } // if
970
971                // When a typedef is a forward declaration:
972                //    typedef struct screen SCREEN;
973                // the declaration portion must be retained:
974                //    struct screen;
975                // because the expansion of the typedef is:
976                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
977                // hence the type-name "screen" must be defined.
978                // Note, qualifiers on the typedef are superfluous for the forward declaration.
979
980                Type *designatorType = tyDecl->base->stripDeclarator();
981                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
982                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, DeclarationNode::Struct, noAttributes, tyDecl->linkage ) );
983                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
984                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
985                } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
986                        declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
987                } // if
988                return tyDecl->clone();
989        }
990
991        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
992                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
993                if ( i != typedefNames.end() ) {
994                        typedefNames.erase( i ) ;
995                } // if
996
997                typedeclNames.insert( typeDecl->name, typeDecl );
998        }
999
1000        void ReplaceTypedef::premutate( FunctionDecl * ) {
1001                GuardScope( typedefNames );
1002                GuardScope( typedeclNames );
1003        }
1004
1005        void ReplaceTypedef::premutate( ObjectDecl * ) {
1006                GuardScope( typedefNames );
1007                GuardScope( typedeclNames );
1008        }
1009
1010        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1011                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1012                        // replace the current object declaration with a function declaration
1013                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1014                        objDecl->attributes.clear();
1015                        objDecl->set_type( nullptr );
1016                        delete objDecl;
1017                        return newDecl;
1018                } // if
1019                return objDecl;
1020        }
1021
1022        void ReplaceTypedef::premutate( CastExpr * ) {
1023                GuardScope( typedefNames );
1024                GuardScope( typedeclNames );
1025        }
1026
1027        void ReplaceTypedef::premutate( CompoundStmt * ) {
1028                GuardScope( typedefNames );
1029                GuardScope( typedeclNames );
1030                scopeLevel += 1;
1031                GuardAction( [this](){ scopeLevel -= 1; } );
1032        }
1033
1034        template<typename AggDecl>
1035        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1036                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1037                        Type *type = nullptr;
1038                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1039                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1040                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1041                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1042                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
1043                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1044                        } // if
1045                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1046                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1047                        // add the implicit typedef to the AST
1048                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1049                } // if
1050        }
1051
1052        template< typename AggDecl >
1053        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1054                SemanticErrorException errors;
1055
1056                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1057                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
1058                declsToAddBefore.clear();
1059                declsToAddAfter.clear();
1060
1061                GuardScope( typedefNames );
1062                GuardScope( typedeclNames );
1063                mutateAll( aggr->parameters, *visitor );
1064
1065                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1066                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1067                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1068
1069                        try {
1070                                *i = maybeMutate( *i, *visitor );
1071                        } catch ( SemanticErrorException &e ) {
1072                                errors.append( e );
1073                        }
1074
1075                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1076                }
1077
1078                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1079                if ( !errors.isEmpty() ) { throw errors; }
1080        }
1081
1082        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1083                visit_children = false;
1084                addImplicitTypedef( structDecl );
1085                handleAggregate( structDecl );
1086        }
1087
1088        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1089                visit_children = false;
1090                addImplicitTypedef( unionDecl );
1091                handleAggregate( unionDecl );
1092        }
1093
1094        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1095                addImplicitTypedef( enumDecl );
1096        }
1097
1098        void ReplaceTypedef::premutate( FunctionType * ) {
1099                GuardValue( inFunctionType );
1100                inFunctionType = true;
1101        }
1102
1103        void ReplaceTypedef::premutate( TraitDecl * ) {
1104                GuardScope( typedefNames );
1105                GuardScope( typedeclNames);
1106        }
1107
1108        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1109                PassVisitor<VerifyCtorDtorAssign> verifier;
1110                acceptAll( translationUnit, verifier );
1111        }
1112
1113        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1114                FunctionType * funcType = funcDecl->get_functionType();
1115                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1116                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1117
1118                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1119                        if ( params.size() == 0 ) {
1120                                SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
1121                        }
1122                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1123                        if ( ! refType ) {
1124                                SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
1125                        }
1126                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1127                                SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
1128                        }
1129                }
1130        }
1131
1132        template< typename Aggr >
1133        void validateGeneric( Aggr * inst ) {
1134                std::list< TypeDecl * > * params = inst->get_baseParameters();
1135                if ( params ) {
1136                        std::list< Expression * > & args = inst->get_parameters();
1137
1138                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1139                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1140                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1141                        //   vector(int) v;
1142                        // after insertion of default values becomes
1143                        //   vector(int, heap_allocator(T))
1144                        // and the substitution is built with T=int so that after substitution, the result is
1145                        //   vector(int, heap_allocator(int))
1146                        TypeSubstitution sub;
1147                        auto paramIter = params->begin();
1148                        for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
1149                                if ( i < args.size() ) {
1150                                        TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
1151                                        sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
1152                                } else if ( i == args.size() ) {
1153                                        Type * defaultType = (*paramIter)->get_init();
1154                                        if ( defaultType ) {
1155                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1156                                                sub.add( (*paramIter)->get_name(), defaultType->clone() );
1157                                        }
1158                                }
1159                        }
1160
1161                        sub.apply( inst );
1162                        if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
1163                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1164                }
1165        }
1166
1167        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1168                validateGeneric( inst );
1169        }
1170
1171        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1172                validateGeneric( inst );
1173        }
1174
1175        void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
1176                storageClasses = objectDecl->get_storageClasses();
1177        }
1178
1179        Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
1180                // transform [storage_class] ... (struct S){ 3, ... };
1181                // into [storage_class] struct S temp =  { 3, ... };
1182                static UniqueName indexName( "_compLit" );
1183
1184                ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1185                compLitExpr->set_result( nullptr );
1186                compLitExpr->set_initializer( nullptr );
1187                delete compLitExpr;
1188                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1189                return new VariableExpr( tempvar );
1190        }
1191
1192        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1193                PassVisitor<ReturnTypeFixer> fixer;
1194                acceptAll( translationUnit, fixer );
1195        }
1196
1197        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1198                FunctionType * ftype = functionDecl->get_functionType();
1199                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1200                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1201                if ( retVals.size() == 1 ) {
1202                        // 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).
1203                        // ensure other return values have a name.
1204                        DeclarationWithType * ret = retVals.front();
1205                        if ( ret->get_name() == "" ) {
1206                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1207                        }
1208                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1209                }
1210        }
1211
1212        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1213                // xxx - need to handle named return values - this information needs to be saved somehow
1214                // so that resolution has access to the names.
1215                // Note that this pass needs to happen early so that other passes which look for tuple types
1216                // find them in all of the right places, including function return types.
1217                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1218                if ( retVals.size() > 1 ) {
1219                        // generate a single return parameter which is the tuple of all of the return values
1220                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1221                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1222                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
1223                        deleteAll( retVals );
1224                        retVals.clear();
1225                        retVals.push_back( newRet );
1226                }
1227        }
1228
1229        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1230                PassVisitor<ArrayLength> len;
1231                acceptAll( translationUnit, len );
1232        }
1233
1234        void ArrayLength::previsit( ObjectDecl * objDecl ) {
1235                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1236                        if ( at->dimension ) return;
1237                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1238                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1239                        }
1240                }
1241        }
1242
1243        void ArrayLength::previsit( ArrayType * type ) {
1244                if ( type->dimension ) {
1245                        // need to resolve array dimensions early so that constructor code can correctly determine
1246                        // if a type is a VLA (and hence whether its elements need to be constructed)
1247                        ResolvExpr::findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
1248
1249                        // must re-evaluate whether a type is a VLA, now that more information is available
1250                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1251                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1252                }
1253        }
1254
1255        struct LabelFinder {
1256                std::set< Label > & labels;
1257                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1258                void previsit( Statement * stmt ) {
1259                        for ( Label & l : stmt->labels ) {
1260                                labels.insert( l );
1261                        }
1262                }
1263        };
1264
1265        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1266                GuardValue( labels );
1267                PassVisitor<LabelFinder> finder( labels );
1268                funcDecl->accept( finder );
1269        }
1270
1271        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1272                // convert &&label into label address
1273                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1274                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1275                                if ( labels.count( nameExpr->name ) ) {
1276                                        Label name = nameExpr->name;
1277                                        delete addrExpr;
1278                                        return new LabelAddressExpr( name );
1279                                }
1280                        }
1281                }
1282                return addrExpr;
1283        }
1284
1285        void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1286                if ( ! dereferenceOperator ) {
1287                        if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1288                                FunctionType * ftype = funcDecl->get_functionType();
1289                                if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1290                                        dereferenceOperator = funcDecl;
1291                                }
1292                        }
1293                }
1294        }
1295} // namespace SymTab
1296
1297// Local Variables: //
1298// tab-width: 4 //
1299// mode: c++ //
1300// compile-command: "make install" //
1301// End: //
Note: See TracBrowser for help on using the repository browser.