source: src/ResolvExpr/CandidateFinder.cpp@ a86b2ca6

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since a86b2ca6 was c15085d, checked in by Fangren Yu <f37yu@…>, 5 years ago

tracing memory allocation of resolver passes

  • Property mode set to 100644
File size: 60.4 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// CandidateFinder.cpp --
8//
9// Author : Aaron B. Moss
10// Created On : Wed Jun 5 14:30:00 2019
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Oct 1 14:55:00 2019
13// Update Count : 2
14//
15
16#include "CandidateFinder.hpp"
17
18#include <deque>
19#include <iterator> // for back_inserter
20#include <sstream>
21#include <string>
22#include <unordered_map>
23#include <vector>
24
25#include "Candidate.hpp"
26#include "CompilationState.h"
27#include "Cost.h"
28#include "ExplodedArg.hpp"
29#include "RenameVars.h" // for renameTyVars
30#include "Resolver.h"
31#include "ResolveTypeof.h"
32#include "SatisfyAssertions.hpp"
33#include "typeops.h" // for adjustExprType, conversionCost, polyCost, specCost
34#include "Unify.h"
35#include "AST/Expr.hpp"
36#include "AST/Node.hpp"
37#include "AST/Pass.hpp"
38#include "AST/Print.hpp"
39#include "AST/SymbolTable.hpp"
40#include "AST/Type.hpp"
41#include "Common/utility.h" // for move, copy
42#include "SymTab/Mangler.h"
43#include "SymTab/Validate.h" // for validateType
44#include "Tuples/Tuples.h" // for handleTupleAssignment
45
46#define PRINT( text ) if ( resolvep ) { text }
47
48namespace ResolvExpr {
49
50const ast::Expr * referenceToRvalueConversion( const ast::Expr * expr, Cost & cost ) {
51 if ( expr->result.as< ast::ReferenceType >() ) {
52 // cast away reference from expr
53 cost.incReference();
54 return new ast::CastExpr{ expr, expr->result->stripReferences() };
55 }
56
57 return expr;
58}
59
60/// Unique identifier for matching expression resolutions to their requesting expression
61UniqueId globalResnSlot = 0;
62
63Cost computeConversionCost(
64 const ast::Type * argType, const ast::Type * paramType, bool argIsLvalue,
65 const ast::SymbolTable & symtab, const ast::TypeEnvironment & env
66) {
67 PRINT(
68 std::cerr << std::endl << "converting ";
69 ast::print( std::cerr, argType, 2 );
70 std::cerr << std::endl << " to ";
71 ast::print( std::cerr, paramType, 2 );
72 std::cerr << std::endl << "environment is: ";
73 ast::print( std::cerr, env, 2 );
74 std::cerr << std::endl;
75 )
76 Cost convCost = conversionCost( argType, paramType, argIsLvalue, symtab, env );
77 PRINT(
78 std::cerr << std::endl << "cost is " << convCost << std::endl;
79 )
80 if ( convCost == Cost::infinity ) return convCost;
81 convCost.incPoly( polyCost( paramType, symtab, env ) + polyCost( argType, symtab, env ) );
82 PRINT(
83 std::cerr << "cost with polycost is " << convCost << std::endl;
84 )
85 return convCost;
86}
87
88namespace {
89 /// First index is which argument, second is which alternative, third is which exploded element
90 using ExplodedArgs_new = std::deque< std::vector< ExplodedArg > >;
91
92 /// Returns a list of alternatives with the minimum cost in the given list
93 CandidateList findMinCost( const CandidateList & candidates ) {
94 CandidateList out;
95 Cost minCost = Cost::infinity;
96 for ( const CandidateRef & r : candidates ) {
97 if ( r->cost < minCost ) {
98 minCost = r->cost;
99 out.clear();
100 out.emplace_back( r );
101 } else if ( r->cost == minCost ) {
102 out.emplace_back( r );
103 }
104 }
105 return out;
106 }
107
108 /// Computes conversion cost for a given expression to a given type
109 const ast::Expr * computeExpressionConversionCost(
110 const ast::Expr * arg, const ast::Type * paramType, const ast::SymbolTable & symtab, const ast::TypeEnvironment & env, Cost & outCost
111 ) {
112 Cost convCost = computeConversionCost(
113 arg->result, paramType, arg->get_lvalue(), symtab, env );
114 outCost += convCost;
115
116 // If there is a non-zero conversion cost, ignoring poly cost, then the expression requires
117 // conversion. Ignore poly cost for now, since this requires resolution of the cast to
118 // infer parameters and this does not currently work for the reason stated below
119 Cost tmpCost = convCost;
120 tmpCost.incPoly( -tmpCost.get_polyCost() );
121 if ( tmpCost != Cost::zero ) {
122 ast::ptr< ast::Type > newType = paramType;
123 env.apply( newType );
124 return new ast::CastExpr{ arg, newType };
125
126 // xxx - *should* be able to resolve this cast, but at the moment pointers are not
127 // castable to zero_t, but are implicitly convertible. This is clearly inconsistent,
128 // once this is fixed it should be possible to resolve the cast.
129 // xxx - this isn't working, it appears because type1 (parameter) is seen as widenable,
130 // but it shouldn't be because this makes the conversion from DT* to DT* since
131 // commontype(zero_t, DT*) is DT*, rather than nothing
132
133 // CandidateFinder finder{ symtab, env };
134 // finder.find( arg, ResolvMode::withAdjustment() );
135 // assertf( finder.candidates.size() > 0,
136 // "Somehow castable expression failed to find alternatives." );
137 // assertf( finder.candidates.size() == 1,
138 // "Somehow got multiple alternatives for known cast expression." );
139 // return finder.candidates.front()->expr;
140 }
141
142 return arg;
143 }
144
145 /// Computes conversion cost for a given candidate
146 Cost computeApplicationConversionCost(
147 CandidateRef cand, const ast::SymbolTable & symtab
148 ) {
149 auto appExpr = cand->expr.strict_as< ast::ApplicationExpr >();
150 auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
151 auto function = pointer->base.strict_as< ast::FunctionType >();
152
153 Cost convCost = Cost::zero;
154 const auto & params = function->params;
155 auto param = params.begin();
156 auto & args = appExpr->args;
157
158 for ( unsigned i = 0; i < args.size(); ++i ) {
159 const ast::Type * argType = args[i]->result;
160 PRINT(
161 std::cerr << "arg expression:" << std::endl;
162 ast::print( std::cerr, args[i], 2 );
163 std::cerr << "--- results are" << std::endl;
164 ast::print( std::cerr, argType, 2 );
165 )
166
167 if ( param == params.end() ) {
168 if ( function->isVarArgs ) {
169 convCost.incUnsafe();
170 PRINT( std::cerr << "end of params with varargs function: inc unsafe: "
171 << convCost << std::endl; ; )
172 // convert reference-typed expressions into value-typed expressions
173 cand->expr = ast::mutate_field_index(
174 appExpr, &ast::ApplicationExpr::args, i,
175 referenceToRvalueConversion( args[i], convCost ) );
176 continue;
177 } else return Cost::infinity;
178 }
179
180 if ( auto def = args[i].as< ast::DefaultArgExpr >() ) {
181 // Default arguments should be free - don't include conversion cost.
182 // Unwrap them here because they are not relevant to the rest of the system
183 cand->expr = ast::mutate_field_index(
184 appExpr, &ast::ApplicationExpr::args, i, def->expr );
185 ++param;
186 continue;
187 }
188
189 // mark conversion cost and also specialization cost of param type
190 const ast::Type * paramType = (*param)->get_type();
191 cand->expr = ast::mutate_field_index(
192 appExpr, &ast::ApplicationExpr::args, i,
193 computeExpressionConversionCost(
194 args[i], paramType, symtab, cand->env, convCost ) );
195 convCost.decSpec( specCost( paramType ) );
196 ++param; // can't be in for-loop update because of the continue
197 }
198
199 if ( param != params.end() ) return Cost::infinity;
200
201 // specialization cost of return types can't be accounted for directly, it disables
202 // otherwise-identical calls, like this example based on auto-newline in the I/O lib:
203 //
204 // forall(otype OS) {
205 // void ?|?(OS&, int); // with newline
206 // OS& ?|?(OS&, int); // no newline, always chosen due to more specialization
207 // }
208
209 // mark type variable and specialization cost of forall clause
210 convCost.incVar( function->forall.size() );
211 for ( const ast::TypeDecl * td : function->forall ) {
212 convCost.decSpec( td->assertions.size() );
213 }
214
215 return convCost;
216 }
217
218 void makeUnifiableVars(
219 const ast::ParameterizedType * type, ast::OpenVarSet & unifiableVars,
220 ast::AssertionSet & need
221 ) {
222 for ( const ast::TypeDecl * tyvar : type->forall ) {
223 unifiableVars[ tyvar->name ] = ast::TypeDecl::Data{ tyvar };
224 for ( const ast::DeclWithType * assn : tyvar->assertions ) {
225 need[ assn ].isUsed = true;
226 }
227 }
228 }
229
230 /// Gets a default value from an initializer, nullptr if not present
231 const ast::ConstantExpr * getDefaultValue( const ast::Init * init ) {
232 if ( auto si = dynamic_cast< const ast::SingleInit * >( init ) ) {
233 if ( auto ce = si->value.as< ast::CastExpr >() ) {
234 return ce->arg.as< ast::ConstantExpr >();
235 } else {
236 return si->value.as< ast::ConstantExpr >();
237 }
238 }
239 return nullptr;
240 }
241
242 /// State to iteratively build a match of parameter expressions to arguments
243 struct ArgPack {
244 std::size_t parent; ///< Index of parent pack
245 ast::ptr< ast::Expr > expr; ///< The argument stored here
246 Cost cost; ///< The cost of this argument
247 ast::TypeEnvironment env; ///< Environment for this pack
248 ast::AssertionSet need; ///< Assertions outstanding for this pack
249 ast::AssertionSet have; ///< Assertions found for this pack
250 ast::OpenVarSet open; ///< Open variables for this pack
251 unsigned nextArg; ///< Index of next argument in arguments list
252 unsigned tupleStart; ///< Number of tuples that start at this index
253 unsigned nextExpl; ///< Index of next exploded element
254 unsigned explAlt; ///< Index of alternative for nextExpl > 0
255
256 ArgPack()
257 : parent( 0 ), expr(), cost( Cost::zero ), env(), need(), have(), open(), nextArg( 0 ),
258 tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
259
260 ArgPack(
261 const ast::TypeEnvironment & env, const ast::AssertionSet & need,
262 const ast::AssertionSet & have, const ast::OpenVarSet & open )
263 : parent( 0 ), expr(), cost( Cost::zero ), env( env ), need( need ), have( have ),
264 open( open ), nextArg( 0 ), tupleStart( 0 ), nextExpl( 0 ), explAlt( 0 ) {}
265
266 ArgPack(
267 std::size_t parent, const ast::Expr * expr, ast::TypeEnvironment && env,
268 ast::AssertionSet && need, ast::AssertionSet && have, ast::OpenVarSet && open,
269 unsigned nextArg, unsigned tupleStart = 0, Cost cost = Cost::zero,
270 unsigned nextExpl = 0, unsigned explAlt = 0 )
271 : parent(parent), expr( expr ), cost( cost ), env( move( env ) ), need( move( need ) ),
272 have( move( have ) ), open( move( open ) ), nextArg( nextArg ), tupleStart( tupleStart ),
273 nextExpl( nextExpl ), explAlt( explAlt ) {}
274
275 ArgPack(
276 const ArgPack & o, ast::TypeEnvironment && env, ast::AssertionSet && need,
277 ast::AssertionSet && have, ast::OpenVarSet && open, unsigned nextArg, Cost added )
278 : parent( o.parent ), expr( o.expr ), cost( o.cost + added ), env( move( env ) ),
279 need( move( need ) ), have( move( have ) ), open( move( open ) ), nextArg( nextArg ),
280 tupleStart( o.tupleStart ), nextExpl( 0 ), explAlt( 0 ) {}
281
282 /// true if this pack is in the middle of an exploded argument
283 bool hasExpl() const { return nextExpl > 0; }
284
285 /// Gets the list of exploded candidates for this pack
286 const ExplodedArg & getExpl( const ExplodedArgs_new & args ) const {
287 return args[ nextArg-1 ][ explAlt ];
288 }
289
290 /// Ends a tuple expression, consolidating the appropriate args
291 void endTuple( const std::vector< ArgPack > & packs ) {
292 // add all expressions in tuple to list, summing cost
293 std::deque< const ast::Expr * > exprs;
294 const ArgPack * pack = this;
295 if ( expr ) { exprs.emplace_front( expr ); }
296 while ( pack->tupleStart == 0 ) {
297 pack = &packs[pack->parent];
298 exprs.emplace_front( pack->expr );
299 cost += pack->cost;
300 }
301 // reset pack to appropriate tuple
302 std::vector< ast::ptr< ast::Expr > > exprv( exprs.begin(), exprs.end() );
303 expr = new ast::TupleExpr{ expr->location, move( exprv ) };
304 tupleStart = pack->tupleStart - 1;
305 parent = pack->parent;
306 }
307 };
308
309 /// Instantiates an argument to match a parameter, returns false if no matching results left
310 bool instantiateArgument(
311 const ast::Type * paramType, const ast::Init * init, const ExplodedArgs_new & args,
312 std::vector< ArgPack > & results, std::size_t & genStart, const ast::SymbolTable & symtab,
313 unsigned nTuples = 0
314 ) {
315 if ( auto tupleType = dynamic_cast< const ast::TupleType * >( paramType ) ) {
316 // paramType is a TupleType -- group args into a TupleExpr
317 ++nTuples;
318 for ( const ast::Type * type : *tupleType ) {
319 // xxx - dropping initializer changes behaviour from previous, but seems correct
320 // ^^^ need to handle the case where a tuple has a default argument
321 if ( ! instantiateArgument(
322 type, nullptr, args, results, genStart, symtab, nTuples ) ) return false;
323 nTuples = 0;
324 }
325 // re-constitute tuples for final generation
326 for ( auto i = genStart; i < results.size(); ++i ) {
327 results[i].endTuple( results );
328 }
329 return true;
330 } else if ( const ast::TypeInstType * ttype = Tuples::isTtype( paramType ) ) {
331 // paramType is a ttype, consumes all remaining arguments
332
333 // completed tuples; will be spliced to end of results to finish
334 std::vector< ArgPack > finalResults{};
335
336 // iterate until all results completed
337 std::size_t genEnd;
338 ++nTuples;
339 do {
340 genEnd = results.size();
341
342 // add another argument to results
343 for ( std::size_t i = genStart; i < genEnd; ++i ) {
344 unsigned nextArg = results[i].nextArg;
345
346 // use next element of exploded tuple if present
347 if ( results[i].hasExpl() ) {
348 const ExplodedArg & expl = results[i].getExpl( args );
349
350 unsigned nextExpl = results[i].nextExpl + 1;
351 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
352
353 results.emplace_back(
354 i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
355 copy( results[i].need ), copy( results[i].have ),
356 copy( results[i].open ), nextArg, nTuples, Cost::zero, nextExpl,
357 results[i].explAlt );
358
359 continue;
360 }
361
362 // finish result when out of arguments
363 if ( nextArg >= args.size() ) {
364 ArgPack newResult{
365 results[i].env, results[i].need, results[i].have, results[i].open };
366 newResult.nextArg = nextArg;
367 const ast::Type * argType = nullptr;
368
369 if ( nTuples > 0 || ! results[i].expr ) {
370 // first iteration or no expression to clone,
371 // push empty tuple expression
372 newResult.parent = i;
373 newResult.expr = new ast::TupleExpr{ CodeLocation{}, {} };
374 argType = newResult.expr->result;
375 } else {
376 // clone result to collect tuple
377 newResult.parent = results[i].parent;
378 newResult.cost = results[i].cost;
379 newResult.tupleStart = results[i].tupleStart;
380 newResult.expr = results[i].expr;
381 argType = newResult.expr->result;
382
383 if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
384 // the case where a ttype value is passed directly is special,
385 // e.g. for argument forwarding purposes
386 // xxx - what if passing multiple arguments, last of which is
387 // ttype?
388 // xxx - what would happen if unify was changed so that unifying
389 // tuple
390 // types flattened both before unifying lists? then pass in
391 // TupleType (ttype) below.
392 --newResult.tupleStart;
393 } else {
394 // collapse leftover arguments into tuple
395 newResult.endTuple( results );
396 argType = newResult.expr->result;
397 }
398 }
399
400 // check unification for ttype before adding to final
401 if (
402 unify(
403 ttype, argType, newResult.env, newResult.need, newResult.have,
404 newResult.open, symtab )
405 ) {
406 finalResults.emplace_back( move( newResult ) );
407 }
408
409 continue;
410 }
411
412 // add each possible next argument
413 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
414 const ExplodedArg & expl = args[nextArg][j];
415
416 // fresh copies of parent parameters for this iteration
417 ast::TypeEnvironment env = results[i].env;
418 ast::OpenVarSet open = results[i].open;
419
420 env.addActual( expl.env, open );
421
422 // skip empty tuple arguments by (nearly) cloning parent into next gen
423 if ( expl.exprs.empty() ) {
424 results.emplace_back(
425 results[i], move( env ), copy( results[i].need ),
426 copy( results[i].have ), move( open ), nextArg + 1, expl.cost );
427
428 continue;
429 }
430
431 // add new result
432 results.emplace_back(
433 i, expl.exprs.front(), move( env ), copy( results[i].need ),
434 copy( results[i].have ), move( open ), nextArg + 1, nTuples,
435 expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
436 }
437 }
438
439 // reset for next round
440 genStart = genEnd;
441 nTuples = 0;
442 } while ( genEnd != results.size() );
443
444 // splice final results onto results
445 for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
446 results.emplace_back( move( finalResults[i] ) );
447 }
448 return ! finalResults.empty();
449 }
450
451 // iterate each current subresult
452 std::size_t genEnd = results.size();
453 for ( std::size_t i = genStart; i < genEnd; ++i ) {
454 unsigned nextArg = results[i].nextArg;
455
456 // use remainder of exploded tuple if present
457 if ( results[i].hasExpl() ) {
458 const ExplodedArg & expl = results[i].getExpl( args );
459 const ast::Expr * expr = expl.exprs[ results[i].nextExpl ];
460
461 ast::TypeEnvironment env = results[i].env;
462 ast::AssertionSet need = results[i].need, have = results[i].have;
463 ast::OpenVarSet open = results[i].open;
464
465 const ast::Type * argType = expr->result;
466
467 PRINT(
468 std::cerr << "param type is ";
469 ast::print( std::cerr, paramType );
470 std::cerr << std::endl << "arg type is ";
471 ast::print( std::cerr, argType );
472 std::cerr << std::endl;
473 )
474
475 if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
476 unsigned nextExpl = results[i].nextExpl + 1;
477 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
478
479 results.emplace_back(
480 i, expr, move( env ), move( need ), move( have ), move( open ), nextArg,
481 nTuples, Cost::zero, nextExpl, results[i].explAlt );
482 }
483
484 continue;
485 }
486
487 // use default initializers if out of arguments
488 if ( nextArg >= args.size() ) {
489 if ( const ast::ConstantExpr * cnst = getDefaultValue( init ) ) {
490 ast::TypeEnvironment env = results[i].env;
491 ast::AssertionSet need = results[i].need, have = results[i].have;
492 ast::OpenVarSet open = results[i].open;
493
494 if ( unify( paramType, cnst->result, env, need, have, open, symtab ) ) {
495 results.emplace_back(
496 i, new ast::DefaultArgExpr{ cnst->location, cnst }, move( env ),
497 move( need ), move( have ), move( open ), nextArg, nTuples );
498 }
499 }
500
501 continue;
502 }
503
504 // Check each possible next argument
505 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
506 const ExplodedArg & expl = args[nextArg][j];
507
508 // fresh copies of parent parameters for this iteration
509 ast::TypeEnvironment env = results[i].env;
510 ast::AssertionSet need = results[i].need, have = results[i].have;
511 ast::OpenVarSet open = results[i].open;
512
513 env.addActual( expl.env, open );
514
515 // skip empty tuple arguments by (nearly) cloning parent into next gen
516 if ( expl.exprs.empty() ) {
517 results.emplace_back(
518 results[i], move( env ), move( need ), move( have ), move( open ),
519 nextArg + 1, expl.cost );
520
521 continue;
522 }
523
524 // consider only first exploded arg
525 const ast::Expr * expr = expl.exprs.front();
526 const ast::Type * argType = expr->result;
527
528 PRINT(
529 std::cerr << "param type is ";
530 ast::print( std::cerr, paramType );
531 std::cerr << std::endl << "arg type is ";
532 ast::print( std::cerr, argType );
533 std::cerr << std::endl;
534 )
535
536 // attempt to unify types
537 if ( unify( paramType, argType, env, need, have, open, symtab ) ) {
538 // add new result
539 results.emplace_back(
540 i, expr, move( env ), move( need ), move( have ), move( open ),
541 nextArg + 1, nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
542 }
543 }
544 }
545
546 // reset for next parameter
547 genStart = genEnd;
548
549 return genEnd != results.size(); // were any new results added?
550 }
551
552 /// Generate a cast expression from `arg` to `toType`
553 const ast::Expr * restructureCast(
554 ast::ptr< ast::Expr > & arg, const ast::Type * toType, ast::GeneratedFlag isGenerated = ast::GeneratedCast
555 ) {
556 if (
557 arg->result->size() > 1
558 && ! toType->isVoid()
559 && ! dynamic_cast< const ast::ReferenceType * >( toType )
560 ) {
561 // Argument is a tuple and the target type is neither void nor a reference. Cast each
562 // member of the tuple to its corresponding target type, producing the tuple of those
563 // cast expressions. If there are more components of the tuple than components in the
564 // target type, then excess components do not come out in the result expression (but
565 // UniqueExpr ensures that the side effects will still be produced)
566 if ( Tuples::maybeImpureIgnoreUnique( arg ) ) {
567 // expressions which may contain side effects require a single unique instance of
568 // the expression
569 arg = new ast::UniqueExpr{ arg->location, arg };
570 }
571 std::vector< ast::ptr< ast::Expr > > components;
572 for ( unsigned i = 0; i < toType->size(); ++i ) {
573 // cast each component
574 ast::ptr< ast::Expr > idx = new ast::TupleIndexExpr{ arg->location, arg, i };
575 components.emplace_back(
576 restructureCast( idx, toType->getComponent( i ), isGenerated ) );
577 }
578 return new ast::TupleExpr{ arg->location, move( components ) };
579 } else {
580 // handle normally
581 return new ast::CastExpr{ arg->location, arg, toType, isGenerated };
582 }
583 }
584
585 /// Gets the name from an untyped member expression (must be NameExpr)
586 const std::string & getMemberName( const ast::UntypedMemberExpr * memberExpr ) {
587 if ( memberExpr->member.as< ast::ConstantExpr >() ) {
588 SemanticError( memberExpr, "Indexed access to struct fields unsupported: " );
589 }
590
591 return memberExpr->member.strict_as< ast::NameExpr >()->name;
592 }
593
594 /// Actually visits expressions to find their candidate interpretations
595 class Finder final : public ast::WithShortCircuiting {
596 const ast::SymbolTable & symtab;
597 public:
598 static size_t traceId;
599 CandidateFinder & selfFinder;
600 CandidateList & candidates;
601 const ast::TypeEnvironment & tenv;
602 ast::ptr< ast::Type > & targetType;
603
604 enum Errors {
605 NotFound,
606 NoMatch,
607 ArgsToFew,
608 ArgsToMany,
609 RetsToFew,
610 RetsToMany,
611 NoReason
612 };
613
614 struct {
615 Errors code = NotFound;
616 } reason;
617
618 Finder( CandidateFinder & f )
619 : symtab( f.localSyms ), selfFinder( f ), candidates( f.candidates ), tenv( f.env ),
620 targetType( f.targetType ) {}
621
622 void previsit( const ast::Node * ) { visit_children = false; }
623
624 /// Convenience to add candidate to list
625 template<typename... Args>
626 void addCandidate( Args &&... args ) {
627 candidates.emplace_back( new Candidate{ std::forward<Args>( args )... } );
628 reason.code = NoReason;
629 }
630
631 void postvisit( const ast::ApplicationExpr * applicationExpr ) {
632 addCandidate( applicationExpr, tenv );
633 }
634
635 /// Set up candidate assertions for inference
636 void inferParameters( CandidateRef & newCand, CandidateList & out ) {
637 // Set need bindings for any unbound assertions
638 UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
639 for ( auto & assn : newCand->need ) {
640 // skip already-matched assertions
641 if ( assn.second.resnSlot != 0 ) continue;
642 // assign slot for expression if needed
643 if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
644 // fix slot to assertion
645 assn.second.resnSlot = crntResnSlot;
646 }
647 // pair slot to expression
648 if ( crntResnSlot != 0 ) {
649 newCand->expr.get_and_mutate()->inferred.resnSlots().emplace_back( crntResnSlot );
650 }
651
652 // add to output list; assertion satisfaction will occur later
653 out.emplace_back( newCand );
654 }
655
656 /// Completes a function candidate with arguments located
657 void validateFunctionCandidate(
658 const CandidateRef & func, ArgPack & result, const std::vector< ArgPack > & results,
659 CandidateList & out
660 ) {
661 ast::ApplicationExpr * appExpr =
662 new ast::ApplicationExpr{ func->expr->location, func->expr };
663 // sum cost and accumulate arguments
664 std::deque< const ast::Expr * > args;
665 Cost cost = func->cost;
666 const ArgPack * pack = &result;
667 while ( pack->expr ) {
668 args.emplace_front( pack->expr );
669 cost += pack->cost;
670 pack = &results[pack->parent];
671 }
672 std::vector< ast::ptr< ast::Expr > > vargs( args.begin(), args.end() );
673 appExpr->args = move( vargs );
674 // build and validate new candidate
675 auto newCand =
676 std::make_shared<Candidate>( appExpr, result.env, result.open, result.need, cost );
677 PRINT(
678 std::cerr << "instantiate function success: " << appExpr << std::endl;
679 std::cerr << "need assertions:" << std::endl;
680 ast::print( std::cerr, result.need, 2 );
681 )
682 inferParameters( newCand, out );
683 }
684
685 /// Builds a list of candidates for a function, storing them in out
686 void makeFunctionCandidates(
687 const CandidateRef & func, const ast::FunctionType * funcType,
688 const ExplodedArgs_new & args, CandidateList & out
689 ) {
690 ast::OpenVarSet funcOpen;
691 ast::AssertionSet funcNeed, funcHave;
692 ast::TypeEnvironment funcEnv{ func->env };
693 makeUnifiableVars( funcType, funcOpen, funcNeed );
694 // add all type variables as open variables now so that those not used in the
695 // parameter list are still considered open
696 funcEnv.add( funcType->forall );
697
698 if ( targetType && ! targetType->isVoid() && ! funcType->returns.empty() ) {
699 // attempt to narrow based on expected target type
700 const ast::Type * returnType = funcType->returns.front()->get_type();
701 if ( ! unify(
702 returnType, targetType, funcEnv, funcNeed, funcHave, funcOpen, symtab )
703 ) {
704 // unification failed, do not pursue this candidate
705 return;
706 }
707 }
708
709 // iteratively build matches, one parameter at a time
710 std::vector< ArgPack > results;
711 results.emplace_back( funcEnv, funcNeed, funcHave, funcOpen );
712 std::size_t genStart = 0;
713
714 for ( const ast::DeclWithType * param : funcType->params ) {
715 auto obj = strict_dynamic_cast< const ast::ObjectDecl * >( param );
716 // Try adding the arguments corresponding to the current parameter to the existing
717 // matches
718 if ( ! instantiateArgument(
719 obj->type, obj->init, args, results, genStart, symtab ) ) return;
720 }
721
722 if ( funcType->isVarArgs ) {
723 // append any unused arguments to vararg pack
724 std::size_t genEnd;
725 do {
726 genEnd = results.size();
727
728 // iterate results
729 for ( std::size_t i = genStart; i < genEnd; ++i ) {
730 unsigned nextArg = results[i].nextArg;
731
732 // use remainder of exploded tuple if present
733 if ( results[i].hasExpl() ) {
734 const ExplodedArg & expl = results[i].getExpl( args );
735
736 unsigned nextExpl = results[i].nextExpl + 1;
737 if ( nextExpl == expl.exprs.size() ) { nextExpl = 0; }
738
739 results.emplace_back(
740 i, expl.exprs[ results[i].nextExpl ], copy( results[i].env ),
741 copy( results[i].need ), copy( results[i].have ),
742 copy( results[i].open ), nextArg, 0, Cost::zero, nextExpl,
743 results[i].explAlt );
744
745 continue;
746 }
747
748 // finish result when out of arguments
749 if ( nextArg >= args.size() ) {
750 validateFunctionCandidate( func, results[i], results, out );
751
752 continue;
753 }
754
755 // add each possible next argument
756 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
757 const ExplodedArg & expl = args[nextArg][j];
758
759 // fresh copies of parent parameters for this iteration
760 ast::TypeEnvironment env = results[i].env;
761 ast::OpenVarSet open = results[i].open;
762
763 env.addActual( expl.env, open );
764
765 // skip empty tuple arguments by (nearly) cloning parent into next gen
766 if ( expl.exprs.empty() ) {
767 results.emplace_back(
768 results[i], move( env ), copy( results[i].need ),
769 copy( results[i].have ), move( open ), nextArg + 1,
770 expl.cost );
771
772 continue;
773 }
774
775 // add new result
776 results.emplace_back(
777 i, expl.exprs.front(), move( env ), copy( results[i].need ),
778 copy( results[i].have ), move( open ), nextArg + 1, 0, expl.cost,
779 expl.exprs.size() == 1 ? 0 : 1, j );
780 }
781 }
782
783 genStart = genEnd;
784 } while( genEnd != results.size() );
785 } else {
786 // filter out the results that don't use all the arguments
787 for ( std::size_t i = genStart; i < results.size(); ++i ) {
788 ArgPack & result = results[i];
789 if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
790 validateFunctionCandidate( func, result, results, out );
791 }
792 }
793 }
794 }
795
796 /// Adds implicit struct-conversions to the alternative list
797 void addAnonConversions( const CandidateRef & cand ) {
798 // adds anonymous member interpretations whenever an aggregate value type is seen.
799 // it's okay for the aggregate expression to have reference type -- cast it to the
800 // base type to treat the aggregate as the referenced value
801 ast::ptr< ast::Expr > aggrExpr( cand->expr );
802 ast::ptr< ast::Type > & aggrType = aggrExpr.get_and_mutate()->result;
803 cand->env.apply( aggrType );
804
805 if ( aggrType.as< ast::ReferenceType >() ) {
806 aggrExpr = new ast::CastExpr{ aggrExpr, aggrType->stripReferences() };
807 }
808
809 if ( auto structInst = aggrExpr->result.as< ast::StructInstType >() ) {
810 addAggMembers( structInst, aggrExpr, *cand, Cost::safe, "" );
811 } else if ( auto unionInst = aggrExpr->result.as< ast::UnionInstType >() ) {
812 addAggMembers( unionInst, aggrExpr, *cand, Cost::safe, "" );
813 }
814 }
815
816 /// Adds aggregate member interpretations
817 void addAggMembers(
818 const ast::ReferenceToType * aggrInst, const ast::Expr * expr,
819 const Candidate & cand, const Cost & addedCost, const std::string & name
820 ) {
821 for ( const ast::Decl * decl : aggrInst->lookup( name ) ) {
822 auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( decl );
823 CandidateRef newCand = std::make_shared<Candidate>(
824 cand, new ast::MemberExpr{ expr->location, dwt, expr }, addedCost );
825 // add anonymous member interpretations whenever an aggregate value type is seen
826 // as a member expression
827 addAnonConversions( newCand );
828 candidates.emplace_back( move( newCand ) );
829 }
830 }
831
832 /// Adds tuple member interpretations
833 void addTupleMembers(
834 const ast::TupleType * tupleType, const ast::Expr * expr, const Candidate & cand,
835 const Cost & addedCost, const ast::Expr * member
836 ) {
837 if ( auto constantExpr = dynamic_cast< const ast::ConstantExpr * >( member ) ) {
838 // get the value of the constant expression as an int, must be between 0 and the
839 // length of the tuple to have meaning
840 long long val = constantExpr->intValue();
841 if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
842 addCandidate(
843 cand, new ast::TupleIndexExpr{ expr->location, expr, (unsigned)val },
844 addedCost );
845 }
846 }
847 }
848
849 void postvisit( const ast::UntypedExpr * untypedExpr ) {
850 CandidateFinder funcFinder{ symtab, tenv };
851 funcFinder.find( untypedExpr->func, ResolvMode::withAdjustment() );
852 // short-circuit if no candidates
853 if ( funcFinder.candidates.empty() ) return;
854
855 reason.code = NoMatch;
856
857 std::vector< CandidateFinder > argCandidates =
858 selfFinder.findSubExprs( untypedExpr->args );
859
860 // take care of possible tuple assignments
861 // if not tuple assignment, handled as normal function call
862 Tuples::handleTupleAssignment( selfFinder, untypedExpr, argCandidates );
863
864 // find function operators
865 ast::ptr< ast::Expr > opExpr = new ast::NameExpr{ untypedExpr->location, "?()" };
866 CandidateFinder opFinder{ symtab, tenv };
867 // okay if there aren't any function operations
868 opFinder.find( opExpr, ResolvMode::withoutFailFast() );
869 PRINT(
870 std::cerr << "known function ops:" << std::endl;
871 print( std::cerr, opFinder.candidates, 1 );
872 )
873
874 // pre-explode arguments
875 ExplodedArgs_new argExpansions;
876 for ( const CandidateFinder & args : argCandidates ) {
877 argExpansions.emplace_back();
878 auto & argE = argExpansions.back();
879 for ( const CandidateRef & arg : args ) { argE.emplace_back( *arg, symtab ); }
880 }
881
882 // Find function matches
883 CandidateList found;
884 SemanticErrorException errors;
885 for ( CandidateRef & func : funcFinder ) {
886 try {
887 PRINT(
888 std::cerr << "working on alternative:" << std::endl;
889 print( std::cerr, *func, 2 );
890 )
891
892 // check if the type is a pointer to function
893 const ast::Type * funcResult = func->expr->result->stripReferences();
894 if ( auto pointer = dynamic_cast< const ast::PointerType * >( funcResult ) ) {
895 if ( auto function = pointer->base.as< ast::FunctionType >() ) {
896 CandidateRef newFunc{ new Candidate{ *func } };
897 newFunc->expr =
898 referenceToRvalueConversion( newFunc->expr, newFunc->cost );
899 makeFunctionCandidates( newFunc, function, argExpansions, found );
900 }
901 } else if (
902 auto inst = dynamic_cast< const ast::TypeInstType * >( funcResult )
903 ) {
904 if ( const ast::EqvClass * clz = func->env.lookup( inst->name ) ) {
905 if ( auto function = clz->bound.as< ast::FunctionType >() ) {
906 CandidateRef newFunc{ new Candidate{ *func } };
907 newFunc->expr =
908 referenceToRvalueConversion( newFunc->expr, newFunc->cost );
909 makeFunctionCandidates( newFunc, function, argExpansions, found );
910 }
911 }
912 }
913 } catch ( SemanticErrorException & e ) { errors.append( e ); }
914 }
915
916 // Find matches on function operators `?()`
917 if ( ! opFinder.candidates.empty() ) {
918 // add exploded function alternatives to front of argument list
919 std::vector< ExplodedArg > funcE;
920 funcE.reserve( funcFinder.candidates.size() );
921 for ( const CandidateRef & func : funcFinder ) {
922 funcE.emplace_back( *func, symtab );
923 }
924 argExpansions.emplace_front( move( funcE ) );
925
926 for ( const CandidateRef & op : opFinder ) {
927 try {
928 // check if type is pointer-to-function
929 const ast::Type * opResult = op->expr->result->stripReferences();
930 if ( auto pointer = dynamic_cast< const ast::PointerType * >( opResult ) ) {
931 if ( auto function = pointer->base.as< ast::FunctionType >() ) {
932 CandidateRef newOp{ new Candidate{ *op} };
933 newOp->expr =
934 referenceToRvalueConversion( newOp->expr, newOp->cost );
935 makeFunctionCandidates( newOp, function, argExpansions, found );
936 }
937 }
938 } catch ( SemanticErrorException & e ) { errors.append( e ); }
939 }
940 }
941
942 // Implement SFINAE; resolution errors are only errors if there aren't any non-error
943 // candidates
944 if ( found.empty() && ! errors.isEmpty() ) { throw errors; }
945
946 // Compute conversion costs
947 for ( CandidateRef & withFunc : found ) {
948 Cost cvtCost = computeApplicationConversionCost( withFunc, symtab );
949
950 PRINT(
951 auto appExpr = withFunc->expr.strict_as< ast::ApplicationExpr >();
952 auto pointer = appExpr->func->result.strict_as< ast::PointerType >();
953 auto function = pointer->base.strict_as< ast::FunctionType >();
954
955 std::cerr << "Case +++++++++++++ " << appExpr->func << std::endl;
956 std::cerr << "parameters are:" << std::endl;
957 ast::printAll( std::cerr, function->params, 2 );
958 std::cerr << "arguments are:" << std::endl;
959 ast::printAll( std::cerr, appExpr->args, 2 );
960 std::cerr << "bindings are:" << std::endl;
961 ast::print( std::cerr, withFunc->env, 2 );
962 std::cerr << "cost is: " << withFunc->cost << std::endl;
963 std::cerr << "cost of conversion is:" << cvtCost << std::endl;
964 )
965
966 if ( cvtCost != Cost::infinity ) {
967 withFunc->cvtCost = cvtCost;
968 candidates.emplace_back( move( withFunc ) );
969 }
970 }
971 found = move( candidates );
972
973 // use a new list so that candidates are not examined by addAnonConversions twice
974 CandidateList winners = findMinCost( found );
975 promoteCvtCost( winners );
976
977 // function may return a struct/union value, in which case we need to add candidates
978 // for implicit conversions to each of the anonymous members, which must happen after
979 // `findMinCost`, since anon conversions are never the cheapest
980 for ( const CandidateRef & c : winners ) {
981 addAnonConversions( c );
982 }
983 spliceBegin( candidates, winners );
984
985 if ( candidates.empty() && targetType && ! targetType->isVoid() ) {
986 // If resolution is unsuccessful with a target type, try again without, since it
987 // will sometimes succeed when it wouldn't with a target type binding.
988 // For example:
989 // forall( otype T ) T & ?[]( T *, ptrdiff_t );
990 // const char * x = "hello world";
991 // unsigned char ch = x[0];
992 // Fails with simple return type binding (xxx -- check this!) as follows:
993 // * T is bound to unsigned char
994 // * (x: const char *) is unified with unsigned char *, which fails
995 // xxx -- fix this better
996 targetType = nullptr;
997 postvisit( untypedExpr );
998 }
999 }
1000
1001 /// true if expression is an lvalue
1002 static bool isLvalue( const ast::Expr * x ) {
1003 return x->result && ( x->get_lvalue() || x->result.as< ast::ReferenceType >() );
1004 }
1005
1006 void postvisit( const ast::AddressExpr * addressExpr ) {
1007 CandidateFinder finder{ symtab, tenv };
1008 finder.find( addressExpr->arg );
1009
1010 if( finder.candidates.empty() ) return;
1011
1012 reason.code = NoMatch;
1013
1014 for ( CandidateRef & r : finder.candidates ) {
1015 if ( ! isLvalue( r->expr ) ) continue;
1016 addCandidate( *r, new ast::AddressExpr{ addressExpr->location, r->expr } );
1017 }
1018 }
1019
1020 void postvisit( const ast::LabelAddressExpr * labelExpr ) {
1021 addCandidate( labelExpr, tenv );
1022 }
1023
1024 void postvisit( const ast::CastExpr * castExpr ) {
1025 ast::ptr< ast::Type > toType = castExpr->result;
1026 assert( toType );
1027 toType = resolveTypeof( toType, symtab );
1028 toType = SymTab::validateType( castExpr->location, toType, symtab );
1029 toType = adjustExprType( toType, tenv, symtab );
1030
1031 CandidateFinder finder{ symtab, tenv, toType };
1032 finder.find( castExpr->arg, ResolvMode::withAdjustment() );
1033
1034 if( !finder.candidates.empty() ) reason.code = NoMatch;
1035
1036 CandidateList matches;
1037 for ( CandidateRef & cand : finder.candidates ) {
1038 ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1039 ast::OpenVarSet open( cand->open );
1040
1041 cand->env.extractOpenVars( open );
1042
1043 // It is possible that a cast can throw away some values in a multiply-valued
1044 // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of the
1045 // subexpression results that are cast directly. The candidate is invalid if it
1046 // has fewer results than there are types to cast to.
1047 int discardedValues = cand->expr->result->size() - toType->size();
1048 if ( discardedValues < 0 ) continue;
1049
1050 // unification run for side-effects
1051 unify( toType, cand->expr->result, cand->env, need, have, open, symtab );
1052 Cost thisCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1053 symtab, cand->env );
1054 PRINT(
1055 std::cerr << "working on cast with result: " << toType << std::endl;
1056 std::cerr << "and expr type: " << cand->expr->result << std::endl;
1057 std::cerr << "env: " << cand->env << std::endl;
1058 )
1059 if ( thisCost != Cost::infinity ) {
1060 PRINT(
1061 std::cerr << "has finite cost." << std::endl;
1062 )
1063 // count one safe conversion for each value that is thrown away
1064 thisCost.incSafe( discardedValues );
1065 CandidateRef newCand = std::make_shared<Candidate>(
1066 restructureCast( cand->expr, toType, castExpr->isGenerated ),
1067 copy( cand->env ), move( open ), move( need ), cand->cost,
1068 cand->cost + thisCost );
1069 inferParameters( newCand, matches );
1070 }
1071 }
1072
1073 // select first on argument cost, then conversion cost
1074 CandidateList minArgCost = findMinCost( matches );
1075 promoteCvtCost( minArgCost );
1076 candidates = findMinCost( minArgCost );
1077 }
1078
1079 void postvisit( const ast::VirtualCastExpr * castExpr ) {
1080 assertf( castExpr->result, "Implicit virtual cast targets not yet supported." );
1081 CandidateFinder finder{ symtab, tenv };
1082 // don't prune here, all alternatives guaranteed to have same type
1083 finder.find( castExpr->arg, ResolvMode::withoutPrune() );
1084 for ( CandidateRef & r : finder.candidates ) {
1085 addCandidate(
1086 *r,
1087 new ast::VirtualCastExpr{ castExpr->location, r->expr, castExpr->result } );
1088 }
1089 }
1090
1091 void postvisit( const ast::UntypedMemberExpr * memberExpr ) {
1092 CandidateFinder aggFinder{ symtab, tenv };
1093 aggFinder.find( memberExpr->aggregate, ResolvMode::withAdjustment() );
1094 for ( CandidateRef & agg : aggFinder.candidates ) {
1095 // it's okay for the aggregate expression to have reference type -- cast it to the
1096 // base type to treat the aggregate as the referenced value
1097 Cost addedCost = Cost::zero;
1098 agg->expr = referenceToRvalueConversion( agg->expr, addedCost );
1099
1100 // find member of the given type
1101 if ( auto structInst = agg->expr->result.as< ast::StructInstType >() ) {
1102 addAggMembers(
1103 structInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1104 } else if ( auto unionInst = agg->expr->result.as< ast::UnionInstType >() ) {
1105 addAggMembers(
1106 unionInst, agg->expr, *agg, addedCost, getMemberName( memberExpr ) );
1107 } else if ( auto tupleType = agg->expr->result.as< ast::TupleType >() ) {
1108 addTupleMembers( tupleType, agg->expr, *agg, addedCost, memberExpr->member );
1109 }
1110 }
1111 }
1112
1113 void postvisit( const ast::MemberExpr * memberExpr ) {
1114 addCandidate( memberExpr, tenv );
1115 }
1116
1117 void postvisit( const ast::NameExpr * nameExpr ) {
1118 std::vector< ast::SymbolTable::IdData > declList = symtab.lookupId( nameExpr->name );
1119 PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
1120 if( declList.empty() ) return;
1121
1122 reason.code = NoMatch;
1123
1124 for ( auto & data : declList ) {
1125 Cost cost = Cost::zero;
1126 ast::Expr * newExpr = data.combine( nameExpr->location, cost );
1127
1128 CandidateRef newCand = std::make_shared<Candidate>(
1129 newExpr, copy( tenv ), ast::OpenVarSet{}, ast::AssertionSet{}, Cost::zero,
1130 cost );
1131 PRINT(
1132 std::cerr << "decl is ";
1133 ast::print( std::cerr, data.id );
1134 std::cerr << std::endl;
1135 std::cerr << "newExpr is ";
1136 ast::print( std::cerr, newExpr );
1137 std::cerr << std::endl;
1138 )
1139 newCand->expr = ast::mutate_field(
1140 newCand->expr.get(), &ast::Expr::result,
1141 renameTyVars( newCand->expr->result ) );
1142 // add anonymous member interpretations whenever an aggregate value type is seen
1143 // as a name expression
1144 addAnonConversions( newCand );
1145 candidates.emplace_back( move( newCand ) );
1146 }
1147 }
1148
1149 void postvisit( const ast::VariableExpr * variableExpr ) {
1150 // not sufficient to just pass `variableExpr` here, type might have changed since
1151 // creation
1152 addCandidate(
1153 new ast::VariableExpr{ variableExpr->location, variableExpr->var }, tenv );
1154 }
1155
1156 void postvisit( const ast::ConstantExpr * constantExpr ) {
1157 addCandidate( constantExpr, tenv );
1158 }
1159
1160 void postvisit( const ast::SizeofExpr * sizeofExpr ) {
1161 if ( sizeofExpr->type ) {
1162 addCandidate(
1163 new ast::SizeofExpr{
1164 sizeofExpr->location, resolveTypeof( sizeofExpr->type, symtab ) },
1165 tenv );
1166 } else {
1167 // find all candidates for the argument to sizeof
1168 CandidateFinder finder{ symtab, tenv };
1169 finder.find( sizeofExpr->expr );
1170 // find the lowest-cost candidate, otherwise ambiguous
1171 CandidateList winners = findMinCost( finder.candidates );
1172 if ( winners.size() != 1 ) {
1173 SemanticError(
1174 sizeofExpr->expr.get(), "Ambiguous expression in sizeof operand: " );
1175 }
1176 // return the lowest-cost candidate
1177 CandidateRef & choice = winners.front();
1178 choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1179 choice->cost = Cost::zero;
1180 addCandidate( *choice, new ast::SizeofExpr{ sizeofExpr->location, choice->expr } );
1181 }
1182 }
1183
1184 void postvisit( const ast::AlignofExpr * alignofExpr ) {
1185 if ( alignofExpr->type ) {
1186 addCandidate(
1187 new ast::AlignofExpr{
1188 alignofExpr->location, resolveTypeof( alignofExpr->type, symtab ) },
1189 tenv );
1190 } else {
1191 // find all candidates for the argument to alignof
1192 CandidateFinder finder{ symtab, tenv };
1193 finder.find( alignofExpr->expr );
1194 // find the lowest-cost candidate, otherwise ambiguous
1195 CandidateList winners = findMinCost( finder.candidates );
1196 if ( winners.size() != 1 ) {
1197 SemanticError(
1198 alignofExpr->expr.get(), "Ambiguous expression in alignof operand: " );
1199 }
1200 // return the lowest-cost candidate
1201 CandidateRef & choice = winners.front();
1202 choice->expr = referenceToRvalueConversion( choice->expr, choice->cost );
1203 choice->cost = Cost::zero;
1204 addCandidate(
1205 *choice, new ast::AlignofExpr{ alignofExpr->location, choice->expr } );
1206 }
1207 }
1208
1209 void postvisit( const ast::UntypedOffsetofExpr * offsetofExpr ) {
1210 const ast::ReferenceToType * aggInst;
1211 if (( aggInst = offsetofExpr->type.as< ast::StructInstType >() )) ;
1212 else if (( aggInst = offsetofExpr->type.as< ast::UnionInstType >() )) ;
1213 else return;
1214
1215 for ( const ast::Decl * member : aggInst->lookup( offsetofExpr->member ) ) {
1216 auto dwt = strict_dynamic_cast< const ast::DeclWithType * >( member );
1217 addCandidate(
1218 new ast::OffsetofExpr{ offsetofExpr->location, aggInst, dwt }, tenv );
1219 }
1220 }
1221
1222 void postvisit( const ast::OffsetofExpr * offsetofExpr ) {
1223 addCandidate( offsetofExpr, tenv );
1224 }
1225
1226 void postvisit( const ast::OffsetPackExpr * offsetPackExpr ) {
1227 addCandidate( offsetPackExpr, tenv );
1228 }
1229
1230 void postvisit( const ast::LogicalExpr * logicalExpr ) {
1231 CandidateFinder finder1{ symtab, tenv };
1232 finder1.find( logicalExpr->arg1, ResolvMode::withAdjustment() );
1233 if ( finder1.candidates.empty() ) return;
1234
1235 CandidateFinder finder2{ symtab, tenv };
1236 finder2.find( logicalExpr->arg2, ResolvMode::withAdjustment() );
1237 if ( finder2.candidates.empty() ) return;
1238
1239 reason.code = NoMatch;
1240
1241 for ( const CandidateRef & r1 : finder1.candidates ) {
1242 for ( const CandidateRef & r2 : finder2.candidates ) {
1243 ast::TypeEnvironment env{ r1->env };
1244 env.simpleCombine( r2->env );
1245 ast::OpenVarSet open{ r1->open };
1246 mergeOpenVars( open, r2->open );
1247 ast::AssertionSet need;
1248 mergeAssertionSet( need, r1->need );
1249 mergeAssertionSet( need, r2->need );
1250
1251 addCandidate(
1252 new ast::LogicalExpr{
1253 logicalExpr->location, r1->expr, r2->expr, logicalExpr->isAnd },
1254 move( env ), move( open ), move( need ), r1->cost + r2->cost );
1255 }
1256 }
1257 }
1258
1259 void postvisit( const ast::ConditionalExpr * conditionalExpr ) {
1260 // candidates for condition
1261 CandidateFinder finder1{ symtab, tenv };
1262 finder1.find( conditionalExpr->arg1, ResolvMode::withAdjustment() );
1263 if ( finder1.candidates.empty() ) return;
1264
1265 // candidates for true result
1266 CandidateFinder finder2{ symtab, tenv };
1267 finder2.find( conditionalExpr->arg2, ResolvMode::withAdjustment() );
1268 if ( finder2.candidates.empty() ) return;
1269
1270 // candidates for false result
1271 CandidateFinder finder3{ symtab, tenv };
1272 finder3.find( conditionalExpr->arg3, ResolvMode::withAdjustment() );
1273 if ( finder3.candidates.empty() ) return;
1274
1275 reason.code = NoMatch;
1276
1277 for ( const CandidateRef & r1 : finder1.candidates ) {
1278 for ( const CandidateRef & r2 : finder2.candidates ) {
1279 for ( const CandidateRef & r3 : finder3.candidates ) {
1280 ast::TypeEnvironment env{ r1->env };
1281 env.simpleCombine( r2->env );
1282 env.simpleCombine( r3->env );
1283 ast::OpenVarSet open{ r1->open };
1284 mergeOpenVars( open, r2->open );
1285 mergeOpenVars( open, r3->open );
1286 ast::AssertionSet need;
1287 mergeAssertionSet( need, r1->need );
1288 mergeAssertionSet( need, r2->need );
1289 mergeAssertionSet( need, r3->need );
1290 ast::AssertionSet have;
1291
1292 // unify true and false results, then infer parameters to produce new
1293 // candidates
1294 ast::ptr< ast::Type > common;
1295 if (
1296 unify(
1297 r2->expr->result, r3->expr->result, env, need, have, open, symtab,
1298 common )
1299 ) {
1300 // generate typed expression
1301 ast::ConditionalExpr * newExpr = new ast::ConditionalExpr{
1302 conditionalExpr->location, r1->expr, r2->expr, r3->expr };
1303 newExpr->result = common ? common : r2->expr->result;
1304 // convert both options to result type
1305 Cost cost = r1->cost + r2->cost + r3->cost;
1306 newExpr->arg2 = computeExpressionConversionCost(
1307 newExpr->arg2, newExpr->result, symtab, env, cost );
1308 newExpr->arg3 = computeExpressionConversionCost(
1309 newExpr->arg3, newExpr->result, symtab, env, cost );
1310 // output candidate
1311 CandidateRef newCand = std::make_shared<Candidate>(
1312 newExpr, move( env ), move( open ), move( need ), cost );
1313 inferParameters( newCand, candidates );
1314 }
1315 }
1316 }
1317 }
1318 }
1319
1320 void postvisit( const ast::CommaExpr * commaExpr ) {
1321 ast::TypeEnvironment env{ tenv };
1322 ast::ptr< ast::Expr > arg1 = resolveInVoidContext( commaExpr->arg1, symtab, env );
1323
1324 CandidateFinder finder2{ symtab, env };
1325 finder2.find( commaExpr->arg2, ResolvMode::withAdjustment() );
1326
1327 for ( const CandidateRef & r2 : finder2.candidates ) {
1328 addCandidate( *r2, new ast::CommaExpr{ commaExpr->location, arg1, r2->expr } );
1329 }
1330 }
1331
1332 void postvisit( const ast::ImplicitCopyCtorExpr * ctorExpr ) {
1333 addCandidate( ctorExpr, tenv );
1334 }
1335
1336 void postvisit( const ast::ConstructorExpr * ctorExpr ) {
1337 CandidateFinder finder{ symtab, tenv };
1338 finder.find( ctorExpr->callExpr, ResolvMode::withoutPrune() );
1339 for ( CandidateRef & r : finder.candidates ) {
1340 addCandidate( *r, new ast::ConstructorExpr{ ctorExpr->location, r->expr } );
1341 }
1342 }
1343
1344 void postvisit( const ast::RangeExpr * rangeExpr ) {
1345 // resolve low and high, accept candidates where low and high types unify
1346 CandidateFinder finder1{ symtab, tenv };
1347 finder1.find( rangeExpr->low, ResolvMode::withAdjustment() );
1348 if ( finder1.candidates.empty() ) return;
1349
1350 CandidateFinder finder2{ symtab, tenv };
1351 finder2.find( rangeExpr->high, ResolvMode::withAdjustment() );
1352 if ( finder2.candidates.empty() ) return;
1353
1354 reason.code = NoMatch;
1355
1356 for ( const CandidateRef & r1 : finder1.candidates ) {
1357 for ( const CandidateRef & r2 : finder2.candidates ) {
1358 ast::TypeEnvironment env{ r1->env };
1359 env.simpleCombine( r2->env );
1360 ast::OpenVarSet open{ r1->open };
1361 mergeOpenVars( open, r2->open );
1362 ast::AssertionSet need;
1363 mergeAssertionSet( need, r1->need );
1364 mergeAssertionSet( need, r2->need );
1365 ast::AssertionSet have;
1366
1367 ast::ptr< ast::Type > common;
1368 if (
1369 unify(
1370 r1->expr->result, r2->expr->result, env, need, have, open, symtab,
1371 common )
1372 ) {
1373 // generate new expression
1374 ast::RangeExpr * newExpr =
1375 new ast::RangeExpr{ rangeExpr->location, r1->expr, r2->expr };
1376 newExpr->result = common ? common : r1->expr->result;
1377 // add candidate
1378 CandidateRef newCand = std::make_shared<Candidate>(
1379 newExpr, move( env ), move( open ), move( need ),
1380 r1->cost + r2->cost );
1381 inferParameters( newCand, candidates );
1382 }
1383 }
1384 }
1385 }
1386
1387 void postvisit( const ast::UntypedTupleExpr * tupleExpr ) {
1388 std::vector< CandidateFinder > subCandidates =
1389 selfFinder.findSubExprs( tupleExpr->exprs );
1390 std::vector< CandidateList > possibilities;
1391 combos( subCandidates.begin(), subCandidates.end(), back_inserter( possibilities ) );
1392
1393 for ( const CandidateList & subs : possibilities ) {
1394 std::vector< ast::ptr< ast::Expr > > exprs;
1395 exprs.reserve( subs.size() );
1396 for ( const CandidateRef & sub : subs ) { exprs.emplace_back( sub->expr ); }
1397
1398 ast::TypeEnvironment env;
1399 ast::OpenVarSet open;
1400 ast::AssertionSet need;
1401 for ( const CandidateRef & sub : subs ) {
1402 env.simpleCombine( sub->env );
1403 mergeOpenVars( open, sub->open );
1404 mergeAssertionSet( need, sub->need );
1405 }
1406
1407 addCandidate(
1408 new ast::TupleExpr{ tupleExpr->location, move( exprs ) },
1409 move( env ), move( open ), move( need ), sumCost( subs ) );
1410 }
1411 }
1412
1413 void postvisit( const ast::TupleExpr * tupleExpr ) {
1414 addCandidate( tupleExpr, tenv );
1415 }
1416
1417 void postvisit( const ast::TupleIndexExpr * tupleExpr ) {
1418 addCandidate( tupleExpr, tenv );
1419 }
1420
1421 void postvisit( const ast::TupleAssignExpr * tupleExpr ) {
1422 addCandidate( tupleExpr, tenv );
1423 }
1424
1425 void postvisit( const ast::UniqueExpr * unqExpr ) {
1426 CandidateFinder finder{ symtab, tenv };
1427 finder.find( unqExpr->expr, ResolvMode::withAdjustment() );
1428 for ( CandidateRef & r : finder.candidates ) {
1429 // ensure that the the id is passed on so that the expressions are "linked"
1430 addCandidate( *r, new ast::UniqueExpr{ unqExpr->location, r->expr, unqExpr->id } );
1431 }
1432 }
1433
1434 void postvisit( const ast::StmtExpr * stmtExpr ) {
1435 addCandidate( resolveStmtExpr( stmtExpr, symtab ), tenv );
1436 }
1437
1438 void postvisit( const ast::UntypedInitExpr * initExpr ) {
1439 // handle each option like a cast
1440 CandidateList matches;
1441 PRINT(
1442 std::cerr << "untyped init expr: " << initExpr << std::endl;
1443 )
1444 // O(n^2) checks of d-types with e-types
1445 for ( const ast::InitAlternative & initAlt : initExpr->initAlts ) {
1446 // calculate target type
1447 const ast::Type * toType = resolveTypeof( initAlt.type, symtab );
1448 toType = SymTab::validateType( initExpr->location, toType, symtab );
1449 toType = adjustExprType( toType, tenv, symtab );
1450 // The call to find must occur inside this loop, otherwise polymorphic return
1451 // types are not bound to the initialization type, since return type variables are
1452 // only open for the duration of resolving the UntypedExpr.
1453 CandidateFinder finder{ symtab, tenv, toType };
1454 finder.find( initExpr->expr, ResolvMode::withAdjustment() );
1455 for ( CandidateRef & cand : finder.candidates ) {
1456 if(reason.code == NotFound) reason.code = NoMatch;
1457
1458 ast::TypeEnvironment env{ cand->env };
1459 ast::AssertionSet need( cand->need.begin(), cand->need.end() ), have;
1460 ast::OpenVarSet open{ cand->open };
1461
1462 PRINT(
1463 std::cerr << " @ " << toType << " " << initAlt.designation << std::endl;
1464 )
1465
1466 // It is possible that a cast can throw away some values in a multiply-valued
1467 // expression, e.g. cast-to-void, one value to zero. Figure out the prefix of
1468 // the subexpression results that are cast directly. The candidate is invalid
1469 // if it has fewer results than there are types to cast to.
1470 int discardedValues = cand->expr->result->size() - toType->size();
1471 if ( discardedValues < 0 ) continue;
1472
1473 // unification run for side-effects
1474 unify( toType, cand->expr->result, env, need, have, open, symtab );
1475 Cost thisCost = castCost( cand->expr->result, toType, cand->expr->get_lvalue(),
1476 symtab, env );
1477
1478 if ( thisCost != Cost::infinity ) {
1479 // count one safe conversion for each value that is thrown away
1480 thisCost.incSafe( discardedValues );
1481 CandidateRef newCand = std::make_shared<Candidate>(
1482 new ast::InitExpr{
1483 initExpr->location, restructureCast( cand->expr, toType ),
1484 initAlt.designation },
1485 copy( cand->env ), move( open ), move( need ), cand->cost, thisCost );
1486 inferParameters( newCand, matches );
1487 }
1488 }
1489 }
1490
1491 // select first on argument cost, then conversion cost
1492 CandidateList minArgCost = findMinCost( matches );
1493 promoteCvtCost( minArgCost );
1494 candidates = findMinCost( minArgCost );
1495 }
1496
1497 void postvisit( const ast::InitExpr * ) {
1498 assertf( false, "CandidateFinder should never see a resolved InitExpr." );
1499 }
1500
1501 void postvisit( const ast::DeletedExpr * ) {
1502 assertf( false, "CandidateFinder should never see a DeletedExpr." );
1503 }
1504
1505 void postvisit( const ast::GenericExpr * ) {
1506 assertf( false, "_Generic is not yet supported." );
1507 }
1508 };
1509
1510 size_t Finder::traceId = Stats::Heap::new_stacktrace_id("Finder");
1511 /// Prunes a list of candidates down to those that have the minimum conversion cost for a given
1512 /// return type. Skips ambiguous candidates.
1513 CandidateList pruneCandidates( CandidateList & candidates ) {
1514 struct PruneStruct {
1515 CandidateRef candidate;
1516 bool ambiguous;
1517
1518 PruneStruct() = default;
1519 PruneStruct( const CandidateRef & c ) : candidate( c ), ambiguous( false ) {}
1520 };
1521
1522 // find lowest-cost candidate for each type
1523 std::unordered_map< std::string, PruneStruct > selected;
1524 for ( CandidateRef & candidate : candidates ) {
1525 std::string mangleName;
1526 {
1527 ast::ptr< ast::Type > newType = candidate->expr->result;
1528 assertf(candidate->expr->result, "Result of expression %p for candidate is null", candidate->expr.get());
1529 candidate->env.apply( newType );
1530 mangleName = Mangle::mangle( newType );
1531 }
1532
1533 auto found = selected.find( mangleName );
1534 if ( found != selected.end() ) {
1535 if ( candidate->cost < found->second.candidate->cost ) {
1536 PRINT(
1537 std::cerr << "cost " << candidate->cost << " beats "
1538 << found->second.candidate->cost << std::endl;
1539 )
1540
1541 found->second = PruneStruct{ candidate };
1542 } else if ( candidate->cost == found->second.candidate->cost ) {
1543 // if one of the candidates contains a deleted identifier, can pick the other,
1544 // since deleted expressions should not be ambiguous if there is another option
1545 // that is at least as good
1546 if ( findDeletedExpr( candidate->expr ) ) {
1547 // do nothing
1548 PRINT( std::cerr << "candidate is deleted" << std::endl; )
1549 } else if ( findDeletedExpr( found->second.candidate->expr ) ) {
1550 PRINT( std::cerr << "current is deleted" << std::endl; )
1551 found->second = PruneStruct{ candidate };
1552 } else {
1553 PRINT( std::cerr << "marking ambiguous" << std::endl; )
1554 found->second.ambiguous = true;
1555 }
1556 } else {
1557 PRINT(
1558 std::cerr << "cost " << candidate->cost << " loses to "
1559 << found->second.candidate->cost << std::endl;
1560 )
1561 }
1562 } else {
1563 selected.emplace_hint( found, mangleName, candidate );
1564 }
1565 }
1566
1567 // report unambiguous min-cost candidates
1568 CandidateList out;
1569 for ( auto & target : selected ) {
1570 if ( target.second.ambiguous ) continue;
1571
1572 CandidateRef cand = target.second.candidate;
1573
1574 ast::ptr< ast::Type > newResult = cand->expr->result;
1575 cand->env.applyFree( newResult );
1576 cand->expr = ast::mutate_field(
1577 cand->expr.get(), &ast::Expr::result, move( newResult ) );
1578
1579 out.emplace_back( cand );
1580 }
1581 return out;
1582 }
1583
1584} // anonymous namespace
1585
1586void CandidateFinder::find( const ast::Expr * expr, ResolvMode mode ) {
1587 // Find alternatives for expression
1588 ast::Pass<Finder> finder{ *this };
1589 expr->accept( finder );
1590
1591 if ( mode.failFast && candidates.empty() ) {
1592 switch(finder.pass.reason.code) {
1593 case Finder::NotFound:
1594 { SemanticError( expr, "No alternatives for expression " ); break; }
1595 case Finder::NoMatch:
1596 { SemanticError( expr, "Invalid application of existing declaration(s) in expression " ); break; }
1597 case Finder::ArgsToFew:
1598 case Finder::ArgsToMany:
1599 case Finder::RetsToFew:
1600 case Finder::RetsToMany:
1601 case Finder::NoReason:
1602 default:
1603 { SemanticError( expr->location, "No reasonable alternatives for expression : reasons unkown" ); }
1604 }
1605 }
1606
1607 if ( mode.satisfyAssns || mode.prune ) {
1608 // trim candidates to just those where the assertions are satisfiable
1609 // - necessary pre-requisite to pruning
1610 CandidateList satisfied;
1611 std::vector< std::string > errors;
1612 for ( CandidateRef & candidate : candidates ) {
1613 satisfyAssertions( candidate, localSyms, satisfied, errors );
1614 }
1615
1616 // fail early if none such
1617 if ( mode.failFast && satisfied.empty() ) {
1618 std::ostringstream stream;
1619 stream << "No alternatives with satisfiable assertions for " << expr << "\n";
1620 for ( const auto& err : errors ) {
1621 stream << err;
1622 }
1623 SemanticError( expr->location, stream.str() );
1624 }
1625
1626 // reset candidates
1627 candidates = move( satisfied );
1628 }
1629
1630 if ( mode.prune ) {
1631 // trim candidates to single best one
1632 PRINT(
1633 std::cerr << "alternatives before prune:" << std::endl;
1634 print( std::cerr, candidates );
1635 )
1636
1637 CandidateList pruned = pruneCandidates( candidates );
1638
1639 if ( mode.failFast && pruned.empty() ) {
1640 std::ostringstream stream;
1641 CandidateList winners = findMinCost( candidates );
1642 stream << "Cannot choose between " << winners.size() << " alternatives for "
1643 "expression\n";
1644 ast::print( stream, expr );
1645 stream << " Alternatives are:\n";
1646 print( stream, winners, 1 );
1647 SemanticError( expr->location, stream.str() );
1648 }
1649
1650 auto oldsize = candidates.size();
1651 candidates = move( pruned );
1652
1653 PRINT(
1654 std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
1655 )
1656 PRINT(
1657 std::cerr << "there are " << candidates.size() << " alternatives after elimination"
1658 << std::endl;
1659 )
1660 }
1661
1662 // adjust types after pruning so that types substituted by pruneAlternatives are correctly
1663 // adjusted
1664 if ( mode.adjust ) {
1665 for ( CandidateRef & r : candidates ) {
1666 r->expr = ast::mutate_field(
1667 r->expr.get(), &ast::Expr::result,
1668 adjustExprType( r->expr->result, r->env, localSyms ) );
1669 }
1670 }
1671
1672 // Central location to handle gcc extension keyword, etc. for all expressions
1673 for ( CandidateRef & r : candidates ) {
1674 if ( r->expr->extension != expr->extension ) {
1675 r->expr.get_and_mutate()->extension = expr->extension;
1676 }
1677 }
1678}
1679
1680std::vector< CandidateFinder > CandidateFinder::findSubExprs(
1681 const std::vector< ast::ptr< ast::Expr > > & xs
1682) {
1683 std::vector< CandidateFinder > out;
1684
1685 for ( const auto & x : xs ) {
1686 out.emplace_back( localSyms, env );
1687 out.back().find( x, ResolvMode::withAdjustment() );
1688
1689 PRINT(
1690 std::cerr << "findSubExprs" << std::endl;
1691 print( std::cerr, out.back().candidates );
1692 )
1693 }
1694
1695 return out;
1696}
1697
1698} // namespace ResolvExpr
1699
1700// Local Variables: //
1701// tab-width: 4 //
1702// mode: c++ //
1703// compile-command: "make install" //
1704// End: //
Note: See TracBrowser for help on using the repository browser.