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

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 9a707e4e was a4ca48c, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Convert Resolver to PassVisitor?

  • Property mode set to 100644
File size: 19.9 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Resolver.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Tus Aug  8 16:06:00 2017
13// Update Count     : 212
14//
15
16#include <stddef.h>                      // for NULL
17#include <cassert>                       // for strict_dynamic_cast, assert
18#include <memory>                        // for allocator, allocator_traits<...
19#include <tuple>                         // for get
20
21#include "Alternative.h"                 // for Alternative, AltList
22#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
23#include "Common/PassVisitor.h"          // for PassVisitor
24#include "Common/SemanticError.h"        // for SemanticError
25#include "Common/utility.h"              // for ValueGuard, group_iterate
26#include "CurrentObject.h"               // for CurrentObject
27#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
28#include "RenameVars.h"                  // for RenameVars, global_renamer
29#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
30#include "ResolveTypeof.h"               // for resolveTypeof
31#include "Resolver.h"
32#include "SymTab/Autogen.h"              // for SizeType
33#include "SymTab/Indexer.h"              // for Indexer
34#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
35#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
36#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
37#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
38#include "SynTree/Type.h"                // for Type, BasicType, PointerType
39#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
40#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
41#include "typeops.h"                     // for extractResultType
42
43using namespace std;
44
45namespace ResolvExpr {
46        struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting {
47                Resolver() {}
48                Resolver( const SymTab::Indexer & other ) {
49                        indexer = other;
50                }
51
52                void previsit( FunctionDecl *functionDecl );
53                void postvisit( FunctionDecl *functionDecl );
54                void previsit( ObjectDecl *functionDecl );
55                void previsit( TypeDecl *typeDecl );
56                void previsit( EnumDecl * enumDecl );
57
58                void previsit( ArrayType * at );
59                void previsit( PointerType * at );
60
61                void previsit( ExprStmt *exprStmt );
62                void previsit( AsmExpr *asmExpr );
63                void previsit( AsmStmt *asmStmt );
64                void previsit( IfStmt *ifStmt );
65                void previsit( WhileStmt *whileStmt );
66                void previsit( ForStmt *forStmt );
67                void previsit( SwitchStmt *switchStmt );
68                void previsit( CaseStmt *caseStmt );
69                void previsit( BranchStmt *branchStmt );
70                void previsit( ReturnStmt *returnStmt );
71                void previsit( ThrowStmt *throwStmt );
72                void previsit( CatchStmt *catchStmt );
73
74                void previsit( SingleInit *singleInit );
75                void previsit( ListInit *listInit );
76                void previsit( ConstructorInit *ctorInit );
77          private:
78        typedef std::list< Initializer * >::iterator InitIterator;
79
80                template< typename PtrType >
81                void handlePtrType( PtrType * type );
82
83          void resolveAggrInit( ReferenceToType *, InitIterator &, InitIterator & );
84          void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator &, TypeSubstitution sub );
85          void fallbackInit( ConstructorInit * ctorInit );
86
87                Type * functionReturn = nullptr;
88                CurrentObject currentObject = nullptr;
89                bool inEnumDecl = false;
90        };
91
92        void resolve( std::list< Declaration * > translationUnit ) {
93                PassVisitor<Resolver> resolver;
94                acceptAll( translationUnit, resolver );
95        }
96
97        // used in resolveTypeof
98        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
99                TypeEnvironment env;
100                return resolveInVoidContext( expr, indexer, env );
101        }
102
103        namespace {
104                void finishExpr( Expression *expr, const TypeEnvironment &env ) {
105                        expr->set_env( new TypeSubstitution );
106                        env.makeSubstitution( *expr->get_env() );
107                }
108        } // namespace
109
110        Expression *findVoidExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
111                global_renamer.reset();
112                TypeEnvironment env;
113                Expression *newExpr = resolveInVoidContext( untyped, indexer, env );
114                finishExpr( newExpr, env );
115                return newExpr;
116        }
117
118        namespace {
119                Expression *findSingleExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
120                        TypeEnvironment env;
121                        AlternativeFinder finder( indexer, env );
122                        finder.find( untyped );
123#if 0
124                        if ( finder.get_alternatives().size() != 1 ) {
125                                std::cout << "untyped expr is ";
126                                untyped->print( std::cout );
127                                std::cout << std::endl << "alternatives are:";
128                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
129                                        i->print( std::cout );
130                                } // for
131                        } // if
132#endif
133                        assertf( finder.get_alternatives().size() == 1, "findSingleExpression: must have exactly one alternative at the end." );
134                        Alternative &choice = finder.get_alternatives().front();
135                        Expression *newExpr = choice.expr->clone();
136                        finishExpr( newExpr, choice.env );
137                        return newExpr;
138                }
139
140                bool isIntegralType( Type *type ) {
141                        if ( dynamic_cast< EnumInstType * >( type ) ) {
142                                return true;
143                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
144                                return bt->isInteger();
145                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
146                                return true;
147                        } else {
148                                return false;
149                        } // if
150                }
151
152                Expression *findIntegralExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
153                        TypeEnvironment env;
154                        AlternativeFinder finder( indexer, env );
155                        finder.find( untyped );
156#if 0
157                        if ( finder.get_alternatives().size() != 1 ) {
158                                std::cout << "untyped expr is ";
159                                untyped->print( std::cout );
160                                std::cout << std::endl << "alternatives are:";
161                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
162                                        i->print( std::cout );
163                                } // for
164                        } // if
165#endif
166                        Expression *newExpr = 0;
167                        const TypeEnvironment *newEnv = 0;
168                        for ( AltList::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
169                                if ( i->expr->get_result()->size() == 1 && isIntegralType( i->expr->get_result() ) ) {
170                                        if ( newExpr ) {
171                                                throw SemanticError( "Too many interpretations for case control expression", untyped );
172                                        } else {
173                                                newExpr = i->expr->clone();
174                                                newEnv = &i->env;
175                                        } // if
176                                } // if
177                        } // for
178                        if ( ! newExpr ) {
179                                throw SemanticError( "No interpretations for case control expression", untyped );
180                        } // if
181                        finishExpr( newExpr, *newEnv );
182                        return newExpr;
183                }
184
185        }
186
187        void Resolver::previsit( ObjectDecl *objectDecl ) {
188                Type *new_type = resolveTypeof( objectDecl->get_type(), indexer );
189                objectDecl->set_type( new_type );
190                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
191                // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
192                // initContext because of a function type can contain object declarations in the return and parameter types. So
193                // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
194                // the RHS.
195                GuardValue( currentObject );
196                currentObject = CurrentObject( objectDecl->get_type() );
197                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
198                        // enumerator initializers should not use the enum type to initialize, since
199                        // the enum type is still incomplete at this point. Use signed int instead.
200                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
201                }
202        }
203
204        template< typename PtrType >
205        void Resolver::handlePtrType( PtrType * type ) {
206                if ( type->get_dimension() ) {
207                        CastExpr *castExpr = new CastExpr( type->get_dimension(), SymTab::SizeType->clone() );
208                        Expression *newExpr = findSingleExpression( castExpr, indexer );
209                        delete type->get_dimension();
210                        type->set_dimension( newExpr );
211                }
212        }
213
214        void Resolver::previsit( ArrayType * at ) {
215                handlePtrType( at );
216        }
217
218        void Resolver::previsit( PointerType * pt ) {
219                handlePtrType( pt );
220        }
221
222        void Resolver::previsit( TypeDecl *typeDecl ) {
223                if ( typeDecl->get_base() ) {
224                        Type *new_type = resolveTypeof( typeDecl->get_base(), indexer );
225                        typeDecl->set_base( new_type );
226                } // if
227        }
228
229        void Resolver::previsit( FunctionDecl *functionDecl ) {
230#if 0
231                std::cerr << "resolver visiting functiondecl ";
232                functionDecl->print( std::cerr );
233                std::cerr << std::endl;
234#endif
235                Type *new_type = resolveTypeof( functionDecl->get_type(), indexer );
236                functionDecl->set_type( new_type );
237                GuardValue( functionReturn );
238                functionReturn = ResolvExpr::extractResultType( functionDecl->get_functionType() );
239        }
240
241
242        void Resolver::postvisit( FunctionDecl *functionDecl ) {
243                // default value expressions have an environment which shouldn't be there and trips up later passes.
244                // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
245                // see how it's useful.
246                for ( Declaration * d : functionDecl->get_functionType()->get_parameters() ) {
247                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
248                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->get_init() ) ) {
249                                        delete init->get_value()->get_env();
250                                        init->get_value()->set_env( nullptr );
251                                }
252                        }
253                }
254        }
255
256        void Resolver::previsit( EnumDecl * ) {
257                // in case we decide to allow nested enums
258                GuardValue( inEnumDecl );
259                inEnumDecl = true;
260        }
261
262        void Resolver::previsit( ExprStmt *exprStmt ) {
263                visit_children = false;
264                assertf( exprStmt->get_expr(), "ExprStmt has null Expression in resolver" );
265                Expression *newExpr = findVoidExpression( exprStmt->get_expr(), indexer );
266                delete exprStmt->get_expr();
267                exprStmt->set_expr( newExpr );
268        }
269
270        void Resolver::previsit( AsmExpr *asmExpr ) {
271                visit_children = false;
272                Expression *newExpr = findVoidExpression( asmExpr->get_operand(), indexer );
273                delete asmExpr->get_operand();
274                asmExpr->set_operand( newExpr );
275                if ( asmExpr->get_inout() ) {
276                        newExpr = findVoidExpression( asmExpr->get_inout(), indexer );
277                        delete asmExpr->get_inout();
278                        asmExpr->set_inout( newExpr );
279                } // if
280        }
281
282        void Resolver::previsit( AsmStmt *asmStmt ) {
283                visit_children = false;
284                acceptAll( asmStmt->get_input(), *visitor );
285                acceptAll( asmStmt->get_output(), *visitor );
286        }
287
288        void Resolver::previsit( IfStmt *ifStmt ) {
289                Expression *newExpr = findSingleExpression( ifStmt->get_condition(), indexer );
290                delete ifStmt->get_condition();
291                ifStmt->set_condition( newExpr );
292        }
293
294        void Resolver::previsit( WhileStmt *whileStmt ) {
295                Expression *newExpr = findSingleExpression( whileStmt->get_condition(), indexer );
296                delete whileStmt->get_condition();
297                whileStmt->set_condition( newExpr );
298        }
299
300        void Resolver::previsit( ForStmt *forStmt ) {
301                if ( forStmt->get_condition() ) {
302                        Expression * newExpr = findSingleExpression( forStmt->get_condition(), indexer );
303                        delete forStmt->get_condition();
304                        forStmt->set_condition( newExpr );
305                } // if
306
307                if ( forStmt->get_increment() ) {
308                        Expression * newExpr = findVoidExpression( forStmt->get_increment(), indexer );
309                        delete forStmt->get_increment();
310                        forStmt->set_increment( newExpr );
311                } // if
312        }
313
314        void Resolver::previsit( SwitchStmt *switchStmt ) {
315                GuardValue( currentObject );
316                Expression *newExpr;
317                newExpr = findIntegralExpression( switchStmt->get_condition(), indexer );
318                delete switchStmt->get_condition();
319                switchStmt->set_condition( newExpr );
320
321                currentObject = CurrentObject( newExpr->get_result() );
322        }
323
324        void Resolver::previsit( CaseStmt *caseStmt ) {
325                if ( caseStmt->get_condition() ) {
326                        std::list< InitAlternative > initAlts = currentObject.getOptions();
327                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
328                        CastExpr * castExpr = new CastExpr( caseStmt->get_condition(), initAlts.front().type->clone() );
329                        Expression * newExpr = findSingleExpression( castExpr, indexer );
330                        castExpr = strict_dynamic_cast< CastExpr * >( newExpr );
331                        caseStmt->set_condition( castExpr->get_arg() );
332                        castExpr->set_arg( nullptr );
333                        delete castExpr;
334                }
335        }
336
337        void Resolver::previsit( BranchStmt *branchStmt ) {
338                visit_children = false;
339                // must resolve the argument for a computed goto
340                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
341                        if ( Expression * arg = branchStmt->get_computedTarget() ) {
342                                VoidType v = Type::Qualifiers();                // cast to void * for the alternative finder
343                                PointerType pt( Type::Qualifiers(), v.clone() );
344                                CastExpr * castExpr = new CastExpr( arg, pt.clone() );
345                                Expression * newExpr = findSingleExpression( castExpr, indexer ); // find best expression
346                                branchStmt->set_target( newExpr );
347                        } // if
348                } // if
349        }
350
351        void Resolver::previsit( ReturnStmt *returnStmt ) {
352                visit_children = false;
353                if ( returnStmt->get_expr() ) {
354                        CastExpr *castExpr = new CastExpr( returnStmt->get_expr(), functionReturn->clone() );
355                        Expression *newExpr = findSingleExpression( castExpr, indexer );
356                        delete castExpr;
357                        returnStmt->set_expr( newExpr );
358                } // if
359        }
360
361        void Resolver::previsit( ThrowStmt *throwStmt ) {
362                visit_children = false;
363                // TODO: Replace *exception type with &exception type.
364                if ( throwStmt->get_expr() ) {
365                        StructDecl * exception_decl =
366                                indexer.lookupStruct( "__cfaehm__base_exception_t" );
367                        assert( exception_decl );
368                        Expression * wrapped = new CastExpr(
369                                throwStmt->get_expr(),
370                                new PointerType(
371                                        noQualifiers,
372                                        new StructInstType(
373                                                noQualifiers,
374                                                exception_decl
375                                                )
376                                        )
377                                );
378                        Expression * newExpr = findSingleExpression( wrapped, indexer );
379                        throwStmt->set_expr( newExpr );
380                }
381        }
382
383        void Resolver::previsit( CatchStmt *catchStmt ) {
384                if ( catchStmt->get_cond() ) {
385                        Expression * wrapped = new CastExpr(
386                                catchStmt->get_cond(),
387                                new BasicType( noQualifiers, BasicType::Bool )
388                                );
389                        catchStmt->set_cond( findSingleExpression( wrapped, indexer ) );
390                }
391        }
392
393        template< typename T >
394        bool isCharType( T t ) {
395                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
396                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
397                                bt->get_kind() == BasicType::UnsignedChar;
398                }
399                return false;
400        }
401
402        void Resolver::previsit( SingleInit *singleInit ) {
403                visit_children = false;
404                // resolve initialization using the possibilities as determined by the currentObject cursor
405                UntypedInitExpr * untyped = new UntypedInitExpr( singleInit->get_value(), currentObject.getOptions() );
406                Expression * newExpr = findSingleExpression( untyped, indexer );
407                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
408
409                // move cursor to the object that is actually initialized
410                currentObject.setNext( initExpr->get_designation() );
411
412                // discard InitExpr wrapper and retain relevant pieces
413                newExpr = initExpr->get_expr();
414                newExpr->set_env( initExpr->get_env() );
415                initExpr->set_expr( nullptr );
416                initExpr->set_env( nullptr );
417                delete initExpr;
418
419                // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
420                Type * initContext = currentObject.getCurrentType();
421
422                // check if actual object's type is char[]
423                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
424                        if ( isCharType( at->get_base() ) ) {
425                                // check if the resolved type is char *
426                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
427                                        if ( isCharType( pt->get_base() ) ) {
428                                                // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
429                                                CastExpr *ce = strict_dynamic_cast< CastExpr * >( newExpr );
430                                                newExpr = ce->get_arg();
431                                                ce->set_arg( nullptr );
432                                                delete ce;
433                                        }
434                                }
435                        }
436                }
437
438                // set initializer expr to resolved express
439                singleInit->set_value( newExpr );
440
441                // move cursor to next object in preparation for next initializer
442                currentObject.increment();
443        }
444
445        void Resolver::previsit( ListInit * listInit ) {
446                visit_children = false;
447                // move cursor into brace-enclosed initializer-list
448                currentObject.enterListInit();
449                // xxx - fix this so that the list isn't copied, iterator should be used to change current element
450                std::list<Designation *> newDesignations;
451                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
452                        // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
453                        // the initializer against that object.
454                        Designation * des = std::get<0>(p);
455                        Initializer * init = std::get<1>(p);
456                        newDesignations.push_back( currentObject.findNext( des ) );
457                        init->accept( *visitor );
458                }
459                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
460                listInit->get_designations() = newDesignations; // xxx - memory management
461                currentObject.exitListInit();
462
463                // xxx - this part has not be folded into CurrentObject yet
464                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
465                //      Type * base = tt->get_baseType()->get_base();
466                //      if ( base ) {
467                //              // know the implementation type, so try using that as the initContext
468                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
469                //              currentObject = &tmpObj;
470                //              visit( listInit );
471                //      } else {
472                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
473                //              Parent::visit( listInit );
474                //      }
475                // } else {
476        }
477
478        // ConstructorInit - fall back on C-style initializer
479        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
480                // could not find valid constructor, or found an intrinsic constructor
481                // fall back on C-style initializer
482                delete ctorInit->get_ctor();
483                ctorInit->set_ctor( NULL );
484                delete ctorInit->get_dtor();
485                ctorInit->set_dtor( NULL );
486                maybeAccept( ctorInit->get_init(), *visitor );
487        }
488
489        // needs to be callable from outside the resolver, so this is a standalone function
490        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
491                assert( ctorInit );
492                PassVisitor<Resolver> resolver( indexer );
493                ctorInit->accept( resolver );
494        }
495
496        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
497                assert( stmtExpr );
498                PassVisitor<Resolver> resolver( indexer );
499                stmtExpr->accept( resolver );
500        }
501
502        void Resolver::previsit( ConstructorInit *ctorInit ) {
503                visit_children = false;
504                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
505                maybeAccept( ctorInit->get_ctor(), *visitor );
506                maybeAccept( ctorInit->get_dtor(), *visitor );
507
508                // found a constructor - can get rid of C-style initializer
509                delete ctorInit->get_init();
510                ctorInit->set_init( NULL );
511
512                // intrinsic single parameter constructors and destructors do nothing. Since this was
513                // implicitly generated, there's no way for it to have side effects, so get rid of it
514                // to clean up generated code.
515                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
516                        delete ctorInit->get_ctor();
517                        ctorInit->set_ctor( NULL );
518                }
519
520                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) {
521                        delete ctorInit->get_dtor();
522                        ctorInit->set_dtor( NULL );
523                }
524
525                // xxx - todo -- what about arrays?
526                // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
527                //      // can reduce the constructor down to a SingleInit using the
528                //      // second argument from the ctor call, since
529                //      delete ctorInit->get_ctor();
530                //      ctorInit->set_ctor( NULL );
531
532                //      Expression * arg =
533                //      ctorInit->set_init( new SingleInit( arg ) );
534                // }
535        }
536} // namespace ResolvExpr
537
538// Local Variables: //
539// tab-width: 4 //
540// mode: c++ //
541// compile-command: "make install" //
542// End: //
Note: See TracBrowser for help on using the repository browser.