source: src/ResolvExpr/Resolver.cc @ 9be45a2

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 9be45a2 was 933f32f, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Merge branch 'master' into cleanup-dtors

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