source: src/SymTab/Validate.cc@ 638ac26

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum stuck-waitfor-destruct
Last change on this file since 638ac26 was a12c81f3, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Replace qualified types with the actual type

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