source: src/InitTweak/FixInit.cc @ 92b3de1

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

Convert AutogenTupleRoutines? to PassVisitor?

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