source: src/ResolvExpr/Resolver.cc@ 1ed958c3

new-env with_gc
Last change on this file since 1ed958c3 was eba74ba, checked in by Aaron Moss <a3moss@…>, 7 years ago

Merge remote-tracking branch 'origin/master' into with_gc

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