source: src/SymTab/Validate.cc@ d56e5bc

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 d56e5bc was 436c0de, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Merge branch 'master' of plg.uwaterloo.ca:/u/cforall/software/cfa/cfa-cc

Conflicts:

src/InitTweak/GenInit.cc

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