source: src/InitTweak/FixInit.cc @ 381bea6

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

Merge branch 'master' into cleanup-dtors

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