source: src/InitTweak/FixInit.cc @ db4ecc5

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 db4ecc5 was db4ecc5, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

add ImplicitCopyCtorExpr? node, implicit copy constructors are inserted into the right places (but there is room for elision)

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