source: src/InitTweak/FixInit.cc @ 8a6cf7e

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 8a6cf7e was 8a6cf7e, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Fix various reference features.

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