source: src/InitTweak/FixInit.cc @ cf18eea

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

don't copy construct function type arguments or va_list type arguments

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