source: src/ResolvExpr/Resolver.cc@ 2a8f0c1

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 2a8f0c1 was 2a8f0c1, checked in by Aaron Moss <a3moss@…>, 7 years ago

Add first ported resolver function

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