source: src/SymTab/Validate.cc@ 24de7b1

new-env with_gc
Last change on this file since 24de7b1 was 8d7bef2, checked in by Aaron Moss <a3moss@…>, 8 years ago

First compiling build of CFA-CC with GC

  • Property mode set to 100644
File size: 41.6 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
[b128d3e]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 28 13:47:23 2017
13// Update Count : 359
[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.
[51b73452]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
46#include <utility> // for pair
[30f9072]47
48#include "CodeGen/CodeGenerator.h" // for genName
[9236060]49#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
[30f9072]50#include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd
[d180746]51#include "Common/ScopedMap.h" // for ScopedMap
[30f9072]52#include "Common/SemanticError.h" // for SemanticError
53#include "Common/UniqueName.h" // for UniqueName
54#include "Common/utility.h" // for operator+, cloneAll, deleteAll
[be9288a]55#include "Concurrency/Keywords.h" // for applyKeywords
[30f9072]56#include "FixFunction.h" // for FixFunction
57#include "Indexer.h" // for Indexer
[8b11840]58#include "InitTweak/GenInit.h" // for fixReturnStatements
[d180746]59#include "InitTweak/InitTweak.h" // for isCtorDtorAssign
60#include "Parser/LinkageSpec.h" // for C
61#include "ResolvExpr/typeops.h" // for typesCompatible
[be9288a]62#include "SymTab/Autogen.h" // for SizeType
63#include "SynTree/Attribute.h" // for noAttributes, Attribute
[30f9072]64#include "SynTree/Constant.h" // for Constant
[d180746]65#include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
66#include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio...
67#include "SynTree/Initializer.h" // for ListInit, Initializer
68#include "SynTree/Label.h" // for operator==, Label
69#include "SynTree/Mutator.h" // for Mutator
70#include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType
71#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
72#include "SynTree/Visitor.h" // for Visitor
73
74class CompoundStmt;
75class ReturnStmt;
76class SwitchStmt;
[51b73452]77
78
[c8ffe20b]79#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
[51b73452]80
81namespace SymTab {
[a09e45b]82 struct HoistStruct final : public WithDeclsToAdd, public WithGuards {
[82dd287]83 /// Flattens nested struct types
[0dd3a2f]84 static void hoistStruct( std::list< Declaration * > &translationUnit );
[9cb8e88d]85
[a09e45b]86 void previsit( EnumInstType * enumInstType );
87 void previsit( StructInstType * structInstType );
88 void previsit( UnionInstType * unionInstType );
89 void previsit( StructDecl * aggregateDecl );
90 void previsit( UnionDecl * aggregateDecl );
[9cb8e88d]91
[a08ba92]92 private:
[0dd3a2f]93 template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
[c8ffe20b]94
[bdad6eb7]95 AggregateDecl * parentAggr = nullptr;
[a08ba92]96 };
[c8ffe20b]97
[cce9429]98 /// Fix return types so that every function returns exactly one value
[d24d4e1]99 struct ReturnTypeFixer {
[cce9429]100 static void fix( std::list< Declaration * > &translationUnit );
101
[0db6fc0]102 void postvisit( FunctionDecl * functionDecl );
103 void postvisit( FunctionType * ftype );
[cce9429]104 };
105
[de91427b]106 /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
[d24d4e1]107 struct EnumAndPointerDecay {
[06edda0]108 void previsit( EnumDecl *aggregateDecl );
109 void previsit( FunctionType *func );
[a08ba92]110 };
[82dd287]111
112 /// Associates forward declarations of aggregates with their definitions
[b95fe40]113 struct LinkReferenceToTypes final : public WithIndexer, public WithGuards {
[522363e]114 LinkReferenceToTypes( const Indexer *indexer );
115 void postvisit( TypeInstType *typeInst );
[be9036d]116
[522363e]117 void postvisit( EnumInstType *enumInst );
118 void postvisit( StructInstType *structInst );
119 void postvisit( UnionInstType *unionInst );
120 void postvisit( TraitInstType *traitInst );
[be9036d]121
[522363e]122 void postvisit( EnumDecl *enumDecl );
123 void postvisit( StructDecl *structDecl );
124 void postvisit( UnionDecl *unionDecl );
125 void postvisit( TraitDecl * traitDecl );
[be9036d]126
[b95fe40]127 void previsit( StructDecl *structDecl );
128 void previsit( UnionDecl *unionDecl );
129
130 void renameGenericParams( std::list< TypeDecl * > & params );
131
[06edda0]132 private:
[522363e]133 const Indexer *local_indexer;
[9cb8e88d]134
[c0aa336]135 typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
[0dd3a2f]136 typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
137 typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
[c0aa336]138 ForwardEnumsType forwardEnums;
[0dd3a2f]139 ForwardStructsType forwardStructs;
140 ForwardUnionsType forwardUnions;
[b95fe40]141 /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
142 bool inGeneric = false;
[a08ba92]143 };
[c8ffe20b]144
[06edda0]145 /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID.
[522363e]146 struct ForallPointerDecay final {
[8b11840]147 void previsit( ObjectDecl * object );
148 void previsit( FunctionDecl * func );
[bd7e609]149 void previsit( StructDecl * aggrDecl );
150 void previsit( UnionDecl * aggrDecl );
[a08ba92]151 };
[c8ffe20b]152
[d24d4e1]153 struct ReturnChecker : public WithGuards {
[de91427b]154 /// Checks that return statements return nothing if their return type is void
155 /// and return something if the return type is non-void.
156 static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
157
[0db6fc0]158 void previsit( FunctionDecl * functionDecl );
159 void previsit( ReturnStmt * returnStmt );
[de91427b]160
[0db6fc0]161 typedef std::list< DeclarationWithType * > ReturnVals;
162 ReturnVals returnVals;
[de91427b]163 };
164
[a506df4]165 struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards {
[de91427b]166 EliminateTypedef() : scopeLevel( 0 ) {}
167 /// Replaces typedefs by forward declarations
[0dd3a2f]168 static void eliminateTypedef( std::list< Declaration * > &translationUnit );
[85c4ef0]169
[a506df4]170 Type * postmutate( TypeInstType * aggregateUseType );
171 Declaration * postmutate( TypedefDecl * typeDecl );
172 void premutate( TypeDecl * typeDecl );
173 void premutate( FunctionDecl * funcDecl );
174 void premutate( ObjectDecl * objDecl );
175 DeclarationWithType * postmutate( ObjectDecl * objDecl );
176
177 void premutate( CastExpr * castExpr );
178
179 void premutate( CompoundStmt * compoundStmt );
180 CompoundStmt * postmutate( CompoundStmt * compoundStmt );
181
182 void premutate( StructDecl * structDecl );
183 Declaration * postmutate( StructDecl * structDecl );
184 void premutate( UnionDecl * unionDecl );
185 Declaration * postmutate( UnionDecl * unionDecl );
186 void premutate( EnumDecl * enumDecl );
187 Declaration * postmutate( EnumDecl * enumDecl );
188 Declaration * postmutate( TraitDecl * contextDecl );
189
[1f370451]190 void premutate( FunctionType * ftype );
191
[a506df4]192 private:
[85c4ef0]193 template<typename AggDecl>
194 AggDecl *handleAggregate( AggDecl * aggDecl );
195
[45161b4d]196 template<typename AggDecl>
197 void addImplicitTypedef( AggDecl * aggDecl );
[70a06f6]198
[8d7bef2]199 typedef ScopedMap< std::string, std::pair< TypedefDecl*, int > > TypedefMap;
[679864e1]200 typedef std::map< std::string, TypeDecl * > TypeDeclMap;
[cc79d97]201 TypedefMap typedefNames;
[679864e1]202 TypeDeclMap typedeclNames;
[cc79d97]203 int scopeLevel;
[1f370451]204 bool inFunctionType = false;
[a08ba92]205 };
[c8ffe20b]206
[d24d4e1]207 struct VerifyCtorDtorAssign {
[d1969a6]208 /// ensure that constructors, destructors, and assignment have at least one
209 /// parameter, the first of which must be a pointer, and that ctor/dtors have no
[9cb8e88d]210 /// return values.
211 static void verify( std::list< Declaration * > &translationUnit );
212
[0db6fc0]213 void previsit( FunctionDecl *funcDecl );
[5f98ce5]214 };
[70a06f6]215
[11ab8ea8]216 /// ensure that generic types have the correct number of type arguments
[d24d4e1]217 struct ValidateGenericParameters {
[0db6fc0]218 void previsit( StructInstType * inst );
219 void previsit( UnionInstType * inst );
[5f98ce5]220 };
[70a06f6]221
[d24d4e1]222 struct ArrayLength {
[fbd7ad6]223 /// for array types without an explicit length, compute the length and store it so that it
224 /// is known to the rest of the phases. For example,
225 /// int x[] = { 1, 2, 3 };
226 /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
227 /// here x and y are known at compile-time to have length 3, so change this into
228 /// int x[3] = { 1, 2, 3 };
229 /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
230 static void computeLength( std::list< Declaration * > & translationUnit );
231
[0db6fc0]232 void previsit( ObjectDecl * objDecl );
[fbd7ad6]233 };
234
[d24d4e1]235 struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> {
[68fe077a]236 Type::StorageClasses storageClasses;
[630a82a]237
[d24d4e1]238 void premutate( ObjectDecl *objectDecl );
239 Expression * postmutate( CompoundLiteralExpr *compLitExpr );
[9cb8e88d]240 };
241
[5809461]242 struct LabelAddressFixer final : public WithGuards {
243 std::set< Label > labels;
244
245 void premutate( FunctionDecl * funcDecl );
246 Expression * postmutate( AddressExpr * addrExpr );
247 };
[4fbdfae0]248
249 FunctionDecl * dereferenceOperator = nullptr;
250 struct FindSpecialDeclarations final {
251 void previsit( FunctionDecl * funcDecl );
252 };
253
[522363e]254 void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) {
[06edda0]255 PassVisitor<EnumAndPointerDecay> epc;
[522363e]256 PassVisitor<LinkReferenceToTypes> lrt( nullptr );
257 PassVisitor<ForallPointerDecay> fpd;
[d24d4e1]258 PassVisitor<CompoundLiteral> compoundliteral;
[0db6fc0]259 PassVisitor<ValidateGenericParameters> genericParams;
[4fbdfae0]260 PassVisitor<FindSpecialDeclarations> finder;
[5809461]261 PassVisitor<LabelAddressFixer> labelAddrFixer;
[630a82a]262
[fbcde64]263 EliminateTypedef::eliminateTypedef( translationUnit );
[11ab8ea8]264 HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order
[cce9429]265 ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
[8e0147a]266 acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling
[861799c7]267 acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
[11ab8ea8]268 acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes
[ed8a0d2]269 VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors
[bd7e609]270 ReturnChecker::checkFunctionReturns( translationUnit );
271 InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen
[bcda04c]272 Concurrency::applyKeywords( translationUnit );
[bd7e609]273 acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution
[06edda0]274 autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay
[bcda04c]275 Concurrency::implementMutexFuncs( translationUnit );
276 Concurrency::implementThreadStarter( translationUnit );
[d24d4e1]277 mutateAll( translationUnit, compoundliteral );
[fbd7ad6]278 ArrayLength::computeLength( translationUnit );
[bd7e609]279 acceptAll( translationUnit, finder ); // xxx - remove this pass soon
[5809461]280 mutateAll( translationUnit, labelAddrFixer );
[a08ba92]281 }
[9cb8e88d]282
[a08ba92]283 void validateType( Type *type, const Indexer *indexer ) {
[06edda0]284 PassVisitor<EnumAndPointerDecay> epc;
[522363e]285 PassVisitor<LinkReferenceToTypes> lrt( indexer );
286 PassVisitor<ForallPointerDecay> fpd;
[bda58ad]287 type->accept( epc );
[cce9429]288 type->accept( lrt );
[06edda0]289 type->accept( fpd );
[a08ba92]290 }
[c8ffe20b]291
[a08ba92]292 void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
[a09e45b]293 PassVisitor<HoistStruct> hoister;
294 acceptAll( translationUnit, hoister );
[a08ba92]295 }
[c8ffe20b]296
[a08ba92]297 bool isStructOrUnion( Declaration *decl ) {
[0dd3a2f]298 return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
[a08ba92]299 }
[c0aa336]300
[a08ba92]301 template< typename AggDecl >
302 void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
[bdad6eb7]303 if ( parentAggr ) {
[0dd3a2f]304 // Add elements in stack order corresponding to nesting structure.
[a09e45b]305 declsToAddBefore.push_front( aggregateDecl );
[0dd3a2f]306 } else {
[bdad6eb7]307 GuardValue( parentAggr );
308 parentAggr = aggregateDecl;
[0dd3a2f]309 } // if
310 // Always remove the hoisted aggregate from the inner structure.
[68f9c43]311 GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, isStructOrUnion ); } );
[a08ba92]312 }
[c8ffe20b]313
[a09e45b]314 void HoistStruct::previsit( EnumInstType * inst ) {
315 if ( inst->baseEnum ) {
316 declsToAddBefore.push_front( inst->baseEnum );
[c0aa336]317 }
318 }
319
[a09e45b]320 void HoistStruct::previsit( StructInstType * inst ) {
321 if ( inst->baseStruct ) {
322 declsToAddBefore.push_front( inst->baseStruct );
[c0aa336]323 }
324 }
325
[a09e45b]326 void HoistStruct::previsit( UnionInstType * inst ) {
327 if ( inst->baseUnion ) {
328 declsToAddBefore.push_front( inst->baseUnion );
[c0aa336]329 }
330 }
331
[a09e45b]332 void HoistStruct::previsit( StructDecl * aggregateDecl ) {
[0dd3a2f]333 handleAggregate( aggregateDecl );
[a08ba92]334 }
[c8ffe20b]335
[a09e45b]336 void HoistStruct::previsit( UnionDecl * aggregateDecl ) {
[0dd3a2f]337 handleAggregate( aggregateDecl );
[a08ba92]338 }
[c8ffe20b]339
[06edda0]340 void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) {
[0dd3a2f]341 // Set the type of each member of the enumeration to be EnumConstant
342 for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
[f6d7e0f]343 ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
[0dd3a2f]344 assert( obj );
[f2e40a9f]345 obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
[0dd3a2f]346 } // for
[a08ba92]347 }
[51b73452]348
[a08ba92]349 namespace {
[83de11e]350 template< typename DWTList >
[4bda2cf]351 void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
352 auto nvals = dwts.size();
353 bool containsVoid = false;
354 for ( auto & dwt : dwts ) {
355 // fix each DWT and record whether a void was found
356 containsVoid |= fixFunction( dwt );
357 }
358
359 // the only case in which "void" is valid is where it is the only one in the list
360 if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
[a16764a6]361 SemanticError( func, "invalid type void in function type " );
[4bda2cf]362 }
363
364 // one void is the only thing in the list; remove it.
365 if ( containsVoid ) {
366 dwts.clear();
367 }
[0dd3a2f]368 }
[a08ba92]369 }
[c8ffe20b]370
[06edda0]371 void EnumAndPointerDecay::previsit( FunctionType *func ) {
[0dd3a2f]372 // Fix up parameters and return types
[4bda2cf]373 fixFunctionList( func->parameters, func->isVarArgs, func );
374 fixFunctionList( func->returnVals, false, func );
[a08ba92]375 }
[c8ffe20b]376
[522363e]377 LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) {
[0dd3a2f]378 if ( other_indexer ) {
[522363e]379 local_indexer = other_indexer;
[0dd3a2f]380 } else {
[522363e]381 local_indexer = &indexer;
[0dd3a2f]382 } // if
[a08ba92]383 }
[c8ffe20b]384
[522363e]385 void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) {
386 EnumDecl *st = local_indexer->lookupEnum( enumInst->get_name() );
[c0aa336]387 // it's not a semantic error if the enum is not found, just an implicit forward declaration
388 if ( st ) {
389 //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
390 enumInst->set_baseEnum( st );
391 } // if
392 if ( ! st || st->get_members().empty() ) {
393 // use of forward declaration
394 forwardEnums[ enumInst->get_name() ].push_back( enumInst );
395 } // if
396 }
397
[48fa824]398 void checkGenericParameters( ReferenceToType * inst ) {
399 for ( Expression * param : inst->parameters ) {
400 if ( ! dynamic_cast< TypeExpr * >( param ) ) {
[a16764a6]401 SemanticError( inst, "Expression parameters for generic types are currently unsupported: " );
[48fa824]402 }
403 }
404 }
405
[522363e]406 void LinkReferenceToTypes::postvisit( StructInstType *structInst ) {
407 StructDecl *st = local_indexer->lookupStruct( structInst->get_name() );
[0dd3a2f]408 // it's not a semantic error if the struct is not found, just an implicit forward declaration
409 if ( st ) {
[98735ef]410 //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
[0dd3a2f]411 structInst->set_baseStruct( st );
412 } // if
413 if ( ! st || st->get_members().empty() ) {
414 // use of forward declaration
415 forwardStructs[ structInst->get_name() ].push_back( structInst );
416 } // if
[48fa824]417 checkGenericParameters( structInst );
[a08ba92]418 }
[c8ffe20b]419
[522363e]420 void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) {
421 UnionDecl *un = local_indexer->lookupUnion( unionInst->get_name() );
[0dd3a2f]422 // it's not a semantic error if the union is not found, just an implicit forward declaration
423 if ( un ) {
424 unionInst->set_baseUnion( un );
425 } // if
426 if ( ! un || un->get_members().empty() ) {
427 // use of forward declaration
428 forwardUnions[ unionInst->get_name() ].push_back( unionInst );
429 } // if
[48fa824]430 checkGenericParameters( unionInst );
[a08ba92]431 }
[c8ffe20b]432
[be9036d]433 template< typename Decl >
434 void normalizeAssertions( std::list< Decl * > & assertions ) {
435 // ensure no duplicate trait members after the clone
436 auto pred = [](Decl * d1, Decl * d2) {
437 // only care if they're equal
438 DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 );
439 DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 );
440 if ( dwt1 && dwt2 ) {
441 if ( dwt1->get_name() == dwt2->get_name() && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) {
442 // std::cerr << "=========== equal:" << std::endl;
443 // std::cerr << "d1: " << d1 << std::endl;
444 // std::cerr << "d2: " << d2 << std::endl;
445 return false;
446 }
[2c57025]447 }
[be9036d]448 return d1 < d2;
449 };
450 std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred );
451 // if ( unique_members.size() != assertions.size() ) {
452 // std::cerr << "============different" << std::endl;
453 // std::cerr << unique_members.size() << " " << assertions.size() << std::endl;
454 // }
455
456 std::list< Decl * > order;
457 order.splice( order.end(), assertions );
458 std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) {
459 return unique_members.count( decl );
460 });
461 }
462
463 // expand assertions from trait instance, performing the appropriate type variable substitutions
464 template< typename Iterator >
465 void expandAssertions( TraitInstType * inst, Iterator out ) {
466 assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toString( inst ).c_str() );
467 std::list< DeclarationWithType * > asserts;
468 for ( Declaration * decl : inst->baseTrait->members ) {
[e3e16bc]469 asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
[2c57025]470 }
[be9036d]471 // substitute trait decl parameters for instance parameters
472 applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
473 }
474
[522363e]475 void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) {
[be9036d]476 if ( traitDecl->name == "sized" ) {
477 // "sized" is a special trait - flick the sized status on for the type variable
478 assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
479 TypeDecl * td = traitDecl->parameters.front();
480 td->set_sized( true );
481 }
482
483 // move assertions from type parameters into the body of the trait
484 for ( TypeDecl * td : traitDecl->parameters ) {
485 for ( DeclarationWithType * assert : td->assertions ) {
486 if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
487 expandAssertions( inst, back_inserter( traitDecl->members ) );
488 } else {
489 traitDecl->members.push_back( assert->clone() );
490 }
491 }
492 td->assertions.clear();
493 } // for
494 }
[2ae171d8]495
[522363e]496 void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) {
[2ae171d8]497 // handle other traits
[522363e]498 TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name );
[4a9ccc3]499 if ( ! traitDecl ) {
[a16764a6]500 SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
[17cd4eb]501 } // if
[4a9ccc3]502 if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
[a16764a6]503 SemanticError( traitInst, "incorrect number of trait parameters: " );
[4a9ccc3]504 } // if
[be9036d]505 traitInst->baseTrait = traitDecl;
[79970ed]506
[4a9ccc3]507 // need to carry over the 'sized' status of each decl in the instance
508 for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
[5c4d27f]509 TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
510 if ( ! expr ) {
[a16764a6]511 SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
[5c4d27f]512 }
[4a9ccc3]513 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
514 TypeDecl * formalDecl = std::get<0>(p);
515 TypeDecl * instDecl = inst->get_baseType();
516 if ( formalDecl->get_sized() ) instDecl->set_sized( true );
517 }
518 }
[be9036d]519 // normalizeAssertions( traitInst->members );
[a08ba92]520 }
[c8ffe20b]521
[522363e]522 void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) {
[c0aa336]523 // visit enum members first so that the types of self-referencing members are updated properly
524 if ( ! enumDecl->get_members().empty() ) {
525 ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
526 if ( fwds != forwardEnums.end() ) {
527 for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
528 (*inst )->set_baseEnum( enumDecl );
529 } // for
530 forwardEnums.erase( fwds );
531 } // if
532 } // if
533 }
534
[b95fe40]535 void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) {
536 // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
537 // forall(otype T)
538 // struct Box {
539 // T x;
540 // };
541 // forall(otype T)
542 // void f(Box(T) b) {
543 // ...
544 // }
545 // The T in Box and the T in f are different, so internally the naming must reflect that.
546 GuardValue( inGeneric );
547 inGeneric = ! params.empty();
548 for ( TypeDecl * td : params ) {
549 td->name = "__" + td->name + "_generic_";
550 }
551 }
552
553 void LinkReferenceToTypes::previsit( StructDecl * structDecl ) {
554 renameGenericParams( structDecl->parameters );
555 }
556
557 void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) {
558 renameGenericParams( unionDecl->parameters );
559 }
560
[522363e]561 void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) {
[677c1be]562 // visit struct members first so that the types of self-referencing members are updated properly
[522363e]563 // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults)
[0dd3a2f]564 if ( ! structDecl->get_members().empty() ) {
565 ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
566 if ( fwds != forwardStructs.end() ) {
567 for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
568 (*inst )->set_baseStruct( structDecl );
569 } // for
570 forwardStructs.erase( fwds );
571 } // if
572 } // if
[a08ba92]573 }
[c8ffe20b]574
[522363e]575 void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) {
[0dd3a2f]576 if ( ! unionDecl->get_members().empty() ) {
577 ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
578 if ( fwds != forwardUnions.end() ) {
579 for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
580 (*inst )->set_baseUnion( unionDecl );
581 } // for
582 forwardUnions.erase( fwds );
583 } // if
584 } // if
[a08ba92]585 }
[c8ffe20b]586
[522363e]587 void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) {
[b95fe40]588 // ensure generic parameter instances are renamed like the base type
589 if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
[522363e]590 if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->get_name() ) ) {
[0dd3a2f]591 if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
592 typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
593 } // if
594 } // if
[a08ba92]595 }
[c8ffe20b]596
[4a9ccc3]597 /// Fix up assertions - flattens assertion lists, removing all trait instances
[8b11840]598 void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
599 for ( TypeDecl * type : forall ) {
[be9036d]600 std::list< DeclarationWithType * > asserts;
601 asserts.splice( asserts.end(), type->assertions );
602 // expand trait instances into their members
603 for ( DeclarationWithType * assertion : asserts ) {
604 if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
605 // expand trait instance into all of its members
606 expandAssertions( traitInst, back_inserter( type->assertions ) );
607 } else {
608 // pass other assertions through
609 type->assertions.push_back( assertion );
610 } // if
611 } // for
612 // apply FixFunction to every assertion to check for invalid void type
613 for ( DeclarationWithType *& assertion : type->assertions ) {
[4bda2cf]614 bool isVoid = fixFunction( assertion );
615 if ( isVoid ) {
[a16764a6]616 SemanticError( node, "invalid type void in assertion of function " );
[be9036d]617 } // if
618 } // for
619 // normalizeAssertions( type->assertions );
[0dd3a2f]620 } // for
[a08ba92]621 }
[c8ffe20b]622
[522363e]623 void ForallPointerDecay::previsit( ObjectDecl *object ) {
[8b11840]624 forallFixer( object->type->forall, object );
625 if ( PointerType *pointer = dynamic_cast< PointerType * >( object->type ) ) {
626 forallFixer( pointer->base->forall, object );
[0dd3a2f]627 } // if
628 object->fixUniqueId();
[a08ba92]629 }
[c8ffe20b]630
[522363e]631 void ForallPointerDecay::previsit( FunctionDecl *func ) {
[8b11840]632 forallFixer( func->type->forall, func );
[0dd3a2f]633 func->fixUniqueId();
[a08ba92]634 }
[c8ffe20b]635
[bd7e609]636 void ForallPointerDecay::previsit( StructDecl * aggrDecl ) {
637 forallFixer( aggrDecl->parameters, aggrDecl );
638 }
639
640 void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) {
641 forallFixer( aggrDecl->parameters, aggrDecl );
642 }
643
[de91427b]644 void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
[0db6fc0]645 PassVisitor<ReturnChecker> checker;
[de91427b]646 acceptAll( translationUnit, checker );
647 }
648
[0db6fc0]649 void ReturnChecker::previsit( FunctionDecl * functionDecl ) {
[0508ab3]650 GuardValue( returnVals );
[de91427b]651 returnVals = functionDecl->get_functionType()->get_returnVals();
652 }
653
[0db6fc0]654 void ReturnChecker::previsit( ReturnStmt * returnStmt ) {
[74d1804]655 // Previously this also checked for the existence of an expr paired with no return values on
656 // the function return type. This is incorrect, since you can have an expression attached to
657 // a return statement in a void-returning function in C. The expression is treated as if it
658 // were cast to void.
[30f9072]659 if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) {
[a16764a6]660 SemanticError( returnStmt, "Non-void function returns no values: " );
[de91427b]661 }
662 }
663
664
[a08ba92]665 bool isTypedef( Declaration *decl ) {
[0dd3a2f]666 return dynamic_cast< TypedefDecl * >( decl );
[a08ba92]667 }
[c8ffe20b]668
[a08ba92]669 void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
[a506df4]670 PassVisitor<EliminateTypedef> eliminator;
[0dd3a2f]671 mutateAll( translationUnit, eliminator );
[a506df4]672 if ( eliminator.pass.typedefNames.count( "size_t" ) ) {
[5f98ce5]673 // grab and remember declaration of size_t
[a506df4]674 SizeType = eliminator.pass.typedefNames["size_t"].first->get_base()->clone();
[5f98ce5]675 } else {
[40e636a]676 // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
677 // eventually should have a warning for this case.
678 SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[5f98ce5]679 }
[68f9c43]680 filter( translationUnit, isTypedef );
[a08ba92]681 }
[c8ffe20b]682
[a506df4]683 Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) {
[9cb8e88d]684 // instances of typedef types will come here. If it is an instance
[cc79d97]685 // of a typdef type, link the instance to its actual type.
686 TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
[0dd3a2f]687 if ( def != typedefNames.end() ) {
[f53836b]688 Type *ret = def->second.first->base->clone();
[6f95000]689 ret->get_qualifiers() |= typeInst->get_qualifiers();
[1f370451]690 // attributes are not carried over from typedef to function parameters/return values
691 if ( ! inFunctionType ) {
692 ret->attributes.splice( ret->attributes.end(), typeInst->attributes );
693 } else {
694 ret->attributes.clear();
695 }
[0215a76f]696 // place instance parameters on the typedef'd type
[f53836b]697 if ( ! typeInst->parameters.empty() ) {
[0215a76f]698 ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
699 if ( ! rtt ) {
[a16764a6]700 SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name );
[0215a76f]701 }
702 rtt->get_parameters().clear();
[f53836b]703 cloneAll( typeInst->parameters, rtt->parameters );
704 mutateAll( rtt->parameters, *visitor ); // recursively fix typedefs on parameters
[1db21619]705 } // if
[0dd3a2f]706 return ret;
[679864e1]707 } else {
708 TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
[f53836b]709 assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->name.c_str() );
[1e8b02f5]710 typeInst->set_baseType( base->second );
[0dd3a2f]711 } // if
712 return typeInst;
[a08ba92]713 }
[c8ffe20b]714
[f53836b]715 struct VarLenChecker : WithShortCircuiting {
716 void previsit( FunctionType * ) { visit_children = false; }
717 void previsit( ArrayType * at ) {
718 isVarLen |= at->isVarLen;
719 }
720 bool isVarLen = false;
721 };
722
723 bool isVariableLength( Type * t ) {
724 PassVisitor<VarLenChecker> varLenChecker;
725 maybeAccept( t, varLenChecker );
726 return varLenChecker.pass.isVarLen;
727 }
728
[a506df4]729 Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) {
[cc79d97]730 if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
[9cb8e88d]731 // typedef to the same name from the same scope
[cc79d97]732 // must be from the same type
733
734 Type * t1 = tyDecl->get_base();
735 Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
[1cbca6e]736 if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
[a16764a6]737 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
[f53836b]738 }
[4b97770]739 // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs
740 // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs
741 // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required
742 // to fix this corner case likely outweighs the utility of allowing it.
[f53836b]743 if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) {
[a16764a6]744 SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name );
[85c4ef0]745 }
[cc79d97]746 } else {
[8d7bef2]747 typedefNames[ tyDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
[cc79d97]748 } // if
749
[0dd3a2f]750 // When a typedef is a forward declaration:
751 // typedef struct screen SCREEN;
752 // the declaration portion must be retained:
753 // struct screen;
754 // because the expansion of the typedef is:
755 // void rtn( SCREEN *p ) => void rtn( struct screen *p )
756 // hence the type-name "screen" must be defined.
757 // Note, qualifiers on the typedef are superfluous for the forward declaration.
[6f95000]758
759 Type *designatorType = tyDecl->get_base()->stripDeclarator();
760 if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
[cbce272]761 return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() );
[6f95000]762 } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
[cbce272]763 return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() );
[6f95000]764 } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
[cbce272]765 return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() );
[0dd3a2f]766 } else {
[a506df4]767 return tyDecl->clone();
[0dd3a2f]768 } // if
[a08ba92]769 }
[c8ffe20b]770
[a506df4]771 void EliminateTypedef::premutate( TypeDecl * typeDecl ) {
[cc79d97]772 TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
[0dd3a2f]773 if ( i != typedefNames.end() ) {
774 typedefNames.erase( i ) ;
775 } // if
[679864e1]776
777 typedeclNames[ typeDecl->get_name() ] = typeDecl;
[a08ba92]778 }
[c8ffe20b]779
[a506df4]780 void EliminateTypedef::premutate( FunctionDecl * ) {
781 GuardScope( typedefNames );
[a08ba92]782 }
[c8ffe20b]783
[a506df4]784 void EliminateTypedef::premutate( ObjectDecl * ) {
785 GuardScope( typedefNames );
786 }
[dd020c0]787
[a506df4]788 DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) {
789 if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->get_type() ) ) { // function type?
[02e5ab6]790 // replace the current object declaration with a function declaration
[68f9c43]791 return new FunctionDecl{
792 objDecl->get_name(), objDecl->get_storageClasses(), objDecl->get_linkage(),
793 funtype, 0, objDecl->get_attributes(), objDecl->get_funcSpec() };
[1db21619]794 } // if
[a506df4]795 return objDecl;
[a08ba92]796 }
[c8ffe20b]797
[a506df4]798 void EliminateTypedef::premutate( CastExpr * ) {
799 GuardScope( typedefNames );
[a08ba92]800 }
[c8ffe20b]801
[a506df4]802 void EliminateTypedef::premutate( CompoundStmt * ) {
803 GuardScope( typedefNames );
[cc79d97]804 scopeLevel += 1;
[a506df4]805 GuardAction( [this](){ scopeLevel -= 1; } );
806 }
807
808 CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) {
[2bf9c37]809 // remove and delete decl stmts
810 filter( compoundStmt->kids, [](Statement * stmt) {
811 if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) {
[0dd3a2f]812 if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
[2bf9c37]813 return true;
[0dd3a2f]814 } // if
815 } // if
[2bf9c37]816 return false;
[68f9c43]817 } );
[a506df4]818 return compoundStmt;
[a08ba92]819 }
[85c4ef0]820
[43c89a7]821 // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
[45161b4d]822 // as well
[85c4ef0]823 template<typename AggDecl>
824 AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
[68f9c43]825 filter( aggDecl->members, isTypedef );
[85c4ef0]826 return aggDecl;
827 }
828
[45161b4d]829 template<typename AggDecl>
830 void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
831 if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
[62e5546]832 Type *type = nullptr;
[45161b4d]833 if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
834 type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
835 } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
836 type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
837 } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
838 type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
839 } // if
[8d7bef2]840 TypedefDecl* tyDecl = new TypedefDecl{ aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() };
841 typedefNames[ aggDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
[45161b4d]842 } // if
843 }
[4e06c1e]844
[a506df4]845 void EliminateTypedef::premutate( StructDecl * structDecl ) {
[45161b4d]846 addImplicitTypedef( structDecl );
[a506df4]847 }
848
849
850 Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) {
[85c4ef0]851 return handleAggregate( structDecl );
852 }
853
[a506df4]854 void EliminateTypedef::premutate( UnionDecl * unionDecl ) {
[45161b4d]855 addImplicitTypedef( unionDecl );
[a506df4]856 }
857
858 Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) {
[85c4ef0]859 return handleAggregate( unionDecl );
860 }
861
[a506df4]862 void EliminateTypedef::premutate( EnumDecl * enumDecl ) {
[45161b4d]863 addImplicitTypedef( enumDecl );
[a506df4]864 }
865
866 Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) {
[85c4ef0]867 return handleAggregate( enumDecl );
868 }
869
[a506df4]870 Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) {
871 return handleAggregate( traitDecl );
[85c4ef0]872 }
873
[1f370451]874 void EliminateTypedef::premutate( FunctionType * ) {
875 GuardValue( inFunctionType );
876 inFunctionType = true;
877 }
878
[d1969a6]879 void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
[0db6fc0]880 PassVisitor<VerifyCtorDtorAssign> verifier;
[9cb8e88d]881 acceptAll( translationUnit, verifier );
882 }
883
[0db6fc0]884 void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) {
[9cb8e88d]885 FunctionType * funcType = funcDecl->get_functionType();
886 std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
887 std::list< DeclarationWithType * > &params = funcType->get_parameters();
888
[bff227f]889 if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc.
[9cb8e88d]890 if ( params.size() == 0 ) {
[a16764a6]891 SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " );
[9cb8e88d]892 }
[ce8c12f]893 ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() );
[084fecc]894 if ( ! refType ) {
[a16764a6]895 SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " );
[9cb8e88d]896 }
[bff227f]897 if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
[a16764a6]898 SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " );
[9cb8e88d]899 }
900 }
901 }
[70a06f6]902
[11ab8ea8]903 template< typename Aggr >
904 void validateGeneric( Aggr * inst ) {
905 std::list< TypeDecl * > * params = inst->get_baseParameters();
[30f9072]906 if ( params ) {
[11ab8ea8]907 std::list< Expression * > & args = inst->get_parameters();
[67cf18c]908
909 // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list).
910 // A substitution is used to ensure that defaults are replaced correctly, e.g.,
911 // forall(otype T, otype alloc = heap_allocator(T)) struct vector;
912 // vector(int) v;
913 // after insertion of default values becomes
914 // vector(int, heap_allocator(T))
915 // and the substitution is built with T=int so that after substitution, the result is
916 // vector(int, heap_allocator(int))
917 TypeSubstitution sub;
918 auto paramIter = params->begin();
919 for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) {
920 if ( i < args.size() ) {
[e3e16bc]921 TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) );
[67cf18c]922 sub.add( (*paramIter)->get_name(), expr->get_type()->clone() );
923 } else if ( i == args.size() ) {
924 Type * defaultType = (*paramIter)->get_init();
925 if ( defaultType ) {
926 args.push_back( new TypeExpr( defaultType->clone() ) );
927 sub.add( (*paramIter)->get_name(), defaultType->clone() );
928 }
929 }
930 }
931
932 sub.apply( inst );
[a16764a6]933 if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " );
934 if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " );
[11ab8ea8]935 }
936 }
937
[0db6fc0]938 void ValidateGenericParameters::previsit( StructInstType * inst ) {
[11ab8ea8]939 validateGeneric( inst );
940 }
[9cb8e88d]941
[0db6fc0]942 void ValidateGenericParameters::previsit( UnionInstType * inst ) {
[11ab8ea8]943 validateGeneric( inst );
[9cb8e88d]944 }
[70a06f6]945
[d24d4e1]946 void CompoundLiteral::premutate( ObjectDecl *objectDecl ) {
[a7c90d4]947 storageClasses = objectDecl->get_storageClasses();
[630a82a]948 }
949
[d24d4e1]950 Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) {
[630a82a]951 // transform [storage_class] ... (struct S){ 3, ... };
952 // into [storage_class] struct S temp = { 3, ... };
953 static UniqueName indexName( "_compLit" );
954
[68f9c43]955 ObjectDecl * tempvar = new ObjectDecl{
956 indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() };
[d24d4e1]957 declsToAddBefore.push_back( tempvar ); // add modified temporary to current block
958 return new VariableExpr( tempvar );
[630a82a]959 }
[cce9429]960
961 void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
[0db6fc0]962 PassVisitor<ReturnTypeFixer> fixer;
[cce9429]963 acceptAll( translationUnit, fixer );
964 }
965
[0db6fc0]966 void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) {
[9facf3b]967 FunctionType * ftype = functionDecl->get_functionType();
968 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
[56e49b0]969 assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() );
[9facf3b]970 if ( retVals.size() == 1 ) {
[861799c7]971 // 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).
972 // ensure other return values have a name.
[9facf3b]973 DeclarationWithType * ret = retVals.front();
974 if ( ret->get_name() == "" ) {
975 ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
976 }
[c6d2e93]977 ret->get_attributes().push_back( new Attribute( "unused" ) );
[9facf3b]978 }
979 }
[cce9429]980
[0db6fc0]981 void ReturnTypeFixer::postvisit( FunctionType * ftype ) {
[cce9429]982 // xxx - need to handle named return values - this information needs to be saved somehow
983 // so that resolution has access to the names.
984 // Note that this pass needs to happen early so that other passes which look for tuple types
985 // find them in all of the right places, including function return types.
986 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
987 if ( retVals.size() > 1 ) {
988 // generate a single return parameter which is the tuple of all of the return values
[e3e16bc]989 TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
[cce9429]990 // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
[68fe077a]991 ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
[cce9429]992 retVals.clear();
993 retVals.push_back( newRet );
994 }
995 }
[fbd7ad6]996
997 void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
[0db6fc0]998 PassVisitor<ArrayLength> len;
[fbd7ad6]999 acceptAll( translationUnit, len );
1000 }
1001
[0db6fc0]1002 void ArrayLength::previsit( ObjectDecl * objDecl ) {
[fbd7ad6]1003 if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
[30f9072]1004 if ( at->get_dimension() ) return;
[fbd7ad6]1005 if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
1006 at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
1007 }
1008 }
1009 }
[4fbdfae0]1010
[5809461]1011 struct LabelFinder {
1012 std::set< Label > & labels;
1013 LabelFinder( std::set< Label > & labels ) : labels( labels ) {}
1014 void previsit( Statement * stmt ) {
1015 for ( Label & l : stmt->labels ) {
1016 labels.insert( l );
1017 }
1018 }
1019 };
1020
1021 void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) {
1022 GuardValue( labels );
1023 PassVisitor<LabelFinder> finder( labels );
1024 funcDecl->accept( finder );
1025 }
1026
1027 Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) {
1028 // convert &&label into label address
1029 if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) {
1030 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) {
1031 if ( labels.count( nameExpr->name ) ) {
[68f9c43]1032 return new LabelAddressExpr{ nameExpr->name };
[5809461]1033 }
1034 }
1035 }
1036 return addrExpr;
1037 }
1038
[4fbdfae0]1039 void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) {
1040 if ( ! dereferenceOperator ) {
1041 if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) {
1042 FunctionType * ftype = funcDecl->get_functionType();
1043 if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) {
1044 dereferenceOperator = funcDecl;
1045 }
1046 }
1047 }
1048 }
[51b73452]1049} // namespace SymTab
[0dd3a2f]1050
1051// Local Variables: //
1052// tab-width: 4 //
1053// mode: c++ //
1054// compile-command: "make install" //
1055// End: //
Note: See TracBrowser for help on using the repository browser.