source: src/InitTweak/FixInitNew.cpp @ c36a419

Last change on this file since c36a419 was 0bd3faf, checked in by Andrew Beach <ajbeach@…>, 8 months ago

Removed forward declarations missed in the BaseSyntaxNode? removal. Removed code and modified names to support two versions of the ast.

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