source: src/ResolvExpr/Resolver.cc@ 3ef35bd

new-env with_gc
Last change on this file since 3ef35bd was ff29f08, checked in by Aaron Moss <a3moss@…>, 8 years ago

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

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