source: src/InitTweak/FixInit.cc @ 80ac42d

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 80ac42d was 698ec72, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Convert InsertDtors? to PassVisitor?

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