source: src/SymTab/Validate.cc@ 95d09bdb

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
Last change on this file since 95d09bdb was 95d09bdb, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Hoist aggregates defined as part of a compound literal

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