source: src/ResolvExpr/Resolver.cc@ 0ce063b

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 0ce063b was 4864a73, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Added chain mutation and example use in resolver

  • Property mode set to 100644
File size: 41.1 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 : Aaron B. Moss
10// Created On : Sun May 17 12:17:01 2015
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed May 29 11:00:00 2019
13// Update Count : 241
14//
15
16#include <cassert> // for strict_dynamic_cast, assert
17#include <memory> // for allocator, allocator_traits<...
18#include <tuple> // for get
19#include <vector> // for vector
20
21#include "Alternative.h" // for Alternative, AltList
22#include "AlternativeFinder.h" // for AlternativeFinder, resolveIn...
23#include "CurrentObject.h" // for CurrentObject
24#include "RenameVars.h" // for RenameVars, global_renamer
25#include "Resolver.h"
26#include "ResolvMode.h" // for ResolvMode
27#include "typeops.h" // for extractResultType
28#include "Unify.h" // for unify
29#include "AST/Chain.hpp"
30#include "AST/Decl.hpp"
31#include "AST/Init.hpp"
32#include "AST/Pass.hpp"
33#include "AST/SymbolTable.hpp"
34#include "Common/PassVisitor.h" // for PassVisitor
35#include "Common/SemanticError.h" // for SemanticError
36#include "Common/utility.h" // for ValueGuard, group_iterate
37#include "InitTweak/GenInit.h"
38#include "InitTweak/InitTweak.h" // for isIntrinsicSingleArgCallStmt
39#include "ResolvExpr/TypeEnvironment.h" // for TypeEnvironment
40#include "SymTab/Autogen.h" // for SizeType
41#include "SymTab/Indexer.h" // for Indexer
42#include "SynTree/Declaration.h" // for ObjectDecl, TypeDecl, Declar...
43#include "SynTree/Expression.h" // for Expression, CastExpr, InitExpr
44#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
45#include "SynTree/Statement.h" // for ForStmt, Statement, BranchStmt
46#include "SynTree/Type.h" // for Type, BasicType, PointerType
47#include "SynTree/TypeSubstitution.h" // for TypeSubstitution
48#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
49#include "Tuples/Tuples.h"
50#include "Validate/FindSpecialDecls.h" // for SizeType
51
52using namespace std;
53
54namespace ResolvExpr {
55 struct Resolver_old final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver_old>, public WithShortCircuiting, public WithStmtsToAdd {
56 Resolver_old() {}
57 Resolver_old( const SymTab::Indexer & other ) {
58 indexer = other;
59 }
60
61 void previsit( FunctionDecl * functionDecl );
62 void postvisit( FunctionDecl * functionDecl );
63 void previsit( ObjectDecl * objectDecll );
64 void previsit( EnumDecl * enumDecl );
65 void previsit( StaticAssertDecl * assertDecl );
66
67 void previsit( ArrayType * at );
68 void previsit( PointerType * at );
69
70 void previsit( ExprStmt * exprStmt );
71 void previsit( AsmExpr * asmExpr );
72 void previsit( AsmStmt * asmStmt );
73 void previsit( IfStmt * ifStmt );
74 void previsit( WhileStmt * whileStmt );
75 void previsit( ForStmt * forStmt );
76 void previsit( SwitchStmt * switchStmt );
77 void previsit( CaseStmt * caseStmt );
78 void previsit( BranchStmt * branchStmt );
79 void previsit( ReturnStmt * returnStmt );
80 void previsit( ThrowStmt * throwStmt );
81 void previsit( CatchStmt * catchStmt );
82 void previsit( WaitForStmt * stmt );
83
84 void previsit( SingleInit * singleInit );
85 void previsit( ListInit * listInit );
86 void previsit( ConstructorInit * ctorInit );
87 private:
88 typedef std::list< Initializer * >::iterator InitIterator;
89
90 template< typename PtrType >
91 void handlePtrType( PtrType * type );
92
93 void fallbackInit( ConstructorInit * ctorInit );
94
95 Type * functionReturn = nullptr;
96 CurrentObject currentObject = nullptr;
97 bool inEnumDecl = false;
98 };
99
100 struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
101 void previsit( FunctionDecl * );
102 void previsit( WithStmt * );
103
104 void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
105 };
106
107 void resolve( std::list< Declaration * > translationUnit ) {
108 PassVisitor<Resolver_old> resolver;
109 acceptAll( translationUnit, resolver );
110 }
111
112 void resolveDecl( Declaration * decl, const SymTab::Indexer & indexer ) {
113 PassVisitor<Resolver_old> resolver( indexer );
114 maybeAccept( decl, resolver );
115 }
116
117 namespace {
118 struct DeleteFinder : public WithShortCircuiting {
119 DeletedExpr * delExpr = nullptr;
120 void previsit( DeletedExpr * expr ) {
121 if ( delExpr ) visit_children = false;
122 else delExpr = expr;
123 }
124
125 void previsit( Expression * ) {
126 if ( delExpr ) visit_children = false;
127 }
128 };
129 }
130
131 DeletedExpr * findDeletedExpr( Expression * expr ) {
132 PassVisitor<DeleteFinder> finder;
133 expr->accept( finder );
134 return finder.pass.delExpr;
135 }
136
137 namespace {
138 struct StripCasts {
139 Expression * postmutate( CastExpr * castExpr ) {
140 if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
141 // generated cast is to the same type as its argument, so it's unnecessary -- remove it
142 Expression * expr = castExpr->arg;
143 castExpr->arg = nullptr;
144 std::swap( expr->env, castExpr->env );
145 return expr;
146 }
147 return castExpr;
148 }
149
150 static void strip( Expression *& expr ) {
151 PassVisitor<StripCasts> stripper;
152 expr = expr->acceptMutator( stripper );
153 }
154 };
155
156 void finishExpr( Expression *& expr, const TypeEnvironment & env, TypeSubstitution * oldenv = nullptr ) {
157 expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
158 env.makeSubstitution( *expr->env );
159 StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
160 }
161
162 void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
163 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
164 if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
165 // cast is to the same type as its argument, so it's unnecessary -- remove it
166 expr = castExpr->arg;
167 castExpr->arg = nullptr;
168 std::swap( expr->env, castExpr->env );
169 delete castExpr;
170 }
171 }
172 }
173 } // namespace
174
175 namespace {
176 void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
177 assertf( untyped, "expected a non-null expression." );
178
179 // xxx - this isn't thread-safe, but should work until we parallelize the resolver
180 static unsigned recursion_level = 0;
181
182 ++recursion_level;
183 TypeEnvironment env;
184 AlternativeFinder finder( indexer, env );
185 finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
186 --recursion_level;
187
188 #if 0
189 if ( finder.get_alternatives().size() != 1 ) {
190 std::cerr << "untyped expr is ";
191 untyped->print( std::cerr );
192 std::cerr << std::endl << "alternatives are:";
193 for ( const Alternative & alt : finder.get_alternatives() ) {
194 alt.print( std::cerr );
195 } // for
196 } // if
197 #endif
198
199 // produce filtered list of alternatives
200 AltList candidates;
201 for ( Alternative & alt : finder.get_alternatives() ) {
202 if ( pred( alt ) ) {
203 candidates.push_back( std::move( alt ) );
204 }
205 }
206
207 // produce invalid error if no candidates
208 if ( candidates.empty() ) {
209 SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
210 }
211
212 // search for cheapest candidate
213 AltList winners;
214 bool seen_undeleted = false;
215 for ( unsigned i = 0; i < candidates.size(); ++i ) {
216 int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost );
217
218 if ( c > 0 ) continue; // skip more expensive than winner
219
220 if ( c < 0 ) {
221 // reset on new cheapest
222 seen_undeleted = ! findDeletedExpr( candidates[i].expr );
223 winners.clear();
224 } else /* if ( c == 0 ) */ {
225 if ( findDeletedExpr( candidates[i].expr ) ) {
226 // skip deleted expression if already seen one equivalent-cost not
227 if ( seen_undeleted ) continue;
228 } else if ( ! seen_undeleted ) {
229 // replace list of equivalent-cost deleted expressions with one non-deleted
230 winners.clear();
231 seen_undeleted = true;
232 }
233 }
234
235 winners.emplace_back( std::move( candidates[i] ) );
236 }
237
238 // promote alternative.cvtCost to .cost
239 // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost
240 for ( Alternative& winner : winners ) {
241 winner.cost = winner.cvtCost;
242 }
243
244 // produce ambiguous errors, if applicable
245 if ( winners.size() != 1 ) {
246 std::ostringstream stream;
247 stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
248 untyped->print( stream );
249 stream << " Alternatives are:\n";
250 printAlts( winners, stream, 1 );
251 SemanticError( untyped->location, stream.str() );
252 }
253
254 // single selected choice
255 Alternative& choice = winners.front();
256
257 // fail on only expression deleted
258 if ( ! seen_undeleted ) {
259 SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
260 }
261
262 // xxx - check for ambiguous expressions
263
264 // output selected choice
265 alt = std::move( choice );
266 }
267
268 /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
269 void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
270 if ( ! untyped ) return;
271 Alternative choice;
272 findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
273 finishExpr( choice.expr, choice.env, untyped->env );
274 delete untyped;
275 untyped = choice.expr;
276 choice.expr = nullptr;
277 }
278
279 bool standardAlternativeFilter( const Alternative & ) {
280 // currently don't need to filter, under normal circumstances.
281 // in the future, this may be useful for removing deleted expressions
282 return true;
283 }
284 } // namespace
285
286 // used in resolveTypeof
287 Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer ) {
288 TypeEnvironment env;
289 return resolveInVoidContext( expr, indexer, env );
290 }
291
292 Expression * resolveInVoidContext( Expression * expr, const SymTab::Indexer & indexer, TypeEnvironment & env ) {
293 // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
294 // interpretations, an exception has already been thrown.
295 assertf( expr, "expected a non-null expression." );
296
297 CastExpr * untyped = new CastExpr( expr ); // cast to void
298 untyped->location = expr->location;
299
300 // set up and resolve expression cast to void
301 Alternative choice;
302 findUnfinishedKindExpression( untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
303 CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
304 assert( castExpr );
305 env = std::move( choice.env );
306
307 // clean up resolved expression
308 Expression * ret = castExpr->arg;
309 castExpr->arg = nullptr;
310
311 // unlink the arg so that it isn't deleted twice at the end of the program
312 untyped->arg = nullptr;
313 return ret;
314 }
315
316 void findVoidExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
317 resetTyVarRenaming();
318 TypeEnvironment env;
319 Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
320 finishExpr( newExpr, env, untyped->env );
321 delete untyped;
322 untyped = newExpr;
323 }
324
325 void findSingleExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
326 findKindExpression( untyped, indexer, "", standardAlternativeFilter );
327 }
328
329 void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
330 assert( untyped && type );
331 // transfer location to generated cast for error purposes
332 CodeLocation location = untyped->location;
333 untyped = new CastExpr( untyped, type );
334 untyped->location = location;
335 findSingleExpression( untyped, indexer );
336 removeExtraneousCast( untyped, indexer );
337 }
338
339 namespace {
340 bool isIntegralType( const Alternative & alt ) {
341 Type * type = alt.expr->result;
342 if ( dynamic_cast< EnumInstType * >( type ) ) {
343 return true;
344 } else if ( BasicType * bt = dynamic_cast< BasicType * >( type ) ) {
345 return bt->isInteger();
346 } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
347 return true;
348 } else {
349 return false;
350 } // if
351 }
352
353 void findIntegralExpression( Expression *& untyped, const SymTab::Indexer & indexer ) {
354 findKindExpression( untyped, indexer, "condition", isIntegralType );
355 }
356 }
357
358
359 bool isStructOrUnion( const Alternative & alt ) {
360 Type * t = alt.expr->result->stripReferences();
361 return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
362 }
363
364 void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
365 PassVisitor<ResolveWithExprs> resolver;
366 acceptAll( translationUnit, resolver );
367 }
368
369 void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
370 for ( Expression *& expr : withExprs ) {
371 // only struct- and union-typed expressions are viable candidates
372 findKindExpression( expr, indexer, "with statement", isStructOrUnion );
373
374 // if with expression might be impure, create a temporary so that it is evaluated once
375 if ( Tuples::maybeImpure( expr ) ) {
376 static UniqueName tmpNamer( "_with_tmp_" );
377 ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
378 expr = new VariableExpr( tmp );
379 newStmts.push_back( new DeclStmt( tmp ) );
380 if ( InitTweak::isConstructable( tmp->type ) ) {
381 // generate ctor/dtor and resolve them
382 tmp->init = InitTweak::genCtorInit( tmp );
383 tmp->accept( *visitor );
384 }
385 }
386 }
387 }
388
389 void ResolveWithExprs::previsit( WithStmt * withStmt ) {
390 resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
391 }
392
393 void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
394 {
395 // resolve with-exprs with parameters in scope and add any newly generated declarations to the
396 // front of the function body.
397 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
398 indexer.addFunctionType( functionDecl->type );
399 std::list< Statement * > newStmts;
400 resolveWithExprs( functionDecl->withExprs, newStmts );
401 if ( functionDecl->statements ) {
402 functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
403 } else {
404 assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
405 }
406 }
407 }
408
409 void Resolver_old::previsit( ObjectDecl * objectDecl ) {
410 // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that
411 // class-variable initContext is changed multiple time because the LHS is analysed twice.
412 // The second analysis changes initContext because of a function type can contain object
413 // declarations in the return and parameter types. So each value of initContext is
414 // retained, so the type on the first analysis is preserved and used for selecting the RHS.
415 GuardValue( currentObject );
416 currentObject = CurrentObject( objectDecl->get_type() );
417 if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
418 // enumerator initializers should not use the enum type to initialize, since
419 // the enum type is still incomplete at this point. Use signed int instead.
420 currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
421 }
422 }
423
424 template< typename PtrType >
425 void Resolver_old::handlePtrType( PtrType * type ) {
426 if ( type->get_dimension() ) {
427 findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer );
428 }
429 }
430
431 void Resolver_old::previsit( ArrayType * at ) {
432 handlePtrType( at );
433 }
434
435 void Resolver_old::previsit( PointerType * pt ) {
436 handlePtrType( pt );
437 }
438
439 void Resolver_old::previsit( FunctionDecl * functionDecl ) {
440#if 0
441 std::cerr << "resolver visiting functiondecl ";
442 functionDecl->print( std::cerr );
443 std::cerr << std::endl;
444#endif
445 GuardValue( functionReturn );
446 functionReturn = ResolvExpr::extractResultType( functionDecl->type );
447 }
448
449 void Resolver_old::postvisit( FunctionDecl * functionDecl ) {
450 // default value expressions have an environment which shouldn't be there and trips up
451 // later passes.
452 // xxx - it might be necessary to somehow keep the information from this environment, but I
453 // can't currently see how it's useful.
454 for ( Declaration * d : functionDecl->type->parameters ) {
455 if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
456 if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
457 delete init->value->env;
458 init->value->env = nullptr;
459 }
460 }
461 }
462 }
463
464 void Resolver_old::previsit( EnumDecl * ) {
465 // in case we decide to allow nested enums
466 GuardValue( inEnumDecl );
467 inEnumDecl = true;
468 }
469
470 void Resolver_old::previsit( StaticAssertDecl * assertDecl ) {
471 findIntegralExpression( assertDecl->condition, indexer );
472 }
473
474 void Resolver_old::previsit( ExprStmt * exprStmt ) {
475 visit_children = false;
476 assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
477 findVoidExpression( exprStmt->expr, indexer );
478 }
479
480 void Resolver_old::previsit( AsmExpr * asmExpr ) {
481 visit_children = false;
482 findVoidExpression( asmExpr->operand, indexer );
483 if ( asmExpr->get_inout() ) {
484 findVoidExpression( asmExpr->inout, indexer );
485 } // if
486 }
487
488 void Resolver_old::previsit( AsmStmt * asmStmt ) {
489 visit_children = false;
490 acceptAll( asmStmt->get_input(), *visitor );
491 acceptAll( asmStmt->get_output(), *visitor );
492 }
493
494 void Resolver_old::previsit( IfStmt * ifStmt ) {
495 findIntegralExpression( ifStmt->condition, indexer );
496 }
497
498 void Resolver_old::previsit( WhileStmt * whileStmt ) {
499 findIntegralExpression( whileStmt->condition, indexer );
500 }
501
502 void Resolver_old::previsit( ForStmt * forStmt ) {
503 if ( forStmt->condition ) {
504 findIntegralExpression( forStmt->condition, indexer );
505 } // if
506
507 if ( forStmt->increment ) {
508 findVoidExpression( forStmt->increment, indexer );
509 } // if
510 }
511
512 void Resolver_old::previsit( SwitchStmt * switchStmt ) {
513 GuardValue( currentObject );
514 findIntegralExpression( switchStmt->condition, indexer );
515
516 currentObject = CurrentObject( switchStmt->condition->result );
517 }
518
519 void Resolver_old::previsit( CaseStmt * caseStmt ) {
520 if ( caseStmt->condition ) {
521 std::list< InitAlternative > initAlts = currentObject.getOptions();
522 assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
523 // must remove cast from case statement because RangeExpr cannot be cast.
524 Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
525 findSingleExpression( newExpr, indexer );
526 // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
527 // Ideally we would perform the conversion internally here.
528 if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
529 newExpr = castExpr->arg;
530 castExpr->arg = nullptr;
531 std::swap( newExpr->env, castExpr->env );
532 delete castExpr;
533 }
534 caseStmt->condition = newExpr;
535 }
536 }
537
538 void Resolver_old::previsit( BranchStmt * branchStmt ) {
539 visit_children = false;
540 // must resolve the argument for a computed goto
541 if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
542 if ( branchStmt->computedTarget ) {
543 // computed goto argument is void *
544 findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
545 } // if
546 } // if
547 }
548
549 void Resolver_old::previsit( ReturnStmt * returnStmt ) {
550 visit_children = false;
551 if ( returnStmt->expr ) {
552 findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
553 } // if
554 }
555
556 void Resolver_old::previsit( ThrowStmt * throwStmt ) {
557 visit_children = false;
558 // TODO: Replace *exception type with &exception type.
559 if ( throwStmt->get_expr() ) {
560 StructDecl * exception_decl =
561 indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
562 assert( exception_decl );
563 Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
564 findSingleExpression( throwStmt->expr, exceptType, indexer );
565 }
566 }
567
568 void Resolver_old::previsit( CatchStmt * catchStmt ) {
569 if ( catchStmt->cond ) {
570 findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
571 }
572 }
573
574 template< typename iterator_t >
575 inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
576 while( it != end && !(*it)->get_type()->get_mutex() ) {
577 it++;
578 }
579
580 return it != end;
581 }
582
583 void Resolver_old::previsit( WaitForStmt * stmt ) {
584 visit_children = false;
585
586 // Resolve all clauses first
587 for( auto& clause : stmt->clauses ) {
588
589 TypeEnvironment env;
590 AlternativeFinder funcFinder( indexer, env );
591
592 // Find all alternatives for a function in canonical form
593 funcFinder.findWithAdjustment( clause.target.function );
594
595 if ( funcFinder.get_alternatives().empty() ) {
596 stringstream ss;
597 ss << "Use of undeclared indentifier '";
598 ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
599 ss << "' in call to waitfor";
600 SemanticError( stmt->location, ss.str() );
601 }
602
603 if(clause.target.arguments.empty()) {
604 SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
605 }
606
607 // Find all alternatives for all arguments in canonical form
608 std::vector< AlternativeFinder > argAlternatives;
609 funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
610
611 // List all combinations of arguments
612 std::vector< AltList > possibilities;
613 combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
614
615 AltList func_candidates;
616 std::vector< AltList > args_candidates;
617
618 // For every possible function :
619 // try matching the arguments to the parameters
620 // not the other way around because we have more arguments than parameters
621 SemanticErrorException errors;
622 for ( Alternative & func : funcFinder.get_alternatives() ) {
623 try {
624 PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
625 if( !pointer ) {
626 SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
627 }
628
629 FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
630 if( !function ) {
631 SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
632 }
633
634
635 {
636 auto param = function->parameters.begin();
637 auto param_end = function->parameters.end();
638
639 if( !advance_to_mutex( param, param_end ) ) {
640 SemanticError(function, "candidate function not viable: no mutex parameters\n");
641 }
642 }
643
644 Alternative newFunc( func );
645 // Strip reference from function
646 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
647
648 // For all the set of arguments we have try to match it with the parameter of the current function alternative
649 for ( auto & argsList : possibilities ) {
650
651 try {
652 // Declare data structures need for resolution
653 OpenVarSet openVars;
654 AssertionSet resultNeed, resultHave;
655 TypeEnvironment resultEnv( func.env );
656 makeUnifiableVars( function, openVars, resultNeed );
657 // add all type variables as open variables now so that those not used in the parameter
658 // list are still considered open.
659 resultEnv.add( function->forall );
660
661 // Load type variables from arguemnts into one shared space
662 simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
663
664 // Make sure we don't widen any existing bindings
665 resultEnv.forbidWidening();
666
667 // Find any unbound type variables
668 resultEnv.extractOpenVars( openVars );
669
670 auto param = function->parameters.begin();
671 auto param_end = function->parameters.end();
672
673 int n_mutex_param = 0;
674
675 // For every arguments of its set, check if it matches one of the parameter
676 // The order is important
677 for( auto & arg : argsList ) {
678
679 // Ignore non-mutex arguments
680 if( !advance_to_mutex( param, param_end ) ) {
681 // We ran out of parameters but still have arguments
682 // this function doesn't match
683 SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
684 }
685
686 n_mutex_param++;
687
688 // Check if the argument matches the parameter type in the current scope
689 if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
690 // Type doesn't match
691 stringstream ss;
692 ss << "candidate function not viable: no known convertion from '";
693 (*param)->get_type()->print( ss );
694 ss << "' to '";
695 arg.expr->get_result()->print( ss );
696 ss << "' with env '";
697 resultEnv.print(ss);
698 ss << "'\n";
699 SemanticError( function, ss.str() );
700 }
701
702 param++;
703 }
704
705 // All arguments match !
706
707 // Check if parameters are missing
708 if( advance_to_mutex( param, param_end ) ) {
709 do {
710 n_mutex_param++;
711 param++;
712 } while( advance_to_mutex( param, param_end ) );
713
714 // We ran out of arguments but still have parameters left
715 // this function doesn't match
716 SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
717 }
718
719 // All parameters match !
720
721 // Finish the expressions to tie in the proper environments
722 finishExpr( newFunc.expr, resultEnv );
723 for( Alternative & alt : argsList ) {
724 finishExpr( alt.expr, resultEnv );
725 }
726
727 // This is a match store it and save it for later
728 func_candidates.push_back( newFunc );
729 args_candidates.push_back( argsList );
730
731 }
732 catch( SemanticErrorException & e ) {
733 errors.append( e );
734 }
735 }
736 }
737 catch( SemanticErrorException & e ) {
738 errors.append( e );
739 }
740 }
741
742 // Make sure we got the right number of arguments
743 if( func_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor" ); top.append( errors ); throw top; }
744 if( args_candidates.empty() ) { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
745 if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor" ); top.append( errors ); throw top; }
746 if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor" ); top.append( errors ); throw top; }
747 // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
748
749 // Swap the results from the alternative with the unresolved values.
750 // Alternatives will handle deletion on destruction
751 std::swap( clause.target.function, func_candidates.front().expr );
752 for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
753 std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
754 }
755
756 // Resolve the conditions as if it were an IfStmt
757 // Resolve the statments normally
758 findSingleExpression( clause.condition, this->indexer );
759 clause.statement->accept( *visitor );
760 }
761
762
763 if( stmt->timeout.statement ) {
764 // Resolve the timeout as an size_t for now
765 // Resolve the conditions as if it were an IfStmt
766 // Resolve the statments normally
767 findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
768 findSingleExpression( stmt->timeout.condition, this->indexer );
769 stmt->timeout.statement->accept( *visitor );
770 }
771
772 if( stmt->orelse.statement ) {
773 // Resolve the conditions as if it were an IfStmt
774 // Resolve the statments normally
775 findSingleExpression( stmt->orelse.condition, this->indexer );
776 stmt->orelse.statement->accept( *visitor );
777 }
778 }
779
780 template< typename T >
781 bool isCharType( T t ) {
782 if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
783 return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
784 bt->get_kind() == BasicType::UnsignedChar;
785 }
786 return false;
787 }
788
789 void Resolver_old::previsit( SingleInit * singleInit ) {
790 visit_children = false;
791 // resolve initialization using the possibilities as determined by the currentObject cursor
792 Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
793 findSingleExpression( newExpr, indexer );
794 InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
795
796 // move cursor to the object that is actually initialized
797 currentObject.setNext( initExpr->get_designation() );
798
799 // discard InitExpr wrapper and retain relevant pieces
800 newExpr = initExpr->expr;
801 initExpr->expr = nullptr;
802 std::swap( initExpr->env, newExpr->env );
803 // InitExpr may have inferParams in the case where the expression specializes a function
804 // pointer, and newExpr may already have inferParams of its own, so a simple swap is not
805 // sufficient.
806 newExpr->spliceInferParams( initExpr );
807 delete initExpr;
808
809 // get the actual object's type (may not exactly match what comes back from the resolver
810 // due to conversions)
811 Type * initContext = currentObject.getCurrentType();
812
813 removeExtraneousCast( newExpr, indexer );
814
815 // check if actual object's type is char[]
816 if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
817 if ( isCharType( at->get_base() ) ) {
818 // check if the resolved type is char *
819 if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
820 if ( isCharType( pt->get_base() ) ) {
821 if ( CastExpr * ce = dynamic_cast< CastExpr * >( newExpr ) ) {
822 // strip cast if we're initializing a char[] with a char *,
823 // e.g. char x[] = "hello";
824 newExpr = ce->get_arg();
825 ce->set_arg( nullptr );
826 std::swap( ce->env, newExpr->env );
827 delete ce;
828 }
829 }
830 }
831 }
832 }
833
834 // set initializer expr to resolved express
835 singleInit->value = newExpr;
836
837 // move cursor to next object in preparation for next initializer
838 currentObject.increment();
839 }
840
841 void Resolver_old::previsit( ListInit * listInit ) {
842 visit_children = false;
843 // move cursor into brace-enclosed initializer-list
844 currentObject.enterListInit();
845 // xxx - fix this so that the list isn't copied, iterator should be used to change current
846 // element
847 std::list<Designation *> newDesignations;
848 for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
849 // iterate designations and initializers in pairs, moving the cursor to the current
850 // designated object and resolving the initializer against that object.
851 Designation * des = std::get<0>(p);
852 Initializer * init = std::get<1>(p);
853 newDesignations.push_back( currentObject.findNext( des ) );
854 init->accept( *visitor );
855 }
856 // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
857 listInit->get_designations() = newDesignations; // xxx - memory management
858 currentObject.exitListInit();
859
860 // xxx - this part has not be folded into CurrentObject yet
861 // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
862 // Type * base = tt->get_baseType()->get_base();
863 // if ( base ) {
864 // // know the implementation type, so try using that as the initContext
865 // ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
866 // currentObject = &tmpObj;
867 // visit( listInit );
868 // } else {
869 // // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
870 // Parent::visit( listInit );
871 // }
872 // } else {
873 }
874
875 // ConstructorInit - fall back on C-style initializer
876 void Resolver_old::fallbackInit( ConstructorInit * ctorInit ) {
877 // could not find valid constructor, or found an intrinsic constructor
878 // fall back on C-style initializer
879 delete ctorInit->get_ctor();
880 ctorInit->set_ctor( nullptr );
881 delete ctorInit->get_dtor();
882 ctorInit->set_dtor( nullptr );
883 maybeAccept( ctorInit->get_init(), *visitor );
884 }
885
886 // needs to be callable from outside the resolver, so this is a standalone function
887 void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
888 assert( ctorInit );
889 PassVisitor<Resolver_old> resolver( indexer );
890 ctorInit->accept( resolver );
891 }
892
893 void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
894 assert( stmtExpr );
895 PassVisitor<Resolver_old> resolver( indexer );
896 stmtExpr->accept( resolver );
897 stmtExpr->computeResult();
898 // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
899 }
900
901 void Resolver_old::previsit( ConstructorInit * ctorInit ) {
902 visit_children = false;
903 // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
904 maybeAccept( ctorInit->ctor, *visitor );
905 maybeAccept( ctorInit->dtor, *visitor );
906
907 // found a constructor - can get rid of C-style initializer
908 delete ctorInit->init;
909 ctorInit->init = nullptr;
910
911 // intrinsic single parameter constructors and destructors do nothing. Since this was
912 // implicitly generated, there's no way for it to have side effects, so get rid of it
913 // to clean up generated code.
914 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
915 delete ctorInit->ctor;
916 ctorInit->ctor = nullptr;
917 }
918
919 if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
920 delete ctorInit->dtor;
921 ctorInit->dtor = nullptr;
922 }
923
924 // xxx - todo -- what about arrays?
925 // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
926 // // can reduce the constructor down to a SingleInit using the
927 // // second argument from the ctor call, since
928 // delete ctorInit->get_ctor();
929 // ctorInit->set_ctor( nullptr );
930
931 // Expression * arg =
932 // ctorInit->set_init( new SingleInit( arg ) );
933 // }
934 }
935
936 ///////////////////////////////////////////////////////////////////////////
937 //
938 // *** NEW RESOLVER ***
939 //
940 ///////////////////////////////////////////////////////////////////////////
941
942 class Resolver_new final
943 : public ast::WithSymbolTable, public ast::WithGuards,
944 public ast::WithVisitorRef<Resolver_new>, public ast::WithShortCircuiting,
945 public ast::WithStmtsToAdd<> {
946
947 ast::ptr< ast::Type > functionReturn = nullptr;
948 // ast::CurrentObject currentObject = nullptr;
949 // bool inEnumDecl = false;
950
951 public:
952 Resolver_new() = default;
953 Resolver_new( const ast::SymbolTable & syms ) { symtab = syms; }
954
955 void previsit( const ast::FunctionDecl * functionDecl );
956 const ast::FunctionDecl * postvisit( const ast::FunctionDecl * functionDecl );
957 void previsit( const ast::ObjectDecl * objectDecl );
958 void previsit( const ast::EnumDecl * enumDecl );
959 void previsit( const ast::StaticAssertDecl * assertDecl );
960
961 void previsit( const ast::ArrayType * at );
962 void previsit( const ast::PointerType * pt );
963
964 void previsit( const ast::ExprStmt * exprStmt );
965 void previsit( const ast::AsmExpr * asmExpr );
966 void previsit( const ast::AsmStmt * asmStmt );
967 void previsit( const ast::IfStmt * ifStmt );
968 void previsit( const ast::WhileStmt * whileStmt );
969 void previsit( const ast::ForStmt * forStmt );
970 void previsit( const ast::SwitchStmt * switchStmt );
971 void previsit( const ast::CaseStmt * caseStmt );
972 void previsit( const ast::BranchStmt * branchStmt );
973 void previsit( const ast::ReturnStmt * returnStmt );
974 void previsit( const ast::ThrowStmt * throwStmt );
975 void previsit( const ast::CatchStmt * catchStmt );
976 void previsit( const ast::WaitForStmt * stmt );
977
978 void previsit( const ast::SingleInit * singleInit );
979 void previsit( const ast::ListInit * listInit );
980 void previsit( const ast::ConstructorInit * ctorInit );
981 };
982
983 void resolve( std::list< ast::ptr<ast::Decl> >& translationUnit ) {
984 ast::Pass<Resolver_new> resolver;
985 accept_all( translationUnit, resolver );
986 }
987
988 void Resolver_new::previsit( const ast::FunctionDecl * functionDecl ) {
989 GuardValue( functionReturn );
990 functionReturn = extractResultType( functionDecl->type );
991 }
992
993 const ast::FunctionDecl * Resolver_new::postvisit( const ast::FunctionDecl * functionDecl ) {
994 // default value expressions have an environment which shouldn't be there and trips up
995 // later passes.
996 ast::ptr< ast::FunctionDecl > ret = functionDecl;
997 for ( unsigned i = 0; i < functionDecl->type->params.size(); ++i ) {
998 const ast::ptr<ast::DeclWithType> & d = functionDecl->type->params[i];
999
1000 if ( const ast::ObjectDecl * obj = d.as< ast::ObjectDecl >() ) {
1001 if ( const ast::SingleInit * init = obj->init.as< ast::SingleInit >() ) {
1002 if ( init->value->env == nullptr ) continue;
1003 // clone initializer minus the initializer environment
1004 ast::chain_mutate( ret )
1005 ( &ast::FunctionDecl::type )
1006 ( &ast::FunctionType::params )
1007 [i]
1008 ( &ast::ObjectDecl::init )
1009 ( &ast::SingleInit::value )->env = nullptr;
1010
1011 assert( functionDecl != ret.get() || functionDecl->unique() );
1012 assert( ! ret->type->params[i].strict_as< ast::ObjectDecl >()->init.strict_as< ast::SingleInit >()->value->env );
1013 }
1014 }
1015 }
1016 return ret.get();
1017 }
1018
1019 void Resolver_new::previsit( const ast::ObjectDecl * objectDecl ) {
1020 #warning unimplemented; Resolver port in progress
1021 (void)objectDecl;
1022 assert(false);
1023 }
1024
1025 void Resolver_new::previsit( const ast::EnumDecl * enumDecl ) {
1026 #warning unimplemented; Resolver port in progress
1027 (void)enumDecl;
1028 assert(false);
1029 }
1030
1031 void Resolver_new::previsit( const ast::StaticAssertDecl * assertDecl ) {
1032 #warning unimplemented; Resolver port in progress
1033 (void)assertDecl;
1034 assert(false);
1035 }
1036
1037 void Resolver_new::previsit( const ast::ArrayType * at ) {
1038 #warning unimplemented; Resolver port in progress
1039 (void)at;
1040 assert(false);
1041 }
1042
1043 void Resolver_new::previsit( const ast::PointerType * pt ) {
1044 #warning unimplemented; Resolver port in progress
1045 (void)pt;
1046 assert(false);
1047 }
1048
1049 void Resolver_new::previsit( const ast::ExprStmt * exprStmt ) {
1050 #warning unimplemented; Resolver port in progress
1051 (void)exprStmt;
1052 assert(false);
1053 }
1054
1055 void Resolver_new::previsit( const ast::AsmExpr * asmExpr ) {
1056 #warning unimplemented; Resolver port in progress
1057 (void)asmExpr;
1058 assert(false);
1059 }
1060
1061 void Resolver_new::previsit( const ast::AsmStmt * asmStmt ) {
1062 #warning unimplemented; Resolver port in progress
1063 (void)asmStmt;
1064 assert(false);
1065 }
1066
1067 void Resolver_new::previsit( const ast::IfStmt * ifStmt ) {
1068 #warning unimplemented; Resolver port in progress
1069 (void)ifStmt;
1070 assert(false);
1071 }
1072
1073 void Resolver_new::previsit( const ast::WhileStmt * whileStmt ) {
1074 #warning unimplemented; Resolver port in progress
1075 (void)whileStmt;
1076 assert(false);
1077 }
1078
1079 void Resolver_new::previsit( const ast::ForStmt * forStmt ) {
1080 #warning unimplemented; Resolver port in progress
1081 (void)forStmt;
1082 assert(false);
1083 }
1084
1085 void Resolver_new::previsit( const ast::SwitchStmt * switchStmt ) {
1086 #warning unimplemented; Resolver port in progress
1087 (void)switchStmt;
1088 assert(false);
1089 }
1090
1091 void Resolver_new::previsit( const ast::CaseStmt * caseStmt ) {
1092 #warning unimplemented; Resolver port in progress
1093 (void)caseStmt;
1094 assert(false);
1095 }
1096
1097 void Resolver_new::previsit( const ast::BranchStmt * branchStmt ) {
1098 #warning unimplemented; Resolver port in progress
1099 (void)branchStmt;
1100 assert(false);
1101 }
1102
1103 void Resolver_new::previsit( const ast::ReturnStmt * returnStmt ) {
1104 #warning unimplemented; Resolver port in progress
1105 (void)returnStmt;
1106 assert(false);
1107 }
1108
1109 void Resolver_new::previsit( const ast::ThrowStmt * throwStmt ) {
1110 #warning unimplemented; Resolver port in progress
1111 (void)throwStmt;
1112 assert(false);
1113 }
1114
1115 void Resolver_new::previsit( const ast::CatchStmt * catchStmt ) {
1116 #warning unimplemented; Resolver port in progress
1117 (void)catchStmt;
1118 assert(false);
1119 }
1120
1121 void Resolver_new::previsit( const ast::WaitForStmt * stmt ) {
1122 #warning unimplemented; Resolver port in progress
1123 (void)stmt;
1124 assert(false);
1125 }
1126
1127 void Resolver_new::previsit( const ast::SingleInit * singleInit ) {
1128 #warning unimplemented; Resolver port in progress
1129 (void)singleInit;
1130 assert(false);
1131 }
1132
1133 void Resolver_new::previsit( const ast::ListInit * listInit ) {
1134 #warning unimplemented; Resolver port in progress
1135 (void)listInit;
1136 assert(false);
1137 }
1138
1139 void Resolver_new::previsit( const ast::ConstructorInit * ctorInit ) {
1140 #warning unimplemented; Resolver port in progress
1141 (void)ctorInit;
1142 assert(false);
1143 }
1144
1145} // namespace ResolvExpr
1146
1147// Local Variables: //
1148// tab-width: 4 //
1149// mode: c++ //
1150// compile-command: "make install" //
1151// End: //
Note: See TracBrowser for help on using the repository browser.