source: src/ResolvExpr/Resolver.cc@ ad72c8b

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

Resolve with expressions earlier to ensure new local variables are present before other user-code is resolved

  • Property mode set to 100644
File size: 33.1 KB
RevLine 
[a32b204]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//
[71f4e4f]7// Resolver.cc --
[a32b204]8//
9// Author : Richard C. Bilson
10// Created On : Sun May 17 12:17:01 2015
[93401f8]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Sat Feb 17 11:19:40 2018
13// Update Count : 213
[a32b204]14//
15
[ea6332d]16#include <stddef.h> // for NULL
[e3e16bc]17#include <cassert> // for strict_dynamic_cast, assert
[ea6332d]18#include <memory> // for allocator, allocator_traits<...
19#include <tuple> // for get
[bd4f2e9]20#include <vector>
[ea6332d]21
22#include "Alternative.h" // for Alternative, AltList
23#include "AlternativeFinder.h" // for AlternativeFinder, resolveIn...
[a4ca48c]24#include "Common/PassVisitor.h" // for PassVisitor
[ea6332d]25#include "Common/SemanticError.h" // for SemanticError
26#include "Common/utility.h" // for ValueGuard, group_iterate
27#include "CurrentObject.h" // for CurrentObject
[0a60c04]28#include "InitTweak/GenInit.h"
[ea6332d]29#include "InitTweak/InitTweak.h" // for isIntrinsicSingleArgCallStmt
30#include "RenameVars.h" // for RenameVars, global_renamer
31#include "ResolvExpr/TypeEnvironment.h" // for TypeEnvironment
[e4d829b]32#include "Resolver.h"
[ea6332d]33#include "SymTab/Autogen.h" // for SizeType
34#include "SymTab/Indexer.h" // for Indexer
35#include "SynTree/Declaration.h" // for ObjectDecl, TypeDecl, Declar...
36#include "SynTree/Expression.h" // for Expression, CastExpr, InitExpr
37#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
38#include "SynTree/Statement.h" // for ForStmt, Statement, BranchStmt
39#include "SynTree/Type.h" // for Type, BasicType, PointerType
40#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
41#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
[0a60c04]42#include "Tuples/Tuples.h"
[ea6332d]43#include "typeops.h" // for extractResultType
[1dcd9554]44#include "Unify.h" // for unify
[51b73452]45
[d9a0e76]46using namespace std;
[51b73452]47
[d9a0e76]48namespace ResolvExpr {
[0a60c04]49 struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting, public WithStmtsToAdd {
[a4ca48c]50 Resolver() {}
51 Resolver( const SymTab::Indexer & other ) {
52 indexer = other;
[1d2b64f]53 }
[71f4e4f]54
[a4ca48c]55 void previsit( FunctionDecl *functionDecl );
56 void postvisit( FunctionDecl *functionDecl );
[3c398b6]57 void previsit( ObjectDecl *objectDecll );
[a4ca48c]58 void previsit( EnumDecl * enumDecl );
[bd87b138]59 void previsit( StaticAssertDecl * assertDecl );
[a4ca48c]60
61 void previsit( ArrayType * at );
62 void previsit( PointerType * at );
63
64 void previsit( ExprStmt *exprStmt );
65 void previsit( AsmExpr *asmExpr );
66 void previsit( AsmStmt *asmStmt );
67 void previsit( IfStmt *ifStmt );
68 void previsit( WhileStmt *whileStmt );
69 void previsit( ForStmt *forStmt );
70 void previsit( SwitchStmt *switchStmt );
71 void previsit( CaseStmt *caseStmt );
72 void previsit( BranchStmt *branchStmt );
73 void previsit( ReturnStmt *returnStmt );
74 void previsit( ThrowStmt *throwStmt );
75 void previsit( CatchStmt *catchStmt );
[695e00d]76 void previsit( WaitForStmt * stmt );
[a4ca48c]77
78 void previsit( SingleInit *singleInit );
79 void previsit( ListInit *listInit );
80 void previsit( ConstructorInit *ctorInit );
[a32b204]81 private:
[c28a038d]82 typedef std::list< Initializer * >::iterator InitIterator;
[94b4364]83
[40e636a]84 template< typename PtrType >
85 void handlePtrType( PtrType * type );
86
[c28a038d]87 void fallbackInit( ConstructorInit * ctorInit );
[b726084]88
[77971f6]89 Type * functionReturn = nullptr;
[e4d829b]90 CurrentObject currentObject = nullptr;
[a436947]91 bool inEnumDecl = false;
[a32b204]92 };
[d9a0e76]93
[2a6292d]94 struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
95 void previsit( FunctionDecl * );
96 void previsit( WithStmt * );
97
98 void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
99 };
100
[a32b204]101 void resolve( std::list< Declaration * > translationUnit ) {
[a4ca48c]102 PassVisitor<Resolver> resolver;
[a32b204]103 acceptAll( translationUnit, resolver );
[d9a0e76]104 }
105
[8b11840]106 void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
107 PassVisitor<Resolver> resolver( indexer );
108 maybeAccept( decl, resolver );
109 }
110
[c71b256]111 namespace {
112 struct DeleteFinder : public WithShortCircuiting {
113 DeletedExpr * delExpr = nullptr;
114 void previsit( DeletedExpr * expr ) {
115 if ( delExpr ) visit_children = false;
116 else delExpr = expr;
117 }
118
119 void previsit( Expression * ) {
120 if ( delExpr ) visit_children = false;
121 }
122 };
123 }
124
125 DeletedExpr * findDeletedExpr( Expression * expr ) {
126 PassVisitor<DeleteFinder> finder;
127 expr->accept( finder );
128 return finder.pass.delExpr;
[d9a0e76]129 }
[a32b204]130
131 namespace {
[cdb990a]132 struct StripCasts {
133 Expression * postmutate( CastExpr * castExpr ) {
134 if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
135 // generated cast is to the same type as its argument, so it's unnecessary -- remove it
136 Expression * expr = castExpr->arg;
137 castExpr->arg = nullptr;
138 std::swap( expr->env, castExpr->env );
139 return expr;
140 }
141 return castExpr;
142 }
143
144 static void strip( Expression *& expr ) {
145 PassVisitor<StripCasts> stripper;
146 expr = expr->acceptMutator( stripper );
147 }
148 };
149
150 void finishExpr( Expression *&expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
[7664fad]151 expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
[cdb990a]152 env.makeSubstitution( *expr->env );
153 StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
[a32b204]154 }
[0a22cda]155
156 void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
157 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
158 if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
159 // cast is to the same type as its argument, so it's unnecessary -- remove it
160 expr = castExpr->arg;
161 castExpr->arg = nullptr;
162 std::swap( expr->env, castExpr->env );
163 delete castExpr;
164 }
165 }
166 }
[db4ecc5]167 } // namespace
[a32b204]168
[8f98b78]169 namespace {
[c71b256]170 void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, bool adjust = false, bool prune = true, bool failFast = true) {
171 assertf( untyped, "expected a non-null expression." );
[8587878e]172 TypeEnvironment env;
173 AlternativeFinder finder( indexer, env );
[c71b256]174 finder.find( untyped, adjust, prune, failFast );
175
176 #if 0
177 if ( finder.get_alternatives().size() != 1 ) {
178 std::cerr << "untyped expr is ";
179 untyped->print( std::cerr );
180 std::cerr << std::endl << "alternatives are:";
181 for ( const Alternative & alt : finder.get_alternatives() ) {
182 alt.print( std::cerr );
183 } // for
184 } // if
185 #endif
[8587878e]186
187 AltList candidates;
188 for ( Alternative & alt : finder.get_alternatives() ) {
[c71b256]189 if ( pred( alt ) ) {
[8587878e]190 candidates.push_back( std::move( alt ) );
191 }
192 }
193
[c71b256]194 // xxx - if > 1 alternative with same cost, ignore deleted and pick from remaining
[8587878e]195 // choose the lowest cost expression among the candidates
196 AltList winners;
197 findMinCost( candidates.begin(), candidates.end(), back_inserter( winners ) );
198 if ( winners.size() == 0 ) {
[a16764a6]199 SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
[8587878e]200 } else if ( winners.size() != 1 ) {
201 std::ostringstream stream;
[c71b256]202 stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
[8587878e]203 untyped->print( stream );
[93401f8]204 stream << " Alternatives are:\n";
[8587878e]205 printAlts( winners, stream, 1 );
[a16764a6]206 SemanticError( untyped->location, stream.str() );
[8587878e]207 }
208
209 // there is one unambiguous interpretation - move the expression into the with statement
[c71b256]210 Alternative & choice = winners.front();
211 if ( findDeletedExpr( choice.expr ) ) {
[2a08c25]212 SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
[c71b256]213 }
214 alt = std::move( choice );
215 }
216
217 /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
218 void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, bool adjust = false, bool prune = true, bool failFast = true) {
219 if ( ! untyped ) return;
220 Alternative choice;
221 findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, adjust, prune, failFast );
222 finishExpr( choice.expr, choice.env, untyped->env );
[8587878e]223 delete untyped;
[c71b256]224 untyped = choice.expr;
225 choice.expr = nullptr;
[8587878e]226 }
227
[c71b256]228 bool standardAlternativeFilter( const Alternative & ) {
229 // currently don't need to filter, under normal circumstances.
230 // in the future, this may be useful for removing deleted expressions
231 return true;
232 }
233 } // namespace
234
235 // used in resolveTypeof
236 Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
237 TypeEnvironment env;
238 return resolveInVoidContext( expr, indexer, env );
239 }
240
241 Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
242 // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
243 // interpretations, an exception has already been thrown.
244 assertf( expr, "expected a non-null expression." );
245
246 static CastExpr untyped( nullptr ); // cast to void
[2a08c25]247 untyped.location = expr->location;
[c71b256]248
249 // set up and resolve expression cast to void
250 untyped.arg = expr;
251 Alternative choice;
252 findUnfinishedKindExpression( &untyped, choice, indexer, "", standardAlternativeFilter, true );
253 CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
254 env = std::move( choice.env );
255
256 // clean up resolved expression
257 Expression * ret = castExpr->arg;
258 castExpr->arg = nullptr;
259
260 // unlink the arg so that it isn't deleted twice at the end of the program
261 untyped.arg = nullptr;
262 return ret;
263 }
264
265 void findVoidExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
266 resetTyVarRenaming();
267 TypeEnvironment env;
268 Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
269 finishExpr( newExpr, env, untyped->env );
270 delete untyped;
271 untyped = newExpr;
272 }
273
274 void findSingleExpression( Expression *&untyped, const SymTab::Indexer &indexer ) {
275 findKindExpression( untyped, indexer, "", standardAlternativeFilter );
276 }
277
278 void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
279 assert( untyped && type );
[2a08c25]280 // transfer location to generated cast for error purposes
281 CodeLocation location = untyped->location;
[c71b256]282 untyped = new CastExpr( untyped, type );
[2a08c25]283 untyped->location = location;
[c71b256]284 findSingleExpression( untyped, indexer );
285 removeExtraneousCast( untyped, indexer );
286 }
287
288 namespace {
289 bool isIntegralType( const Alternative & alt ) {
290 Type * type = alt.expr->result;
[a32b204]291 if ( dynamic_cast< EnumInstType * >( type ) ) {
292 return true;
293 } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
294 return bt->isInteger();
[89e6ffc]295 } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
296 return true;
[a32b204]297 } else {
298 return false;
299 } // if
300 }
[71f4e4f]301
[08da53d]302 void findIntegralExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
[8587878e]303 findKindExpression( untyped, indexer, "condition", isIntegralType );
[a32b204]304 }
305 }
[71f4e4f]306
[2a6292d]307
308 bool isStructOrUnion( const Alternative & alt ) {
309 Type * t = alt.expr->result->stripReferences();
310 return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
311 }
312
313 void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
314 PassVisitor<ResolveWithExprs> resolver;
315 acceptAll( translationUnit, resolver );
316 }
317
318 void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
319 for ( Expression *& expr : withExprs ) {
320 // only struct- and union-typed expressions are viable candidates
321 findKindExpression( expr, indexer, "with statement", isStructOrUnion );
322
323 // if with expression might be impure, create a temporary so that it is evaluated once
324 if ( Tuples::maybeImpure( expr ) ) {
325 static UniqueName tmpNamer( "_with_tmp_" );
326 ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
327 expr = new VariableExpr( tmp );
328 newStmts.push_back( new DeclStmt( tmp ) );
329 if ( InitTweak::isConstructable( tmp->type ) ) {
330 // generate ctor/dtor and resolve them
331 tmp->init = InitTweak::genCtorInit( tmp );
332 tmp->accept( *visitor );
333 }
334 }
335 }
336 }
337
338 void ResolveWithExprs::previsit( WithStmt * withStmt ) {
339 resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
340 }
341
342 void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
343 {
344 // resolve with-exprs with parameters in scope and add any newly generated declarations to the
345 // front of the function body.
346 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
347 indexer.addFunctionType( functionDecl->type );
348 std::list< Statement * > newStmts;
349 resolveWithExprs( functionDecl->withExprs, newStmts );
350 if ( functionDecl->statements ) {
351 functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
352 } else {
353 assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
354 }
355 }
356 }
357
[a4ca48c]358 void Resolver::previsit( ObjectDecl *objectDecl ) {
[3cfe27f]359 // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
360 // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
361 // initContext because of a function type can contain object declarations in the return and parameter types. So
362 // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
363 // the RHS.
[a4ca48c]364 GuardValue( currentObject );
[e4d829b]365 currentObject = CurrentObject( objectDecl->get_type() );
366 if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
[a436947]367 // enumerator initializers should not use the enum type to initialize, since
368 // the enum type is still incomplete at this point. Use signed int instead.
[e4d829b]369 currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
[a436947]370 }
[bfbf97f]371 }
372
[40e636a]373 template< typename PtrType >
374 void Resolver::handlePtrType( PtrType * type ) {
375 if ( type->get_dimension() ) {
[08da53d]376 findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
[d1d17f5]377 }
[40e636a]378 }
379
[a4ca48c]380 void Resolver::previsit( ArrayType * at ) {
[40e636a]381 handlePtrType( at );
[a32b204]382 }
[94b4364]383
[a4ca48c]384 void Resolver::previsit( PointerType * pt ) {
[40e636a]385 handlePtrType( pt );
386 }
387
[a4ca48c]388 void Resolver::previsit( FunctionDecl *functionDecl ) {
[d9a0e76]389#if 0
[a4ca48c]390 std::cerr << "resolver visiting functiondecl ";
391 functionDecl->print( std::cerr );
392 std::cerr << std::endl;
[d9a0e76]393#endif
[a4ca48c]394 GuardValue( functionReturn );
[60914351]395 functionReturn = ResolvExpr::extractResultType( functionDecl->type );
[a4ca48c]396 }
[88d1066]397
[a4ca48c]398 void Resolver::postvisit( FunctionDecl *functionDecl ) {
[88d1066]399 // default value expressions have an environment which shouldn't be there and trips up later passes.
400 // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
401 // see how it's useful.
[c28a038d]402 for ( Declaration * d : functionDecl->type->parameters ) {
[88d1066]403 if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
[c28a038d]404 if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
405 delete init->value->env;
406 init->value->env = nullptr;
[88d1066]407 }
408 }
409 }
[a32b204]410 }
[51b73452]411
[a4ca48c]412 void Resolver::previsit( EnumDecl * ) {
[a436947]413 // in case we decide to allow nested enums
[a4ca48c]414 GuardValue( inEnumDecl );
[a436947]415 inEnumDecl = true;
416 }
417
[bd87b138]418 void Resolver::previsit( StaticAssertDecl * assertDecl ) {
419 findIntegralExpression( assertDecl->condition, indexer );
420 }
421
[a4ca48c]422 void Resolver::previsit( ExprStmt *exprStmt ) {
423 visit_children = false;
[08da53d]424 assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
425 findVoidExpression( exprStmt->expr, indexer );
[a32b204]426 }
[51b73452]427
[a4ca48c]428 void Resolver::previsit( AsmExpr *asmExpr ) {
429 visit_children = false;
[08da53d]430 findVoidExpression( asmExpr->operand, indexer );
[7f5566b]431 if ( asmExpr->get_inout() ) {
[08da53d]432 findVoidExpression( asmExpr->inout, indexer );
[7f5566b]433 } // if
434 }
435
[a4ca48c]436 void Resolver::previsit( AsmStmt *asmStmt ) {
437 visit_children = false;
438 acceptAll( asmStmt->get_input(), *visitor );
439 acceptAll( asmStmt->get_output(), *visitor );
[7f5566b]440 }
441
[a4ca48c]442 void Resolver::previsit( IfStmt *ifStmt ) {
[8587878e]443 findIntegralExpression( ifStmt->condition, indexer );
[a32b204]444 }
[51b73452]445
[a4ca48c]446 void Resolver::previsit( WhileStmt *whileStmt ) {
[8587878e]447 findIntegralExpression( whileStmt->condition, indexer );
[a32b204]448 }
[51b73452]449
[a4ca48c]450 void Resolver::previsit( ForStmt *forStmt ) {
[08da53d]451 if ( forStmt->condition ) {
[8587878e]452 findIntegralExpression( forStmt->condition, indexer );
[a32b204]453 } // if
[71f4e4f]454
[08da53d]455 if ( forStmt->increment ) {
456 findVoidExpression( forStmt->increment, indexer );
[a32b204]457 } // if
458 }
[51b73452]459
[a4ca48c]460 void Resolver::previsit( SwitchStmt *switchStmt ) {
461 GuardValue( currentObject );
[08da53d]462 findIntegralExpression( switchStmt->condition, indexer );
[71f4e4f]463
[08da53d]464 currentObject = CurrentObject( switchStmt->condition->result );
[a32b204]465 }
[51b73452]466
[a4ca48c]467 void Resolver::previsit( CaseStmt *caseStmt ) {
[cdb990a]468 if ( caseStmt->condition ) {
[e4d829b]469 std::list< InitAlternative > initAlts = currentObject.getOptions();
470 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
[08da53d]471 // must remove cast from case statement because RangeExpr cannot be cast.
472 Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
473 findSingleExpression( newExpr, indexer );
[cdb990a]474 // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
475 // Ideally we would perform the conversion internally here.
476 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
477 newExpr = castExpr->arg;
478 castExpr->arg = nullptr;
479 std::swap( newExpr->env, castExpr->env );
480 delete castExpr;
481 }
482 caseStmt->condition = newExpr;
[32b8144]483 }
[a32b204]484 }
[51b73452]485
[a4ca48c]486 void Resolver::previsit( BranchStmt *branchStmt ) {
487 visit_children = false;
[de62360d]488 // must resolve the argument for a computed goto
489 if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
[08da53d]490 if ( branchStmt->computedTarget ) {
491 // computed goto argument is void *
492 findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
[de62360d]493 } // if
494 } // if
495 }
496
[a4ca48c]497 void Resolver::previsit( ReturnStmt *returnStmt ) {
498 visit_children = false;
[08da53d]499 if ( returnStmt->expr ) {
500 findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
[a32b204]501 } // if
502 }
[51b73452]503
[a4ca48c]504 void Resolver::previsit( ThrowStmt *throwStmt ) {
505 visit_children = false;
[cbce272]506 // TODO: Replace *exception type with &exception type.
[307a732]507 if ( throwStmt->get_expr() ) {
[cbce272]508 StructDecl * exception_decl =
[36982fc]509 indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
[cbce272]510 assert( exception_decl );
[08da53d]511 Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
512 findSingleExpression( throwStmt->expr, exceptType, indexer );
[307a732]513 }
514 }
515
[a4ca48c]516 void Resolver::previsit( CatchStmt *catchStmt ) {
[08da53d]517 if ( catchStmt->cond ) {
518 findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
[cbce272]519 }
520 }
521
[1dcd9554]522 template< typename iterator_t >
523 inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
524 while( it != end && !(*it)->get_type()->get_mutex() ) {
525 it++;
526 }
527
528 return it != end;
529 }
530
[695e00d]531 void Resolver::previsit( WaitForStmt * stmt ) {
[8f98b78]532 visit_children = false;
[1dcd9554]533
534 // Resolve all clauses first
535 for( auto& clause : stmt->clauses ) {
536
537 TypeEnvironment env;
[8f98b78]538 AlternativeFinder funcFinder( indexer, env );
[1dcd9554]539
540 // Find all alternatives for a function in canonical form
541 funcFinder.findWithAdjustment( clause.target.function );
542
543 if ( funcFinder.get_alternatives().empty() ) {
544 stringstream ss;
545 ss << "Use of undeclared indentifier '";
546 ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
547 ss << "' in call to waitfor";
[a16764a6]548 SemanticError( stmt->location, ss.str() );
[1dcd9554]549 }
550
[b9f383f]551 if(clause.target.arguments.empty()) {
552 SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
553 }
554
[1dcd9554]555 // Find all alternatives for all arguments in canonical form
[bd4f2e9]556 std::vector< AlternativeFinder > argAlternatives;
[1dcd9554]557 funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
558
559 // List all combinations of arguments
[bd4f2e9]560 std::vector< AltList > possibilities;
[1dcd9554]561 combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
562
563 AltList func_candidates;
564 std::vector< AltList > args_candidates;
565
566 // For every possible function :
567 // try matching the arguments to the parameters
568 // not the other way around because we have more arguments than parameters
[a16764a6]569 SemanticErrorException errors;
[1dcd9554]570 for ( Alternative & func : funcFinder.get_alternatives() ) {
571 try {
572 PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
573 if( !pointer ) {
[a16764a6]574 SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
[1dcd9554]575 }
576
577 FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
578 if( !function ) {
[a16764a6]579 SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
[1dcd9554]580 }
581
582
583 {
584 auto param = function->parameters.begin();
585 auto param_end = function->parameters.end();
586
587 if( !advance_to_mutex( param, param_end ) ) {
[a16764a6]588 SemanticError(function, "candidate function not viable: no mutex parameters\n");
[1dcd9554]589 }
590 }
591
592 Alternative newFunc( func );
593 // Strip reference from function
[a181494]594 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[1dcd9554]595
596 // For all the set of arguments we have try to match it with the parameter of the current function alternative
597 for ( auto & argsList : possibilities ) {
598
599 try {
600 // Declare data structures need for resolution
601 OpenVarSet openVars;
602 AssertionSet resultNeed, resultHave;
[6f326b1]603 TypeEnvironment resultEnv( func.env );
604 makeUnifiableVars( function, openVars, resultNeed );
605 // add all type variables as open variables now so that those not used in the parameter
606 // list are still considered open.
607 resultEnv.add( function->forall );
[1dcd9554]608
609 // Load type variables from arguemnts into one shared space
610 simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
611
612 // Make sure we don't widen any existing bindings
[d286cf68]613 resultEnv.forbidWidening();
[c5283ba]614
[1dcd9554]615 // Find any unbound type variables
616 resultEnv.extractOpenVars( openVars );
617
618 auto param = function->parameters.begin();
619 auto param_end = function->parameters.end();
620
[c5283ba]621 int n_mutex_param = 0;
[b9f383f]622
[1dcd9554]623 // For every arguments of its set, check if it matches one of the parameter
624 // The order is important
625 for( auto & arg : argsList ) {
626
627 // Ignore non-mutex arguments
628 if( !advance_to_mutex( param, param_end ) ) {
629 // We ran out of parameters but still have arguments
630 // this function doesn't match
[c5283ba]631 SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
[1dcd9554]632 }
633
[c5283ba]634 n_mutex_param++;
[b9f383f]635
[1dcd9554]636 // Check if the argument matches the parameter type in the current scope
[b9f383f]637 if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
[1dcd9554]638 // Type doesn't match
639 stringstream ss;
640 ss << "candidate function not viable: no known convertion from '";
641 (*param)->get_type()->print( ss );
[b9f383f]642 ss << "' to '";
643 arg.expr->get_result()->print( ss );
[5248789]644 ss << "' with env '";
645 resultEnv.print(ss);
[1dcd9554]646 ss << "'\n";
[a16764a6]647 SemanticError( function, ss.str() );
[1dcd9554]648 }
649
650 param++;
651 }
652
653 // All arguments match !
654
655 // Check if parameters are missing
656 if( advance_to_mutex( param, param_end ) ) {
[c5283ba]657 do {
658 n_mutex_param++;
659 param++;
660 } while( advance_to_mutex( param, param_end ) );
661
[1dcd9554]662 // We ran out of arguments but still have parameters left
663 // this function doesn't match
[c5283ba]664 SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
[1dcd9554]665 }
666
667 // All parameters match !
668
669 // Finish the expressions to tie in the proper environments
670 finishExpr( newFunc.expr, resultEnv );
671 for( Alternative & alt : argsList ) {
672 finishExpr( alt.expr, resultEnv );
673 }
674
675 // This is a match store it and save it for later
676 func_candidates.push_back( newFunc );
677 args_candidates.push_back( argsList );
678
679 }
[a16764a6]680 catch( SemanticErrorException &e ) {
[1dcd9554]681 errors.append( e );
682 }
683 }
684 }
[a16764a6]685 catch( SemanticErrorException &e ) {
[1dcd9554]686 errors.append( e );
687 }
688 }
689
690 // Make sure we got the right number of arguments
[a16764a6]691 if( func_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor" ); top.append( errors ); throw top; }
692 if( args_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
693 if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor" ); top.append( errors ); throw top; }
694 if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor" ); top.append( errors ); throw top; }
[c71b256]695 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
[1dcd9554]696
697 // Swap the results from the alternative with the unresolved values.
698 // Alternatives will handle deletion on destruction
699 std::swap( clause.target.function, func_candidates.front().expr );
700 for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
701 std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
702 }
703
704 // Resolve the conditions as if it were an IfStmt
705 // Resolve the statments normally
[08da53d]706 findSingleExpression( clause.condition, this->indexer );
[8f98b78]707 clause.statement->accept( *visitor );
[1dcd9554]708 }
709
710
711 if( stmt->timeout.statement ) {
712 // Resolve the timeout as an size_t for now
713 // Resolve the conditions as if it were an IfStmt
714 // Resolve the statments normally
[08da53d]715 findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
716 findSingleExpression( stmt->timeout.condition, this->indexer );
[8f98b78]717 stmt->timeout.statement->accept( *visitor );
[1dcd9554]718 }
719
720 if( stmt->orelse.statement ) {
721 // Resolve the conditions as if it were an IfStmt
722 // Resolve the statments normally
[08da53d]723 findSingleExpression( stmt->orelse.condition, this->indexer );
[8f98b78]724 stmt->orelse.statement->accept( *visitor );
[1dcd9554]725 }
726 }
727
[b5c5684]728 template< typename T >
729 bool isCharType( T t ) {
730 if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
[71f4e4f]731 return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
[b5c5684]732 bt->get_kind() == BasicType::UnsignedChar;
733 }
734 return false;
735 }
736
[a4ca48c]737 void Resolver::previsit( SingleInit *singleInit ) {
738 visit_children = false;
[62423350]739 // resolve initialization using the possibilities as determined by the currentObject cursor
[0a22cda]740 Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
[08da53d]741 findSingleExpression( newExpr, indexer );
[e3e16bc]742 InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
[62423350]743
744 // move cursor to the object that is actually initialized
[e4d829b]745 currentObject.setNext( initExpr->get_designation() );
[62423350]746
747 // discard InitExpr wrapper and retain relevant pieces
[08da53d]748 newExpr = initExpr->expr;
749 initExpr->expr = nullptr;
750 std::swap( initExpr->env, newExpr->env );
[cdb990a]751 // InitExpr may have inferParams in the case where the expression specializes a function pointer,
752 // and newExpr may already have inferParams of its own, so a simple swap is not sufficient.
753 newExpr->spliceInferParams( initExpr );
[e4d829b]754 delete initExpr;
755
[62423350]756 // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
757 Type * initContext = currentObject.getCurrentType();
758
[0a22cda]759 removeExtraneousCast( newExpr, indexer );
760
[62423350]761 // check if actual object's type is char[]
762 if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
763 if ( isCharType( at->get_base() ) ) {
764 // check if the resolved type is char *
765 if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
766 if ( isCharType( pt->get_base() ) ) {
[0a22cda]767 if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
768 // strip cast if we're initializing a char[] with a char *, e.g. char x[] = "hello";
769 newExpr = ce->get_arg();
770 ce->set_arg( nullptr );
771 std::swap( ce->env, newExpr->env );
772 delete ce;
773 }
[62423350]774 }
775 }
776 }
777 }
[94b4364]778
[62423350]779 // set initializer expr to resolved express
[0a22cda]780 singleInit->value = newExpr;
[62423350]781
782 // move cursor to next object in preparation for next initializer
783 currentObject.increment();
784 }
[94b4364]785
[a4ca48c]786 void Resolver::previsit( ListInit * listInit ) {
787 visit_children = false;
[62423350]788 // move cursor into brace-enclosed initializer-list
[e4d829b]789 currentObject.enterListInit();
790 // xxx - fix this so that the list isn't copied, iterator should be used to change current element
791 std::list<Designation *> newDesignations;
792 for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
[62423350]793 // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
794 // the initializer against that object.
[e4d829b]795 Designation * des = std::get<0>(p);
796 Initializer * init = std::get<1>(p);
797 newDesignations.push_back( currentObject.findNext( des ) );
[a4ca48c]798 init->accept( *visitor );
[b5c5684]799 }
[62423350]800 // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
[e4d829b]801 listInit->get_designations() = newDesignations; // xxx - memory management
802 currentObject.exitListInit();
803
[62423350]804 // xxx - this part has not be folded into CurrentObject yet
[e4d829b]805 // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
806 // Type * base = tt->get_baseType()->get_base();
807 // if ( base ) {
808 // // know the implementation type, so try using that as the initContext
809 // ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
810 // currentObject = &tmpObj;
811 // visit( listInit );
812 // } else {
813 // // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
814 // Parent::visit( listInit );
815 // }
816 // } else {
[a32b204]817 }
[71f4e4f]818
[f1e012b]819 // ConstructorInit - fall back on C-style initializer
820 void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
821 // could not find valid constructor, or found an intrinsic constructor
822 // fall back on C-style initializer
823 delete ctorInit->get_ctor();
824 ctorInit->set_ctor( NULL );
[71a145de]825 delete ctorInit->get_dtor();
826 ctorInit->set_dtor( NULL );
[a4ca48c]827 maybeAccept( ctorInit->get_init(), *visitor );
[f1e012b]828 }
829
[1d2b64f]830 // needs to be callable from outside the resolver, so this is a standalone function
831 void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
832 assert( ctorInit );
[a4ca48c]833 PassVisitor<Resolver> resolver( indexer );
[1d2b64f]834 ctorInit->accept( resolver );
835 }
836
837 void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
838 assert( stmtExpr );
[a4ca48c]839 PassVisitor<Resolver> resolver( indexer );
[1d2b64f]840 stmtExpr->accept( resolver );
[5e2c348]841 stmtExpr->computeResult();
[dd05e12]842 // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
[1d2b64f]843 }
844
[a4ca48c]845 void Resolver::previsit( ConstructorInit *ctorInit ) {
846 visit_children = false;
[1ba88a0]847 // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
[dd05e12]848 maybeAccept( ctorInit->ctor, *visitor );
849 maybeAccept( ctorInit->dtor, *visitor );
[071a31a]850
[5b2f5bb]851 // found a constructor - can get rid of C-style initializer
[dd05e12]852 delete ctorInit->init;
853 ctorInit->init = nullptr;
[ec79847]854
855 // intrinsic single parameter constructors and destructors do nothing. Since this was
856 // implicitly generated, there's no way for it to have side effects, so get rid of it
857 // to clean up generated code.
[dd05e12]858 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
859 delete ctorInit->ctor;
860 ctorInit->ctor = nullptr;
[ec79847]861 }
[f9cebb5]862
[dd05e12]863 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
864 delete ctorInit->dtor;
865 ctorInit->dtor = nullptr;
[ec79847]866 }
[a465caff]867
868 // xxx - todo -- what about arrays?
869 // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
870 // // can reduce the constructor down to a SingleInit using the
871 // // second argument from the ctor call, since
872 // delete ctorInit->get_ctor();
873 // ctorInit->set_ctor( NULL );
874
875 // Expression * arg =
876 // ctorInit->set_init( new SingleInit( arg ) );
877 // }
[71f4e4f]878 }
[51b73452]879} // namespace ResolvExpr
[a32b204]880
881// Local Variables: //
882// tab-width: 4 //
883// mode: c++ //
884// compile-command: "make install" //
885// End: //
Note: See TracBrowser for help on using the repository browser.