source: src/InitTweak/FixInit.cc @ 4e06c1e

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 4e06c1e was 4e06c1e, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

changes for switch and choose statements

  • Property mode set to 100644
File size: 27.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
[adcc065]11// Last Modified By : Peter A. Buhr
[4e06c1e]12// Last Modified On : Tue Jul 12 17:41:15 2016
13// Update Count     : 34
[71f4e4f]14//
15
16#include <stack>
17#include <list>
[c2931ea]18#include <iterator>
19#include <algorithm>
[a0fdbd5]20#include "FixInit.h"
[7b3f66b]21#include "InitTweak.h"
[db4ecc5]22#include "ResolvExpr/Resolver.h"
[845cedc]23#include "ResolvExpr/typeops.h"
[71f4e4f]24#include "SynTree/Declaration.h"
25#include "SynTree/Type.h"
26#include "SynTree/Expression.h"
27#include "SynTree/Statement.h"
28#include "SynTree/Initializer.h"
29#include "SynTree/Mutator.h"
[db4ecc5]30#include "SymTab/Indexer.h"
[71f4e4f]31#include "GenPoly/PolyMutator.h"
[c2931ea]32#include "SynTree/AddStmtVisitor.h"
[71f4e4f]33
[845cedc]34bool ctordtorp = false;
[c2931ea]35bool ctorp = false;
36bool cpctorp = false;
[e39aa0f]37bool dtorp = false;
[845cedc]38#define PRINT( text ) if ( ctordtorp ) { text }
[c2931ea]39#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
40#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
[845cedc]41
[71f4e4f]42namespace InitTweak {
43        namespace {
44                const std::list<Label> noLabels;
[e0323a2]45                const std::list<Expression*> noDesignators;
[71f4e4f]46
[c2931ea]47                class InsertImplicitCalls : public GenPoly::PolyMutator {
48                public:
[adcc065]49                        /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
50                        /// function calls need their parameters to be copy constructed
[c2931ea]51                        static void insert( std::list< Declaration * > & translationUnit );
52
53                        virtual Expression * mutate( ApplicationExpr * appExpr );
54                };
55
56                class ResolveCopyCtors : public SymTab::Indexer {
57                public:
[adcc065]58                        /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
59                        /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
60                        /// arguments and return value temporaries
[c2931ea]61                        static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
62
63                        virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
64
65                        /// create and resolve ctor/dtor expression: fname(var, [cpArg])
66                        ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
67                        /// true if type does not need to be copy constructed to ensure correctness
68                        bool skipCopyConstruct( Type * );
69                private:
70                        TypeSubstitution * env;
71                };
72
73                /// collects constructed object decls - used as a base class
74                class ObjDeclCollector : public AddStmtVisitor {
75                  public:
76                        typedef AddStmtVisitor Parent;
77                        using Parent::visit;
78                        typedef std::set< ObjectDecl * > ObjectSet;
79                        virtual void visit( CompoundStmt *compoundStmt );
80                        virtual void visit( DeclStmt *stmt );
81                  protected:
82                        ObjectSet curVars;
83                };
84
85                struct printSet {
86                        typedef ObjDeclCollector::ObjectSet ObjectSet;
87                        printSet( const ObjectSet & objs ) : objs( objs ) {}
88                        const ObjectSet & objs;
89                };
90                std::ostream & operator<<( std::ostream & out, const printSet & set) {
91                        out << "{ ";
92                        for ( ObjectDecl * obj : set.objs ) {
93                                out << obj->get_name() << ", " ;
[adcc065]94                        } // for
[c2931ea]95                        out << " }";
96                        return out;
97                }
98
99                class LabelFinder : public ObjDeclCollector {
100                  public:
101                        typedef ObjDeclCollector Parent;
102                        typedef std::map< Label, ObjectSet > LabelMap;
103                        // map of Label -> live variables at that label
104                        LabelMap vars;
105
106                        void handleStmt( Statement * stmt );
107
108                        // xxx - This needs to be done better.
[adcc065]109                        // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
110                        // expressions, all statements, etc.)  important to have this to provide a single entry point so that as new
111                        // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
112                        // every specialized class knows about every new kind of statement that might be added.
[c2931ea]113                        virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
114                        virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
115                        virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
116                        virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
117                        virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
118                        virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
119                        virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
120                        virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
121                        virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
122                        virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
123                        virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
124                        virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
125                        virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
126                        virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
127                        virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
128                        virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
129                };
130
131                class InsertDtors : public ObjDeclCollector {
132                public:
[adcc065]133                        /// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
134                        /// (currently by FixInit)
[c2931ea]135                        static void insert( std::list< Declaration * > & translationUnit );
136
137                        typedef ObjDeclCollector Parent;
138                        typedef std::list< ObjectDecl * > OrderedDecls;
139                        typedef std::list< OrderedDecls > OrderedDeclsStack;
140
141                        InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
142
143                        virtual void visit( ObjectDecl * objDecl );
144
145                        virtual void visit( CompoundStmt * compoundStmt );
146                        virtual void visit( ReturnStmt * returnStmt );
147                        virtual void visit( BranchStmt * stmt );
148                private:
149                        void handleGoto( BranchStmt * stmt );
150
151                        LabelFinder::LabelMap & labelVars;
152                        OrderedDeclsStack reverseDeclOrder;
153                };
154
155                class FixInit : public GenPoly::PolyMutator {
156                  public:
157                        /// expand each object declaration to use its constructor after it is declared.
158                        static void fixInitializers( std::list< Declaration * > &translationUnit );
159
160                        virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
161                };
162
163                class FixCopyCtors : public GenPoly::PolyMutator {
164                  public:
[adcc065]165                        /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
166                        /// and destructors
[c2931ea]167                        static void fixCopyCtors( std::list< Declaration * > &translationUnit );
168
169                        virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
170                };
171        } // namespace
[db4ecc5]172
[71f4e4f]173        void fix( std::list< Declaration * > & translationUnit ) {
[db4ecc5]174                InsertImplicitCalls::insert( translationUnit );
175                ResolveCopyCtors::resolveImplicitCalls( translationUnit );
[c2931ea]176                InsertDtors::insert( translationUnit );
[71f4e4f]177                FixInit::fixInitializers( translationUnit );
[c2931ea]178
[db4ecc5]179                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
180                FixCopyCtors::fixCopyCtors( translationUnit );
181        }
182
[c2931ea]183        namespace {
184                void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
185                        InsertImplicitCalls inserter;
186                        mutateAll( translationUnit, inserter );
187                }
[db4ecc5]188
[c2931ea]189                void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
190                        ResolveCopyCtors resolver;
191                        acceptAll( translationUnit, resolver );
192                }
[71f4e4f]193
[c2931ea]194                void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
195                        FixInit fixer;
196                        mutateAll( translationUnit, fixer );
197                }
[71f4e4f]198
[c2931ea]199                void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
200                        LabelFinder finder;
201                        InsertDtors inserter( finder );
202                        acceptAll( translationUnit, finder );
203                        acceptAll( translationUnit, inserter );
204                }
205
206                void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
207                        FixCopyCtors fixer;
208                        mutateAll( translationUnit, fixer );
209                }
[db4ecc5]210
[c2931ea]211                Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
212                        appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
213                        assert( appExpr );
214
215                        if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
216                                if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
217                                        // optimization: don't need to copy construct in order to call intrinsic functions
218                                        return appExpr;
219                                } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
220                                        FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
221                                        assert( ftype );
222                                        if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
223                                                Type * t1 = ftype->get_parameters().front()->get_type();
224                                                Type * t2 = ftype->get_parameters().back()->get_type();
225                                                PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
226                                                assert( ptrType );
227
228                                                if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
229                                                        // optimization: don't need to copy construct in order to call a copy constructor or
230                                                        // assignment operator
231                                                        return appExpr;
[adcc065]232                                                } // if
[c2931ea]233                                        } else if ( funcDecl->get_name() == "^?{}" ) {
234                                                // correctness: never copy construct arguments to a destructor
[845cedc]235                                                return appExpr;
[adcc065]236                                        } // if
237                                } // if
238                        } // if
[c2931ea]239                        CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
240
241                        // wrap each function call so that it is easy to identify nodes that have to be copy constructed
242                        ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
243                        // save the type substitution onto the new node so that it is easy to find.
244                        // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
245                        // The substitution is needed to obtain the type of temporary variables so that copy constructor
246                        // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
247                        // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
248                        // saves the environment, or compute the types of temporaries here, but it's much simpler to
249                        // save the environment here, and more cohesive to compute temporary variables and resolve copy
250                        // constructor calls together.
251                        assert( env );
252                        expr->set_env( env );
253                        return expr;
[db4ecc5]254                }
255
[c2931ea]256                bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
257                        return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
258                }
259
260                ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
261                        assert( var );
262                        UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
263                        untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
264                        if (cpArg) untyped->get_args().push_back( cpArg );
265
266                        // resolve copy constructor
[adcc065]267                        // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
268                        // (VariableExpr and already resolved expression)
[c2931ea]269                        CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
270                        ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
271                        if ( resolved->get_env() ) {
272                                env->add( *resolved->get_env() );
[adcc065]273                        } // if
[cf18eea]274
[c2931ea]275                        assert( resolved );
276                        delete untyped;
277                        return resolved;
[540de412]278                }
[db4ecc5]279
[c2931ea]280                void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
281                        static UniqueName tempNamer("_tmp_cp");
282                        static UniqueName retNamer("_tmp_cp_ret");
283
284                        CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
285                        Visitor::visit( impCpCtorExpr );
286                        env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
287
288                        ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
289
290                        // take each argument and attempt to copy construct it.
291                        for ( Expression * & arg : appExpr->get_args() ) {
292                                CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
293                                // xxx - need to handle tuple arguments
294                                assert( ! arg->get_results().empty() );
295                                Type * result = arg->get_results().front();
296                                if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
297                                // type may involve type variables, so apply type substitution to get temporary variable's actual type
298                                result = result->clone();
299                                impCpCtorExpr->get_env()->apply( result );
300                                ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
301                                tmp->get_type()->set_isConst( false );
302
303                                // create and resolve copy constructor
304                                CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
305                                ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
306
307                                // if the chosen constructor is intrinsic, the copy is unnecessary, so
308                                // don't create the temporary and don't call the copy constructor
309                                VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
310                                assert( function );
311                                if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
312                                        // replace argument to function call with temporary
313                                        arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
314                                        impCpCtorExpr->get_tempDecls().push_back( tmp );
315                                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
[adcc065]316                                } // if
317                        } // for
[db4ecc5]318
[adcc065]319                        // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
320                        // initialized with the return value and is destructed later
[c2931ea]321                        // xxx - handle multiple return values
322                        ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
[adcc065]323                        // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
324                        // level. Trying to pass that environment along.
[c2931ea]325                        callExpr->set_env( impCpCtorExpr->get_env()->clone() );
326                        for ( Type * result : appExpr->get_results() ) {
327                                result = result->clone();
328                                impCpCtorExpr->get_env()->apply( result );
329                                ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
330                                ret->get_type()->set_isConst( false );
331                                impCpCtorExpr->get_returnDecls().push_back( ret );
332                                CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
333                                impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
[adcc065]334                        } // for
[c2931ea]335                        CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
[db4ecc5]336                }
337
338
[c2931ea]339                Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
340                        CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
341
342                        impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
343                        assert( impCpCtorExpr );
[db4ecc5]344
[c2931ea]345                        std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
346                        std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
347                        std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
[845cedc]348
[c2931ea]349                        // add all temporary declarations and their constructors
350                        for ( ObjectDecl * obj : tempDecls ) {
351                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]352                        } // for
[c2931ea]353                        for ( ObjectDecl * obj : returnDecls ) {
354                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]355                        } // for
[db4ecc5]356
[c2931ea]357                        // add destructors after current statement
358                        for ( Expression * dtor : dtors ) {
359                                stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
[adcc065]360                        } // for
[db4ecc5]361
[c2931ea]362                        // xxx - update to work with multiple return values
363                        ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
364                        Expression * callExpr = impCpCtorExpr->get_callExpr();
365
366                        CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
367
368                        // detach fields from wrapper node so that it can be deleted without deleting too much
369                        dtors.clear();
370                        tempDecls.clear();
371                        returnDecls.clear();
372                        impCpCtorExpr->set_callExpr( NULL );
373                        impCpCtorExpr->set_env( NULL );
374                        delete impCpCtorExpr;
375
376                        if ( returnDecl ) {
377                                UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
378                                assign->get_args().push_back( new VariableExpr( returnDecl ) );
379                                assign->get_args().push_back( callExpr );
380                                // know the result type of the assignment is the type of the LHS (minus the pointer), so
381                                // add that onto the assignment expression so that later steps have the necessary information
382                                assign->add_result( returnDecl->get_type()->clone() );
383
384                                Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
385                                if ( callExpr->get_results().front()->get_isLvalue() ) {
[adcc065]386                                        // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
387                                        // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
388                                        // type of the return temporary from T to T* to properly capture the return value. Then dereference
389                                        // the result of the comma expression, since the lvalue returning call was originally wrapped with
390                                        // an AddressExpr.  Effectively, this turns
[c2931ea]391                                        //   lvalue T f();
392                                        //   &*f()
393                                        // into
394                                        //   T * tmp_cp_retN;
395                                        //   tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
396                                        // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
397                                        assign->get_args().back() = new AddressExpr( assign->get_args().back() );
398
399                                        Type * resultType = returnDecl->get_type()->clone();
400                                        returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
401                                        UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
402                                        deref->get_args().push_back( retExpr );
403                                        deref->add_result( resultType );
404                                        retExpr = deref;
[adcc065]405                                } // if
[c2931ea]406                                // xxx - might need to set env on retExpr...
407                                // retExpr->set_env( env->clone() );
408                                return retExpr;
409                        } else {
410                                return callExpr;
[adcc065]411                        } // if
[4ffdd63]412                }
[c2931ea]413
414                DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
[adcc065]415                        // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
416                        // is removed from the ObjectDecl
[c2931ea]417                        objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
418
419                        if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
420                                // a decision should have been made by the resolver, so ctor and init are not both non-NULL
421                                assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
422                                if ( Statement * ctor = ctorInit->get_ctor() ) {
423                                        if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
424                                                // generate:
425                                                // static bool __objName_uninitialized = true;
426                                                // if (__objName_uninitialized) {
427                                                //   __ctor(__objName);
428                                                //   void dtor_atexit() {
429                                                //     __dtor(__objName);
430                                                //   }
431                                                //   on_exit(dtorOnExit, &__objName);
432                                                //   __objName_uninitialized = false;
433                                                // }
434
435                                                // generate first line
436                                                BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
437                                                SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
438                                                ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
439                                                isUninitializedVar->fixUniqueId();
440
441                                                // void dtor_atexit(...) {...}
442                                                FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
443                                                dtorCaller->fixUniqueId();
[3f97e68]444                                                dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor()->clone() );
[c2931ea]445
446                                                // on_exit(dtor_atexit);
447                                                UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
448                                                callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
449
450                                                // __objName_uninitialized = false;
451                                                UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
452                                                setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
453                                                setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
454
455                                                // generate body of if
456                                                CompoundStmt * initStmts = new CompoundStmt( noLabels );
457                                                std::list< Statement * > & body = initStmts->get_kids();
458                                                body.push_back( ctor );
459                                                body.push_back( new DeclStmt( noLabels, dtorCaller ) );
460                                                body.push_back( new ExprStmt( noLabels, callAtexit ) );
461                                                body.push_back( new ExprStmt( noLabels, setTrue ) );
462
463                                                // put it all together
464                                                IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
465                                                stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
466                                                stmtsToAddAfter.push_back( ifStmt );
467                                        } else {
468                                                stmtsToAddAfter.push_back( ctor );
[adcc065]469                                        } // if
[c2931ea]470                                        objDecl->set_init( NULL );
471                                        ctorInit->set_ctor( NULL );
472                                } else if ( Initializer * init = ctorInit->get_init() ) {
473                                        objDecl->set_init( init );
474                                        ctorInit->set_init( NULL );
475                                } else {
476                                        // no constructor and no initializer, which is okay
477                                        objDecl->set_init( NULL );
[adcc065]478                                } // if
[c2931ea]479                                delete ctorInit;
[adcc065]480                        } // if
[c2931ea]481                        return objDecl;
[db4ecc5]482                }
483
[c2931ea]484                void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
485                        std::set< ObjectDecl * > prevVars = curVars;
486                        Parent::visit( compoundStmt );
487                        curVars = prevVars;
[db4ecc5]488                }
489
[c2931ea]490                void ObjDeclCollector::visit( DeclStmt *stmt ) {
[4b2589a]491                        // keep track of all variables currently in scope
[c2931ea]492                        if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
493                                curVars.insert( objDecl );
[adcc065]494                        } // if
[e39aa0f]495                        Parent::visit( stmt );
[db4ecc5]496                }
497
[c2931ea]498                void LabelFinder::handleStmt( Statement * stmt ) {
[4b2589a]499                        // for each label, remember the variables in scope at that label.
[c2931ea]500                        for ( Label l : stmt->get_labels() ) {
501                                vars[l] = curVars;
[adcc065]502                        } // for
[71f4e4f]503                }
[f1e012b]504
[ec79847]505                template<typename Iterator, typename OutputIterator>
506                void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
507                        for ( Iterator it = begin ; it != end ; ++it ) {
[adcc065]508                                // extract destructor statement from the object decl and insert it into the output. Note that this is
509                                // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
510                                // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
511                                // contain side effects.
[c2931ea]512                                ObjectDecl * objDecl = *it;
513                                ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
514                                assert( ctorInit && ctorInit->get_dtor() );
515                                *out++ = ctorInit->get_dtor()->clone();
[adcc065]516                        } // for
[f1e012b]517                }
[39786813]518
[c2931ea]519                void InsertDtors::visit( ObjectDecl * objDecl ) {
520                        // remember non-static destructed objects so that their destructors can be inserted later
521                        if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
522                                if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
523                                        // a decision should have been made by the resolver, so ctor and init are not both non-NULL
524                                        assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
525                                        Statement * dtor = ctorInit->get_dtor();
526                                        if ( dtor && ! isInstrinsicSingleArgCallStmt( dtor ) ) {
527                                                // don't need to call intrinsic dtor, because it does nothing, but
528                                                // non-intrinsic dtors must be called
529                                                reverseDeclOrder.front().push_front( objDecl );
[adcc065]530                                        } // if
531                                } // if
532                        } // if
[c2931ea]533                        Parent::visit( objDecl );
534                }
[39786813]535
[c2931ea]536                void InsertDtors::visit( CompoundStmt * compoundStmt ) {
[adcc065]537                        // visit statements - this will also populate reverseDeclOrder list.  don't want to dump all destructors
538                        // when block is left, just the destructors associated with variables defined in this block, so push a new
539                        // list to the top of the stack so that we can differentiate scopes
[c2931ea]540                        reverseDeclOrder.push_front( OrderedDecls() );
541                        Parent::visit( compoundStmt );
[39786813]542
[4b2589a]543                        // add destructors for the current scope that we're exiting
[c2931ea]544                        std::list< Statement * > & statements = compoundStmt->get_kids();
545                        insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
546                        reverseDeclOrder.pop_front();
[39786813]547                }
548
[c2931ea]549                void InsertDtors::visit( ReturnStmt * returnStmt ) {
[4b2589a]550                        // return exits all scopes, so dump destructors for all scopes
[c2931ea]551                        for ( OrderedDecls & od : reverseDeclOrder ) {
552                                insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
[adcc065]553                        } // for
[39786813]554                }
[f1e012b]555
[adcc065]556                // Handle break/continue/goto in the same manner as C++.  Basic idea: any objects that are in scope at the
557                // BranchStmt but not at the labelled (target) statement must be destructed.  If there are any objects in scope
558                // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
559                // of the error.  See C++ Reference 6.6 Jump Statements for details.
[c2931ea]560                void InsertDtors::handleGoto( BranchStmt * stmt ) {
[e39aa0f]561                        assert( stmt->get_target() != "" && "BranchStmt missing a label" );
[c2931ea]562                        // S_L = lvars = set of objects in scope at label definition
563                        // S_G = curVars = set of objects in scope at goto statement
564                        ObjectSet & lvars = labelVars[ stmt->get_target() ];
565
566                        DTOR_PRINT(
567                                std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
568                                std::cerr << "S_G = " << printSet( curVars ) << std::endl;
569                                std::cerr << "S_L = " << printSet( lvars ) << std::endl;
570                        )
571
572                        ObjectSet diff;
573                        // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
574                        std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
575                        DTOR_PRINT(
576                                std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
577                        )
578                        if ( ! diff.empty() ) {
579                                throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
[adcc065]580                        } // if
[c2931ea]581                        // S_G-S_L results in set of objects that must be destructed
582                        diff.clear();
583                        std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
584                        DTOR_PRINT(
585                                std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
586                        )
587                        if ( ! diff.empty() ) {
588                                // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
589                                OrderedDecls ordered;
590                                for ( OrderedDecls & rdo : reverseDeclOrder ) {
591                                        // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
592                                        copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
[adcc065]593                                } // for
[c2931ea]594                                insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
[adcc065]595                        } // if
[c2931ea]596                }
[39786813]597
[c2931ea]598                void InsertDtors::visit( BranchStmt * stmt ) {
599                        switch( stmt->get_type() ) {
[adcc065]600                          case BranchStmt::Continue:
601                          case BranchStmt::Break:
602                                // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
603                                // always be empty), but it serves as a small sanity check.
604                          case BranchStmt::Goto:
605                                handleGoto( stmt );
606                                break;
607                          default:
608                                assert( false );
609                        } // switch
[c2931ea]610                }
611        } // namespace
[71f4e4f]612} // namespace InitTweak
613
614// Local Variables: //
615// tab-width: 4 //
616// mode: c++ //
617// compile-command: "make install" //
618// End: //
Note: See TracBrowser for help on using the repository browser.