source: src/InitTweak/FixInitNew.cpp @ 080d2d7

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 080d2d7 was 39d8950, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Thread global information through resolution. Non-top-level calls to the resolver have a bit of a hack but improvements would require changes to the Pass helpers.

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