source: src/SymTab/Validate.cc@ ca278c1

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 new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since ca278c1 was 21b7161, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Convert FixFunction to PassVisitor

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