source: src/ResolvExpr/Resolver.cc @ 84993ff2

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 84993ff2 was 6a36975, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fix name mangling issues with CatchStmt?

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