source: src/SymTab/Validate.cc@ 3c0d4cd

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since 3c0d4cd was 3c0d4cd, checked in by tdelisle <tdelisle@…>, 7 years ago

Fixed/implemented % of parent printing in timing sections

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