source: src/InitTweak/FixInit.cc @ ea6332d

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since ea6332d was d180746, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Big header cleaning pass - commit 2

  • Property mode set to 100644
File size: 55.0 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 : Wed Jun 21 17:35:05 2017
13// Update Count     : 74
14//
15
16#include <stddef.h>                    // for NULL
17#include <algorithm>                   // for set_difference, copy_if
18#include <cassert>                     // for assert, safe_dynamic_cast
19#include <iostream>                    // for operator<<, ostream, basic_ost...
20#include <iterator>                    // for insert_iterator, back_inserter
21#include <list>                        // for _List_iterator, list, list<>::...
22#include <map>                         // for _Rb_tree_iterator, _Rb_tree_co...
23#include <memory>                      // for allocator_traits<>::value_type
24#include <set>                         // for set, set<>::value_type
25#include <unordered_map>               // for unordered_map, unordered_map<>...
26#include <unordered_set>               // for unordered_set
27#include <utility>                     // for pair
28
29#include "CodeGen/GenType.h"           // for genPrettyType
30#include "Common/PassVisitor.h"        // for PassVisitor, WithStmtsToAdd
31#include "Common/SemanticError.h"      // for SemanticError
32#include "Common/UniqueName.h"         // for UniqueName
33#include "Common/utility.h"            // for CodeLocation, ValueGuard, toSt...
34#include "FixGlobalInit.h"             // for fixGlobalInit
35#include "FixInit.h"
36#include "GenInit.h"                   // for genCtorDtor
37#include "GenPoly/DeclMutator.h"       // for DeclMutator
38#include "GenPoly/GenPoly.h"           // for getFunctionType
39#include "GenPoly/PolyMutator.h"       // for PolyMutator
40#include "InitTweak.h"                 // for getFunctionName, getCallArg
41#include "Parser/LinkageSpec.h"        // for C, Spec, Cforall, isBuiltin
42#include "PassVisitor.h"               // for mutateAll
43#include "ResolvExpr/Resolver.h"       // for findVoidExpression
44#include "ResolvExpr/typeops.h"        // for typesCompatible
45#include "SymTab/Autogen.h"            // for genImplicitCall
46#include "SymTab/Indexer.h"            // for Indexer
47#include "SymTab/Mangler.h"            // for Mangler
48#include "SynTree/AddStmtVisitor.h"    // for AddStmtVisitor
49#include "SynTree/Attribute.h"         // for Attribute
50#include "SynTree/Constant.h"          // for Constant
51#include "SynTree/Declaration.h"       // for ObjectDecl, FunctionDecl, Decl...
52#include "SynTree/Expression.h"        // for UniqueExpr, VariableExpr, Unty...
53#include "SynTree/Initializer.h"       // for ConstructorInit, SingleInit
54#include "SynTree/Label.h"             // for Label, noLabels, operator<
55#include "SynTree/Mutator.h"           // for mutateAll, Mutator, maybeMutate
56#include "SynTree/Statement.h"         // for ExprStmt, CompoundStmt, Branch...
57#include "SynTree/Type.h"              // for Type, Type::StorageClasses
58#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution, operator<<
59#include "SynTree/Visitor.h"           // for acceptAll, maybeAccept
60#include "Tuples/Tuples.h"             // for isTtype
61
62bool ctordtorp = false; // print all debug
63bool ctorp = false; // print ctor debug
64bool cpctorp = false; // print copy ctor debug
65bool dtorp = false; // print dtor debug
66#define PRINT( text ) if ( ctordtorp ) { text }
67#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
68#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
69
70namespace InitTweak {
71        namespace {
72                typedef std::unordered_map< Expression *, TypeSubstitution * > EnvMap;
73                typedef std::unordered_map< int, int > UnqCount;
74
75                class InsertImplicitCalls : public WithTypeSubstitution {
76                public:
77                        /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
78                        /// function calls need their parameters to be copy constructed
79                        static void insert( std::list< Declaration * > & translationUnit, EnvMap & envMap );
80
81                        InsertImplicitCalls( EnvMap & envMap ) : envMap( envMap ) {}
82
83                        Expression * postmutate( ApplicationExpr * appExpr );
84                        void premutate( StmtExpr * stmtExpr );
85
86                        // collects environments for relevant nodes
87                        EnvMap & envMap;
88                };
89
90                class ResolveCopyCtors final : public SymTab::Indexer {
91                public:
92                        /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
93                        /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
94                        /// arguments and return value temporaries
95                        static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount );
96
97                        typedef SymTab::Indexer Parent;
98                        using Parent::visit;
99
100                        ResolveCopyCtors( const EnvMap & envMap, UnqCount & unqCount ) : envMap( envMap ), unqCount( unqCount ) {}
101
102                        virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
103                        virtual void visit( UniqueExpr * unqExpr ) override;
104                        virtual void visit( StmtExpr * stmtExpr ) override;
105
106                        /// create and resolve ctor/dtor expression: fname(var, [cpArg])
107                        Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
108                        /// true if type does not need to be copy constructed to ensure correctness
109                        bool skipCopyConstruct( Type * type );
110                        void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
111                        void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
112
113                        TypeSubstitution * env;
114                        const EnvMap & envMap;
115                        UnqCount & unqCount; // count the number of times each unique expr ID appears
116                };
117
118                /// collects constructed object decls - used as a base class
119                class ObjDeclCollector : public AddStmtVisitor {
120                  public:
121                        typedef AddStmtVisitor Parent;
122                        using Parent::visit;
123                        // use ordered data structure to maintain ordering for set_difference and for consistent error messages
124                        typedef std::list< ObjectDecl * > ObjectSet;
125                        virtual void visit( CompoundStmt *compoundStmt ) override;
126                        virtual void visit( DeclStmt *stmt ) override;
127
128                        // don't go into other functions
129                        virtual void visit( __attribute__((unused)) FunctionDecl *decl ) override {}
130
131                  protected:
132                        ObjectSet curVars;
133                };
134
135                // debug
136                template<typename ObjectSet>
137                struct PrintSet {
138                        PrintSet( const ObjectSet & objs ) : objs( objs ) {}
139                        const ObjectSet & objs;
140                };
141                template<typename ObjectSet>
142                PrintSet<ObjectSet> printSet( const ObjectSet & objs ) { return PrintSet<ObjectSet>( objs ); }
143                template<typename ObjectSet>
144                std::ostream & operator<<( std::ostream & out, const PrintSet<ObjectSet> & set) {
145                        out << "{ ";
146                        for ( ObjectDecl * obj : set.objs ) {
147                                out << obj->get_name() << ", " ;
148                        } // for
149                        out << " }";
150                        return out;
151                }
152
153                class LabelFinder final : public ObjDeclCollector {
154                  public:
155                        typedef ObjDeclCollector Parent;
156                        typedef std::map< Label, ObjectSet > LabelMap;
157                        // map of Label -> live variables at that label
158                        LabelMap vars;
159
160                        void handleStmt( Statement * stmt );
161
162                        // xxx - This needs to be done better.
163                        // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
164                        // expressions, all statements, etc.)  important to have this to provide a single entry point so that as new
165                        // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
166                        // every specialized class knows about every new kind of statement that might be added.
167                        using Parent::visit;
168                        virtual void visit( CompoundStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
169                        virtual void visit( ExprStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
170                        virtual void visit( AsmStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
171                        virtual void visit( IfStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
172                        virtual void visit( WhileStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
173                        virtual void visit( ForStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
174                        virtual void visit( SwitchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
175                        virtual void visit( CaseStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
176                        virtual void visit( BranchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
177                        virtual void visit( ReturnStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
178                        virtual void visit( TryStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
179                        virtual void visit( CatchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
180                        virtual void visit( FinallyStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
181                        virtual void visit( NullStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
182                        virtual void visit( DeclStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
183                        virtual void visit( ImplicitCtorDtorStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
184                };
185
186                class InsertDtors final : public ObjDeclCollector {
187                public:
188                        /// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
189                        /// (currently by FixInit)
190                        static void insert( std::list< Declaration * > & translationUnit );
191
192                        typedef ObjDeclCollector Parent;
193                        typedef std::list< ObjectDecl * > OrderedDecls;
194                        typedef std::list< OrderedDecls > OrderedDeclsStack;
195
196                        InsertDtors( LabelFinder & finder ) : finder( finder ), labelVars( finder.vars ) {}
197
198                        using Parent::visit;
199
200                        virtual void visit( ObjectDecl * objDecl ) override;
201                        virtual void visit( FunctionDecl * funcDecl ) override;
202
203                        virtual void visit( CompoundStmt * compoundStmt ) override;
204                        virtual void visit( ReturnStmt * returnStmt ) override;
205                        virtual void visit( BranchStmt * stmt ) override;
206                private:
207                        void handleGoto( BranchStmt * stmt );
208
209                        LabelFinder & finder;
210                        LabelFinder::LabelMap & labelVars;
211                        OrderedDeclsStack reverseDeclOrder;
212                };
213
214                class FixInit : public WithStmtsToAdd {
215                  public:
216                        /// expand each object declaration to use its constructor after it is declared.
217                        static void fixInitializers( std::list< Declaration * > &translationUnit );
218
219                        DeclarationWithType * postmutate( ObjectDecl *objDecl );
220
221                        std::list< Declaration * > staticDtorDecls;
222                };
223
224                class FixCopyCtors final : public GenPoly::PolyMutator {
225                  public:
226                        FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){}
227                        /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
228                        /// and destructors
229                        static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount );
230
231                        typedef GenPoly::PolyMutator Parent;
232                        using Parent::mutate;
233                        virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
234                        virtual Expression * mutate( UniqueExpr * unqExpr ) override;
235                        virtual Expression * mutate( StmtExpr * stmtExpr ) override;
236
237                        UnqCount & unqCount;
238                };
239
240                class GenStructMemberCalls final : public SymTab::Indexer {
241                  public:
242                        typedef Indexer Parent;
243                        /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
244                        /// for any member that is missing a corresponding ctor/dtor call.
245                        /// error if a member is used before constructed
246                        static void generate( std::list< Declaration * > & translationUnit );
247
248                        using Parent::visit;
249
250                        virtual void visit( FunctionDecl * funcDecl ) override;
251
252                        virtual void visit( MemberExpr * memberExpr ) override;
253                        virtual void visit( ApplicationExpr * appExpr ) override;
254
255                        SemanticError errors;
256                  private:
257                        void handleFirstParam( Expression * firstParam );
258                        template< typename... Params >
259                        void emit( CodeLocation, const Params &... params );
260
261                        FunctionDecl * function = 0;
262                        std::set< DeclarationWithType * > unhandled;
263                        std::map< DeclarationWithType *, CodeLocation > usedUninit;
264                        ObjectDecl * thisParam = 0;
265                        bool isCtor = false; // true if current function is a constructor
266                        StructDecl * structDecl = 0;
267                };
268
269                // very simple resolver-like mutator class - used to
270                // resolve UntypedExprs that are found within newly
271                // generated constructor/destructor calls
272                class MutatingResolver final : public Mutator {
273                  public:
274                        MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
275
276                        using Mutator::mutate;
277                        virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override;
278                        virtual Expression* mutate( UntypedExpr *untypedExpr ) override;
279
280                  private:
281                        SymTab::Indexer & indexer;
282                };
283
284                class FixCtorExprs final : public GenPoly::DeclMutator {
285                  public:
286                        /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
287                        static void fix( std::list< Declaration * > & translationUnit );
288
289                        using GenPoly::DeclMutator::mutate;
290                        virtual Expression * mutate( ConstructorExpr * ctorExpr ) override;
291                };
292        } // namespace
293
294        void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
295                // fixes ConstructorInit for global variables. should happen before fixInitializers.
296                InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
297
298                EnvMap envMap;
299                UnqCount unqCount;
300
301                InsertImplicitCalls::insert( translationUnit, envMap );
302                ResolveCopyCtors::resolveImplicitCalls( translationUnit, envMap, unqCount );
303                InsertDtors::insert( translationUnit );
304                FixInit::fixInitializers( translationUnit );
305
306                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
307                FixCopyCtors::fixCopyCtors( translationUnit, unqCount );
308
309                GenStructMemberCalls::generate( translationUnit );
310                // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
311                // hack in the way untyped assignments are generated, where the first argument cannot have
312                // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
313                // Thus such assignment exprs must never pushed through expression resolution (and thus should
314                // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
315                // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
316                // don't look right, and a member can be constructed more than once.
317                FixCtorExprs::fix( translationUnit );
318        }
319
320        namespace {
321                void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit, EnvMap & envMap ) {
322                        PassVisitor<InsertImplicitCalls> inserter( envMap );
323                        mutateAll( translationUnit, inserter );
324                }
325
326                void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount ) {
327                        ResolveCopyCtors resolver( envMap, unqCount );
328                        acceptAll( translationUnit, resolver );
329                }
330
331                void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
332                        PassVisitor<FixInit> fixer;
333
334                        // can't use mutateAll, because need to insert declarations at top-level
335                        // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
336                        SemanticError errors;
337                        for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
338                                try {
339                                        *i = maybeMutate( *i, fixer );
340                                        translationUnit.splice( i, fixer.pass.staticDtorDecls );
341                                } catch( SemanticError &e ) {
342                                        e.set_location( (*i)->location );
343                                        errors.append( e );
344                                } // try
345                        } // for
346                        if ( ! errors.isEmpty() ) {
347                                throw errors;
348                        } // if
349                }
350
351                void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
352                        LabelFinder finder;
353                        InsertDtors inserter( finder );
354                        acceptAll( translationUnit, inserter );
355                }
356
357                void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
358                        FixCopyCtors fixer( unqCount );
359                        mutateAll( translationUnit, fixer );
360                }
361
362                void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
363                        GenStructMemberCalls warner;
364                        acceptAll( translationUnit, warner );
365                }
366
367                void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
368                        FixCtorExprs fixer;
369                        fixer.mutateDeclarationList( translationUnit );
370                }
371
372                Expression * InsertImplicitCalls::postmutate( ApplicationExpr * appExpr ) {
373                        assert( appExpr );
374
375                        if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
376                                if ( LinkageSpec::isBuiltin( function->get_var()->get_linkage() ) ) {
377                                        // optimization: don't need to copy construct in order to call intrinsic functions
378                                        return appExpr;
379                                } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
380                                        FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
381                                        assert( ftype );
382                                        if ( isConstructor( funcDecl->get_name() ) && ftype->get_parameters().size() == 2 ) {
383                                                Type * t1 = ftype->get_parameters().front()->get_type();
384                                                Type * t2 = ftype->get_parameters().back()->get_type();
385                                                PointerType * ptrType = safe_dynamic_cast< PointerType * > ( t1 );
386
387                                                if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
388                                                        // optimization: don't need to copy construct in order to call a copy constructor
389                                                        return appExpr;
390                                                } // if
391                                        } else if ( isDestructor( funcDecl->get_name() ) ) {
392                                                // correctness: never copy construct arguments to a destructor
393                                                return appExpr;
394                                        } // if
395                                } // if
396                        } // if
397                        CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
398
399                        // wrap each function call so that it is easy to identify nodes that have to be copy constructed
400                        ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
401                        // save the type substitution into the envMap so that it is easy to find.
402                        // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
403                        // The substitution is needed to obtain the type of temporary variables so that copy constructor
404                        // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
405                        // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
406                        // saves the environment, or compute the types of temporaries here, but it's much simpler to
407                        // save the environment here, and more cohesive to compute temporary variables and resolve copy
408                        // constructor calls together.
409                        assert( env );
410                        envMap[expr] = env;
411                        return expr;
412                }
413
414                void InsertImplicitCalls::premutate( StmtExpr * stmtExpr ) {
415                        assert( env );
416                        envMap[stmtExpr] = env;
417                }
418
419                bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
420                        return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type ) || Tuples::isTtype( type );
421                }
422
423                Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
424                        assert( var );
425                        // arrays are not copy constructed, so this should always be an ExprStmt
426                        ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg );
427                        ExprStmt * exprStmt = safe_dynamic_cast< ExprStmt * >( stmt->get_callStmt() );
428                        Expression * untyped = exprStmt->get_expr();
429
430                        // resolve copy constructor
431                        // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
432                        // (VariableExpr and already resolved expression)
433                        CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
434                        Expression * resolved = ResolvExpr::findVoidExpression( untyped, *this );
435                        assert( resolved );
436                        if ( resolved->get_env() ) {
437                                // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
438                                env->add( *resolved->get_env() );
439                                delete resolved->get_env();
440                                resolved->set_env( nullptr );
441                        } // if
442
443                        delete stmt;
444                        return resolved;
445                }
446
447                void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
448                        static UniqueName tempNamer("_tmp_cp");
449                        assert( env );
450                        CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
451                        assert( arg->has_result() );
452                        Type * result = arg->get_result();
453                        if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types
454
455                        // type may involve type variables, so apply type substitution to get temporary variable's actual type
456                        result = result->clone();
457                        env->apply( result );
458                        ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
459                        tmp->get_type()->set_const( false );
460
461                        // create and resolve copy constructor
462                        CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
463                        Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg );
464
465                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) {
466                                // if the chosen constructor is intrinsic, the copy is unnecessary, so
467                                // don't create the temporary and don't call the copy constructor
468                                VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
469                                assert( function );
470                                if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) return;
471                        }
472
473                        // replace argument to function call with temporary
474                        arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
475                        impCpCtorExpr->get_tempDecls().push_back( tmp );
476                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
477                }
478
479                void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
480                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
481                }
482
483                void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
484                        CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
485                        Parent::visit( impCpCtorExpr );
486                        env = envMap.at(impCpCtorExpr);
487                        assert( env );
488
489                        ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
490
491                        // take each argument and attempt to copy construct it.
492                        for ( Expression * & arg : appExpr->get_args() ) {
493                                copyConstructArg( arg, impCpCtorExpr );
494                        } // for
495
496                        // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
497                        // initialized with the return value and is destructed later
498                        // xxx - handle named return values?
499                        Type * result = appExpr->get_result();
500                        if ( ! result->isVoid() ) {
501                                static UniqueName retNamer("_tmp_cp_ret");
502                                result = result->clone();
503                                env->apply( result );
504                                ObjectDecl * ret = new ObjectDecl( retNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
505                                ret->get_type()->set_const( false );
506                                impCpCtorExpr->get_returnDecls().push_back( ret );
507                                CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
508                                if ( ! result->get_lvalue() ) {
509                                        // destructing lvalue returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
510                                        destructRet( ret, impCpCtorExpr );
511                                }
512                        } // for
513                        CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
514                }
515
516                void ResolveCopyCtors::visit( StmtExpr * stmtExpr ) {
517                        Parent::visit( stmtExpr );
518                        env = envMap.at(stmtExpr);
519                        assert( stmtExpr->get_result() );
520                        Type * result = stmtExpr->get_result();
521                        if ( ! result->isVoid() ) {
522                                static UniqueName retNamer("_tmp_stmtexpr_ret");
523
524                                // create variable that will hold the result of the stmt expr
525                                result = result->clone();
526                                env->apply( result );
527                                ObjectDecl * ret = new ObjectDecl( retNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
528                                ret->get_type()->set_const( false );
529                                stmtExpr->get_returnDecls().push_front( ret );
530
531                                // must have a non-empty body, otherwise it wouldn't have a result
532                                CompoundStmt * body = stmtExpr->get_statements();
533                                assert( ! body->get_kids().empty() );
534                                // must be an ExprStmt, otherwise it wouldn't have a result
535                                ExprStmt * last = safe_dynamic_cast< ExprStmt * >( body->get_kids().back() );
536                                last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) );
537
538                                stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
539                        } // if
540
541                }
542
543                void ResolveCopyCtors::visit( UniqueExpr * unqExpr ) {
544                        static std::unordered_set< int > vars;
545                        unqCount[ unqExpr->get_id() ]++;  // count the number of unique expressions for each ID
546                        if ( vars.count( unqExpr->get_id() ) ) {
547                                // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
548                                return;
549                        }
550
551                        Parent::visit( unqExpr );
552                        // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
553                        assert( unqExpr->get_result() );
554                        if ( ImplicitCopyCtorExpr * impCpCtorExpr = dynamic_cast<ImplicitCopyCtorExpr*>( unqExpr->get_expr() ) ) {
555                                // note the variable used as the result from the call
556                                assert( impCpCtorExpr->get_result() && impCpCtorExpr->get_returnDecls().size() == 1 );
557                                unqExpr->set_var( new VariableExpr( impCpCtorExpr->get_returnDecls().front() ) );
558                        } else {
559                                // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
560                                unqExpr->set_object( new ObjectDecl( toString("_unq", unqExpr->get_id()), Type::StorageClasses(), LinkageSpec::C, nullptr, unqExpr->get_result()->clone(), nullptr ) );
561                                unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) );
562                        }
563                        vars.insert( unqExpr->get_id() );
564                }
565
566                Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
567                        CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
568
569                        impCpCtorExpr = safe_dynamic_cast< ImplicitCopyCtorExpr * >( Parent::mutate( impCpCtorExpr ) );
570                        std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
571                        std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
572                        std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
573
574                        // add all temporary declarations and their constructors
575                        for ( ObjectDecl * obj : tempDecls ) {
576                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
577                        } // for
578                        for ( ObjectDecl * obj : returnDecls ) {
579                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
580                        } // for
581
582                        // add destructors after current statement
583                        for ( Expression * dtor : dtors ) {
584                                stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
585                        } // for
586
587                        // xxx - update to work with multiple return values
588                        ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
589                        Expression * callExpr = impCpCtorExpr->get_callExpr();
590
591                        CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
592
593                        // detach fields from wrapper node so that it can be deleted without deleting too much
594                        dtors.clear();
595                        tempDecls.clear();
596                        returnDecls.clear();
597                        impCpCtorExpr->set_callExpr( NULL );
598                        impCpCtorExpr->set_env( NULL );
599                        delete impCpCtorExpr;
600
601                        if ( returnDecl ) {
602                                UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
603                                assign->get_args().push_back( new VariableExpr( returnDecl ) );
604                                assign->get_args().push_back( callExpr );
605                                // know the result type of the assignment is the type of the LHS (minus the pointer), so
606                                // add that onto the assignment expression so that later steps have the necessary information
607                                assign->set_result( returnDecl->get_type()->clone() );
608
609                                Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
610                                if ( callExpr->get_result()->get_lvalue() ) {
611                                        // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
612                                        // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
613                                        // type of the return temporary from T to T* to properly capture the return value. Then dereference
614                                        // the result of the comma expression, since the lvalue returning call was originally wrapped with
615                                        // an AddressExpr.  Effectively, this turns
616                                        //   lvalue T f();
617                                        //   &*f();
618                                        // into
619                                        //   T * f();
620                                        //   T * tmp_cp_retN;
621                                        //   &*(tmp_cp_retN = &*f(), tmp_cp_retN);              // the first * and second & are generated here
622                                        // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
623                                        assign->get_args().back() = new AddressExpr( assign->get_args().back() );
624
625                                        returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
626                                        retExpr->set_result( new PointerType( Type::Qualifiers(), retExpr->get_result() ) );
627                                        retExpr = UntypedExpr::createDeref( retExpr );
628                                } // if
629                                // move env from callExpr to retExpr
630                                retExpr->set_env( callExpr->get_env() );
631                                callExpr->set_env( nullptr );
632                                return retExpr;
633                        } else {
634                                return callExpr;
635                        } // if
636                }
637
638                Expression * FixCopyCtors::mutate( StmtExpr * stmtExpr ) {
639                        // function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression,
640                        // since temporaries can be shared across sub-expressions, e.g.
641                        //   [A, A] f();
642                        //   g([A] x, [A] y);
643                        //   f(g());
644                        // f is executed once, so the return temporary is shared across the tuple constructors for x and y.
645                        std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
646                        for ( Statement *& stmt : stmts ) {
647                                stmt = stmt->acceptMutator( *this );
648                        } // for
649                        // stmtExpr = safe_dynamic_cast< StmtExpr * >( Parent::mutate( stmtExpr ) );
650                        assert( stmtExpr->get_result() );
651                        Type * result = stmtExpr->get_result();
652                        if ( ! result->isVoid() ) {
653                                for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) {
654                                        stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
655                                } // for
656                                // add destructors after current statement
657                                for ( Expression * dtor : stmtExpr->get_dtors() ) {
658                                        stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
659                                } // for
660                                // must have a non-empty body, otherwise it wouldn't have a result
661                                CompoundStmt * body = stmtExpr->get_statements();
662                                assert( ! body->get_kids().empty() );
663                                assert( ! stmtExpr->get_returnDecls().empty() );
664                                body->get_kids().push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) );
665                                stmtExpr->get_returnDecls().clear();
666                                stmtExpr->get_dtors().clear();
667                        }
668                        assert( stmtExpr->get_returnDecls().empty() );
669                        assert( stmtExpr->get_dtors().empty() );
670                        return stmtExpr;
671                }
672
673                Expression * FixCopyCtors::mutate( UniqueExpr * unqExpr ) {
674                        unqCount[ unqExpr->get_id() ]--;
675                        static std::unordered_map< int, std::list< Statement * > > dtors;
676                        static std::unordered_map< int, UniqueExpr * > unqMap;
677                        static std::unordered_set< int > addDeref;
678                        // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes
679                        if ( unqMap.count( unqExpr->get_id() ) ) {
680                                // take data from other UniqueExpr to ensure consistency
681                                delete unqExpr->get_expr();
682                                unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() );
683                                delete unqExpr->get_result();
684                                unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
685                                if ( unqCount[ unqExpr->get_id() ] == 0 ) {  // insert destructor after the last use of the unique expression
686                                        stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
687                                }
688                                if ( addDeref.count( unqExpr->get_id() ) ) {
689                                        // other UniqueExpr was dereferenced because it was an lvalue return, so this one should be too
690                                        return UntypedExpr::createDeref( unqExpr );
691                                }
692                                return unqExpr;
693                        }
694                        FixCopyCtors fixer( unqCount );
695                        unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
696                        stmtsToAdd.splice( stmtsToAdd.end(), fixer.stmtsToAdd );
697                        unqMap[unqExpr->get_id()] = unqExpr;
698                        if ( unqCount[ unqExpr->get_id() ] == 0 ) {  // insert destructor after the last use of the unique expression
699                                stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
700                        } else { // remember dtors for last instance of unique expr
701                                dtors[ unqExpr->get_id() ] = fixer.stmtsToAddAfter;
702                        }
703                        if ( UntypedExpr * deref = dynamic_cast< UntypedExpr * >( unqExpr->get_expr() ) ) {
704                                // unique expression is now a dereference, because the inner expression is an lvalue returning function call.
705                                // Normalize the expression by dereferencing the unique expression, rather than the inner expression
706                                // (i.e. move the dereference out a level)
707                                assert( getFunctionName( deref ) == "*?" );
708                                unqExpr->set_expr( getCallArg( deref, 0 ) );
709                                getCallArg( deref, 0 ) = unqExpr;
710                                addDeref.insert( unqExpr->get_id() );
711                                return deref;
712                        }
713                        return unqExpr;
714                }
715
716                DeclarationWithType *FixInit::postmutate( ObjectDecl *objDecl ) {
717                        // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postmutate)
718                        if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
719                                // a decision should have been made by the resolver, so ctor and init are not both non-NULL
720                                assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
721                                if ( Statement * ctor = ctorInit->get_ctor() ) {
722                                        if ( objDecl->get_storageClasses().is_static ) {
723                                                // originally wanted to take advantage of gcc nested functions, but
724                                                // we get memory errors with this approach. To remedy this, the static
725                                                // variable is hoisted when the destructor needs to be called.
726                                                //
727                                                // generate:
728                                                // static T __objName_static_varN;
729                                                // void __objName_dtor_atexitN() {
730                                                //   __dtor__...;
731                                                // }
732                                                // int f(...) {
733                                                //   ...
734                                                //   static bool __objName_uninitialized = true;
735                                                //   if (__objName_uninitialized) {
736                                                //     __ctor(__objName);
737                                                //     __objName_uninitialized = false;
738                                                //     atexit(__objName_dtor_atexitN);
739                                                //   }
740                                                //   ...
741                                                // }
742
743                                                static UniqueName dtorCallerNamer( "_dtor_atexit" );
744
745                                                // static bool __objName_uninitialized = true
746                                                BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
747                                                SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant::from_int( 1 ) ) );
748                                                ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr );
749                                                isUninitializedVar->fixUniqueId();
750
751                                                // __objName_uninitialized = false;
752                                                UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
753                                                setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
754                                                setTrue->get_args().push_back( new ConstantExpr( Constant::from_int( 0 ) ) );
755
756                                                // generate body of if
757                                                CompoundStmt * initStmts = new CompoundStmt( noLabels );
758                                                std::list< Statement * > & body = initStmts->get_kids();
759                                                body.push_back( ctor );
760                                                body.push_back( new ExprStmt( noLabels, setTrue ) );
761
762                                                // put it all together
763                                                IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
764                                                stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
765                                                stmtsToAddAfter.push_back( ifStmt );
766
767                                                Statement * dtor = ctorInit->get_dtor();
768                                                objDecl->set_init( nullptr );
769                                                ctorInit->set_ctor( nullptr );
770                                                ctorInit->set_dtor( nullptr );
771                                                if ( dtor ) {
772                                                        // if the object has a non-trivial destructor, have to
773                                                        // hoist it and the object into the global space and
774                                                        // call the destructor function with atexit.
775
776                                                        Statement * dtorStmt = dtor->clone();
777
778                                                        // void __objName_dtor_atexitN(...) {...}
779                                                        FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) );
780                                                        dtorCaller->fixUniqueId();
781                                                        dtorCaller->get_statements()->push_back( dtorStmt );
782
783                                                        // atexit(dtor_atexit);
784                                                        UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
785                                                        callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
786
787                                                        body.push_back( new ExprStmt( noLabels, callAtexit ) );
788
789                                                        // hoist variable and dtor caller decls to list of decls that will be added into global scope
790                                                        staticDtorDecls.push_back( objDecl );
791                                                        staticDtorDecls.push_back( dtorCaller );
792
793                                                        // need to rename object uniquely since it now appears
794                                                        // at global scope and there could be multiple function-scoped
795                                                        // static variables with the same name in different functions.
796                                                        // Note: it isn't sufficient to modify only the mangleName, because
797                                                        // then subsequent Indexer passes can choke on seeing the object's name
798                                                        // if another object has the same name and type. An unfortunate side-effect
799                                                        // of renaming the object is that subsequent NameExprs may fail to resolve,
800                                                        // but there shouldn't be any remaining past this point.
801                                                        static UniqueName staticNamer( "_static_var" );
802                                                        objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
803                                                        objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
804
805                                                        // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
806                                                        // create a new object which is never used
807                                                        static UniqueName dummyNamer( "_dummy" );
808                                                        ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
809                                                        delete ctorInit;
810                                                        return dummy;
811                                                }
812                                        } else {
813                                                ImplicitCtorDtorStmt * implicit = safe_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor );
814                                                ExprStmt * ctorStmt = dynamic_cast< ExprStmt * >( implicit->get_callStmt() );
815                                                ApplicationExpr * ctorCall = nullptr;
816                                                if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->get_expr() )) && ctorCall->get_args().size() == 2 ) {
817                                                        // clean up intrinsic copy constructor calls by making them into SingleInits
818                                                        objDecl->set_init( new SingleInit( ctorCall->get_args().back() ) );
819                                                        ctorCall->get_args().pop_back();
820                                                } else {
821                                                        stmtsToAddAfter.push_back( ctor );
822                                                        objDecl->set_init( nullptr );
823                                                        ctorInit->set_ctor( nullptr );
824                                                }
825                                        } // if
826                                } else if ( Initializer * init = ctorInit->get_init() ) {
827                                        objDecl->set_init( init );
828                                        ctorInit->set_init( nullptr );
829                                } else {
830                                        // no constructor and no initializer, which is okay
831                                        objDecl->set_init( nullptr );
832                                } // if
833                                delete ctorInit;
834                        } // if
835                        return objDecl;
836                }
837
838                void ObjDeclCollector::visit( CompoundStmt * compoundStmt ) {
839                        ObjectSet prevVars = curVars;
840                        Parent::visit( compoundStmt );
841                        curVars = prevVars;
842                }
843
844                void ObjDeclCollector::visit( DeclStmt * stmt ) {
845                        // keep track of all variables currently in scope
846                        if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
847                                curVars.push_back( objDecl );
848                        } // if
849                        Parent::visit( stmt );
850                }
851
852                void LabelFinder::handleStmt( Statement * stmt ) {
853                        // for each label, remember the variables in scope at that label.
854                        for ( Label l : stmt->get_labels() ) {
855                                vars[l] = curVars;
856                        } // for
857                }
858
859                template<typename Iterator, typename OutputIterator>
860                void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
861                        for ( Iterator it = begin ; it != end ; ++it ) {
862                                // extract destructor statement from the object decl and insert it into the output. Note that this is
863                                // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
864                                // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
865                                // contain side effects.
866                                ObjectDecl * objDecl = *it;
867                                ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
868                                assert( ctorInit && ctorInit->get_dtor() );
869                                *out++ = ctorInit->get_dtor()->clone();
870                        } // for
871                }
872
873                void InsertDtors::visit( ObjectDecl * objDecl ) {
874                        // remember non-static destructed objects so that their destructors can be inserted later
875                        if ( ! objDecl->get_storageClasses().is_static ) {
876                                if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
877                                        // a decision should have been made by the resolver, so ctor and init are not both non-NULL
878                                        assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
879                                        Statement * dtor = ctorInit->get_dtor();
880                                        if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
881                                                // don't need to call intrinsic dtor, because it does nothing, but
882                                                // non-intrinsic dtors must be called
883                                                reverseDeclOrder.front().push_front( objDecl );
884                                        } // if
885                                } // if
886                        } // if
887                        Parent::visit( objDecl );
888                }
889
890                template< typename Visitor >
891                void handleFuncDecl( FunctionDecl * funcDecl, Visitor & visitor ) {
892                        maybeAccept( funcDecl->get_functionType(), visitor );
893                        maybeAccept( funcDecl->get_statements(), visitor );
894                }
895
896                void InsertDtors::visit( FunctionDecl * funcDecl ) {
897                        // each function needs to have its own set of labels
898                        ValueGuard< LabelFinder::LabelMap > oldLabels( labelVars );
899                        labelVars.clear();
900                        handleFuncDecl( funcDecl, finder );
901
902                        // all labels for this function have been collected, insert destructors as appropriate.
903                        // can't be Parent::mutate, because ObjDeclCollector bottoms out on FunctionDecl
904                        handleFuncDecl( funcDecl, *this );
905                }
906
907                void InsertDtors::visit( CompoundStmt * compoundStmt ) {
908                        // visit statements - this will also populate reverseDeclOrder list.  don't want to dump all destructors
909                        // when block is left, just the destructors associated with variables defined in this block, so push a new
910                        // list to the top of the stack so that we can differentiate scopes
911                        reverseDeclOrder.push_front( OrderedDecls() );
912                        Parent::visit( compoundStmt );
913
914                        // add destructors for the current scope that we're exiting, unless the last statement is a return, which
915                        // causes unreachable code warnings
916                        std::list< Statement * > & statements = compoundStmt->get_kids();
917                        if ( ! statements.empty() && ! dynamic_cast< ReturnStmt * >( statements.back() ) ) {
918                                insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
919                        }
920                        reverseDeclOrder.pop_front();
921                }
922
923                void InsertDtors::visit( __attribute((unused)) ReturnStmt * returnStmt ) {
924                        // return exits all scopes, so dump destructors for all scopes
925                        for ( OrderedDecls & od : reverseDeclOrder ) {
926                                insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
927                        } // for
928                }
929
930                // Handle break/continue/goto in the same manner as C++.  Basic idea: any objects that are in scope at the
931                // BranchStmt but not at the labelled (target) statement must be destructed.  If there are any objects in scope
932                // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
933                // of the error.  See C++ Reference 6.6 Jump Statements for details.
934                void InsertDtors::handleGoto( BranchStmt * stmt ) {
935                        assert( stmt->get_target() != "" && "BranchStmt missing a label" );
936                        // S_L = lvars = set of objects in scope at label definition
937                        // S_G = curVars = set of objects in scope at goto statement
938                        ObjectSet & lvars = labelVars[ stmt->get_target() ];
939
940                        DTOR_PRINT(
941                                std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
942                                std::cerr << "S_G = " << printSet( curVars ) << std::endl;
943                                std::cerr << "S_L = " << printSet( lvars ) << std::endl;
944                        )
945
946                        ObjectSet diff;
947                        // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
948                        std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
949                        DTOR_PRINT(
950                                std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
951                        )
952                        if ( ! diff.empty() ) {
953                                throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
954                        } // if
955                        // S_G-S_L results in set of objects that must be destructed
956                        diff.clear();
957                        std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
958                        DTOR_PRINT(
959                                std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
960                        )
961                        if ( ! diff.empty() ) {
962                                // create an auxilliary set for fast lookup -- can't make diff a set, because diff ordering should be consistent for error messages.
963                                std::unordered_set<ObjectDecl *> needsDestructor( diff.begin(), diff.end() );
964
965                                // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
966                                OrderedDecls ordered;
967                                for ( OrderedDecls & rdo : reverseDeclOrder ) {
968                                        // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
969                                        copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return needsDestructor.count( objDecl ); } );
970                                } // for
971                                insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
972                        } // if
973                }
974
975                void InsertDtors::visit( BranchStmt * stmt ) {
976                        switch( stmt->get_type() ) {
977                          case BranchStmt::Continue:
978                          case BranchStmt::Break:
979                                // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
980                                // always be empty), but it serves as a small sanity check.
981                          case BranchStmt::Goto:
982                                handleGoto( stmt );
983                                break;
984                          default:
985                                assert( false );
986                        } // switch
987                }
988
989                bool checkWarnings( FunctionDecl * funcDecl ) {
990                        // only check for warnings if the current function is a user-defined
991                        // constructor or destructor
992                        if ( ! funcDecl ) return false;
993                        if ( ! funcDecl->get_statements() ) return false;
994                        return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
995                }
996
997                void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
998                        ValueGuard< FunctionDecl * > oldFunction( funcDecl );
999                        ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
1000                        ValueGuard< std::map< DeclarationWithType *, CodeLocation > > oldUsedUninit( usedUninit );
1001                        ValueGuard< ObjectDecl * > oldThisParam( thisParam );
1002                        ValueGuard< bool > oldIsCtor( isCtor );
1003                        ValueGuard< StructDecl * > oldStructDecl( structDecl );
1004                        errors = SemanticError();  // clear previous errors
1005
1006                        // need to start with fresh sets
1007                        unhandled.clear();
1008                        usedUninit.clear();
1009
1010                        function = funcDecl;
1011                        isCtor = isConstructor( function->get_name() );
1012                        if ( checkWarnings( function ) ) {
1013                                FunctionType * type = function->get_functionType();
1014                                assert( ! type->get_parameters().empty() );
1015                                thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
1016                                PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
1017                                StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
1018                                if ( structType ) {
1019                                        structDecl = structType->get_baseStruct();
1020                                        for ( Declaration * member : structDecl->get_members() ) {
1021                                                if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
1022                                                        // record all of the struct type's members that need to be constructed or
1023                                                        // destructed by the end of the function
1024                                                        unhandled.insert( field );
1025                                                }
1026                                        }
1027                                }
1028                        }
1029                        Parent::visit( function );
1030
1031                        // remove the unhandled objects from usedUninit, because a call is inserted
1032                        // to handle them - only objects that are later constructed are used uninitialized.
1033                        std::map< DeclarationWithType *, CodeLocation > diff;
1034                        // need the comparator since usedUninit and unhandled have different types
1035                        struct comp_t {
1036                                typedef decltype(usedUninit)::value_type usedUninit_t;
1037                                typedef decltype(unhandled)::value_type unhandled_t;
1038                                bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
1039                                bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
1040                        } comp;
1041                        std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
1042                        for ( auto p : diff ) {
1043                                DeclarationWithType * member = p.first;
1044                                CodeLocation loc = p.second;
1045                                // xxx - make error message better by also tracking the location that the object is constructed at?
1046                                emit( loc, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", member->get_name(), " used before being constructed" );
1047                        }
1048
1049                        if ( ! unhandled.empty() ) {
1050                                // need to explicitly re-add function parameters in order to resolve copy constructors
1051                                enterScope();
1052                                maybeAccept( function->get_functionType(), *this );
1053
1054                                // need to iterate through members in reverse in order for
1055                                // ctor/dtor statements to come out in the right order
1056                                for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
1057                                        DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
1058                                        // skip non-DWT members
1059                                        if ( ! field ) continue;
1060                                        // skip handled members
1061                                        if ( ! unhandled.count( field ) ) continue;
1062
1063                                        // insert and resolve default/copy constructor call for each field that's unhandled
1064                                        std::list< Statement * > stmt;
1065                                        UntypedExpr * deref = UntypedExpr::createDeref( new VariableExpr( thisParam ) );
1066
1067                                        Expression * arg2 = 0;
1068                                        if ( isCopyConstructor( function ) ) {
1069                                                // if copy ctor, need to pass second-param-of-this-function.field
1070                                                std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
1071                                                assert( params.size() == 2 );
1072                                                arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
1073                                        }
1074                                        InitExpander srcParam( arg2 );
1075                                        SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
1076
1077                                        assert( stmt.size() <= 1 );
1078                                        if ( stmt.size() == 1 ) {
1079                                                Statement * callStmt = stmt.front();
1080
1081                                                MutatingResolver resolver( *this );
1082                                                try {
1083                                                        callStmt->acceptMutator( resolver );
1084                                                        if ( isCtor ) {
1085                                                                function->get_statements()->push_front( callStmt );
1086                                                        } else {
1087                                                                // destructor statements should be added at the end
1088                                                                function->get_statements()->push_back( callStmt );
1089                                                        }
1090                                                } catch ( SemanticError & error ) {
1091                                                        emit( funcDecl->location, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed",  " and no ", isCtor ? "default constructor" : "destructor", " found" );
1092                                                }
1093                                        }
1094                                }
1095                                leaveScope();
1096                        }
1097                        if (! errors.isEmpty()) {
1098                                throw errors;
1099                        }
1100                }
1101
1102                void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
1103                        if ( ! checkWarnings( function ) ) return;
1104
1105                        std::string fname = getFunctionName( appExpr );
1106                        if ( fname == function->get_name() ) {
1107                                // call to same kind of function
1108                                Expression * firstParam = appExpr->get_args().front();
1109
1110                                if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
1111                                        // if calling another constructor on thisParam, assume that function handles
1112                                        // all members - if it doesn't a warning will appear in that function.
1113                                        if ( varExpr->get_var() == thisParam ) {
1114                                                unhandled.clear();
1115                                        }
1116                                } else {
1117                                        // if first parameter is a member expression then
1118                                        // remove the member from unhandled set.
1119                                        handleFirstParam( firstParam );
1120                                }
1121                        }
1122
1123                        Parent::visit( appExpr );
1124                }
1125
1126                void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
1127                        using namespace std;
1128                        if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
1129                                if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
1130                                        if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1131                                                if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1132                                                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1133                                                                if ( varExpr->get_var() == thisParam ) {
1134                                                                        unhandled.erase( memberExpr->get_member() );
1135                                                                }
1136                                                        }
1137                                                }
1138                                        }
1139                                }
1140                        }
1141                }
1142
1143                void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
1144                        if ( ! checkWarnings( function ) ) return;
1145                        if ( ! isCtor ) return;
1146
1147                        if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1148                                if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1149                                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1150                                                if ( varExpr->get_var() == thisParam ) {
1151                                                        if ( unhandled.count( memberExpr->get_member() ) ) {
1152                                                                // emit a warning because a member was used before it was constructed
1153                                                                usedUninit.insert( { memberExpr->get_member(), memberExpr->location } );
1154                                                        }
1155                                                }
1156                                        }
1157                                }
1158                        }
1159                        Parent::visit( memberExpr );
1160                }
1161
1162                template< typename Visitor, typename... Params >
1163                void error( Visitor & v, CodeLocation loc, const Params &... params ) {
1164                        SemanticError err( toString( params... ) );
1165                        err.set_location( loc );
1166                        v.errors.append( err );
1167                }
1168
1169                template< typename... Params >
1170                void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
1171                        // toggle warnings vs. errors here.
1172                        // warn( params... );
1173                        error( *this, loc, params... );
1174                }
1175
1176                DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
1177                        // add object to the indexer assumes that there will be no name collisions
1178                        // in generated code. If this changes, add mutate methods for entities with
1179                        // scope and call {enter,leave}Scope explicitly.
1180                        objectDecl->accept( indexer );
1181                        return objectDecl;
1182                }
1183
1184                Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
1185                        return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
1186                }
1187
1188                Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
1189                        static UniqueName tempNamer( "_tmp_ctor_expr" );
1190                        // xxx - is the size check necessary?
1191                        assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
1192
1193                        // xxx - ideally we would reuse the temporary generated from the copy constructor passes from within firstArg if it exists and not generate a temporary if it's unnecessary.
1194                        ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
1195                        addDeclaration( tmp );
1196
1197                        // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
1198                        ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
1199                        TypeSubstitution * env = ctorExpr->get_env();
1200                        ctorExpr->set_callExpr( nullptr );
1201                        ctorExpr->set_env( nullptr );
1202
1203                        Expression *& firstArg = callExpr->get_args().front();
1204                        UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
1205                        assign->get_args().push_back( new VariableExpr( tmp ) );
1206                        assign->get_args().push_back( firstArg );
1207                        assign->set_result( ctorExpr->get_result()->clone() );
1208                        firstArg = assign;
1209
1210                        CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
1211                        commaExpr->set_env( env );
1212                        delete ctorExpr;
1213                        return commaExpr;
1214                }
1215        } // namespace
1216} // namespace InitTweak
1217
1218// Local Variables: //
1219// tab-width: 4 //
1220// mode: c++ //
1221// compile-command: "make install" //
1222// End: //
Note: See TracBrowser for help on using the repository browser.