source: src/SymTab/Validate.cc @ 6bc70a38

ADTast-experimental
Last change on this file since 6bc70a38 was 21a2a7d, checked in by Andrew Beach <ajbeach@…>, 17 months ago

Replaced ScopedMap::erase with a version that should avoid the order of declaration problems and also better reflects how it is actually used.

  • Property mode set to 100644
File size: 52.1 KB
RevLine 
[0dd3a2f]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//
[9cb8e88d]7// Validate.cc --
[0dd3a2f]8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
[5dcb881]11// Last Modified By : Andrew Beach
[b9f8274]12// Last Modified On : Tue Jul 12 15:00:00 2022
13// Update Count     : 367
[0dd3a2f]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//
[3c13c03]25// - The type "void" never occurs in lists of function parameter or return types.  A function
26//   taking no arguments has no argument types.
[0dd3a2f]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.
[51b7345]39
[0db6fc0]40#include "Validate.h"
41
[d180746]42#include <cassert>                     // for assertf, assert
[30f9072]43#include <cstddef>                     // for size_t
[d180746]44#include <list>                        // for list
45#include <string>                      // for string
[18e683b]46#include <unordered_map>               // for unordered_map
[d180746]47#include <utility>                     // for pair
[30f9072]48
49#include "CodeGen/CodeGenerator.h"     // for genName
[9236060]50#include "CodeGen/OperatorTable.h"     // for isCtorDtor, isCtorDtorAssign
[25fcb84]51#include "ControlStruct/Mutate.h"      // for ForExprMutator
[18e683b]52#include "Common/CodeLocation.h"       // for CodeLocation
[7abee38]53#include "Common/Stats.h"              // for Stats::Heap
[30f9072]54#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
[d180746]55#include "Common/ScopedMap.h"          // for ScopedMap
[30f9072]56#include "Common/SemanticError.h"      // for SemanticError
57#include "Common/UniqueName.h"         // for UniqueName
58#include "Common/utility.h"            // for operator+, cloneAll, deleteAll
[16ba4a6]59#include "CompilationState.h"          // skip some passes in new-ast build
[be9288a]60#include "Concurrency/Keywords.h"      // for applyKeywords
[30f9072]61#include "FixFunction.h"               // for FixFunction
62#include "Indexer.h"                   // for Indexer
[8b11840]63#include "InitTweak/GenInit.h"         // for fixReturnStatements
[d180746]64#include "InitTweak/InitTweak.h"       // for isCtorDtorAssign
[e563edf]65#include "ResolvExpr/typeops.h"        // for extractResultType
66#include "ResolvExpr/Unify.h"          // for typesCompatible
[4934ea3]67#include "ResolvExpr/Resolver.h"       // for findSingleExpression
[2b79a70]68#include "ResolvExpr/ResolveTypeof.h"  // for resolveTypeof
[be9288a]69#include "SymTab/Autogen.h"            // for SizeType
[9939dc3]70#include "SymTab/ValidateType.h"       // for decayEnumsAndPointers, decayFo...
[07de76b]71#include "SynTree/LinkageSpec.h"       // for C
[be9288a]72#include "SynTree/Attribute.h"         // for noAttributes, Attribute
[30f9072]73#include "SynTree/Constant.h"          // for Constant
[d180746]74#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
75#include "SynTree/Expression.h"        // for CompoundLiteralExpr, Expressio...
76#include "SynTree/Initializer.h"       // for ListInit, Initializer
77#include "SynTree/Label.h"             // for operator==, Label
78#include "SynTree/Mutator.h"           // for Mutator
79#include "SynTree/Type.h"              // for Type, TypeInstType, EnumInstType
80#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
81#include "SynTree/Visitor.h"           // for Visitor
[fd2debf]82#include "Validate/HandleAttributes.h" // for handleAttributes
[2bfc6b2]83#include "Validate/FindSpecialDecls.h" // for FindSpecialDecls
[d180746]84
85class CompoundStmt;
86class ReturnStmt;
87class SwitchStmt;
[51b7345]88
[b16923d]89#define debugPrint( x ) if ( doDebug ) x
[51b7345]90
91namespace SymTab {
[15f5c5e]92        /// hoists declarations that are difficult to hoist while parsing
93        struct HoistTypeDecls final : public WithDeclsToAdd {
[29f9e20]94                void previsit( SizeofExpr * );
95                void previsit( AlignofExpr * );
96                void previsit( UntypedOffsetofExpr * );
[95d09bdb]97                void previsit( CompoundLiteralExpr * );
[29f9e20]98                void handleType( Type * );
99        };
100
[a12c81f3]101        struct FixQualifiedTypes final : public WithIndexer {
[6e50a6b]102                FixQualifiedTypes() : WithIndexer(false) {}
[a12c81f3]103                Type * postmutate( QualifiedType * );
104        };
105
[a09e45b]106        struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
[82dd287]107                /// Flattens nested struct types
[0dd3a2f]108                static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]109
[a09e45b]110                void previsit( StructDecl * aggregateDecl );
111                void previsit( UnionDecl * aggregateDecl );
[0f40912]112                void previsit( StaticAssertDecl * assertDecl );
[d419d8e]113                void previsit( StructInstType * type );
114                void previsit( UnionInstType * type );
115                void previsit( EnumInstType * type );
[9cb8e88d]116
[a08ba92]117          private:
[ef5b828]118                template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl );
[c8ffe20b]119
[bdad6eb7]120                AggregateDecl * parentAggr = nullptr;
[a08ba92]121        };
[c8ffe20b]122
[cce9429]123        /// Fix return types so that every function returns exactly one value
[d24d4e1]124        struct ReturnTypeFixer {
[cce9429]125                static void fix( std::list< Declaration * > &translationUnit );
126
[0db6fc0]127                void postvisit( FunctionDecl * functionDecl );
128                void postvisit( FunctionType * ftype );
[cce9429]129        };
130
[6e50a6b]131        /// Does early resolution on the expressions that give enumeration constants their values
132        struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting {
133                ResolveEnumInitializers( const Indexer * indexer );
134                void postvisit( EnumDecl * enumDecl );
135
136          private:
137                const Indexer * local_indexer;
138
139        };
140
[06edda0]141        /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
[c1ed2ee]142        struct ForallPointerDecay_old final {
[8b11840]143                void previsit( ObjectDecl * object );
144                void previsit( FunctionDecl * func );
[bbf3fda]145                void previsit( FunctionType * ftype );
[bd7e609]146                void previsit( StructDecl * aggrDecl );
147                void previsit( UnionDecl * aggrDecl );
[a08ba92]148        };
[c8ffe20b]149
[d24d4e1]150        struct ReturnChecker : public WithGuards {
[de91427b]151                /// Checks that return statements return nothing if their return type is void
152                /// and return something if the return type is non-void.
153                static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
154
[0db6fc0]155                void previsit( FunctionDecl * functionDecl );
156                void previsit( ReturnStmt * returnStmt );
[de91427b]157
[0db6fc0]158                typedef std::list< DeclarationWithType * > ReturnVals;
159                ReturnVals returnVals;
[de91427b]160        };
161
[48ed81c]162        struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd {
163                ReplaceTypedef() : scopeLevel( 0 ) {}
[de91427b]164                /// Replaces typedefs by forward declarations
[48ed81c]165                static void replaceTypedef( std::list< Declaration * > &translationUnit );
[85c4ef0]166
[48ed81c]167                void premutate( QualifiedType * );
168                Type * postmutate( QualifiedType * qualType );
[a506df4]169                Type * postmutate( TypeInstType * aggregateUseType );
170                Declaration * postmutate( TypedefDecl * typeDecl );
171                void premutate( TypeDecl * typeDecl );
172                void premutate( FunctionDecl * funcDecl );
173                void premutate( ObjectDecl * objDecl );
174                DeclarationWithType * postmutate( ObjectDecl * objDecl );
175
176                void premutate( CastExpr * castExpr );
177
178                void premutate( CompoundStmt * compoundStmt );
179
180                void premutate( StructDecl * structDecl );
181                void premutate( UnionDecl * unionDecl );
182                void premutate( EnumDecl * enumDecl );
[0bcc2b7]183                void premutate( TraitDecl * );
[a506df4]184
[1f370451]185                void premutate( FunctionType * ftype );
186
[a506df4]187          private:
[45161b4d]188                template<typename AggDecl>
189                void addImplicitTypedef( AggDecl * aggDecl );
[48ed81c]190                template< typename AggDecl >
191                void handleAggregate( AggDecl * aggr );
[70a06f6]192
[46f6134]193                typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
[e491159]194                typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
[0bcc2b7]195                typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap;
[cc79d97]196                TypedefMap typedefNames;
[679864e1]197                TypeDeclMap typedeclNames;
[cc79d97]198                int scopeLevel;
[1f370451]199                bool inFunctionType = false;
[a08ba92]200        };
[c8ffe20b]201
[69918cea]202        struct EliminateTypedef {
203                /// removes TypedefDecls from the AST
204                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
205
206                template<typename AggDecl>
[ef5b828]207                void handleAggregate( AggDecl * aggregateDecl );
[69918cea]208
209                void previsit( StructDecl * aggregateDecl );
210                void previsit( UnionDecl * aggregateDecl );
211                void previsit( CompoundStmt * compoundStmt );
212        };
213
[d24d4e1]214        struct VerifyCtorDtorAssign {
[d1969a6]215                /// ensure that constructors, destructors, and assignment have at least one
216                /// parameter, the first of which must be a pointer, and that ctor/dtors have no
[9cb8e88d]217                /// return values.
218                static void verify( std::list< Declaration * > &translationUnit );
219
[ef5b828]220                void previsit( FunctionDecl * funcDecl );
[5f98ce5]221        };
[70a06f6]222
[11ab8ea8]223        /// ensure that generic types have the correct number of type arguments
[d24d4e1]224        struct ValidateGenericParameters {
[0db6fc0]225                void previsit( StructInstType * inst );
226                void previsit( UnionInstType * inst );
[5f98ce5]227        };
[70a06f6]228
[6e50a6b]229        /// desugar declarations and uses of dimension paramaters like [N],
230        /// from type-system managed values, to tunnneling via ordinary types,
231        /// as char[-] in and sizeof(-) out
232        struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards {
233                static void translateDimensions( std::list< Declaration * > &translationUnit );
234                TranslateDimensionGenericParameters();
235
236                bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type
237                bool visitingChildOfSUIT = false;
238                void changeState_ChildOfSUIT( bool newVal );
239                void premutate( StructInstType * sit );
240                void premutate( UnionInstType * uit );
241                void premutate( BaseSyntaxNode * node );
242
243                TypeDecl * postmutate( TypeDecl * td );
244                Expression * postmutate( DimensionExpr * de );
245                Expression * postmutate( Expression * e );
246        };
247
[2b79a70]248        struct FixObjectType : public WithIndexer {
249                /// resolves typeof type in object, function, and type declarations
250                static void fix( std::list< Declaration * > & translationUnit );
251
252                void previsit( ObjectDecl * );
253                void previsit( FunctionDecl * );
254                void previsit( TypeDecl * );
255        };
256
[09867ec]257        struct InitializerLength {
[fbd7ad6]258                /// for array types without an explicit length, compute the length and store it so that it
259                /// is known to the rest of the phases. For example,
260                ///   int x[] = { 1, 2, 3 };
261                ///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
262                /// here x and y are known at compile-time to have length 3, so change this into
263                ///   int x[3] = { 1, 2, 3 };
264                ///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
265                static void computeLength( std::list< Declaration * > & translationUnit );
266
[0db6fc0]267                void previsit( ObjectDecl * objDecl );
[09867ec]268        };
269
270        struct ArrayLength : public WithIndexer {
271                static void computeLength( std::list< Declaration * > & translationUnit );
272
[3ff4c1e]273                void previsit( ArrayType * arrayType );
[fbd7ad6]274        };
275
[d24d4e1]276        struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
[68fe077a]277                Type::StorageClasses storageClasses;
[630a82a]278
[ef5b828]279                void premutate( ObjectDecl * objectDecl );
280                Expression * postmutate( CompoundLiteralExpr * compLitExpr );
[9cb8e88d]281        };
282
[5809461]283        struct LabelAddressFixer final : public WithGuards {
284                std::set< Label > labels;
285
286                void premutate( FunctionDecl * funcDecl );
287                Expression * postmutate( AddressExpr * addrExpr );
288        };
[4fbdfae0]289
[b9f8274]290        void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
[15f5c5e]291                PassVisitor<HoistTypeDecls> hoistDecls;
[3c0d4cd]292                {
293                        Stats::Heap::newPass("validate-A");
294                        Stats::Time::BlockGuard guard("validate-A");
[98538288]295                        VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
[3c0d4cd]296                        acceptAll( translationUnit, hoistDecls );
297                        ReplaceTypedef::replaceTypedef( translationUnit );
298                        ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
[9939dc3]299                        decayEnumsAndPointers( translationUnit ); // 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
[3c0d4cd]300                }
[5dcb881]301                PassVisitor<FixQualifiedTypes> fixQual;
[3c0d4cd]302                {
303                        Stats::Heap::newPass("validate-B");
304                        Stats::Time::BlockGuard guard("validate-B");
[72e76fd]305                        linkReferenceToTypes( translationUnit ); // Must happen before auto-gen, because it uses the sized flag.
[6e50a6b]306                        mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed
307                        HoistStruct::hoistStruct( translationUnit );
308                        EliminateTypedef::eliminateTypedef( translationUnit );
[3c0d4cd]309                }
[5dcb881]310                PassVisitor<ValidateGenericParameters> genericParams;
311                PassVisitor<ResolveEnumInitializers> rei( nullptr );
[3c0d4cd]312                {
313                        Stats::Heap::newPass("validate-C");
314                        Stats::Time::BlockGuard guard("validate-C");
[6e50a6b]315                        Stats::Time::TimeBlock("Validate Generic Parameters", [&]() {
316                                acceptAll( translationUnit, genericParams );  // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef
317                        });
318                        Stats::Time::TimeBlock("Translate Dimensions", [&]() {
319                                TranslateDimensionGenericParameters::translateDimensions( translationUnit );
320                        });
[7c919559]321                        if (!useNewAST) {
[6e50a6b]322                        Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() {
323                                acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling
324                        });
[7c919559]325                        }
[6e50a6b]326                        Stats::Time::TimeBlock("Check Function Returns", [&]() {
327                                ReturnChecker::checkFunctionReturns( translationUnit );
328                        });
329                        Stats::Time::TimeBlock("Fix Return Statements", [&]() {
330                                InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
331                        });
[3c0d4cd]332                }
333                {
334                        Stats::Heap::newPass("validate-D");
335                        Stats::Time::BlockGuard guard("validate-D");
[c884f2d]336                        Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() {
337                                Concurrency::applyKeywords( translationUnit );
338                        });
339                        Stats::Time::TimeBlock("Forall Pointer Decay", [&]() {
[9490621]340                                decayForallPointers( translationUnit ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
[c884f2d]341                        });
342                        Stats::Time::TimeBlock("Hoist Control Declarations", [&]() {
343                                ControlStruct::hoistControlDecls( translationUnit );  // hoist initialization out of for statements; must happen before autogenerateRoutines
344                        });
345                        Stats::Time::TimeBlock("Generate Autogen routines", [&]() {
[c1ed2ee]346                                autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old
[c884f2d]347                        });
[3c0d4cd]348                }
[5dcb881]349                PassVisitor<CompoundLiteral> compoundliteral;
[3c0d4cd]350                {
351                        Stats::Heap::newPass("validate-E");
352                        Stats::Time::BlockGuard guard("validate-E");
[c884f2d]353                        Stats::Time::TimeBlock("Implement Mutex Func", [&]() {
354                                Concurrency::implementMutexFuncs( translationUnit );
355                        });
356                        Stats::Time::TimeBlock("Implement Thread Start", [&]() {
357                                Concurrency::implementThreadStarter( translationUnit );
358                        });
359                        Stats::Time::TimeBlock("Compound Literal", [&]() {
360                                mutateAll( translationUnit, compoundliteral );
361                        });
[16ba4a6]362                        if (!useNewAST) {
363                                Stats::Time::TimeBlock("Resolve With Expressions", [&]() {
364                                        ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables
365                                });
366                        }
[3c0d4cd]367                }
[5dcb881]368                PassVisitor<LabelAddressFixer> labelAddrFixer;
[3c0d4cd]369                {
370                        Stats::Heap::newPass("validate-F");
371                        Stats::Time::BlockGuard guard("validate-F");
[16ba4a6]372                        if (!useNewAST) {
373                                Stats::Time::TimeCall("Fix Object Type",
374                                        FixObjectType::fix, translationUnit);
375                        }
[09867ec]376                        Stats::Time::TimeCall("Initializer Length",
377                                InitializerLength::computeLength, translationUnit);
378                        if (!useNewAST) {
379                                Stats::Time::TimeCall("Array Length",
380                                        ArrayLength::computeLength, translationUnit);
381                        }
[095b99a]382                        Stats::Time::TimeCall("Find Special Declarations",
383                                Validate::findSpecialDecls, translationUnit);
384                        Stats::Time::TimeCall("Fix Label Address",
385                                mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer);
[16ba4a6]386                        if (!useNewAST) {
387                                Stats::Time::TimeCall("Handle Attributes",
388                                        Validate::handleAttributes, translationUnit);
389                        }
[3c0d4cd]390                }
[a08ba92]391        }
[9cb8e88d]392
[15f5c5e]393        void HoistTypeDecls::handleType( Type * type ) {
[29f9e20]394                // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here
395                AggregateDecl * aggr = nullptr;
396                if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) {
397                        aggr = inst->baseStruct;
398                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) {
399                        aggr = inst->baseUnion;
400                } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) {
401                        aggr = inst->baseEnum;
402                }
403                if ( aggr && aggr->body ) {
404                        declsToAddBefore.push_front( aggr );
405                }
406        }
407
[15f5c5e]408        void HoistTypeDecls::previsit( SizeofExpr * expr ) {
[29f9e20]409                handleType( expr->type );
410        }
411
[15f5c5e]412        void HoistTypeDecls::previsit( AlignofExpr * expr ) {
[29f9e20]413                handleType( expr->type );
414        }
415
[15f5c5e]416        void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) {
[29f9e20]417                handleType( expr->type );
418        }
419
[95d09bdb]420        void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) {
421                handleType( expr->result );
422        }
423
[29f9e20]424
[a12c81f3]425        Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) {
426                Type * parent = qualType->parent;
427                Type * child = qualType->child;
428                if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) {
429                        // .T => lookup T at global scope
[062e8df]430                        if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
[a12c81f3]431                                auto td = indexer.globalLookupType( inst->name );
[062e8df]432                                if ( ! td ) {
433                                        SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) );
434                                }
[a12c81f3]435                                auto base = td->base;
[062e8df]436                                assert( base );
[8a3ecb9]437                                Type * ret = base->clone();
438                                ret->get_qualifiers() = qualType->get_qualifiers();
439                                return ret;
[a12c81f3]440                        } else {
[062e8df]441                                // .T => T is not a type name
442                                assertf( false, "unhandled global qualified child type: %s", toCString(child) );
[a12c81f3]443                        }
444                } else {
445                        // S.T => S must be an aggregate type, find the declaration for T in S.
446                        AggregateDecl * aggr = nullptr;
447                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) {
448                                aggr = inst->baseStruct;
449                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) {
450                                aggr = inst->baseUnion;
451                        } else {
[062e8df]452                                SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) );
[a12c81f3]453                        }
454                        assert( aggr ); // TODO: need to handle forward declarations
455                        for ( Declaration * member : aggr->members ) {
[7e08acf]456                                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) {
[8a3ecb9]457                                        // name on the right is a typedef
[a12c81f3]458                                        if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) {
459                                                if ( aggr->name == inst->name ) {
[062e8df]460                                                        assert( aggr->base );
[8a3ecb9]461                                                        Type * ret = aggr->base->clone();
462                                                        ret->get_qualifiers() = qualType->get_qualifiers();
[7e08acf]463                                                        TypeSubstitution sub = parent->genericSubstitution();
464                                                        sub.apply(ret);
[8a3ecb9]465                                                        return ret;
[a12c81f3]466                                                }
467                                        }
468                                } else {
469                                        // S.T - S is not an aggregate => error
470                                        assertf( false, "unhandled qualified child type: %s", toCString(qualType) );
471                                }
472                        }
473                        // failed to find a satisfying definition of type
[062e8df]474                        SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) );
[a12c81f3]475                }
476
477                // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup?
478        }
479
480
[a08ba92]481        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[a09e45b]482                PassVisitor<HoistStruct> hoister;
483                acceptAll( translationUnit, hoister );
[a08ba92]484        }
[c8ffe20b]485
[ef5b828]486        bool shouldHoist( Declaration * decl ) {
[0f40912]487                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl );
[a08ba92]488        }
[c0aa336]489
[d419d8e]490        namespace {
491                void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) {
492                        if ( aggr->parent ) qualifiedName( aggr->parent, ss );
493                        ss << "__" << aggr->name;
494                }
495
496                // mangle nested type names using entire parent chain
497                std::string qualifiedName( AggregateDecl * aggr ) {
498                        std::ostringstream ss;
499                        qualifiedName( aggr, ss );
500                        return ss.str();
501                }
502        }
503
[a08ba92]504        template< typename AggDecl >
[ef5b828]505        void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) {
[bdad6eb7]506                if ( parentAggr ) {
[d419d8e]507                        aggregateDecl->parent = parentAggr;
508                        aggregateDecl->name = qualifiedName( aggregateDecl );
[0dd3a2f]509                        // Add elements in stack order corresponding to nesting structure.
[a09e45b]510                        declsToAddBefore.push_front( aggregateDecl );
[0dd3a2f]511                } else {
[bdad6eb7]512                        GuardValue( parentAggr );
513                        parentAggr = aggregateDecl;
[0dd3a2f]514                } // if
515                // Always remove the hoisted aggregate from the inner structure.
[0f40912]516                GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } );
[a08ba92]517        }
[c8ffe20b]518
[0f40912]519        void HoistStruct::previsit( StaticAssertDecl * assertDecl ) {
520                if ( parentAggr ) {
521                        declsToAddBefore.push_back( assertDecl );
522                }
523        }
524
[a09e45b]525        void HoistStruct::previsit( StructDecl * aggregateDecl ) {
[0dd3a2f]526                handleAggregate( aggregateDecl );
[a08ba92]527        }
[c8ffe20b]528
[a09e45b]529        void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
[0dd3a2f]530                handleAggregate( aggregateDecl );
[a08ba92]531        }
[c8ffe20b]532
[d419d8e]533        void HoistStruct::previsit( StructInstType * type ) {
534                // need to reset type name after expanding to qualified name
535                assert( type->baseStruct );
536                type->name = type->baseStruct->name;
537        }
538
539        void HoistStruct::previsit( UnionInstType * type ) {
540                assert( type->baseUnion );
541                type->name = type->baseUnion->name;
542        }
543
544        void HoistStruct::previsit( EnumInstType * type ) {
545                assert( type->baseEnum );
546                type->name = type->baseEnum->name;
547        }
548
549
[ef5b828]550        bool isTypedef( Declaration * decl ) {
[69918cea]551                return dynamic_cast< TypedefDecl * >( decl );
552        }
553
554        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
555                PassVisitor<EliminateTypedef> eliminator;
556                acceptAll( translationUnit, eliminator );
557                filter( translationUnit, isTypedef, true );
558        }
559
560        template< typename AggDecl >
[ef5b828]561        void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) {
[69918cea]562                filter( aggregateDecl->members, isTypedef, true );
563        }
564
565        void EliminateTypedef::previsit( StructDecl * aggregateDecl ) {
566                handleAggregate( aggregateDecl );
567        }
568
569        void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) {
570                handleAggregate( aggregateDecl );
571        }
572
573        void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) {
574                // remove and delete decl stmts
575                filter( compoundStmt->kids, [](Statement * stmt) {
[ef5b828]576                        if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
[69918cea]577                                if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) {
578                                        return true;
579                                } // if
580                        } // if
581                        return false;
582                }, true);
583        }
584
[be9036d]585        // expand assertions from trait instance, performing the appropriate type variable substitutions
586        template< typename Iterator >
587        void expandAssertions( TraitInstType * inst, Iterator out ) {
[eaa6430]588                assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
[be9036d]589                std::list< DeclarationWithType * > asserts;
590                for ( Declaration * decl : inst->baseTrait->members ) {
[e3e16bc]591                        asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
[2c57025]592                }
[be9036d]593                // substitute trait decl parameters for instance parameters
594                applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
595        }
596
[6e50a6b]597        ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) {
598                if ( other_indexer ) {
599                        local_indexer = other_indexer;
600                } else {
601                        local_indexer = &indexer;
602                } // if
603        }
604
605        void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) {
606                if ( enumDecl->body ) {
607                        for ( Declaration * member : enumDecl->members ) {
608                                ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member );
609                                if ( field->init ) {
610                                        // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information.
611                                        SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init );
[4559b34]612                                        if ( !enumDecl->base || dynamic_cast<BasicType *>(enumDecl->base))
613                                                ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
614                                        else {
615                                                if (dynamic_cast<PointerType *>(enumDecl->base)) {
616                                                        auto typePtr = dynamic_cast<PointerType *>(enumDecl->base);
617                                                        ResolvExpr::findSingleExpression( init->value,
618                                                         new PointerType( Type::Qualifiers(), typePtr->base ), indexer );
619                                                } else {
620                                                        ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer );
621                                                }
622                                        }
[6e50a6b]623                                }
624                        }
[4559b34]625
[6e50a6b]626                } // if
627        }
628
[4a9ccc3]629        /// Fix up assertions - flattens assertion lists, removing all trait instances
[8b11840]630        void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
631                for ( TypeDecl * type : forall ) {
[be9036d]632                        std::list< DeclarationWithType * > asserts;
633                        asserts.splice( asserts.end(), type->assertions );
634                        // expand trait instances into their members
635                        for ( DeclarationWithType * assertion : asserts ) {
[ef5b828]636                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
[be9036d]637                                        // expand trait instance into all of its members
638                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
639                                        delete traitInst;
640                                } else {
641                                        // pass other assertions through
642                                        type->assertions.push_back( assertion );
643                                } // if
644                        } // for
645                        // apply FixFunction to every assertion to check for invalid void type
646                        for ( DeclarationWithType *& assertion : type->assertions ) {
[4bda2cf]647                                bool isVoid = fixFunction( assertion );
648                                if ( isVoid ) {
[a16764a6]649                                        SemanticError( node, "invalid type void in assertion of function " );
[be9036d]650                                } // if
651                        } // for
652                        // normalizeAssertions( type->assertions );
[0dd3a2f]653                } // for
[a08ba92]654        }
[c8ffe20b]655
[9490621]656        /// Replace all traits in assertion lists with their assertions.
657        void expandTraits( std::list< TypeDecl * > & forall ) {
658                for ( TypeDecl * type : forall ) {
659                        std::list< DeclarationWithType * > asserts;
660                        asserts.splice( asserts.end(), type->assertions );
661                        // expand trait instances into their members
662                        for ( DeclarationWithType * assertion : asserts ) {
663                                if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
664                                        // expand trait instance into all of its members
665                                        expandAssertions( traitInst, back_inserter( type->assertions ) );
666                                        delete traitInst;
667                                } else {
668                                        // pass other assertions through
669                                        type->assertions.push_back( assertion );
670                                } // if
671                        } // for
672                }
673        }
674
675        /// Fix each function in the assertion list and check for invalid void type.
676        void fixAssertions(
677                        std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
678                for ( TypeDecl * type : forall ) {
679                        for ( DeclarationWithType *& assertion : type->assertions ) {
680                                bool isVoid = fixFunction( assertion );
681                                if ( isVoid ) {
682                                        SemanticError( node, "invalid type void in assertion of function " );
683                                } // if
684                        } // for
685                }
686        }
687
[ef5b828]688        void ForallPointerDecay_old::previsit( ObjectDecl * object ) {
[3d2b7bc]689                // ensure that operator names only apply to functions or function pointers
690                if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
691                        SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
692                }
[0dd3a2f]693                object->fixUniqueId();
[a08ba92]694        }
[c8ffe20b]695
[ef5b828]696        void ForallPointerDecay_old::previsit( FunctionDecl * func ) {
[0dd3a2f]697                func->fixUniqueId();
[a08ba92]698        }
[c8ffe20b]699
[c1ed2ee]700        void ForallPointerDecay_old::previsit( FunctionType * ftype ) {
[bbf3fda]701                forallFixer( ftype->forall, ftype );
702        }
703
[c1ed2ee]704        void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) {
[bd7e609]705                forallFixer( aggrDecl->parameters, aggrDecl );
706        }
707
[c1ed2ee]708        void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) {
[bd7e609]709                forallFixer( aggrDecl->parameters, aggrDecl );
710        }
711
[de91427b]712        void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
[0db6fc0]713                PassVisitor<ReturnChecker> checker;
[de91427b]714                acceptAll( translationUnit, checker );
715        }
716
[0db6fc0]717        void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
[0508ab3]718                GuardValue( returnVals );
[de91427b]719                returnVals = functionDecl->get_functionType()->get_returnVals();
720        }
721
[0db6fc0]722        void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
[74d1804]723                // Previously this also checked for the existence of an expr paired with no return values on
724                // the  function return type. This is incorrect, since you can have an expression attached to
725                // a return statement in a void-returning function in C. The expression is treated as if it
726                // were cast to void.
[30f9072]727                if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
[a16764a6]728                        SemanticError( returnStmt, "Non-void function returns no values: " );
[de91427b]729                }
730        }
731
732
[48ed81c]733        void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) {
734                PassVisitor<ReplaceTypedef> eliminator;
[0dd3a2f]735                mutateAll( translationUnit, eliminator );
[a506df4]736                if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
[5f98ce5]737                        // grab and remember declaration of size_t
[2bfc6b2]738                        Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone();
[5f98ce5]739                } else {
[40e636a]740                        // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
741                        // eventually should have a warning for this case.
[2bfc6b2]742                        Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[5f98ce5]743                }
[a08ba92]744        }
[c8ffe20b]745
[48ed81c]746        void ReplaceTypedef::premutate( QualifiedType * ) {
747                visit_children = false;
748        }
749
750        Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) {
751                // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type
[ef5b828]752                qualType->parent = qualType->parent->acceptMutator( * visitor );
[48ed81c]753                return qualType;
754        }
755
[a7c31e0]756        static bool isNonParameterAttribute( Attribute * attr ) {
757                static const std::vector<std::string> bad_names = {
758                        "aligned", "__aligned__",
759                };
760                for ( auto name : bad_names ) {
761                        if ( name == attr->name ) {
762                                return true;
763                        }
764                }
765                return false;
766        }
767
[48ed81c]768        Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) {
[9cb8e88d]769                // instances of typedef types will come here. If it is an instance
[cc79d97]770                // of a typdef type, link the instance to its actual type.
[0b3b2ae]771                TypedefMap::const_iterator def = typedefNames.find( typeInst->name );
[0dd3a2f]772                if ( def != typedefNames.end() ) {
[ef5b828]773                        Type * ret = def->second.first->base->clone();
[e82ef13]774                        ret->location = typeInst->location;
[6f95000]775                        ret->get_qualifiers() |= typeInst->get_qualifiers();
[a7c31e0]776                        // GCC ignores certain attributes if they arrive by typedef, this mimics that.
777                        if ( inFunctionType ) {
778                                ret->attributes.remove_if( isNonParameterAttribute );
[1f370451]779                        }
[a7c31e0]780                        ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
[0215a76f]781                        // place instance parameters on the typedef'd type
[f53836b]782                        if ( ! typeInst->parameters.empty() ) {
[ef5b828]783                                ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret);
[0215a76f]784                                if ( ! rtt ) {
[a16764a6]785                                        SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
[0215a76f]786                                }
[0b3b2ae]787                                rtt->parameters.clear();
[f53836b]788                                cloneAll( typeInst->parameters, rtt->parameters );
[ef5b828]789                                mutateAll( rtt->parameters, * visitor );  // recursively fix typedefs on parameters
[1db21619]790                        } // if
[0dd3a2f]791                        delete typeInst;
792                        return ret;
[679864e1]793                } else {
[0b3b2ae]794                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name );
[062e8df]795                        if ( base == typedeclNames.end() ) {
796                                SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) );
797                        }
[1e8b02f5]798                        typeInst->set_baseType( base->second );
[062e8df]799                        return typeInst;
[0dd3a2f]800                } // if
[062e8df]801                assert( false );
[a08ba92]802        }
[c8ffe20b]803
[f53836b]804        struct VarLenChecker : WithShortCircuiting {
805                void previsit( FunctionType * ) { visit_children = false; }
806                void previsit( ArrayType * at ) {
807                        isVarLen |= at->isVarLen;
808                }
809                bool isVarLen = false;
810        };
811
812        bool isVariableLength( Type * t ) {
813                PassVisitor<VarLenChecker> varLenChecker;
814                maybeAccept( t, varLenChecker );
815                return varLenChecker.pass.isVarLen;
816        }
817
[48ed81c]818        Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) {
[0b3b2ae]819                if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) {
[9cb8e88d]820                        // typedef to the same name from the same scope
[cc79d97]821                        // must be from the same type
822
[0b3b2ae]823                        Type * t1 = tyDecl->base;
824                        Type * t2 = typedefNames[ tyDecl->name ].first->base;
[1cbca6e]825                        if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[a16764a6]826                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
[f53836b]827                        }
[4b97770]828                        // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
829                        // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
830                        // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
831                        // to fix this corner case likely outweighs the utility of allowing it.
[f53836b]832                        if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
[a16764a6]833                                SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
[85c4ef0]834                        }
[cc79d97]835                } else {
[0b3b2ae]836                        typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
[cc79d97]837                } // if
838
[0dd3a2f]839                // When a typedef is a forward declaration:
840                //    typedef struct screen SCREEN;
841                // the declaration portion must be retained:
842                //    struct screen;
843                // because the expansion of the typedef is:
[ef5b828]844                //    void rtn( SCREEN * p ) => void rtn( struct screen * p )
[0dd3a2f]845                // hence the type-name "screen" must be defined.
846                // Note, qualifiers on the typedef are superfluous for the forward declaration.
[6f95000]847
[ef5b828]848                Type * designatorType = tyDecl->base->stripDeclarator();
849                if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
[312029a]850                        declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) );
[ef5b828]851                } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
[48ed81c]852                        declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) );
[b0d9ff7]853                } else if ( EnumInstType * enumInst = dynamic_cast< EnumInstType * >( designatorType ) ) {
854                        if ( enumInst->baseEnum ) {
855                                const EnumDecl * enumDecl = enumInst->baseEnum;
856                                declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, enumDecl->isTyped, tyDecl->linkage, enumDecl->base ) );
[3e54399]857                        } else {
[b0d9ff7]858                                declsToAddBefore.push_back( new EnumDecl( enumInst->name, noAttributes, tyDecl->linkage ) );
[3e54399]859                        }
[0dd3a2f]860                } // if
[48ed81c]861                return tyDecl->clone();
[a08ba92]862        }
[c8ffe20b]863
[48ed81c]864        void ReplaceTypedef::premutate( TypeDecl * typeDecl ) {
[21a2a7d]865                typedefNames.erase( typeDecl->name );
[0bcc2b7]866                typedeclNames.insert( typeDecl->name, typeDecl );
[a08ba92]867        }
[c8ffe20b]868
[48ed81c]869        void ReplaceTypedef::premutate( FunctionDecl * ) {
[a506df4]870                GuardScope( typedefNames );
[0bcc2b7]871                GuardScope( typedeclNames );
[a08ba92]872        }
[c8ffe20b]873
[48ed81c]874        void ReplaceTypedef::premutate( ObjectDecl * ) {
[a506df4]875                GuardScope( typedefNames );
[0bcc2b7]876                GuardScope( typedeclNames );
[a506df4]877        }
[dd020c0]878
[48ed81c]879        DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) {
[ef5b828]880                if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type?
[02e5ab6]881                        // replace the current object declaration with a function declaration
[0b3b2ae]882                        FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() );
883                        objDecl->attributes.clear();
[dbe8f244]884                        objDecl->set_type( nullptr );
[0a86a30]885                        delete objDecl;
886                        return newDecl;
[1db21619]887                } // if
[a506df4]888                return objDecl;
[a08ba92]889        }
[c8ffe20b]890
[48ed81c]891        void ReplaceTypedef::premutate( CastExpr * ) {
[a506df4]892                GuardScope( typedefNames );
[0bcc2b7]893                GuardScope( typedeclNames );
[a08ba92]894        }
[c8ffe20b]895
[48ed81c]896        void ReplaceTypedef::premutate( CompoundStmt * ) {
[a506df4]897                GuardScope( typedefNames );
[0bcc2b7]898                GuardScope( typedeclNames );
[cc79d97]899                scopeLevel += 1;
[a506df4]900                GuardAction( [this](){ scopeLevel -= 1; } );
901        }
902
[45161b4d]903        template<typename AggDecl>
[48ed81c]904        void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
[45161b4d]905                if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
[ef5b828]906                        Type * type = nullptr;
[45161b4d]907                        if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
908                                type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
909                        } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
910                                type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
911                        } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
912                                type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
913                        } // if
[0b0f1dd]914                        TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) );
[46f6134]915                        typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
[48ed81c]916                        // add the implicit typedef to the AST
917                        declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) );
[45161b4d]918                } // if
919        }
[4e06c1e]920
[48ed81c]921        template< typename AggDecl >
922        void ReplaceTypedef::handleAggregate( AggDecl * aggr ) {
923                SemanticErrorException errors;
[a506df4]924
[48ed81c]925                ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore );
926                ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter  );
927                declsToAddBefore.clear();
928                declsToAddAfter.clear();
[a506df4]929
[48ed81c]930                GuardScope( typedefNames );
[0bcc2b7]931                GuardScope( typedeclNames );
[ef5b828]932                mutateAll( aggr->parameters, * visitor );
[798a8b3]933                mutateAll( aggr->attributes, * visitor );
[85c4ef0]934
[48ed81c]935                // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body.
936                for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) {
937                        if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); }
[a506df4]938
[48ed81c]939                        try {
[ef5b828]940                                * i = maybeMutate( * i, * visitor );
[48ed81c]941                        } catch ( SemanticErrorException &e ) {
942                                errors.append( e );
943                        }
944
945                        if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); }
946                }
947
948                if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); }
949                if ( !errors.isEmpty() ) { throw errors; }
[85c4ef0]950        }
951
[48ed81c]952        void ReplaceTypedef::premutate( StructDecl * structDecl ) {
953                visit_children = false;
954                addImplicitTypedef( structDecl );
955                handleAggregate( structDecl );
[a506df4]956        }
957
[48ed81c]958        void ReplaceTypedef::premutate( UnionDecl * unionDecl ) {
959                visit_children = false;
960                addImplicitTypedef( unionDecl );
961                handleAggregate( unionDecl );
[85c4ef0]962        }
963
[48ed81c]964        void ReplaceTypedef::premutate( EnumDecl * enumDecl ) {
965                addImplicitTypedef( enumDecl );
[85c4ef0]966        }
967
[48ed81c]968        void ReplaceTypedef::premutate( FunctionType * ) {
[1f370451]969                GuardValue( inFunctionType );
970                inFunctionType = true;
971        }
972
[0bcc2b7]973        void ReplaceTypedef::premutate( TraitDecl * ) {
974                GuardScope( typedefNames );
975                GuardScope( typedeclNames);
976        }
977
[d1969a6]978        void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
[0db6fc0]979                PassVisitor<VerifyCtorDtorAssign> verifier;
[9cb8e88d]980                acceptAll( translationUnit, verifier );
981        }
982
[0db6fc0]983        void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
[9cb8e88d]984                FunctionType * funcType = funcDecl->get_functionType();
985                std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
986                std::list< DeclarationWithType * > &params = funcType->get_parameters();
987
[bff227f]988                if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
[9cb8e88d]989                        if ( params.size() == 0 ) {
[98538288]990                                SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." );
[9cb8e88d]991                        }
[ce8c12f]992                        ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
[084fecc]993                        if ( ! refType ) {
[98538288]994                                SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." );
[9cb8e88d]995                        }
[bff227f]996                        if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
[98538288]997                                if(!returnVals.front()->get_type()->isVoid()) {
998                                        SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." );
999                                }
[9cb8e88d]1000                        }
1001                }
1002        }
[70a06f6]1003
[6e50a6b]1004        // Test for special name on a generic parameter.  Special treatment for the
1005        // special name is a bootstrapping hack.  In most cases, the worlds of T's
1006        // and of N's don't overlap (normal treamtemt).  The foundations in
1007        // array.hfa use tagging for both types and dimensions.  Tagging treats
1008        // its subject parameter even more opaquely than T&, which assumes it is
1009        // possible to have a pointer/reference to such an object.  Tagging only
1010        // seeks to identify the type-system resident at compile time.  Both N's
1011        // and T's can make tags.  The tag definition uses the special name, which
1012        // is treated as "an N or a T."  This feature is not inteded to be used
1013        // outside of the definition and immediate uses of a tag.
1014        static inline bool isReservedTysysIdOnlyName( const std::string & name ) {
1015                // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic
1016                int foundAt = name.find("__CFA_tysys_id_only");
1017                if (foundAt == 0) return true;
1018                if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true;
1019                return false;
1020        }
1021
[11ab8ea8]1022        template< typename Aggr >
1023        void validateGeneric( Aggr * inst ) {
1024                std::list< TypeDecl * > * params = inst->get_baseParameters();
[30f9072]1025                if ( params ) {
[11ab8ea8]1026                        std::list< Expression * > & args = inst->get_parameters();
[67cf18c]1027
1028                        // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
1029                        // A substitution is used to ensure that defaults are replaced correctly, e.g.,
1030                        //   forall(otype T, otype alloc = heap_allocator(T)) struct vector;
1031                        //   vector(int) v;
1032                        // after insertion of default values becomes
1033                        //   vector(int, heap_allocator(T))
1034                        // and the substitution is built with T=int so that after substitution, the result is
1035                        //   vector(int, heap_allocator(int))
1036                        TypeSubstitution sub;
1037                        auto paramIter = params->begin();
[6e50a6b]1038                        auto argIter = args.begin();
1039                        for ( ; paramIter != params->end(); ++paramIter, ++argIter ) {
1040                                if ( argIter != args.end() ) {
1041                                        TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter );
1042                                        if ( expr ) {
1043                                                sub.add( (* paramIter)->get_name(), expr->get_type()->clone() );
1044                                        }
1045                                } else {
[ef5b828]1046                                        Type * defaultType = (* paramIter)->get_init();
[67cf18c]1047                                        if ( defaultType ) {
1048                                                args.push_back( new TypeExpr( defaultType->clone() ) );
[ef5b828]1049                                                sub.add( (* paramIter)->get_name(), defaultType->clone() );
[6e50a6b]1050                                                argIter = std::prev(args.end());
1051                                        } else {
1052                                                SemanticError( inst, "Too few type arguments in generic type " );
[67cf18c]1053                                        }
1054                                }
[6e50a6b]1055                                assert( argIter != args.end() );
1056                                bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension;
1057                                bool typeArgGiven;
1058                                if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) {
1059                                        // coerce a match when declaration is reserved name, which means "either"
1060                                        typeArgGiven = typeParamDeclared;
1061                                } else {
1062                                        typeArgGiven = dynamic_cast< TypeExpr * >( * argIter );
1063                                }
1064                                if ( ! typeParamDeclared &&   typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " );
1065                                if (   typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " );
[67cf18c]1066                        }
1067
1068                        sub.apply( inst );
[a16764a6]1069                        if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
[11ab8ea8]1070                }
1071        }
1072
[0db6fc0]1073        void ValidateGenericParameters::previsit( StructInstType * inst ) {
[11ab8ea8]1074                validateGeneric( inst );
1075        }
[9cb8e88d]1076
[0db6fc0]1077        void ValidateGenericParameters::previsit( UnionInstType * inst ) {
[11ab8ea8]1078                validateGeneric( inst );
[9cb8e88d]1079        }
[70a06f6]1080
[6e50a6b]1081        void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) {
1082                PassVisitor<TranslateDimensionGenericParameters> translator;
1083                mutateAll( translationUnit, translator );
1084        }
1085
1086        TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {}
1087
1088        // Declaration of type variable:           forall( [N] )          ->  forall( N & | sized( N ) )
1089        TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) {
1090                if ( td->kind == TypeDecl::Dimension ) {
1091                        td->kind = TypeDecl::Dtype;
1092                        if ( ! isReservedTysysIdOnlyName( td->name ) ) {
1093                                td->sized = true;
1094                        }
1095                }
1096                return td;
1097        }
1098
1099        // Situational awareness:
1100        // array( float, [[currentExpr]]     )  has  visitingChildOfSUIT == true
1101        // array( float, [[currentExpr]] - 1 )  has  visitingChildOfSUIT == false
1102        // size_t x =    [[currentExpr]]        has  visitingChildOfSUIT == false
1103        void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) {
1104                GuardValue( nextVisitedNodeIsChildOfSUIT );
1105                GuardValue( visitingChildOfSUIT );
1106                visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT;
1107                nextVisitedNodeIsChildOfSUIT = newVal;
1108        }
1109        void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) {
1110                (void) sit;
1111                changeState_ChildOfSUIT(true);
1112        }
1113        void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) {
1114                (void) uit;
1115                changeState_ChildOfSUIT(true);
1116        }
1117        void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) {
1118                (void) node;
1119                changeState_ChildOfSUIT(false);
1120        }
1121
1122        // Passing values as dimension arguments:  array( float,     7 )  -> array( float, char[             7 ] )
1123        // Consuming dimension parameters:         size_t x =    N - 1 ;  -> size_t x =          sizeof(N) - 1   ;
1124        // Intertwined reality:                    array( float, N     )  -> array( float,              N        )
1125        //                                         array( float, N - 1 )  -> array( float, char[ sizeof(N) - 1 ] )
1126        // Intertwined case 1 is not just an optimization.
1127        // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in:
1128        //   forall([N]) void f( array(float, N) & );
1129        //   array(float, 7) a;
1130        //   f(a);
1131
1132        Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) {
1133                // Expression de is an occurrence of N in LHS of above examples.
1134                // Look up the name that de references.
1135                // If we are in a struct body, then this reference can be to an entry of the stuct's forall list.
1136                // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list.
1137                // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs).
1138                // Thus, a potential struct's declaration is highest priority.
1139                // A struct's forall declarations are already renamed with _generic_ suffix.  Try that name variant first.
1140
1141                std::string useName = "__" + de->name + "_generic_";
1142                TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1143
1144                if ( ! namedParamDecl ) {
1145                        useName = de->name;
1146                        namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) );
1147                }
1148
1149                // Expect to find it always.  A misspelled name would have been parsed as an identifier.
1150                assert( namedParamDecl && "Type-system-managed value name not found in symbol table" );
1151
1152                delete de;
1153
1154                TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl );
1155
1156                if ( visitingChildOfSUIT ) {
1157                        // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper
1158                        // But avoid ArrayType-Sizeof
1159                        return new TypeExpr( refToDecl );
1160                } else {
1161                        // the N occurrence is being used directly as a runtime value,
1162                        // if we are in a type instantiation, then the N is within a bigger value computation
1163                        return new SizeofExpr( refToDecl );
1164                }
1165        }
1166
1167        Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) {
1168                if ( visitingChildOfSUIT ) {
1169                        // e is an expression used as an argument to instantiate a type
1170                        if (! dynamic_cast< TypeExpr * >( e ) ) {
1171                                // e is a value expression
1172                                // but not a DimensionExpr, which has a distinct postmutate
1173                                Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false );
1174                                TypeExpr * result = new TypeExpr( typeExprContent );
1175                                return result;
1176                        }
1177                }
1178                return e;
1179        }
1180
[ef5b828]1181        void CompoundLiteral::premutate( ObjectDecl * objectDecl ) {
[a7c90d4]1182                storageClasses = objectDecl->get_storageClasses();
[630a82a]1183        }
1184
[ef5b828]1185        Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) {
[630a82a]1186                // transform [storage_class] ... (struct S){ 3, ... };
1187                // into [storage_class] struct S temp =  { 3, ... };
1188                static UniqueName indexName( "_compLit" );
1189
[ef5b828]1190                ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() );
[d24d4e1]1191                compLitExpr->set_result( nullptr );
1192                compLitExpr->set_initializer( nullptr );
[630a82a]1193                delete compLitExpr;
[d24d4e1]1194                declsToAddBefore.push_back( tempvar );                                  // add modified temporary to current block
1195                return new VariableExpr( tempvar );
[630a82a]1196        }
[cce9429]1197
1198        void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
[0db6fc0]1199                PassVisitor<ReturnTypeFixer> fixer;
[cce9429]1200                acceptAll( translationUnit, fixer );
1201        }
1202
[0db6fc0]1203        void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
[9facf3b]1204                FunctionType * ftype = functionDecl->get_functionType();
1205                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
[56e49b0]1206                assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
[9facf3b]1207                if ( retVals.size() == 1 ) {
[861799c]1208                        // 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).
1209                        // ensure other return values have a name.
[9facf3b]1210                        DeclarationWithType * ret = retVals.front();
1211                        if ( ret->get_name() == "" ) {
1212                                ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
1213                        }
[c6d2e93]1214                        ret->get_attributes().push_back( new Attribute( "unused" ) );
[9facf3b]1215                }
1216        }
[cce9429]1217
[0db6fc0]1218        void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
[cce9429]1219                // xxx - need to handle named return values - this information needs to be saved somehow
1220                // so that resolution has access to the names.
1221                // Note that this pass needs to happen early so that other passes which look for tuple types
1222                // find them in all of the right places, including function return types.
1223                std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
1224                if ( retVals.size() > 1 ) {
1225                        // generate a single return parameter which is the tuple of all of the return values
[e3e16bc]1226                        TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
[cce9429]1227                        // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
[ef5b828]1228                        ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) );
[cce9429]1229                        deleteAll( retVals );
1230                        retVals.clear();
1231                        retVals.push_back( newRet );
1232                }
1233        }
[fbd7ad6]1234
[2b79a70]1235        void FixObjectType::fix( std::list< Declaration * > & translationUnit ) {
1236                PassVisitor<FixObjectType> fixer;
1237                acceptAll( translationUnit, fixer );
1238        }
1239
1240        void FixObjectType::previsit( ObjectDecl * objDecl ) {
[ef5b828]1241                Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer );
[2b79a70]1242                objDecl->set_type( new_type );
1243        }
1244
1245        void FixObjectType::previsit( FunctionDecl * funcDecl ) {
[ef5b828]1246                Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer );
[2b79a70]1247                funcDecl->set_type( new_type );
1248        }
1249
[ef5b828]1250        void FixObjectType::previsit( TypeDecl * typeDecl ) {
[2b79a70]1251                if ( typeDecl->get_base() ) {
[ef5b828]1252                        Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer );
[2b79a70]1253                        typeDecl->set_base( new_type );
1254                } // if
1255        }
1256
[09867ec]1257        void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) {
1258                PassVisitor<InitializerLength> len;
1259                acceptAll( translationUnit, len );
1260        }
1261
[fbd7ad6]1262        void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
[0db6fc0]1263                PassVisitor<ArrayLength> len;
[fbd7ad6]1264                acceptAll( translationUnit, len );
1265        }
1266
[09867ec]1267        void InitializerLength::previsit( ObjectDecl * objDecl ) {
[0b3b2ae]1268                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) {
[f072892]1269                        if ( at->dimension ) return;
[0b3b2ae]1270                        if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) {
[f072892]1271                                at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) );
[fbd7ad6]1272                        }
1273                }
1274        }
[4fbdfae0]1275
[4934ea3]1276        void ArrayLength::previsit( ArrayType * type ) {
[09867ec]1277                if ( type->dimension ) {
1278                        // need to resolve array dimensions early so that constructor code can correctly determine
1279                        // if a type is a VLA (and hence whether its elements need to be constructed)
1280                        ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
1281
1282                        // must re-evaluate whether a type is a VLA, now that more information is available
1283                        // (e.g. the dimension may have been an enumerator, which was unknown prior to this step)
1284                        type->isVarLen = ! InitTweak::isConstExpr( type->dimension );
[4934ea3]1285                }
1286        }
1287
[5809461]1288        struct LabelFinder {
1289                std::set< Label > & labels;
1290                LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1291                void previsit( Statement * stmt ) {
1292                        for ( Label & l : stmt->labels ) {
1293                                labels.insert( l );
1294                        }
1295                }
1296        };
1297
1298        void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1299                GuardValue( labels );
1300                PassVisitor<LabelFinder> finder( labels );
1301                funcDecl->accept( finder );
1302        }
1303
1304        Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1305                // convert &&label into label address
1306                if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1307                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1308                                if ( labels.count( nameExpr->name ) ) {
1309                                        Label name = nameExpr->name;
1310                                        delete addrExpr;
1311                                        return new LabelAddressExpr( name );
1312                                }
1313                        }
1314                }
1315                return addrExpr;
1316        }
[c8e4d2f8]1317
[51b7345]1318} // namespace SymTab
[0dd3a2f]1319
1320// Local Variables: //
1321// tab-width: 4 //
1322// mode: c++ //
1323// compile-command: "make install" //
1324// End: //
Note: See TracBrowser for help on using the repository browser.