source: src/InitTweak/FixInit.cc @ 6cf27a07

ADTaaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 6cf27a07 was 6cf27a07, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

reorganize global init so that it is simpler and generates less unnecessary code

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