source: src/ResolvExpr/Resolver.cc @ f229fc2

new-envwith_gc
Last change on this file since f229fc2 was f229fc2, checked in by Aaron Moss <a3moss@…>, 6 years ago

Modify resolver to use young-generation collection per-top-level expression

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