source: src/SymTab/Validate.cc @ 5dcb881

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since 5dcb881 was 5dcb881, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Split up the validate pass. (Some statistics code is repeated, but this does not effect regular runs.)

  • Property mode set to 100644
File size: 78.8 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 : Fri Nov 12 11:00:00 2021
13// Update Count     : 364
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 <unordered_map>               // for unordered_map
47#include <utility>                     // for pair
48
49#include "AST/Chain.hpp"
50#include "AST/Decl.hpp"
51#include "AST/Node.hpp"
52#include "AST/Pass.hpp"
53#include "AST/SymbolTable.hpp"
54#include "AST/Type.hpp"
55#include "AST/TypeSubstitution.hpp"
56#include "CodeGen/CodeGenerator.h"     // for genName
57#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
58#include "ControlStruct/Mutate.h"      // for ForExprMutator
59#include "Common/CodeLocation.h"       // for CodeLocation
60#include "Common/Stats.h"              // for Stats::Heap
61#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
62#include "Common/ScopedMap.h"          // for ScopedMap
63#include "Common/SemanticError.h"      // for SemanticError
64#include "Common/UniqueName.h"         // for UniqueName
65#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
66#include "CompilationState.h"          // skip some passes in new-ast build
67#include "Concurrency/Keywords.h"      // for applyKeywords
68#include "FixFunction.h"               // for FixFunction
69#include "Indexer.h"                   // for Indexer
70#include "InitTweak/GenInit.h"         // for fixReturnStatements
71#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
72#include "ResolvExpr/typeops.h"        // for typesCompatible
73#include "ResolvExpr/Resolver.h"       // for findSingleExpression
74#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
75#include "SymTab/Autogen.h"            // for SizeType
76#include "SynTree/LinkageSpec.h"       // for C
77#include "SynTree/Attribute.h"         // for noAttributes, Attribute
78#include "SynTree/Constant.h"          // for Constant
79#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
80#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
81#include "SynTree/Initializer.h"       // for ListInit, Initializer
82#include "SynTree/Label.h"             // for operator==, Label
83#include "SynTree/Mutator.h"           // for Mutator
84#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
85#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
86#include "SynTree/Visitor.h"           // for Visitor
87#include "Validate/HandleAttributes.h" // for handleAttributes
88#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
89
90class CompoundStmt;
91class ReturnStmt;
92class SwitchStmt;
93
94#define debugPrint( x ) if ( doDebug ) x
95
96namespace SymTab {
97        /// hoists declarations that are difficult to hoist while parsing
98        struct HoistTypeDecls final : public WithDeclsToAdd {
99                void previsit( SizeofExpr * );
100                void previsit( AlignofExpr * );
101                void previsit( UntypedOffsetofExpr * );
102                void previsit( CompoundLiteralExpr * );
103                void handleType( Type * );
104        };
105
106        struct FixQualifiedTypes final : public WithIndexer {
107                FixQualifiedTypes() : WithIndexer(false) {}
108                Type * postmutate( QualifiedType * );
109        };
110
111        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
112                /// Flattens nested struct types
113                static void hoistStruct( std::list< Declaration * > &translationUnit );
114
115                void previsit( StructDecl * aggregateDecl );
116                void previsit( UnionDecl * aggregateDecl );
117                void previsit( StaticAssertDecl * assertDecl );
118                void previsit( StructInstType * type );
119                void previsit( UnionInstType * type );
120                void previsit( EnumInstType * type );
121
122          private:
123                template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
124
125                AggregateDecl * parentAggr = nullptr;
126        };
127
128        /// Fix return types so that every function returns exactly one value
129        struct ReturnTypeFixer {
130                static void fix( std::list< Declaration * > &translationUnit );
131
132                void postvisit( FunctionDecl * functionDecl );
133                void postvisit( FunctionType * ftype );
134        };
135
136        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
137        struct EnumAndPointerDecay_old {
138                void previsit( EnumDecl * aggregateDecl );
139                void previsit( FunctionType * func );
140        };
141
142        /// Associates forward declarations of aggregates with their definitions
143        struct LinkReferenceToTypes_old final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes_old>, public WithShortCircuiting {
144                LinkReferenceToTypes_old( const Indexer * indexer );
145                void postvisit( TypeInstType * typeInst );
146
147                void postvisit( EnumInstType * enumInst );
148                void postvisit( StructInstType * structInst );
149                void postvisit( UnionInstType * unionInst );
150                void postvisit( TraitInstType * traitInst );
151                void previsit( QualifiedType * qualType );
152                void postvisit( QualifiedType * qualType );
153
154                void postvisit( EnumDecl * enumDecl );
155                void postvisit( StructDecl * structDecl );
156                void postvisit( UnionDecl * unionDecl );
157                void postvisit( TraitDecl * traitDecl );
158
159                void previsit( StructDecl * structDecl );
160                void previsit( UnionDecl * unionDecl );
161
162                void renameGenericParams( std::list< TypeDecl * > & params );
163
164          private:
165                const Indexer * local_indexer;
166
167                typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
168                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
169                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
170                ForwardEnumsType forwardEnums;
171                ForwardStructsType forwardStructs;
172                ForwardUnionsType forwardUnions;
173                /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
174                bool inGeneric = false;
175        };
176
177        /// Does early resolution on the expressions that give enumeration constants their values
178        struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting {
179                ResolveEnumInitializers( const Indexer * indexer );
180                void postvisit( EnumDecl * enumDecl );
181
182          private:
183                const Indexer * local_indexer;
184
185        };
186
187        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
188        struct ForallPointerDecay_old final {
189                void previsit( ObjectDecl * object );
190                void previsit( FunctionDecl * func );
191                void previsit( FunctionType * ftype );
192                void previsit( StructDecl * aggrDecl );
193                void previsit( UnionDecl * aggrDecl );
194        };
195
196        struct ReturnChecker : public WithGuards {
197                /// Checks that return statements return nothing if their return type is void
198                /// and return something if the return type is non-void.
199                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
200
201                void previsit( FunctionDecl * functionDecl );
202                void previsit( ReturnStmt * returnStmt );
203
204                typedef std::list< DeclarationWithType * > ReturnVals;
205                ReturnVals returnVals;
206        };
207
208        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
209                ReplaceTypedef() : scopeLevel( 0 ) {}
210                /// Replaces typedefs by forward declarations
211                static void replaceTypedef( std::list< Declaration * > &translationUnit );
212
213                void premutate( QualifiedType * );
214                Type * postmutate( QualifiedType * qualType );
215                Type * postmutate( TypeInstType * aggregateUseType );
216                Declaration * postmutate( TypedefDecl * typeDecl );
217                void premutate( TypeDecl * typeDecl );
218                void premutate( FunctionDecl * funcDecl );
219                void premutate( ObjectDecl * objDecl );
220                DeclarationWithType * postmutate( ObjectDecl * objDecl );
221
222                void premutate( CastExpr * castExpr );
223
224                void premutate( CompoundStmt * compoundStmt );
225
226                void premutate( StructDecl * structDecl );
227                void premutate( UnionDecl * unionDecl );
228                void premutate( EnumDecl * enumDecl );
229                void premutate( TraitDecl * );
230
231                void premutate( FunctionType * ftype );
232
233          private:
234                template<typename AggDecl>
235                void addImplicitTypedef( AggDecl * aggDecl );
236                template< typename AggDecl >
237                void handleAggregate( AggDecl * aggr );
238
239                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
240                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
241                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
242                TypedefMap typedefNames;
243                TypeDeclMap typedeclNames;
244                int scopeLevel;
245                bool inFunctionType = false;
246        };
247
248        struct EliminateTypedef {
249                /// removes TypedefDecls from the AST
250                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
251
252                template<typename AggDecl>
253                void handleAggregate( AggDecl * aggregateDecl );
254
255                void previsit( StructDecl * aggregateDecl );
256                void previsit( UnionDecl * aggregateDecl );
257                void previsit( CompoundStmt * compoundStmt );
258        };
259
260        struct VerifyCtorDtorAssign {
261                /// ensure that constructors, destructors, and assignment have at least one
262                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
263                /// return values.
264                static void verify( std::list< Declaration * > &translationUnit );
265
266                void previsit( FunctionDecl * funcDecl );
267        };
268
269        /// ensure that generic types have the correct number of type arguments
270        struct ValidateGenericParameters {
271                void previsit( StructInstType * inst );
272                void previsit( UnionInstType * inst );
273        };
274
275        /// desugar declarations and uses of dimension paramaters like [N],
276        /// from type-system managed values, to tunnneling via ordinary types,
277        /// as char[-] in and sizeof(-) out
278        struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards {
279                static void translateDimensions( std::list< Declaration * > &translationUnit );
280                TranslateDimensionGenericParameters();
281
282                bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type
283                bool visitingChildOfSUIT = false;
284                void changeState_ChildOfSUIT( bool newVal );
285                void premutate( StructInstType * sit );
286                void premutate( UnionInstType * uit );
287                void premutate( BaseSyntaxNode * node );
288
289                TypeDecl * postmutate( TypeDecl * td );
290                Expression * postmutate( DimensionExpr * de );
291                Expression * postmutate( Expression * e );
292        };
293
294        struct FixObjectType : public WithIndexer {
295                /// resolves typeof type in object, function, and type declarations
296                static void fix( std::list< Declaration * > & translationUnit );
297
298                void previsit( ObjectDecl * );
299                void previsit( FunctionDecl * );
300                void previsit( TypeDecl * );
301        };
302
303        struct InitializerLength {
304                /// for array types without an explicit length, compute the length and store it so that it
305                /// is known to the rest of the phases. For example,
306                ///   int x[] = { 1, 2, 3 };
307                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
308                /// here x and y are known at compile-time to have length 3, so change this into
309                ///   int x[3] = { 1, 2, 3 };
310                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
311                static void computeLength( std::list< Declaration * > & translationUnit );
312
313                void previsit( ObjectDecl * objDecl );
314        };
315
316        struct ArrayLength : public WithIndexer {
317                static void computeLength( std::list< Declaration * > & translationUnit );
318
319                void previsit( ArrayType * arrayType );
320        };
321
322        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
323                Type::StorageClasses storageClasses;
324
325                void premutate( ObjectDecl * objectDecl );
326                Expression * postmutate( CompoundLiteralExpr * compLitExpr );
327        };
328
329        struct LabelAddressFixer final : public WithGuards {
330                std::set< Label > labels;
331
332                void premutate( FunctionDecl * funcDecl );
333                Expression * postmutate( AddressExpr * addrExpr );
334        };
335
336        void validate_A( std::list< Declaration * > & translationUnit ) {
337                PassVisitor<EnumAndPointerDecay_old> epc;
338                PassVisitor<HoistTypeDecls> hoistDecls;
339                {
340                        Stats::Heap::newPass("validate-A");
341                        Stats::Time::BlockGuard guard("validate-A");
342                        VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
343                        acceptAll( translationUnit, hoistDecls );
344                        ReplaceTypedef::replaceTypedef( translationUnit );
345                        ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
346                        acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes_old because it is an indexer and needs correct types for mangling
347                }
348        }
349
350        void validate_B( std::list< Declaration * > & translationUnit ) {
351                PassVisitor<LinkReferenceToTypes_old> lrt( nullptr );
352                PassVisitor<FixQualifiedTypes> fixQual;
353                {
354                        Stats::Heap::newPass("validate-B");
355                        Stats::Time::BlockGuard guard("validate-B");
356                        acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
357                        mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
358                        HoistStruct::hoistStruct( translationUnit );
359                        EliminateTypedef::eliminateTypedef( translationUnit );
360                }
361        }
362
363        void validate_C( std::list< Declaration * > & translationUnit ) {
364                PassVisitor<ValidateGenericParameters> genericParams;
365                PassVisitor<ResolveEnumInitializers> rei( nullptr );
366                {
367                        Stats::Heap::newPass("validate-C");
368                        Stats::Time::BlockGuard guard("validate-C");
369                        Stats::Time::TimeBlock("Validate Generic Parameters", [&]() {
370                                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef
371                        });
372                        Stats::Time::TimeBlock("Translate Dimensions", [&]() {
373                                TranslateDimensionGenericParameters::translateDimensions( translationUnit );
374                        });
375                        Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() {
376                                acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling
377                        });
378                        Stats::Time::TimeBlock("Check Function Returns", [&]() {
379                                ReturnChecker::checkFunctionReturns( translationUnit );
380                        });
381                        Stats::Time::TimeBlock("Fix Return Statements", [&]() {
382                                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
383                        });
384                }
385        }
386
387        void validate_D( std::list< Declaration * > & translationUnit ) {
388                PassVisitor<ForallPointerDecay_old> fpd;
389                {
390                        Stats::Heap::newPass("validate-D");
391                        Stats::Time::BlockGuard guard("validate-D");
392                        Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
393                                Concurrency::applyKeywords( translationUnit );
394                        });
395                        Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
396                                acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
397                        });
398                        Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
399                                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
400                        });
401                        Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
402                                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
403                        });
404                }
405        }
406
407        void validate_E( std::list< Declaration * > & translationUnit ) {
408                PassVisitor<CompoundLiteral> compoundliteral;
409                {
410                        Stats::Heap::newPass("validate-E");
411                        Stats::Time::BlockGuard guard("validate-E");
412                        Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
413                                Concurrency::implementMutexFuncs( translationUnit );
414                        });
415                        Stats::Time::TimeBlock("Implement Thread Start", [&]() {
416                                Concurrency::implementThreadStarter( translationUnit );
417                        });
418                        Stats::Time::TimeBlock("Compound Literal", [&]() {
419                                mutateAll( translationUnit, compoundliteral );
420                        });
421                        if (!useNewAST) {
422                                Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
423                                        ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
424                                });
425                        }
426                }
427        }
428
429        void validate_F( std::list< Declaration * > & translationUnit ) {
430                PassVisitor<LabelAddressFixer> labelAddrFixer;
431                {
432                        Stats::Heap::newPass("validate-F");
433                        Stats::Time::BlockGuard guard("validate-F");
434                        if (!useNewAST) {
435                                Stats::Time::TimeCall("Fix Object Type",
436                                        FixObjectType::fix, translationUnit);
437                        }
438                        Stats::Time::TimeCall("Initializer Length",
439                                InitializerLength::computeLength, translationUnit);
440                        if (!useNewAST) {
441                                Stats::Time::TimeCall("Array Length",
442                                        ArrayLength::computeLength, translationUnit);
443                        }
444                        Stats::Time::TimeCall("Find Special Declarations",
445                                Validate::findSpecialDecls, translationUnit);
446                        Stats::Time::TimeCall("Fix Label Address",
447                                mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
448                        if (!useNewAST) {
449                                Stats::Time::TimeCall("Handle Attributes",
450                                        Validate::handleAttributes, translationUnit);
451                        }
452                }
453        }
454
455        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
456                validate_A( translationUnit );
457                validate_B( translationUnit );
458                validate_C( translationUnit );
459                validate_D( translationUnit );
460                validate_E( translationUnit );
461                validate_F( translationUnit );
462        }
463
464        void validateType( Type * type, const Indexer * indexer ) {
465                PassVisitor<EnumAndPointerDecay_old> epc;
466                PassVisitor<LinkReferenceToTypes_old> lrt( indexer );
467                PassVisitor<ForallPointerDecay_old> fpd;
468                type->accept( epc );
469                type->accept( lrt );
470                type->accept( fpd );
471        }
472
473
474        void HoistTypeDecls::handleType( Type * type ) {
475                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
476                AggregateDecl * aggr = nullptr;
477                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
478                        aggr = inst->baseStruct;
479                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
480                        aggr = inst->baseUnion;
481                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
482                        aggr = inst->baseEnum;
483                }
484                if ( aggr && aggr->body ) {
485                        declsToAddBefore.push_front( aggr );
486                }
487        }
488
489        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
490                handleType( expr->type );
491        }
492
493        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
494                handleType( expr->type );
495        }
496
497        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
498                handleType( expr->type );
499        }
500
501        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
502                handleType( expr->result );
503        }
504
505
506        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
507                Type * parent = qualType->parent;
508                Type * child = qualType->child;
509                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
510                        // .T => lookup T at global scope
511                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
512                                auto td = indexer.globalLookupType( inst->name );
513                                if ( ! td ) {
514                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
515                                }
516                                auto base = td->base;
517                                assert( base );
518                                Type * ret = base->clone();
519                                ret->get_qualifiers() = qualType->get_qualifiers();
520                                return ret;
521                        } else {
522                                // .T => T is not a type name
523                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
524                        }
525                } else {
526                        // S.T => S must be an aggregate type, find the declaration for T in S.
527                        AggregateDecl * aggr = nullptr;
528                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
529                                aggr = inst->baseStruct;
530                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
531                                aggr = inst->baseUnion;
532                        } else {
533                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
534                        }
535                        assert( aggr ); // TODO: need to handle forward declarations
536                        for ( Declaration * member : aggr->members ) {
537                                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
538                                        // name on the right is a typedef
539                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
540                                                if ( aggr->name == inst->name ) {
541                                                        assert( aggr->base );
542                                                        Type * ret = aggr->base->clone();
543                                                        ret->get_qualifiers() = qualType->get_qualifiers();
544                                                        TypeSubstitution sub = parent->genericSubstitution();
545                                                        sub.apply(ret);
546                                                        return ret;
547                                                }
548                                        }
549                                } else {
550                                        // S.T - S is not an aggregate => error
551                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
552                                }
553                        }
554                        // failed to find a satisfying definition of type
555                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
556                }
557
558                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
559        }
560
561
562        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
563                PassVisitor<HoistStruct> hoister;
564                acceptAll( translationUnit, hoister );
565        }
566
567        bool shouldHoist( Declaration * decl ) {
568                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
569        }
570
571        namespace {
572                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
573                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
574                        ss << "__" << aggr->name;
575                }
576
577                // mangle nested type names using entire parent chain
578                std::string qualifiedName( AggregateDecl * aggr ) {
579                        std::ostringstream ss;
580                        qualifiedName( aggr, ss );
581                        return ss.str();
582                }
583        }
584
585        template< typename AggDecl >
586        void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
587                if ( parentAggr ) {
588                        aggregateDecl->parent = parentAggr;
589                        aggregateDecl->name = qualifiedName( aggregateDecl );
590                        // Add elements in stack order corresponding to nesting structure.
591                        declsToAddBefore.push_front( aggregateDecl );
592                } else {
593                        GuardValue( parentAggr );
594                        parentAggr = aggregateDecl;
595                } // if
596                // Always remove the hoisted aggregate from the inner structure.
597                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
598        }
599
600        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
601                if ( parentAggr ) {
602                        declsToAddBefore.push_back( assertDecl );
603                }
604        }
605
606        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
607                handleAggregate( aggregateDecl );
608        }
609
610        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
611                handleAggregate( aggregateDecl );
612        }
613
614        void HoistStruct::previsit( StructInstType * type ) {
615                // need to reset type name after expanding to qualified name
616                assert( type->baseStruct );
617                type->name = type->baseStruct->name;
618        }
619
620        void HoistStruct::previsit( UnionInstType * type ) {
621                assert( type->baseUnion );
622                type->name = type->baseUnion->name;
623        }
624
625        void HoistStruct::previsit( EnumInstType * type ) {
626                assert( type->baseEnum );
627                type->name = type->baseEnum->name;
628        }
629
630
631        bool isTypedef( Declaration * decl ) {
632                return dynamic_cast< TypedefDecl * >( decl );
633        }
634
635        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
636                PassVisitor<EliminateTypedef> eliminator;
637                acceptAll( translationUnit, eliminator );
638                filter( translationUnit, isTypedef, true );
639        }
640
641        template< typename AggDecl >
642        void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
643                filter( aggregateDecl->members, isTypedef, true );
644        }
645
646        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
647                handleAggregate( aggregateDecl );
648        }
649
650        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
651                handleAggregate( aggregateDecl );
652        }
653
654        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
655                // remove and delete decl stmts
656                filter( compoundStmt->kids, [](Statement * stmt) {
657                        if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
658                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
659                                        return true;
660                                } // if
661                        } // if
662                        return false;
663                }, true);
664        }
665
666        void EnumAndPointerDecay_old::previsit( EnumDecl * enumDecl ) {
667                // Set the type of each member of the enumeration to be EnumConstant
668                for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
669                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( * i );
670                        assert( obj );
671                        obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
672                } // for
673        }
674
675        namespace {
676                template< typename DWTList >
677                void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
678                        auto nvals = dwts.size();
679                        bool containsVoid = false;
680                        for ( auto & dwt : dwts ) {
681                                // fix each DWT and record whether a void was found
682                                containsVoid |= fixFunction( dwt );
683                        }
684
685                        // the only case in which "void" is valid is where it is the only one in the list
686                        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
687                                SemanticError( func, "invalid type void in function type " );
688                        }
689
690                        // one void is the only thing in the list; remove it.
691                        if ( containsVoid ) {
692                                delete dwts.front();
693                                dwts.clear();
694                        }
695                }
696        }
697
698        void EnumAndPointerDecay_old::previsit( FunctionType * func ) {
699                // Fix up parameters and return types
700                fixFunctionList( func->parameters, func->isVarArgs, func );
701                fixFunctionList( func->returnVals, false, func );
702        }
703
704        LinkReferenceToTypes_old::LinkReferenceToTypes_old( const Indexer * other_indexer ) : WithIndexer( false ) {
705                if ( other_indexer ) {
706                        local_indexer = other_indexer;
707                } else {
708                        local_indexer = &indexer;
709                } // if
710        }
711
712        void LinkReferenceToTypes_old::postvisit( EnumInstType * enumInst ) {
713                const EnumDecl * st = local_indexer->lookupEnum( enumInst->name );
714                // it's not a semantic error if the enum is not found, just an implicit forward declaration
715                if ( st ) {
716                        enumInst->baseEnum = const_cast<EnumDecl *>(st); // Just linking in the node
717                } // if
718                if ( ! st || ! st->body ) {
719                        // use of forward declaration
720                        forwardEnums[ enumInst->name ].push_back( enumInst );
721                } // if
722        }
723
724        void LinkReferenceToTypes_old::postvisit( StructInstType * structInst ) {
725                const StructDecl * st = local_indexer->lookupStruct( structInst->name );
726                // it's not a semantic error if the struct is not found, just an implicit forward declaration
727                if ( st ) {
728                        structInst->baseStruct = const_cast<StructDecl *>(st); // Just linking in the node
729                } // if
730                if ( ! st || ! st->body ) {
731                        // use of forward declaration
732                        forwardStructs[ structInst->name ].push_back( structInst );
733                } // if
734        }
735
736        void LinkReferenceToTypes_old::postvisit( UnionInstType * unionInst ) {
737                const UnionDecl * un = local_indexer->lookupUnion( unionInst->name );
738                // it's not a semantic error if the union is not found, just an implicit forward declaration
739                if ( un ) {
740                        unionInst->baseUnion = const_cast<UnionDecl *>(un); // Just linking in the node
741                } // if
742                if ( ! un || ! un->body ) {
743                        // use of forward declaration
744                        forwardUnions[ unionInst->name ].push_back( unionInst );
745                } // if
746        }
747
748        void LinkReferenceToTypes_old::previsit( QualifiedType * ) {
749                visit_children = false;
750        }
751
752        void LinkReferenceToTypes_old::postvisit( QualifiedType * qualType ) {
753                // linking only makes sense for the 'oldest ancestor' of the qualified type
754                qualType->parent->accept( * visitor );
755        }
756
757        template< typename Decl >
758        void normalizeAssertions( std::list< Decl * > & assertions ) {
759                // ensure no duplicate trait members after the clone
760                auto pred = [](Decl * d1, Decl * d2) {
761                        // only care if they're equal
762                        DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
763                        DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
764                        if ( dwt1 && dwt2 ) {
765                                if ( dwt1->name == dwt2->name && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
766                                        // std::cerr << "=========== equal:" << std::endl;
767                                        // std::cerr << "d1: " << d1 << std::endl;
768                                        // std::cerr << "d2: " << d2 << std::endl;
769                                        return false;
770                                }
771                        }
772                        return d1 < d2;
773                };
774                std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
775                // if ( unique_members.size() != assertions.size() ) {
776                //      std::cerr << "============different" << std::endl;
777                //      std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
778                // }
779
780                std::list< Decl * > order;
781                order.splice( order.end(), assertions );
782                std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
783                        return unique_members.count( decl );
784                });
785        }
786
787        // expand assertions from trait instance, performing the appropriate type variable substitutions
788        template< typename Iterator >
789        void expandAssertions( TraitInstType * inst, Iterator out ) {
790                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
791                std::list< DeclarationWithType * > asserts;
792                for ( Declaration * decl : inst->baseTrait->members ) {
793                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
794                }
795                // substitute trait decl parameters for instance parameters
796                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
797        }
798
799        void LinkReferenceToTypes_old::postvisit( TraitDecl * traitDecl ) {
800                if ( traitDecl->name == "sized" ) {
801                        // "sized" is a special trait - flick the sized status on for the type variable
802                        assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
803                        TypeDecl * td = traitDecl->parameters.front();
804                        td->set_sized( true );
805                }
806
807                // move assertions from type parameters into the body of the trait
808                for ( TypeDecl * td : traitDecl->parameters ) {
809                        for ( DeclarationWithType * assert : td->assertions ) {
810                                if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
811                                        expandAssertions( inst, back_inserter( traitDecl->members ) );
812                                } else {
813                                        traitDecl->members.push_back( assert->clone() );
814                                }
815                        }
816                        deleteAll( td->assertions );
817                        td->assertions.clear();
818                } // for
819        }
820
821        void LinkReferenceToTypes_old::postvisit( TraitInstType * traitInst ) {
822                // handle other traits
823                const TraitDecl * traitDecl = local_indexer->lookupTrait( traitInst->name );
824                if ( ! traitDecl ) {
825                        SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
826                } // if
827                if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
828                        SemanticError( traitInst, "incorrect number of trait parameters: " );
829                } // if
830                traitInst->baseTrait = const_cast<TraitDecl *>(traitDecl); // Just linking in the node
831
832                // need to carry over the 'sized' status of each decl in the instance
833                for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
834                        TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
835                        if ( ! expr ) {
836                                SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
837                        }
838                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
839                                TypeDecl * formalDecl = std::get<0>(p);
840                                TypeDecl * instDecl = inst->baseType;
841                                if ( formalDecl->get_sized() ) instDecl->set_sized( true );
842                        }
843                }
844                // normalizeAssertions( traitInst->members );
845        }
846
847        void LinkReferenceToTypes_old::postvisit( EnumDecl * enumDecl ) {
848                // visit enum members first so that the types of self-referencing members are updated properly
849                if ( enumDecl->body ) {
850                        ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
851                        if ( fwds != forwardEnums.end() ) {
852                                for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
853                                        (* inst)->baseEnum = enumDecl;
854                                } // for
855                                forwardEnums.erase( fwds );
856                        } // if
857                } // if
858        }
859
860        void LinkReferenceToTypes_old::renameGenericParams( std::list< TypeDecl * > & params ) {
861                // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
862                //   forall(otype T)
863                //   struct Box {
864                //     T x;
865                //   };
866                //   forall(otype T)
867                //   void f(Box(T) b) {
868                //     ...
869                //   }
870                // The T in Box and the T in f are different, so internally the naming must reflect that.
871                GuardValue( inGeneric );
872                inGeneric = ! params.empty();
873                for ( TypeDecl * td : params ) {
874                        td->name = "__" + td->name + "_generic_";
875                }
876        }
877
878        void LinkReferenceToTypes_old::previsit( StructDecl * structDecl ) {
879                renameGenericParams( structDecl->parameters );
880        }
881
882        void LinkReferenceToTypes_old::previsit( UnionDecl * unionDecl ) {
883                renameGenericParams( unionDecl->parameters );
884        }
885
886        void LinkReferenceToTypes_old::postvisit( StructDecl * structDecl ) {
887                // visit struct members first so that the types of self-referencing members are updated properly
888                // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
889                if ( structDecl->body ) {
890                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
891                        if ( fwds != forwardStructs.end() ) {
892                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
893                                        (* inst)->baseStruct = structDecl;
894                                } // for
895                                forwardStructs.erase( fwds );
896                        } // if
897                } // if
898        }
899
900        void LinkReferenceToTypes_old::postvisit( UnionDecl * unionDecl ) {
901                if ( unionDecl->body ) {
902                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
903                        if ( fwds != forwardUnions.end() ) {
904                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
905                                        (* inst)->baseUnion = unionDecl;
906                                } // for
907                                forwardUnions.erase( fwds );
908                        } // if
909                } // if
910        }
911
912        void LinkReferenceToTypes_old::postvisit( TypeInstType * typeInst ) {
913                // ensure generic parameter instances are renamed like the base type
914                if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
915                if ( const NamedTypeDecl * namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
916                        if ( const TypeDecl * typeDecl = dynamic_cast< const TypeDecl * >( namedTypeDecl ) ) {
917                                typeInst->set_isFtype( typeDecl->kind == TypeDecl::Ftype );
918                        } // if
919                } // if
920        }
921
922        ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) {
923                if ( other_indexer ) {
924                        local_indexer = other_indexer;
925                } else {
926                        local_indexer = &indexer;
927                } // if
928        }
929
930        void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) {
931                if ( enumDecl->body ) {
932                        for ( Declaration * member : enumDecl->members ) {
933                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
934                                if ( field->init ) {
935                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
936                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
937                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
938                                }
939                        }
940                } // if
941        }
942
943        /// Fix up assertions - flattens assertion lists, removing all trait instances
944        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
945                for ( TypeDecl * type : forall ) {
946                        std::list< DeclarationWithType * > asserts;
947                        asserts.splice( asserts.end(), type->assertions );
948                        // expand trait instances into their members
949                        for ( DeclarationWithType * assertion : asserts ) {
950                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
951                                        // expand trait instance into all of its members
952                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
953                                        delete traitInst;
954                                } else {
955                                        // pass other assertions through
956                                        type->assertions.push_back( assertion );
957                                } // if
958                        } // for
959                        // apply FixFunction to every assertion to check for invalid void type
960                        for ( DeclarationWithType *& assertion : type->assertions ) {
961                                bool isVoid = fixFunction( assertion );
962                                if ( isVoid ) {
963                                        SemanticError( node, "invalid type void in assertion of function " );
964                                } // if
965                        } // for
966                        // normalizeAssertions( type->assertions );
967                } // for
968        }
969
970        void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
971                // ensure that operator names only apply to functions or function pointers
972                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
973                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
974                }
975                object->fixUniqueId();
976        }
977
978        void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
979                func->fixUniqueId();
980        }
981
982        void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
983                forallFixer( ftype->forall, ftype );
984        }
985
986        void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
987                forallFixer( aggrDecl->parameters, aggrDecl );
988        }
989
990        void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
991                forallFixer( aggrDecl->parameters, aggrDecl );
992        }
993
994        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
995                PassVisitor<ReturnChecker> checker;
996                acceptAll( translationUnit, checker );
997        }
998
999        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
1000                GuardValue( returnVals );
1001                returnVals = functionDecl->get_functionType()->get_returnVals();
1002        }
1003
1004        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
1005                // Previously this also checked for the existence of an expr paired with no return values on
1006                // the  function return type. This is incorrect, since you can have an expression attached to
1007                // a return statement in a void-returning function in C. The expression is treated as if it
1008                // were cast to void.
1009                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
1010                        SemanticError( returnStmt, "Non-void function returns no values: " );
1011                }
1012        }
1013
1014
1015        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
1016                PassVisitor<ReplaceTypedef> eliminator;
1017                mutateAll( translationUnit, eliminator );
1018                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
1019                        // grab and remember declaration of size_t
1020                        Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
1021                } else {
1022                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
1023                        // eventually should have a warning for this case.
1024                        Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1025                }
1026        }
1027
1028        void ReplaceTypedef::premutate( QualifiedType * ) {
1029                visit_children = false;
1030        }
1031
1032        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
1033                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
1034                qualType->parent = qualType->parent->acceptMutator( * visitor );
1035                return qualType;
1036        }
1037
1038        static bool isNonParameterAttribute( Attribute * attr ) {
1039                static const std::vector<std::string> bad_names = {
1040                        "aligned", "__aligned__",
1041                };
1042                for ( auto name : bad_names ) {
1043                        if ( name == attr->name ) {
1044                                return true;
1045                        }
1046                }
1047                return false;
1048        }
1049
1050        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
1051                // instances of typedef types will come here. If it is an instance
1052                // of a typdef type, link the instance to its actual type.
1053                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
1054                if ( def != typedefNames.end() ) {
1055                        Type * ret = def->second.first->base->clone();
1056                        ret->location = typeInst->location;
1057                        ret->get_qualifiers() |= typeInst->get_qualifiers();
1058                        // GCC ignores certain attributes if they arrive by typedef, this mimics that.
1059                        if ( inFunctionType ) {
1060                                ret->attributes.remove_if( isNonParameterAttribute );
1061                        }
1062                        ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
1063                        // place instance parameters on the typedef'd type
1064                        if ( ! typeInst->parameters.empty() ) {
1065                                ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
1066                                if ( ! rtt ) {
1067                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
1068                                }
1069                                rtt->parameters.clear();
1070                                cloneAll( typeInst->parameters, rtt->parameters );
1071                                mutateAll( rtt->parameters, * visitor );  // recursively fix typedefs on parameters
1072                        } // if
1073                        delete typeInst;
1074                        return ret;
1075                } else {
1076                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
1077                        if ( base == typedeclNames.end() ) {
1078                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
1079                        }
1080                        typeInst->set_baseType( base->second );
1081                        return typeInst;
1082                } // if
1083                assert( false );
1084        }
1085
1086        struct VarLenChecker : WithShortCircuiting {
1087                void previsit( FunctionType * ) { visit_children = false; }
1088                void previsit( ArrayType * at ) {
1089                        isVarLen |= at->isVarLen;
1090                }
1091                bool isVarLen = false;
1092        };
1093
1094        bool isVariableLength( Type * t ) {
1095                PassVisitor<VarLenChecker> varLenChecker;
1096                maybeAccept( t, varLenChecker );
1097                return varLenChecker.pass.isVarLen;
1098        }
1099
1100        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
1101                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
1102                        // typedef to the same name from the same scope
1103                        // must be from the same type
1104
1105                        Type * t1 = tyDecl->base;
1106                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
1107                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
1108                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1109                        }
1110                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
1111                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
1112                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
1113                        // to fix this corner case likely outweighs the utility of allowing it.
1114                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
1115                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
1116                        }
1117                } else {
1118                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
1119                } // if
1120
1121                // When a typedef is a forward declaration:
1122                //    typedef struct screen SCREEN;
1123                // the declaration portion must be retained:
1124                //    struct screen;
1125                // because the expansion of the typedef is:
1126                //    void rtn( SCREEN * p ) => void rtn( struct screen * p )
1127                // hence the type-name "screen" must be defined.
1128                // Note, qualifiers on the typedef are superfluous for the forward declaration.
1129
1130                Type * designatorType = tyDecl->base->stripDeclarator();
1131                if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
1132                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
1133                } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
1134                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
1135                } else if ( EnumInstType * enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
1136                        declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, tyDecl->linkage ) );
1137                } // if
1138                return tyDecl->clone();
1139        }
1140
1141        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
1142                TypedefMap::iterator i = typedefNames.find( typeDecl->name );
1143                if ( i != typedefNames.end() ) {
1144                        typedefNames.erase( i ) ;
1145                } // if
1146
1147                typedeclNames.insert( typeDecl->name, typeDecl );
1148        }
1149
1150        void ReplaceTypedef::premutate( FunctionDecl * ) {
1151                GuardScope( typedefNames );
1152                GuardScope( typedeclNames );
1153        }
1154
1155        void ReplaceTypedef::premutate( ObjectDecl * ) {
1156                GuardScope( typedefNames );
1157                GuardScope( typedeclNames );
1158        }
1159
1160        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
1161                if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
1162                        // replace the current object declaration with a function declaration
1163                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
1164                        objDecl->attributes.clear();
1165                        objDecl->set_type( nullptr );
1166                        delete objDecl;
1167                        return newDecl;
1168                } // if
1169                return objDecl;
1170        }
1171
1172        void ReplaceTypedef::premutate( CastExpr * ) {
1173                GuardScope( typedefNames );
1174                GuardScope( typedeclNames );
1175        }
1176
1177        void ReplaceTypedef::premutate( CompoundStmt * ) {
1178                GuardScope( typedefNames );
1179                GuardScope( typedeclNames );
1180                scopeLevel += 1;
1181                GuardAction( [this](){ scopeLevel -= 1; } );
1182        }
1183
1184        template<typename AggDecl>
1185        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
1186                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
1187                        Type * type = nullptr;
1188                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
1189                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
1190                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
1191                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
1192                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
1193                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
1194                        } // if
1195                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
1196                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
1197                        // add the implicit typedef to the AST
1198                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
1199                } // if
1200        }
1201
1202        template< typename AggDecl >
1203        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
1204                SemanticErrorException errors;
1205
1206                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
1207                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
1208                declsToAddBefore.clear();
1209                declsToAddAfter.clear();
1210
1211                GuardScope( typedefNames );
1212                GuardScope( typedeclNames );
1213                mutateAll( aggr->parameters, * visitor );
1214                mutateAll( aggr->attributes, * visitor );
1215
1216                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
1217                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
1218                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
1219
1220                        try {
1221                                * i = maybeMutate( * i, * visitor );
1222                        } catch ( SemanticErrorException &e ) {
1223                                errors.append( e );
1224                        }
1225
1226                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
1227                }
1228
1229                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
1230                if ( !errors.isEmpty() ) { throw errors; }
1231        }
1232
1233        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
1234                visit_children = false;
1235                addImplicitTypedef( structDecl );
1236                handleAggregate( structDecl );
1237        }
1238
1239        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
1240                visit_children = false;
1241                addImplicitTypedef( unionDecl );
1242                handleAggregate( unionDecl );
1243        }
1244
1245        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
1246                addImplicitTypedef( enumDecl );
1247        }
1248
1249        void ReplaceTypedef::premutate( FunctionType * ) {
1250                GuardValue( inFunctionType );
1251                inFunctionType = true;
1252        }
1253
1254        void ReplaceTypedef::premutate( TraitDecl * ) {
1255                GuardScope( typedefNames );
1256                GuardScope( typedeclNames);
1257        }
1258
1259        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
1260                PassVisitor<VerifyCtorDtorAssign> verifier;
1261                acceptAll( translationUnit, verifier );
1262        }
1263
1264        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
1265                FunctionType * funcType = funcDecl->get_functionType();
1266                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
1267                std::list< DeclarationWithType * > &params = funcType->get_parameters();
1268
1269                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
1270                        if ( params.size() == 0 ) {
1271                                SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." );
1272                        }
1273                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
1274                        if ( ! refType ) {
1275                                SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." );
1276                        }
1277                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
1278                                if(!returnVals.front()->get_type()->isVoid()) {
1279                                        SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." );
1280                                }
1281                        }
1282                }
1283        }
1284
1285        // Test for special name on a generic parameter.  Special treatment for the
1286        // special name is a bootstrapping hack.  In most cases, the worlds of T's
1287        // and of N's don't overlap (normal treamtemt).  The foundations in
1288        // array.hfa use tagging for both types and dimensions.  Tagging treats
1289        // its subject parameter even more opaquely than T&, which assumes it is
1290        // possible to have a pointer/reference to such an object.  Tagging only
1291        // seeks to identify the type-system resident at compile time.  Both N's
1292        // and T's can make tags.  The tag definition uses the special name, which
1293        // is treated as "an N or a T."  This feature is not inteded to be used
1294        // outside of the definition and immediate uses of a tag.
1295        static inline bool isReservedTysysIdOnlyName( const std::string & name ) {
1296                // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic
1297                int foundAt = name.find("__CFA_tysys_id_only");
1298                if (foundAt == 0) return true;
1299                if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
1300                return false;
1301        }
1302
1303        template< typename Aggr >
1304        void validateGeneric( Aggr * inst ) {
1305                std::list< TypeDecl * > * params = inst->get_baseParameters();
1306                if ( params ) {
1307                        std::list< Expression * > & args = inst->get_parameters();
1308
1309                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1310                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1311                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1312                        //   vector(int) v;
1313                        // after insertion of default values becomes
1314                        //   vector(int, heap_allocator(T))
1315                        // and the substitution is built with T=int so that after substitution, the result is
1316                        //   vector(int, heap_allocator(int))
1317                        TypeSubstitution sub;
1318                        auto paramIter = params->begin();
1319                        auto argIter = args.begin();
1320                        for ( ; paramIter != params->end(); ++paramIter, ++argIter ) {
1321                                if ( argIter != args.end() ) {
1322                                        TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter );
1323                                        if ( expr ) {
1324                                                sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1325                                        }
1326                                } else {
1327                                        Type * defaultType = (* paramIter)->get_init();
1328                                        if ( defaultType ) {
1329                                                args.push_back( new TypeExpr( defaultType->clone() ) );
1330                                                sub.add( (* paramIter)->get_name(), defaultType->clone() );
1331                                                argIter = std::prev(args.end());
1332                                        } else {
1333                                                SemanticError( inst, "Too few type arguments in generic type " );
1334                                        }
1335                                }
1336                                assert( argIter != args.end() );
1337                                bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension;
1338                                bool typeArgGiven;
1339                                if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
1340                                        // coerce a match when declaration is reserved name, which means "either"
1341                                        typeArgGiven = typeParamDeclared;
1342                                } else {
1343                                        typeArgGiven = dynamic_cast< TypeExpr * >( * argIter );
1344                                }
1345                                if ( ! typeParamDeclared &&   typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " );
1346                                if (   typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " );
1347                        }
1348
1349                        sub.apply( inst );
1350                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
1351                }
1352        }
1353
1354        void ValidateGenericParameters::previsit( StructInstType * inst ) {
1355                validateGeneric( inst );
1356        }
1357
1358        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
1359                validateGeneric( inst );
1360        }
1361
1362        void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) {
1363                PassVisitor<TranslateDimensionGenericParameters> translator;
1364                mutateAll( translationUnit, translator );
1365        }
1366
1367        TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {}
1368
1369        // Declaration of type variable:           forall( [N] )          ->  forall( N & | sized( N ) )
1370        TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) {
1371                if ( td->kind == TypeDecl::Dimension ) {
1372                        td->kind = TypeDecl::Dtype;
1373                        if ( ! isReservedTysysIdOnlyName( td->name ) ) {
1374                                td->sized = true;
1375                        }
1376                }
1377                return td;
1378        }
1379
1380        // Situational awareness:
1381        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
1382        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
1383        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
1384        void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) {
1385                GuardValue( nextVisitedNodeIsChildOfSUIT );
1386                GuardValue( visitingChildOfSUIT );
1387                visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT;
1388                nextVisitedNodeIsChildOfSUIT = newVal;
1389        }
1390        void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) {
1391                (void) sit;
1392                changeState_ChildOfSUIT(true);
1393        }
1394        void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) {
1395                (void) uit;
1396                changeState_ChildOfSUIT(true);
1397        }
1398        void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) {
1399                (void) node;
1400                changeState_ChildOfSUIT(false);
1401        }
1402
1403        // Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
1404        // Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
1405        // Intertwined reality:                    array( float, N     )  -> array( float,              N        )
1406        //                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
1407        // Intertwined case 1 is not just an optimization.
1408        // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
1409        //   forall([N]) void f( array(float, N) & );
1410        //   array(float, 7) a;
1411        //   f(a);
1412
1413        Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) {
1414                // Expression de is an occurrence of N in LHS of above examples.
1415                // Look up the name that de references.
1416                // If we are in a struct body, then this reference can be to an entry of the stuct's forall list.
1417                // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list.
1418                // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs).
1419                // Thus, a potential struct's declaration is highest priority.
1420                // A struct's forall declarations are already renamed with _generic_ suffix.  Try that name variant first.
1421
1422                std::string useName = "__" + de->name + "_generic_";
1423                TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1424
1425                if ( ! namedParamDecl ) {
1426                        useName = de->name;
1427                        namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1428                }
1429
1430                // Expect to find it always.  A misspelled name would have been parsed as an identifier.
1431                assert( namedParamDecl && "Type-system-managed value name not found in symbol table" );
1432
1433                delete de;
1434
1435                TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl );
1436
1437                if ( visitingChildOfSUIT ) {
1438                        // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper
1439                        // But avoid ArrayType-Sizeof
1440                        return new TypeExpr( refToDecl );
1441                } else {
1442                        // the N occurrence is being used directly as a runtime value,
1443                        // if we are in a type instantiation, then the N is within a bigger value computation
1444                        return new SizeofExpr( refToDecl );
1445                }
1446        }
1447
1448        Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) {
1449                if ( visitingChildOfSUIT ) {
1450                        // e is an expression used as an argument to instantiate a type
1451                        if (! dynamic_cast< TypeExpr * >( e ) ) {
1452                                // e is a value expression
1453                                // but not a DimensionExpr, which has a distinct postmutate
1454                                Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false );
1455                                TypeExpr * result = new TypeExpr( typeExprContent );
1456                                return result;
1457                        }
1458                }
1459                return e;
1460        }
1461
1462        void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
1463                storageClasses = objectDecl->get_storageClasses();
1464        }
1465
1466        Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
1467                // transform [storage_class] ... (struct S){ 3, ... };
1468                // into [storage_class] struct S temp =  { 3, ... };
1469                static UniqueName indexName( "_compLit" );
1470
1471                ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
1472                compLitExpr->set_result( nullptr );
1473                compLitExpr->set_initializer( nullptr );
1474                delete compLitExpr;
1475                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1476                return new VariableExpr( tempvar );
1477        }
1478
1479        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
1480                PassVisitor<ReturnTypeFixer> fixer;
1481                acceptAll( translationUnit, fixer );
1482        }
1483
1484        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
1485                FunctionType * ftype = functionDecl->get_functionType();
1486                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1487                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
1488                if ( retVals.size() == 1 ) {
1489                        // 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).
1490                        // ensure other return values have a name.
1491                        DeclarationWithType * ret = retVals.front();
1492                        if ( ret->get_name() == "" ) {
1493                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1494                        }
1495                        ret->get_attributes().push_back( new Attribute( "unused" ) );
1496                }
1497        }
1498
1499        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
1500                // xxx - need to handle named return values - this information needs to be saved somehow
1501                // so that resolution has access to the names.
1502                // Note that this pass needs to happen early so that other passes which look for tuple types
1503                // find them in all of the right places, including function return types.
1504                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1505                if ( retVals.size() > 1 ) {
1506                        // generate a single return parameter which is the tuple of all of the return values
1507                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
1508                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
1509                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
1510                        deleteAll( retVals );
1511                        retVals.clear();
1512                        retVals.push_back( newRet );
1513                }
1514        }
1515
1516        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1517                PassVisitor<FixObjectType> fixer;
1518                acceptAll( translationUnit, fixer );
1519        }
1520
1521        void FixObjectType::previsit( ObjectDecl * objDecl ) {
1522                Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
1523                objDecl->set_type( new_type );
1524        }
1525
1526        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
1527                Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
1528                funcDecl->set_type( new_type );
1529        }
1530
1531        void FixObjectType::previsit( TypeDecl * typeDecl ) {
1532                if ( typeDecl->get_base() ) {
1533                        Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
1534                        typeDecl->set_base( new_type );
1535                } // if
1536        }
1537
1538        void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) {
1539                PassVisitor<InitializerLength> len;
1540                acceptAll( translationUnit, len );
1541        }
1542
1543        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
1544                PassVisitor<ArrayLength> len;
1545                acceptAll( translationUnit, len );
1546        }
1547
1548        void InitializerLength::previsit( ObjectDecl * objDecl ) {
1549                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
1550                        if ( at->dimension ) return;
1551                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
1552                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
1553                        }
1554                }
1555        }
1556
1557        void ArrayLength::previsit( ArrayType * type ) {
1558                if ( type->dimension ) {
1559                        // need to resolve array dimensions early so that constructor code can correctly determine
1560                        // if a type is a VLA (and hence whether its elements need to be constructed)
1561                        ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1562
1563                        // must re-evaluate whether a type is a VLA, now that more information is available
1564                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1565                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
1566                }
1567        }
1568
1569        struct LabelFinder {
1570                std::set< Label > & labels;
1571                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1572                void previsit( Statement * stmt ) {
1573                        for ( Label & l : stmt->labels ) {
1574                                labels.insert( l );
1575                        }
1576                }
1577        };
1578
1579        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1580                GuardValue( labels );
1581                PassVisitor<LabelFinder> finder( labels );
1582                funcDecl->accept( finder );
1583        }
1584
1585        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1586                // convert &&label into label address
1587                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1588                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1589                                if ( labels.count( nameExpr->name ) ) {
1590                                        Label name = nameExpr->name;
1591                                        delete addrExpr;
1592                                        return new LabelAddressExpr( name );
1593                                }
1594                        }
1595                }
1596                return addrExpr;
1597        }
1598
1599namespace {
1600        /// Replaces enum types by int, and function/array types in function parameter and return
1601        /// lists by appropriate pointers
1602        /*
1603        struct EnumAndPointerDecay_new {
1604                const ast::EnumDecl * previsit( const ast::EnumDecl * enumDecl ) {
1605                        // set the type of each member of the enumeration to be EnumConstant
1606                        for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1607                                // build new version of object with EnumConstant
1608                                ast::ptr< ast::ObjectDecl > obj =
1609                                        enumDecl->members[i].strict_as< ast::ObjectDecl >();
1610                                obj.get_and_mutate()->type =
1611                                        new ast::EnumInstType{ enumDecl->name, ast::CV::Const };
1612
1613                                // set into decl
1614                                ast::EnumDecl * mut = mutate( enumDecl );
1615                                mut->members[i] = obj.get();
1616                                enumDecl = mut;
1617                        }
1618                        return enumDecl;
1619                }
1620
1621                static const ast::FunctionType * fixFunctionList(
1622                        const ast::FunctionType * func,
1623                        std::vector< ast::ptr< ast::DeclWithType > > ast::FunctionType::* field,
1624                        ast::ArgumentFlag isVarArgs = ast::FixedArgs
1625                ) {
1626                        const auto & dwts = func->* field;
1627                        unsigned nvals = dwts.size();
1628                        bool hasVoid = false;
1629                        for ( unsigned i = 0; i < nvals; ++i ) {
1630                                func = ast::mutate_field_index( func, field, i, fixFunction( dwts[i], hasVoid ) );
1631                        }
1632
1633                        // the only case in which "void" is valid is where it is the only one in the list
1634                        if ( hasVoid && ( nvals > 1 || isVarArgs ) ) {
1635                                SemanticError(
1636                                        dwts.front()->location, func, "invalid type void in function type" );
1637                        }
1638
1639                        // one void is the only thing in the list, remove it
1640                        if ( hasVoid ) {
1641                                func = ast::mutate_field(
1642                                        func, field, std::vector< ast::ptr< ast::DeclWithType > >{} );
1643                        }
1644
1645                        return func;
1646                }
1647
1648                const ast::FunctionType * previsit( const ast::FunctionType * func ) {
1649                        func = fixFunctionList( func, &ast::FunctionType::params, func->isVarArgs );
1650                        return fixFunctionList( func, &ast::FunctionType::returns );
1651                }
1652        };
1653
1654        /// expand assertions from a trait instance, performing appropriate type variable substitutions
1655        void expandAssertions(
1656                const ast::TraitInstType * inst, std::vector< ast::ptr< ast::DeclWithType > > & out
1657        ) {
1658                assertf( inst->base, "Trait instance not linked to base trait: %s", toCString( inst ) );
1659
1660                // build list of trait members, substituting trait decl parameters for instance parameters
1661                ast::TypeSubstitution sub{
1662                        inst->base->params.begin(), inst->base->params.end(), inst->params.begin() };
1663                // deliberately take ast::ptr by-value to ensure this does not mutate inst->base
1664                for ( ast::ptr< ast::Decl > decl : inst->base->members ) {
1665                        auto member = decl.strict_as< ast::DeclWithType >();
1666                        sub.apply( member );
1667                        out.emplace_back( member );
1668                }
1669        }
1670
1671        /// Associates forward declarations of aggregates with their definitions
1672        class LinkReferenceToTypes_new final
1673        : public ast::WithSymbolTable, public ast::WithGuards, public
1674          ast::WithVisitorRef<LinkReferenceToTypes_new>, public ast::WithShortCircuiting {
1675
1676                // these maps of uses of forward declarations of types need to have the actual type
1677                // declaration switched in * after * they have been traversed. To enable this in the
1678                // ast::Pass framework, any node that needs to be so mutated has mutate() called on it
1679                // before it is placed in the map, properly updating its parents in the usual traversal,
1680                // then can have the actual mutation applied later
1681                using ForwardEnumsType = std::unordered_multimap< std::string, ast::EnumInstType * >;
1682                using ForwardStructsType = std::unordered_multimap< std::string, ast::StructInstType * >;
1683                using ForwardUnionsType = std::unordered_multimap< std::string, ast::UnionInstType * >;
1684
1685                const CodeLocation & location;
1686                const ast::SymbolTable * localSymtab;
1687
1688                ForwardEnumsType forwardEnums;
1689                ForwardStructsType forwardStructs;
1690                ForwardUnionsType forwardUnions;
1691
1692                /// true if currently in a generic type body, so that type parameter instances can be
1693                /// renamed appropriately
1694                bool inGeneric = false;
1695
1696        public:
1697                /// contstruct using running symbol table
1698                LinkReferenceToTypes_new( const CodeLocation & loc )
1699                : location( loc ), localSymtab( &symtab ) {}
1700
1701                /// construct using provided symbol table
1702                LinkReferenceToTypes_new( const CodeLocation & loc, const ast::SymbolTable & syms )
1703                : location( loc ), localSymtab( &syms ) {}
1704
1705                const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
1706                        // ensure generic parameter instances are renamed like the base type
1707                        if ( inGeneric && typeInst->base ) {
1708                                typeInst = ast::mutate_field(
1709                                        typeInst, &ast::TypeInstType::name, typeInst->base->name );
1710                        }
1711
1712                        if (
1713                                auto typeDecl = dynamic_cast< const ast::TypeDecl * >(
1714                                        localSymtab->lookupType( typeInst->name ) )
1715                        ) {
1716                                typeInst = ast::mutate_field( typeInst, &ast::TypeInstType::kind, typeDecl->kind );
1717                        }
1718
1719                        return typeInst;
1720                }
1721
1722                const ast::Type * postvisit( const ast::EnumInstType * inst ) {
1723                        const ast::EnumDecl * decl = localSymtab->lookupEnum( inst->name );
1724                        // not a semantic error if the enum is not found, just an implicit forward declaration
1725                        if ( decl ) {
1726                                inst = ast::mutate_field( inst, &ast::EnumInstType::base, decl );
1727                        }
1728                        if ( ! decl || ! decl->body ) {
1729                                // forward declaration
1730                                auto mut = mutate( inst );
1731                                forwardEnums.emplace( inst->name, mut );
1732                                inst = mut;
1733                        }
1734                        return inst;
1735                }
1736
1737                void checkGenericParameters( const ast::BaseInstType * inst ) {
1738                        for ( const ast::Expr * param : inst->params ) {
1739                                if ( ! dynamic_cast< const ast::TypeExpr * >( param ) ) {
1740                                        SemanticError(
1741                                                location, inst, "Expression parameters for generic types are currently "
1742                                                "unsupported: " );
1743                                }
1744                        }
1745                }
1746
1747                const ast::StructInstType * postvisit( const ast::StructInstType * inst ) {
1748                        const ast::StructDecl * decl = localSymtab->lookupStruct( inst->name );
1749                        // not a semantic error if the struct is not found, just an implicit forward declaration
1750                        if ( decl ) {
1751                                inst = ast::mutate_field( inst, &ast::StructInstType::base, decl );
1752                        }
1753                        if ( ! decl || ! decl->body ) {
1754                                // forward declaration
1755                                auto mut = mutate( inst );
1756                                forwardStructs.emplace( inst->name, mut );
1757                                inst = mut;
1758                        }
1759                        checkGenericParameters( inst );
1760                        return inst;
1761                }
1762
1763                const ast::UnionInstType * postvisit( const ast::UnionInstType * inst ) {
1764                        const ast::UnionDecl * decl = localSymtab->lookupUnion( inst->name );
1765                        // not a semantic error if the struct is not found, just an implicit forward declaration
1766                        if ( decl ) {
1767                                inst = ast::mutate_field( inst, &ast::UnionInstType::base, decl );
1768                        }
1769                        if ( ! decl || ! decl->body ) {
1770                                // forward declaration
1771                                auto mut = mutate( inst );
1772                                forwardUnions.emplace( inst->name, mut );
1773                                inst = mut;
1774                        }
1775                        checkGenericParameters( inst );
1776                        return inst;
1777                }
1778
1779                const ast::Type * postvisit( const ast::TraitInstType * traitInst ) {
1780                        // handle other traits
1781                        const ast::TraitDecl * traitDecl = localSymtab->lookupTrait( traitInst->name );
1782                        if ( ! traitDecl )       {
1783                                SemanticError( location, "use of undeclared trait " + traitInst->name );
1784                        }
1785                        if ( traitDecl->params.size() != traitInst->params.size() ) {
1786                                SemanticError( location, traitInst, "incorrect number of trait parameters: " );
1787                        }
1788                        traitInst = ast::mutate_field( traitInst, &ast::TraitInstType::base, traitDecl );
1789
1790                        // need to carry over the "sized" status of each decl in the instance
1791                        for ( unsigned i = 0; i < traitDecl->params.size(); ++i ) {
1792                                auto expr = traitInst->params[i].as< ast::TypeExpr >();
1793                                if ( ! expr ) {
1794                                        SemanticError(
1795                                                traitInst->params[i].get(), "Expression parameters for trait instances "
1796                                                "are currently unsupported: " );
1797                                }
1798
1799                                if ( auto inst = expr->type.as< ast::TypeInstType >() ) {
1800                                        if ( traitDecl->params[i]->sized && ! inst->base->sized ) {
1801                                                // traitInst = ast::mutate_field_index(
1802                                                //      traitInst, &ast::TraitInstType::params, i,
1803                                                //      ...
1804                                                // );
1805                                                ast::TraitInstType * mut = ast::mutate( traitInst );
1806                                                ast::chain_mutate( mut->params[i] )
1807                                                        ( &ast::TypeExpr::type )
1808                                                                ( &ast::TypeInstType::base )->sized = true;
1809                                                traitInst = mut;
1810                                        }
1811                                }
1812                        }
1813
1814                        return traitInst;
1815                }
1816
1817                void previsit( const ast::QualifiedType * ) { visit_children = false; }
1818
1819                const ast::Type * postvisit( const ast::QualifiedType * qualType ) {
1820                        // linking only makes sense for the "oldest ancestor" of the qualified type
1821                        return ast::mutate_field(
1822                                qualType, &ast::QualifiedType::parent, qualType->parent->accept( * visitor ) );
1823                }
1824
1825                const ast::Decl * postvisit( const ast::EnumDecl * enumDecl ) {
1826                        // visit enum members first so that the types of self-referencing members are updated
1827                        // properly
1828                        if ( ! enumDecl->body ) return enumDecl;
1829
1830                        // update forward declarations to point here
1831                        auto fwds = forwardEnums.equal_range( enumDecl->name );
1832                        if ( fwds.first != fwds.second ) {
1833                                auto inst = fwds.first;
1834                                do {
1835                                        // forward decl is stored * mutably * in map, can thus be updated
1836                                        inst->second->base = enumDecl;
1837                                } while ( ++inst != fwds.second );
1838                                forwardEnums.erase( fwds.first, fwds.second );
1839                        }
1840
1841                        // ensure that enumerator initializers are properly set
1842                        for ( unsigned i = 0; i < enumDecl->members.size(); ++i ) {
1843                                auto field = enumDecl->members[i].strict_as< ast::ObjectDecl >();
1844                                if ( field->init ) {
1845                                        // need to resolve enumerator initializers early so that other passes that
1846                                        // determine if an expression is constexpr have appropriate information
1847                                        auto init = field->init.strict_as< ast::SingleInit >();
1848
1849                                        enumDecl = ast::mutate_field_index(
1850                                                enumDecl, &ast::EnumDecl::members, i,
1851                                                ast::mutate_field( field, &ast::ObjectDecl::init,
1852                                                        ast::mutate_field( init, &ast::SingleInit::value,
1853                                                                ResolvExpr::findSingleExpression(
1854                                                                        init->value, new ast::BasicType{ ast::BasicType::SignedInt },
1855                                                                        symtab ) ) ) );
1856                                }
1857                        }
1858
1859                        return enumDecl;
1860                }
1861
1862                /// rename generic type parameters uniquely so that they do not conflict with user defined
1863                /// function forall parameters, e.g. the T in Box and the T in f, below
1864                ///   forall(otype T)
1865                ///   struct Box {
1866                ///     T x;
1867                ///   };
1868                ///   forall(otype T)
1869                ///   void f(Box(T) b) {
1870                ///     ...
1871                ///   }
1872                template< typename AggrDecl >
1873                const AggrDecl * renameGenericParams( const AggrDecl * aggr ) {
1874                        GuardValue( inGeneric );
1875                        inGeneric = ! aggr->params.empty();
1876
1877                        for ( unsigned i = 0; i < aggr->params.size(); ++i ) {
1878                                const ast::TypeDecl * td = aggr->params[i];
1879
1880                                aggr = ast::mutate_field_index(
1881                                        aggr, &AggrDecl::params, i,
1882                                        ast::mutate_field( td, &ast::TypeDecl::name, "__" + td->name + "_generic_" ) );
1883                        }
1884                        return aggr;
1885                }
1886
1887                const ast::StructDecl * previsit( const ast::StructDecl * structDecl ) {
1888                        return renameGenericParams( structDecl );
1889                }
1890
1891                void postvisit( const ast::StructDecl * structDecl ) {
1892                        // visit struct members first so that the types of self-referencing members are
1893                        // updated properly
1894                        if ( ! structDecl->body ) return;
1895
1896                        // update forward declarations to point here
1897                        auto fwds = forwardStructs.equal_range( structDecl->name );
1898                        if ( fwds.first != fwds.second ) {
1899                                auto inst = fwds.first;
1900                                do {
1901                                        // forward decl is stored * mutably * in map, can thus be updated
1902                                        inst->second->base = structDecl;
1903                                } while ( ++inst != fwds.second );
1904                                forwardStructs.erase( fwds.first, fwds.second );
1905                        }
1906                }
1907
1908                const ast::UnionDecl * previsit( const ast::UnionDecl * unionDecl ) {
1909                        return renameGenericParams( unionDecl );
1910                }
1911
1912                void postvisit( const ast::UnionDecl * unionDecl ) {
1913                        // visit union members first so that the types of self-referencing members are updated
1914                        // properly
1915                        if ( ! unionDecl->body ) return;
1916
1917                        // update forward declarations to point here
1918                        auto fwds = forwardUnions.equal_range( unionDecl->name );
1919                        if ( fwds.first != fwds.second ) {
1920                                auto inst = fwds.first;
1921                                do {
1922                                        // forward decl is stored * mutably * in map, can thus be updated
1923                                        inst->second->base = unionDecl;
1924                                } while ( ++inst != fwds.second );
1925                                forwardUnions.erase( fwds.first, fwds.second );
1926                        }
1927                }
1928
1929                const ast::Decl * postvisit( const ast::TraitDecl * traitDecl ) {
1930                        // set the "sized" status for the special "sized" trait
1931                        if ( traitDecl->name == "sized" ) {
1932                                assertf( traitDecl->params.size() == 1, "Built-in trait 'sized' has incorrect "
1933                                        "number of parameters: %zd", traitDecl->params.size() );
1934
1935                                traitDecl = ast::mutate_field_index(
1936                                        traitDecl, &ast::TraitDecl::params, 0,
1937                                        ast::mutate_field(
1938                                                traitDecl->params.front().get(), &ast::TypeDecl::sized, true ) );
1939                        }
1940
1941                        // move assertions from type parameters into the body of the trait
1942                        std::vector< ast::ptr< ast::DeclWithType > > added;
1943                        for ( const ast::TypeDecl * td : traitDecl->params ) {
1944                                for ( const ast::DeclWithType * assn : td->assertions ) {
1945                                        auto inst = dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
1946                                        if ( inst ) {
1947                                                expandAssertions( inst, added );
1948                                        } else {
1949                                                added.emplace_back( assn );
1950                                        }
1951                                }
1952                        }
1953                        if ( ! added.empty() ) {
1954                                auto mut = mutate( traitDecl );
1955                                for ( const ast::DeclWithType * decl : added ) {
1956                                        mut->members.emplace_back( decl );
1957                                }
1958                                traitDecl = mut;
1959                        }
1960
1961                        return traitDecl;
1962                }
1963        };
1964
1965        /// Replaces array and function types in forall lists by appropriate pointer type and assigns
1966        /// each object and function declaration a unique ID
1967        class ForallPointerDecay_new {
1968                const CodeLocation & location;
1969        public:
1970                ForallPointerDecay_new( const CodeLocation & loc ) : location( loc ) {}
1971
1972                const ast::ObjectDecl * previsit( const ast::ObjectDecl * obj ) {
1973                        // ensure that operator names only apply to functions or function pointers
1974                        if (
1975                                CodeGen::isOperator( obj->name )
1976                                && ! dynamic_cast< const ast::FunctionType * >( obj->type->stripDeclarator() )
1977                        ) {
1978                                SemanticError( obj->location, toCString( "operator ", obj->name.c_str(), " is not "
1979                                        "a function or function pointer." )  );
1980                        }
1981
1982                        // ensure object has unique ID
1983                        if ( obj->uniqueId ) return obj;
1984                        auto mut = mutate( obj );
1985                        mut->fixUniqueId();
1986                        return mut;
1987                }
1988
1989                const ast::FunctionDecl * previsit( const ast::FunctionDecl * func ) {
1990                        // ensure function has unique ID
1991                        if ( func->uniqueId ) return func;
1992                        auto mut = mutate( func );
1993                        mut->fixUniqueId();
1994                        return mut;
1995                }
1996
1997                /// Fix up assertions -- flattens assertion lists, removing all trait instances
1998                template< typename node_t, typename parent_t >
1999                static const node_t * forallFixer(
2000                        const CodeLocation & loc, const node_t * node,
2001                        ast::FunctionType::ForallList parent_t::* forallField
2002                ) {
2003                        for ( unsigned i = 0; i < (node->* forallField).size(); ++i ) {
2004                                const ast::TypeDecl * type = (node->* forallField)[i];
2005                                if ( type->assertions.empty() ) continue;
2006
2007                                std::vector< ast::ptr< ast::DeclWithType > > asserts;
2008                                asserts.reserve( type->assertions.size() );
2009
2010                                // expand trait instances into their members
2011                                for ( const ast::DeclWithType * assn : type->assertions ) {
2012                                        auto traitInst =
2013                                                dynamic_cast< const ast::TraitInstType * >( assn->get_type() );
2014                                        if ( traitInst ) {
2015                                                // expand trait instance to all its members
2016                                                expandAssertions( traitInst, asserts );
2017                                        } else {
2018                                                // pass other assertions through
2019                                                asserts.emplace_back( assn );
2020                                        }
2021                                }
2022
2023                                // apply FixFunction to every assertion to check for invalid void type
2024                                for ( ast::ptr< ast::DeclWithType > & assn : asserts ) {
2025                                        bool isVoid = false;
2026                                        assn = fixFunction( assn, isVoid );
2027                                        if ( isVoid ) {
2028                                                SemanticError( loc, node, "invalid type void in assertion of function " );
2029                                        }
2030                                }
2031
2032                                // place mutated assertion list in node
2033                                auto mut = mutate( type );
2034                                mut->assertions = move( asserts );
2035                                node = ast::mutate_field_index( node, forallField, i, mut );
2036                        }
2037                        return node;
2038                }
2039
2040                const ast::FunctionType * previsit( const ast::FunctionType * ftype ) {
2041                        return forallFixer( location, ftype, &ast::FunctionType::forall );
2042                }
2043
2044                const ast::StructDecl * previsit( const ast::StructDecl * aggrDecl ) {
2045                        return forallFixer( aggrDecl->location, aggrDecl, &ast::StructDecl::params );
2046                }
2047
2048                const ast::UnionDecl * previsit( const ast::UnionDecl * aggrDecl ) {
2049                        return forallFixer( aggrDecl->location, aggrDecl, &ast::UnionDecl::params );
2050                }
2051        };
2052        */
2053} // anonymous namespace
2054
2055/*
2056const ast::Type * validateType(
2057                const CodeLocation & loc, const ast::Type * type, const ast::SymbolTable & symtab ) {
2058        // ast::Pass< EnumAndPointerDecay_new > epc;
2059        ast::Pass< LinkReferenceToTypes_new > lrt{ loc, symtab };
2060        ast::Pass< ForallPointerDecay_new > fpd{ loc };
2061
2062        return type->accept( lrt )->accept( fpd );
2063}
2064*/
2065
2066} // namespace SymTab
2067
2068// Local Variables: //
2069// tab-width: 4 //
2070// mode: c++ //
2071// compile-command: "make install" //
2072// End: //
Note: See TracBrowser for help on using the repository browser.