source: src/SymTab/Validate.cc@ c84e80a

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 c84e80a was 9facf3b, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

update generation of return variables and the affected test outputs

  • Property mode set to 100644
File size: 30.2 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 : Tue Jul 12 17:49:21 2016
13// Update Count : 298
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 <list>
41#include <iterator>
42#include "Common/ScopedMap.h"
43#include "Common/utility.h"
44#include "Common/UniqueName.h"
45#include "Validate.h"
46#include "SynTree/Visitor.h"
47#include "SynTree/Mutator.h"
48#include "SynTree/Type.h"
49#include "SynTree/Expression.h"
50#include "SynTree/Statement.h"
51#include "SynTree/TypeSubstitution.h"
52#include "Indexer.h"
53#include "FixFunction.h"
54// #include "ImplementationType.h"
55#include "GenPoly/DeclMutator.h"
56#include "AddVisit.h"
57#include "MakeLibCfa.h"
58#include "TypeEquality.h"
59#include "Autogen.h"
60#include "ResolvExpr/typeops.h"
61#include <algorithm>
62#include "InitTweak/InitTweak.h"
63#include "CodeGen/CodeGenerator.h"
64
65#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
66
67namespace SymTab {
68 class HoistStruct final : public Visitor {
69 public:
70 /// Flattens nested struct types
71 static void hoistStruct( std::list< Declaration * > &translationUnit );
72
73 std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
74
75 virtual void visit( StructDecl *aggregateDecl );
76 virtual void visit( UnionDecl *aggregateDecl );
77
78 virtual void visit( CompoundStmt *compoundStmt );
79 virtual void visit( SwitchStmt *switchStmt );
80 private:
81 HoistStruct();
82
83 template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
84
85 std::list< Declaration * > declsToAdd;
86 bool inStruct;
87 };
88
89 /// Fix return types so that every function returns exactly one value
90 class ReturnTypeFixer final : public Visitor {
91 public:
92
93 typedef Visitor Parent;
94 using Parent::visit;
95
96 static void fix( std::list< Declaration * > &translationUnit );
97
98 virtual void visit( FunctionDecl * functionDecl );
99
100 virtual void visit( FunctionType * ftype );
101 };
102
103 /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
104 class EnumAndPointerDecayPass final : public Visitor {
105 typedef Visitor Parent;
106 virtual void visit( EnumDecl *aggregateDecl );
107 virtual void visit( FunctionType *func );
108 };
109
110 /// Associates forward declarations of aggregates with their definitions
111 class LinkReferenceToTypes final : public Indexer {
112 typedef Indexer Parent;
113 public:
114 LinkReferenceToTypes( bool doDebug, const Indexer *indexer );
115 private:
116 using Indexer::visit;
117 void visit( StructInstType *structInst ) final;
118 void visit( UnionInstType *unionInst ) final;
119 void visit( TraitInstType *contextInst ) final;
120 void visit( StructDecl *structDecl ) final;
121 void visit( UnionDecl *unionDecl ) final;
122 void visit( TypeInstType *typeInst ) final;
123
124 const Indexer *indexer;
125
126 typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
127 typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
128 ForwardStructsType forwardStructs;
129 ForwardUnionsType forwardUnions;
130 };
131
132 /// Replaces array and function types in forall lists by appropriate pointer type
133 class Pass3 : public Indexer {
134 typedef Indexer Parent;
135 public:
136 Pass3( const Indexer *indexer );
137 private:
138 virtual void visit( ObjectDecl *object );
139 virtual void visit( FunctionDecl *func );
140
141 const Indexer *indexer;
142 };
143
144 class ReturnChecker : public Visitor {
145 public:
146 /// Checks that return statements return nothing if their return type is void
147 /// and return something if the return type is non-void.
148 static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
149 private:
150 virtual void visit( FunctionDecl * functionDecl );
151
152 virtual void visit( ReturnStmt * returnStmt );
153
154 std::list< DeclarationWithType * > returnVals;
155 };
156
157 class EliminateTypedef : public Mutator {
158 public:
159 EliminateTypedef() : scopeLevel( 0 ) {}
160 /// Replaces typedefs by forward declarations
161 static void eliminateTypedef( std::list< Declaration * > &translationUnit );
162 private:
163 virtual Declaration *mutate( TypedefDecl *typeDecl );
164 virtual TypeDecl *mutate( TypeDecl *typeDecl );
165 virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
166 virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
167 virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
168 virtual Type *mutate( TypeInstType *aggregateUseType );
169 virtual Expression *mutate( CastExpr *castExpr );
170
171 virtual Declaration *mutate( StructDecl * structDecl );
172 virtual Declaration *mutate( UnionDecl * unionDecl );
173 virtual Declaration *mutate( EnumDecl * enumDecl );
174 virtual Declaration *mutate( TraitDecl * contextDecl );
175
176 template<typename AggDecl>
177 AggDecl *handleAggregate( AggDecl * aggDecl );
178
179 template<typename AggDecl>
180 void addImplicitTypedef( AggDecl * aggDecl );
181
182 typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
183 typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
184 typedef std::map< std::string, TypeDecl * > TypeDeclMap;
185 TypedefMap typedefNames;
186 TypeDeclMap typedeclNames;
187 int scopeLevel;
188 };
189
190 class VerifyCtorDtorAssign : public Visitor {
191 public:
192 /// ensure that constructors, destructors, and assignment have at least one
193 /// parameter, the first of which must be a pointer, and that ctor/dtors have no
194 /// return values.
195 static void verify( std::list< Declaration * > &translationUnit );
196
197 virtual void visit( FunctionDecl *funcDecl );
198 };
199
200 class CompoundLiteral final : public GenPoly::DeclMutator {
201 DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
202
203 using GenPoly::DeclMutator::mutate;
204 DeclarationWithType * mutate( ObjectDecl *objectDecl ) final;
205 Expression *mutate( CompoundLiteralExpr *compLitExpr ) final;
206 };
207
208 void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
209 EnumAndPointerDecayPass epc;
210 LinkReferenceToTypes lrt( doDebug, 0 );
211 Pass3 pass3( 0 );
212 CompoundLiteral compoundliteral;
213
214 EliminateTypedef::eliminateTypedef( translationUnit );
215 HoistStruct::hoistStruct( translationUnit );
216 ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
217 autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecayPass
218 acceptAll( translationUnit, epc );
219 acceptAll( translationUnit, lrt );
220 ReturnChecker::checkFunctionReturns( translationUnit );
221 compoundliteral.mutateDeclarationList( translationUnit );
222 acceptAll( translationUnit, pass3 );
223 VerifyCtorDtorAssign::verify( translationUnit );
224 }
225
226 void validateType( Type *type, const Indexer *indexer ) {
227 EnumAndPointerDecayPass epc;
228 LinkReferenceToTypes lrt( false, indexer );
229 Pass3 pass3( indexer );
230 type->accept( epc );
231 type->accept( lrt );
232 type->accept( pass3 );
233 }
234
235 void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
236 HoistStruct hoister;
237 acceptAndAdd( translationUnit, hoister, true );
238 }
239
240 HoistStruct::HoistStruct() : inStruct( false ) {
241 }
242
243 void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
244 std::list< Declaration * >::iterator i = declList.begin();
245 while ( i != declList.end() ) {
246 std::list< Declaration * >::iterator next = i;
247 ++next;
248 if ( pred( *i ) ) {
249 if ( doDelete ) {
250 delete *i;
251 } // if
252 declList.erase( i );
253 } // if
254 i = next;
255 } // while
256 }
257
258 bool isStructOrUnion( Declaration *decl ) {
259 return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
260 }
261 // xxx - shouldn't this be declsToAddBefore?
262 template< typename AggDecl >
263 void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
264 if ( inStruct ) {
265 // Add elements in stack order corresponding to nesting structure.
266 declsToAdd.push_front( aggregateDecl );
267 Visitor::visit( aggregateDecl );
268 } else {
269 inStruct = true;
270 Visitor::visit( aggregateDecl );
271 inStruct = false;
272 } // if
273 // Always remove the hoisted aggregate from the inner structure.
274 filter( aggregateDecl->get_members(), isStructOrUnion, false );
275 }
276
277 void HoistStruct::visit( StructDecl *aggregateDecl ) {
278 handleAggregate( aggregateDecl );
279 }
280
281 void HoistStruct::visit( UnionDecl *aggregateDecl ) {
282 handleAggregate( aggregateDecl );
283 }
284
285 void HoistStruct::visit( CompoundStmt *compoundStmt ) {
286 addVisit( compoundStmt, *this );
287 }
288
289 void HoistStruct::visit( SwitchStmt *switchStmt ) {
290 addVisit( switchStmt, *this );
291 }
292
293 void EnumAndPointerDecayPass::visit( EnumDecl *enumDecl ) {
294 // Set the type of each member of the enumeration to be EnumConstant
295 for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
296 ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
297 assert( obj );
298 obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
299 } // for
300 Parent::visit( enumDecl );
301 }
302
303 namespace {
304 template< typename DWTList >
305 void fixFunctionList( DWTList & dwts, FunctionType * func ) {
306 // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
307 // entirely other fix ups are handled by the FixFunction class
308 typedef typename DWTList::iterator DWTIterator;
309 DWTIterator begin( dwts.begin() ), end( dwts.end() );
310 if ( begin == end ) return;
311 FixFunction fixer;
312 DWTIterator i = begin;
313 *i = (*i)->acceptMutator( fixer );
314 if ( fixer.get_isVoid() ) {
315 DWTIterator j = i;
316 ++i;
317 delete *j;
318 dwts.erase( j );
319 if ( i != end ) {
320 throw SemanticError( "invalid type void in function type ", func );
321 } // if
322 } else {
323 ++i;
324 for ( ; i != end; ++i ) {
325 FixFunction fixer;
326 *i = (*i )->acceptMutator( fixer );
327 if ( fixer.get_isVoid() ) {
328 throw SemanticError( "invalid type void in function type ", func );
329 } // if
330 } // for
331 } // if
332 }
333 }
334
335 void EnumAndPointerDecayPass::visit( FunctionType *func ) {
336 // Fix up parameters and return types
337 fixFunctionList( func->get_parameters(), func );
338 fixFunctionList( func->get_returnVals(), func );
339 Visitor::visit( func );
340 }
341
342 LinkReferenceToTypes::LinkReferenceToTypes( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
343 if ( other_indexer ) {
344 indexer = other_indexer;
345 } else {
346 indexer = this;
347 } // if
348 }
349
350 void LinkReferenceToTypes::visit( StructInstType *structInst ) {
351 Parent::visit( structInst );
352 StructDecl *st = indexer->lookupStruct( structInst->get_name() );
353 // it's not a semantic error if the struct is not found, just an implicit forward declaration
354 if ( st ) {
355 //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
356 structInst->set_baseStruct( st );
357 } // if
358 if ( ! st || st->get_members().empty() ) {
359 // use of forward declaration
360 forwardStructs[ structInst->get_name() ].push_back( structInst );
361 } // if
362 }
363
364 void LinkReferenceToTypes::visit( UnionInstType *unionInst ) {
365 Parent::visit( unionInst );
366 UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
367 // it's not a semantic error if the union is not found, just an implicit forward declaration
368 if ( un ) {
369 unionInst->set_baseUnion( un );
370 } // if
371 if ( ! un || un->get_members().empty() ) {
372 // use of forward declaration
373 forwardUnions[ unionInst->get_name() ].push_back( unionInst );
374 } // if
375 }
376
377 void LinkReferenceToTypes::visit( TraitInstType *contextInst ) {
378 Parent::visit( contextInst );
379 if ( contextInst->get_name() == "sized" ) {
380 // "sized" is a special trait with no members - just flick the sized status on for the type variable
381 if ( contextInst->get_parameters().size() != 1 ) {
382 throw SemanticError( "incorrect number of context parameters: ", contextInst );
383 }
384 TypeExpr * param = safe_dynamic_cast< TypeExpr * > ( contextInst->get_parameters().front() );
385 TypeInstType * inst = safe_dynamic_cast< TypeInstType * > ( param->get_type() );
386 TypeDecl * decl = inst->get_baseType();
387 decl->set_sized( true );
388 // since "sized" is special, the next few steps don't apply
389 return;
390 }
391 TraitDecl *ctx = indexer->lookupTrait( contextInst->get_name() );
392 if ( ! ctx ) {
393 throw SemanticError( "use of undeclared context " + contextInst->get_name() );
394 } // if
395 for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
396 for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
397 if ( TraitInstType *otherCtx = dynamic_cast< TraitInstType * >(*assert ) ) {
398 cloneAll( otherCtx->get_members(), contextInst->get_members() );
399 } else {
400 contextInst->get_members().push_back( (*assert )->clone() );
401 } // if
402 } // for
403 } // for
404
405 if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
406 throw SemanticError( "incorrect number of context parameters: ", contextInst );
407 } // if
408
409 // need to clone members of the context for ownership purposes
410 std::list< Declaration * > members;
411 std::transform( ctx->get_members().begin(), ctx->get_members().end(), back_inserter( members ), [](Declaration * dwt) { return dwt->clone(); } );
412
413 applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), members.begin(), members.end(), back_inserter( contextInst->get_members() ) );
414 }
415
416 void LinkReferenceToTypes::visit( StructDecl *structDecl ) {
417 // visit struct members first so that the types of self-referencing members are updated properly
418 Parent::visit( structDecl );
419 if ( ! structDecl->get_members().empty() ) {
420 ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
421 if ( fwds != forwardStructs.end() ) {
422 for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
423 (*inst )->set_baseStruct( structDecl );
424 } // for
425 forwardStructs.erase( fwds );
426 } // if
427 } // if
428 }
429
430 void LinkReferenceToTypes::visit( UnionDecl *unionDecl ) {
431 Parent::visit( unionDecl );
432 if ( ! unionDecl->get_members().empty() ) {
433 ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
434 if ( fwds != forwardUnions.end() ) {
435 for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
436 (*inst )->set_baseUnion( unionDecl );
437 } // for
438 forwardUnions.erase( fwds );
439 } // if
440 } // if
441 }
442
443 void LinkReferenceToTypes::visit( TypeInstType *typeInst ) {
444 if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
445 if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
446 typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
447 } // if
448 } // if
449 }
450
451 Pass3::Pass3( const Indexer *other_indexer ) : Indexer( false ) {
452 if ( other_indexer ) {
453 indexer = other_indexer;
454 } else {
455 indexer = this;
456 } // if
457 }
458
459 /// Fix up assertions
460 void forallFixer( Type *func ) {
461 for ( Type::ForallList::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
462 std::list< DeclarationWithType * > toBeDone, nextRound;
463 toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
464 while ( ! toBeDone.empty() ) {
465 for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
466 if ( TraitInstType *ctx = dynamic_cast< TraitInstType * >( (*assertion )->get_type() ) ) {
467 for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
468 DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
469 assert( dwt );
470 nextRound.push_back( dwt->clone() );
471 }
472 delete ctx;
473 } else {
474 FixFunction fixer;
475 *assertion = (*assertion )->acceptMutator( fixer );
476 if ( fixer.get_isVoid() ) {
477 throw SemanticError( "invalid type void in assertion of function ", func );
478 }
479 (*type )->get_assertions().push_back( *assertion );
480 } // if
481 } // for
482 toBeDone.clear();
483 toBeDone.splice( toBeDone.end(), nextRound );
484 } // while
485 } // for
486 }
487
488 void Pass3::visit( ObjectDecl *object ) {
489 forallFixer( object->get_type() );
490 if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
491 forallFixer( pointer->get_base() );
492 } // if
493 Parent::visit( object );
494 object->fixUniqueId();
495 }
496
497 void Pass3::visit( FunctionDecl *func ) {
498 forallFixer( func->get_type() );
499 Parent::visit( func );
500 func->fixUniqueId();
501 }
502
503 void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
504 ReturnChecker checker;
505 acceptAll( translationUnit, checker );
506 }
507
508 void ReturnChecker::visit( FunctionDecl * functionDecl ) {
509 std::list< DeclarationWithType * > oldReturnVals = returnVals;
510 returnVals = functionDecl->get_functionType()->get_returnVals();
511 Visitor::visit( functionDecl );
512 returnVals = oldReturnVals;
513 }
514
515 void ReturnChecker::visit( ReturnStmt * returnStmt ) {
516 // Previously this also checked for the existence of an expr paired with no return values on
517 // the function return type. This is incorrect, since you can have an expression attached to
518 // a return statement in a void-returning function in C. The expression is treated as if it
519 // were cast to void.
520 if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) {
521 throw SemanticError( "Non-void function returns no values: " , returnStmt );
522 }
523 }
524
525
526 bool isTypedef( Declaration *decl ) {
527 return dynamic_cast< TypedefDecl * >( decl );
528 }
529
530 void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
531 EliminateTypedef eliminator;
532 mutateAll( translationUnit, eliminator );
533 if ( eliminator.typedefNames.count( "size_t" ) ) {
534 // grab and remember declaration of size_t
535 SizeType = eliminator.typedefNames["size_t"].first->get_base()->clone();
536 } else {
537 // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
538 // eventually should have a warning for this case.
539 SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
540 }
541 filter( translationUnit, isTypedef, true );
542
543 }
544
545 Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
546 // instances of typedef types will come here. If it is an instance
547 // of a typdef type, link the instance to its actual type.
548 TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
549 if ( def != typedefNames.end() ) {
550 Type *ret = def->second.first->get_base()->clone();
551 ret->get_qualifiers() += typeInst->get_qualifiers();
552 // place instance parameters on the typedef'd type
553 if ( ! typeInst->get_parameters().empty() ) {
554 ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
555 if ( ! rtt ) {
556 throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
557 }
558 rtt->get_parameters().clear();
559 cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
560 mutateAll( rtt->get_parameters(), *this ); // recursively fix typedefs on parameters
561 } // if
562 delete typeInst;
563 return ret;
564 } else {
565 TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
566 assert( base != typedeclNames.end() );
567 typeInst->set_baseType( base->second );
568 } // if
569 return typeInst;
570 }
571
572 Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
573 Declaration *ret = Mutator::mutate( tyDecl );
574
575 if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
576 // typedef to the same name from the same scope
577 // must be from the same type
578
579 Type * t1 = tyDecl->get_base();
580 Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
581 if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
582 throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
583 }
584 } else {
585 typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
586 } // if
587
588 // When a typedef is a forward declaration:
589 // typedef struct screen SCREEN;
590 // the declaration portion must be retained:
591 // struct screen;
592 // because the expansion of the typedef is:
593 // void rtn( SCREEN *p ) => void rtn( struct screen *p )
594 // hence the type-name "screen" must be defined.
595 // Note, qualifiers on the typedef are superfluous for the forward declaration.
596 if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
597 return new StructDecl( aggDecl->get_name() );
598 } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
599 return new UnionDecl( aggDecl->get_name() );
600 } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( tyDecl->get_base() ) ) {
601 return new EnumDecl( enumDecl->get_name() );
602 } else {
603 return ret->clone();
604 } // if
605 }
606
607 TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
608 TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
609 if ( i != typedefNames.end() ) {
610 typedefNames.erase( i ) ;
611 } // if
612
613 typedeclNames[ typeDecl->get_name() ] = typeDecl;
614 return Mutator::mutate( typeDecl );
615 }
616
617 DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
618 typedefNames.beginScope();
619 DeclarationWithType *ret = Mutator::mutate( funcDecl );
620 typedefNames.endScope();
621 return ret;
622 }
623
624 DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
625 typedefNames.beginScope();
626 DeclarationWithType *ret = Mutator::mutate( objDecl );
627 typedefNames.endScope();
628 // is the type a function?
629 if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
630 // replace the current object declaration with a function declaration
631 return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
632 } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
633 throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
634 } // if
635 return ret;
636 }
637
638 Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
639 typedefNames.beginScope();
640 Expression *ret = Mutator::mutate( castExpr );
641 typedefNames.endScope();
642 return ret;
643 }
644
645 CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
646 typedefNames.beginScope();
647 scopeLevel += 1;
648 CompoundStmt *ret = Mutator::mutate( compoundStmt );
649 scopeLevel -= 1;
650 std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
651 while ( i != compoundStmt->get_kids().end() ) {
652 std::list< Statement * >::iterator next = i+1;
653 if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
654 if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
655 delete *i;
656 compoundStmt->get_kids().erase( i );
657 } // if
658 } // if
659 i = next;
660 } // while
661 typedefNames.endScope();
662 return ret;
663 }
664
665 // there may be typedefs nested within aggregates in order for everything to work properly, these should be removed
666 // as well
667 template<typename AggDecl>
668 AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
669 std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
670 for ( ; it != aggDecl->get_members().end(); ) {
671 std::list< Declaration * >::iterator next = it+1;
672 if ( dynamic_cast< TypedefDecl * >( *it ) ) {
673 delete *it;
674 aggDecl->get_members().erase( it );
675 } // if
676 it = next;
677 }
678 return aggDecl;
679 }
680
681 template<typename AggDecl>
682 void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
683 if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
684 Type *type = nullptr;
685 if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
686 type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
687 } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
688 type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
689 } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) {
690 type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
691 } // if
692 TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), DeclarationNode::NoStorageClass, type ) );
693 typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
694 } // if
695 }
696
697 Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
698 addImplicitTypedef( structDecl );
699 Mutator::mutate( structDecl );
700 return handleAggregate( structDecl );
701 }
702
703 Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
704 addImplicitTypedef( unionDecl );
705 Mutator::mutate( unionDecl );
706 return handleAggregate( unionDecl );
707 }
708
709 Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
710 addImplicitTypedef( enumDecl );
711 Mutator::mutate( enumDecl );
712 return handleAggregate( enumDecl );
713 }
714
715 Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) {
716 Mutator::mutate( contextDecl );
717 return handleAggregate( contextDecl );
718 }
719
720 void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
721 VerifyCtorDtorAssign verifier;
722 acceptAll( translationUnit, verifier );
723 }
724
725 void VerifyCtorDtorAssign::visit( FunctionDecl * funcDecl ) {
726 FunctionType * funcType = funcDecl->get_functionType();
727 std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
728 std::list< DeclarationWithType * > &params = funcType->get_parameters();
729
730 if ( InitTweak::isCtorDtorAssign( funcDecl->get_name() ) ) {
731 if ( params.size() == 0 ) {
732 throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
733 }
734 if ( ! dynamic_cast< PointerType * >( params.front()->get_type() ) ) {
735 throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a pointer ", funcDecl );
736 }
737 if ( InitTweak::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
738 throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
739 }
740 }
741
742 Visitor::visit( funcDecl );
743 }
744
745 DeclarationWithType * CompoundLiteral::mutate( ObjectDecl *objectDecl ) {
746 storageclass = objectDecl->get_storageClass();
747 DeclarationWithType * temp = Mutator::mutate( objectDecl );
748 storageclass = DeclarationNode::NoStorageClass;
749 return temp;
750 }
751
752 Expression *CompoundLiteral::mutate( CompoundLiteralExpr *compLitExpr ) {
753 // transform [storage_class] ... (struct S){ 3, ... };
754 // into [storage_class] struct S temp = { 3, ... };
755 static UniqueName indexName( "_compLit" );
756
757 ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageclass, LinkageSpec::C, 0, compLitExpr->get_type(), compLitExpr->get_initializer() );
758 compLitExpr->set_type( 0 );
759 compLitExpr->set_initializer( 0 );
760 delete compLitExpr;
761 DeclarationWithType * newtempvar = mutate( tempvar );
762 addDeclaration( newtempvar ); // add modified temporary to current block
763 return new VariableExpr( newtempvar );
764 }
765
766 void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
767 ReturnTypeFixer fixer;
768 acceptAll( translationUnit, fixer );
769 }
770
771 void ReturnTypeFixer::visit( FunctionDecl * functionDecl ) {
772 Parent::visit( functionDecl );
773 FunctionType * ftype = functionDecl->get_functionType();
774 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
775 assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %d", functionDecl->get_name().c_str(), retVals.size() );
776 if ( retVals.size() == 1 ) {
777 // 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)
778 // ensure other return values have a name
779 DeclarationWithType * ret = retVals.front();
780 if ( ret->get_name() == "" ) {
781 ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
782 }
783 }
784 }
785
786 void ReturnTypeFixer::visit( FunctionType * ftype ) {
787 // xxx - need to handle named return values - this information needs to be saved somehow
788 // so that resolution has access to the names.
789 // Note that this pass needs to happen early so that other passes which look for tuple types
790 // find them in all of the right places, including function return types.
791 std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
792 if ( retVals.size() > 1 ) {
793 // generate a single return parameter which is the tuple of all of the return values
794 TupleType * tupleType = safe_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
795 // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
796 ObjectDecl * newRet = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
797 deleteAll( retVals );
798 retVals.clear();
799 retVals.push_back( newRet );
800 }
801 }
802} // namespace SymTab
803
804// Local Variables: //
805// tab-width: 4 //
806// mode: c++ //
807// compile-command: "make install" //
808// End: //
Note: See TracBrowser for help on using the repository browser.