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