source: src/InitTweak/FixInit.cc @ 7c40a24

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

Convert Box Pass3 to PassVisitor?

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