source: src/InitTweak/FixInit.cpp @ ca9d65e

Last change on this file since ca9d65e was ca9d65e, checked in by Peter A. Buhr <pabuhr@…>, 5 months ago

second attempt at simplifying SemanticError? messages

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