source: src/SymTab/Validate.cc@ a62cbb3

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

add hoistType flag (currently unused)

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