source: src/InitTweak/FixInit.cc @ a0fdbd5

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since a0fdbd5 was a0fdbd5, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

remove RemoveInit?'s ObjectDecl? mutate which duplicates constructor calls on polymorphic objects, change name of RemoveInit? files to more accurate GenInit?

  • Property mode set to 100644
File size: 18.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// FixInit.h --
8//
9// Author           : Rob Schluntz
10// Created On       : Wed Jan 13 16:29:30 2016
11// Last Modified By : Rob Schluntz
12// Last Modified On : Thu Apr 28 12:25:14 2016
13// Update Count     : 30
14//
15
16#include <stack>
17#include <list>
18#include "FixInit.h"
19#include "ResolvExpr/Resolver.h"
20#include "ResolvExpr/typeops.h"
21#include "SynTree/Declaration.h"
22#include "SynTree/Type.h"
23#include "SynTree/Expression.h"
24#include "SynTree/Statement.h"
25#include "SynTree/Initializer.h"
26#include "SynTree/Mutator.h"
27#include "SymTab/Indexer.h"
28#include "GenPoly/PolyMutator.h"
29#include "GenPoly/GenPoly.h"
30
31bool ctordtorp = false;
32#define PRINT( text ) if ( ctordtorp ) { text }
33
34namespace InitTweak {
35        namespace {
36                const std::list<Label> noLabels;
37                const std::list<Expression*> noDesignators;
38        }
39
40        class InsertImplicitCalls : public GenPoly::PolyMutator {
41        public:
42                /// wrap function application expressions as ImplicitCopyCtorExpr nodes
43                /// so that it is easy to identify which function calls need their parameters
44                /// to be copy constructed
45                static void insert( std::list< Declaration * > & translationUnit );
46
47                virtual Expression * mutate( ApplicationExpr * appExpr );
48        };
49
50        class ResolveCopyCtors : public SymTab::Indexer {
51        public:
52                /// generate temporary ObjectDecls for each argument and return value of each
53                /// ImplicitCopyCtorExpr, generate/resolve copy construction expressions for each,
54                /// and generate/resolve destructors for both arguments and return value temporaries
55                static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
56
57                virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
58
59                /// create and resolve ctor/dtor expression: fname(var, [cpArg])
60                ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
61                /// true if type does not need to be copy constructed to ensure correctness
62                bool skipCopyConstruct( Type * );
63        };
64
65        class FixInit : public GenPoly::PolyMutator {
66          public:
67                /// expand each object declaration to use its constructor after it is declared.
68                /// insert destructor calls at the appropriate places
69                static void fixInitializers( std::list< Declaration * > &translationUnit );
70
71                virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
72
73                virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
74                virtual Statement * mutate( ReturnStmt * returnStmt );
75                virtual Statement * mutate( BranchStmt * branchStmt );
76
77          private:
78                // stack of list of statements - used to differentiate scopes
79                std::list< std::list< Statement * > > dtorStmts;
80        };
81
82        class FixCopyCtors : public GenPoly::PolyMutator {
83          public:
84                /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors,
85                /// call expression, and destructors
86                static void fixCopyCtors( std::list< Declaration * > &translationUnit );
87
88                virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
89
90          private:
91                // stack of list of statements - used to differentiate scopes
92                std::list< std::list< Statement * > > dtorStmts;
93        };
94
95        void fix( std::list< Declaration * > & translationUnit ) {
96                InsertImplicitCalls::insert( translationUnit );
97                ResolveCopyCtors::resolveImplicitCalls( translationUnit );
98                FixInit::fixInitializers( translationUnit );
99                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
100                FixCopyCtors::fixCopyCtors( translationUnit );
101        }
102
103        void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
104                InsertImplicitCalls inserter;
105                mutateAll( translationUnit, inserter );
106        }
107
108        void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
109                ResolveCopyCtors resolver;
110                acceptAll( translationUnit, resolver );
111        }
112
113        void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
114                FixInit fixer;
115                mutateAll( translationUnit, fixer );
116        }
117
118        void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
119                FixCopyCtors fixer;
120                mutateAll( translationUnit, fixer );
121        }
122
123        Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
124                appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
125                assert( appExpr );
126
127                if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
128                        if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
129                                // optimization: don't need to copy construct in order to call intrinsic functions
130                                return appExpr;
131                        } else if ( FunctionDecl * funcDecl = dynamic_cast< FunctionDecl * > ( function->get_var() ) ) {
132                                FunctionType * ftype = funcDecl->get_functionType();
133                                if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
134                                        Type * t1 = ftype->get_parameters().front()->get_type();
135                                        Type * t2 = ftype->get_parameters().back()->get_type();
136                                        PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
137                                        assert( ptrType );
138                                        if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
139                                                // optimization: don't need to copy construct in order to call a copy constructor or
140                                                // assignment operator
141                                                return appExpr;
142                                        }
143                                } else if ( funcDecl->get_name() == "^?{}" ) {
144                                        // correctness: never copy construct arguments to a destructor
145                                        return appExpr;
146                                }
147                        }
148                }
149                PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
150
151                // wrap each function call so that it is easy to identify nodes that have to be copy constructed
152                ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
153                // save a copy of the type substitution onto the new node so that it is easy to find.
154                // The substitution is needed to obtain the type of temporary variables so that copy constructor
155                // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
156                // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
157                // saves the environment, or compute the types of temporaries here, but it's more simpler to
158                // save the environment here, and more cohesive to compute temporary variables and resolve copy
159                // constructor calls together.
160                assert( env );
161                expr->set_env( env->clone() );
162                return expr;
163        }
164
165        bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
166                return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
167        }
168
169        ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
170                assert( var );
171                UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
172                untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
173                if (cpArg) untyped->get_args().push_back( cpArg );
174
175                // resolve copy constructor
176                // should only be one alternative for copy ctor and dtor expressions, since
177                // all arguments are fixed (VariableExpr and already resolved expression)
178                PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
179                ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
180
181                assert( resolved );
182                delete untyped;
183                return resolved;
184        }
185
186        void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
187                static UniqueName tempNamer("_tmp_cp");
188                static UniqueName retNamer("_tmp_cp_ret");
189
190                PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
191                Visitor::visit( impCpCtorExpr );
192
193                ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
194
195                // take each argument and attempt to copy construct it.
196                for ( Expression * & arg : appExpr->get_args() ) {
197                        PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
198                        // xxx - need to handle tuple arguments
199                        assert( ! arg->get_results().empty() );
200                        Type * result = arg->get_results().front();
201                        if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
202                        // type may involve type variables, so apply type substitution to get temporary variable's actual type
203                        result = result->clone();
204                        impCpCtorExpr->get_env()->apply( result );
205                        ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
206                        tmp->get_type()->set_isConst( false );
207
208                        // create and resolve copy constructor
209                        PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
210                        ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
211
212                        // if the chosen constructor is intrinsic, the copy is unnecessary, so
213                        // don't create the temporary and don't call the copy constructor
214                        VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
215                        assert( function );
216                        if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
217                                // replace argument to function call with temporary
218                                arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
219                                impCpCtorExpr->get_tempDecls().push_back( tmp );
220                                impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
221                        }
222                }
223
224                // each return value from the call needs to be connected with an ObjectDecl
225                // at the call site, which is initialized with the return value and is destructed
226                // later
227                // xxx - handle multiple return values
228                ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
229                // xxx - is this right? callExpr may not have the right environment, because it was attached
230                // at a higher level. Trying to pass that environment along.
231                callExpr->set_env( impCpCtorExpr->get_env()->clone() );
232                for ( Type * result : appExpr->get_results() ) {
233                        ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result->clone(), 0 );
234                        ret->get_type()->set_isConst( false );
235                        impCpCtorExpr->get_returnDecls().push_back( ret );
236                        PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
237                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
238                }
239                PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
240        }
241
242
243        Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
244                PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
245
246                // assert( impCpCtorExpr->get_callExpr()->get_env() );
247                impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
248                assert( impCpCtorExpr );
249
250                std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
251                std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
252                std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
253
254                // add all temporary declarations and their constructors
255                for ( ObjectDecl * obj : tempDecls ) {
256                        stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
257                }
258                for ( ObjectDecl * obj : returnDecls ) {
259                        stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
260                }
261
262                // add destructors after current statement
263                for ( Expression * dtor : dtors ) {
264                        stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
265                }
266
267                // xxx - update to work with multiple return values
268                ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
269                Expression * callExpr = impCpCtorExpr->get_callExpr();
270
271                PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
272
273                // xxx - some of these aren't necessary, and can be removed once this is stable
274                dtors.clear();
275                tempDecls.clear();
276                returnDecls.clear();
277                impCpCtorExpr->set_callExpr( NULL );
278                delete impCpCtorExpr;
279
280                if ( returnDecl ) {
281                        UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
282                        assign->get_args().push_back( new VariableExpr( returnDecl ) );
283                        assign->get_args().push_back( callExpr );
284                        // know the result type of the assignment is the type of the LHS (minus the pointer), so
285                        // add that onto the assignment expression so that later steps have the necessary information
286                        assign->add_result( returnDecl->get_type()->clone() );
287                        // return new CommaExpr( assign, new VariableExpr( returnDecl ) );
288                        return assign;
289                } else {
290                        return callExpr;
291                }
292        }
293
294        DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
295                // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
296                // when the init is removed from the ObjectDecl
297                objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
298
299                if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
300                        // a decision should have been made by the resolver, so ctor and init are not both non-NULL
301                        assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
302                        if ( Statement * ctor = ctorInit->get_ctor() ) {
303                                if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
304                                        // generate:
305                                        // static bool __objName_uninitialized = true;
306                                        // if (__objName_uninitialized) {
307                                        //   __ctor(__objName);
308                                        //   void dtor_atexit() {
309                                        //     __dtor(__objName);
310                                        //   }
311                                        //   on_exit(dtorOnExit, &__objName);
312                                        //   __objName_uninitialized = false;
313                                        // }
314
315                                        // generate first line
316                                        BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
317                                        SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
318                                        ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
319                                        isUninitializedVar->fixUniqueId();
320
321                                        // void dtor_atexit(...) {...}
322                                        FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
323                                        dtorCaller->fixUniqueId();
324                                        dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
325
326                                        // on_exit(dtor_atexit);
327                                        UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
328                                        callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
329
330                                        // __objName_uninitialized = false;
331                                        UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
332                                        setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
333                                        setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
334
335                                        // generate body of if
336                                        CompoundStmt * initStmts = new CompoundStmt( noLabels );
337                                        std::list< Statement * > & body = initStmts->get_kids();
338                                        body.push_back( ctor );
339                                        body.push_back( new DeclStmt( noLabels, dtorCaller ) );
340                                        body.push_back( new ExprStmt( noLabels, callAtexit ) );
341                                        body.push_back( new ExprStmt( noLabels, setTrue ) );
342
343                                        // put it all together
344                                        IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
345                                        stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
346                                        stmtsToAddAfter.push_back( ifStmt );
347                                } else {
348                                        stmtsToAddAfter.push_back( ctor );
349                                        dtorStmts.back().push_front( ctorInit->get_dtor() );
350                                }
351                                objDecl->set_init( NULL );
352                                ctorInit->set_ctor( NULL );
353                                ctorInit->set_dtor( NULL );  // xxx - only destruct when constructing? Probably not?
354                        } else if ( Initializer * init = ctorInit->get_init() ) {
355                                objDecl->set_init( init );
356                                ctorInit->set_init( NULL );
357                        } else {
358                                // no constructor and no initializer, which is okay
359                                objDecl->set_init( NULL );
360                        }
361                        delete ctorInit;
362                }
363                return objDecl;
364        }
365
366        template<typename Iterator, typename OutputIterator>
367        void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
368                for ( Iterator it = begin ; it != end ; ++it ) {
369                        // remove if instrinsic destructor statement
370                        // xxx - test user manually calling intrinsic functions - what happens?
371                        if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( *it ) ) {
372                                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( exprStmt->get_expr() );
373                                assert( appExpr );
374                                VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
375                                assert( function );
376                                // check for Intrinsic only - don't want to remove all overridable dtors because autogenerated dtor
377                                // will call all member dtors, and some members may have a user defined dtor.
378                                if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
379                                        // don't need to call intrinsic dtor, because it does nothing
380                                } else {
381                                        // non-intrinsic dtors must be called
382                                        *out++ = (*it)->clone();
383                                }
384                        } else {
385                                // could also be a compound statement with a loop, in the case of an array
386                                *out++ = (*it)->clone();
387                        }
388                }
389        }
390
391
392        CompoundStmt * FixInit::mutate( CompoundStmt * compoundStmt ) {
393                // mutate statements - this will also populate dtorStmts list.
394                // don't want to dump all destructors when block is left,
395                // just the destructors associated with variables defined in this block,
396                // so push a new list to the top of the stack so that we can differentiate scopes
397                dtorStmts.push_back( std::list<Statement *>() );
398
399                compoundStmt = PolyMutator::mutate( compoundStmt );
400                std::list< Statement * > & statements = compoundStmt->get_kids();
401
402                insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( statements ) );
403
404                deleteAll( dtorStmts.back() );
405                dtorStmts.pop_back();
406                return compoundStmt;
407        }
408
409        Statement * FixInit::mutate( ReturnStmt * returnStmt ) {
410                for ( std::list< std::list< Statement * > >::reverse_iterator list = dtorStmts.rbegin(); list != dtorStmts.rend(); ++list ) {
411                        insertDtors( list->begin(), list->end(), back_inserter( stmtsToAdd ) );
412                }
413                return Mutator::mutate( returnStmt );
414        }
415
416        Statement * FixInit::mutate( BranchStmt * branchStmt ) {
417                // TODO: adding to the end of a block isn't sufficient, since
418                // return/break/goto should trigger destructor when block is left.
419                switch( branchStmt->get_type() ) {
420                        case BranchStmt::Continue:
421                        case BranchStmt::Break:
422                                insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( stmtsToAdd ) );
423                                break;
424                        case BranchStmt::Goto:
425                                // xxx
426                                // if goto leaves a block, generate dtors for every block it leaves
427                                // if goto is in same block but earlier statement, destruct every object that was defined after the statement
428                                break;
429                        default:
430                                assert( false );
431                }
432                return Mutator::mutate( branchStmt );
433        }
434
435
436} // namespace InitTweak
437
438// Local Variables: //
439// tab-width: 4 //
440// mode: c++ //
441// compile-command: "make install" //
442// End: //
Note: See TracBrowser for help on using the repository browser.