source: src/InitTweak/FixInit.cc @ 96fc67b

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 96fc67b was 96fc67b, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Replace variable in array destructor with dereference

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