source: src/InitTweak/FixInitNew.cpp @ b29a1e8

Last change on this file since b29a1e8 was b29a1e8, checked in by Andrew Beach <ajbeach@…>, 11 months ago

Removed unused includes from a file. (Clean-up, plus it cuts down on code that might be the problem in that pass.)

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