source: src/InitTweak/FixInit.cc@ d48e529

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since d48e529 was 698ec72, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Convert InsertDtors to PassVisitor

  • Property mode set to 100644
File size: 52.8 KB
RevLine 
[71f4e4f]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
[adcc065]11// Last Modified By : Peter A. Buhr
[d56e5bc]12// Last Modified On : Wed Jun 21 17:35:05 2017
13// Update Count : 74
[71f4e4f]14//
[be9288a]15#include "FixInit.h"
[71f4e4f]16
[d180746]17#include <stddef.h> // for NULL
18#include <algorithm> // for set_difference, copy_if
[e3e16bc]19#include <cassert> // for assert, strict_dynamic_cast
[d180746]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
[134322e]29
[d180746]30#include "CodeGen/GenType.h" // for genPrettyType
[bff227f]31#include "CodeGen/OperatorTable.h"
[d180746]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
[71f4e4f]61
[f0121d7]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
[845cedc]66#define PRINT( text ) if ( ctordtorp ) { text }
[c2931ea]67#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
68#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
[845cedc]69
[71f4e4f]70namespace InitTweak {
71 namespace {
[597db97f]72 typedef std::unordered_map< int, int > UnqCount;
[31f379c]73
[c0714bf]74 struct InsertImplicitCalls : public WithTypeSubstitution {
[adcc065]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
[c0714bf]77 static void insert( std::list< Declaration * > & translationUnit );
[134322e]78
79 Expression * postmutate( ApplicationExpr * appExpr );
[c2931ea]80 };
81
[c0714bf]82 struct ResolveCopyCtors final : public WithIndexer, public WithShortCircuiting, public WithTypeSubstitution {
[adcc065]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
[c0714bf]86 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount );
[c2931ea]87
[c0714bf]88 ResolveCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ) {}
[31f379c]89
[c0714bf]90 void postvisit( ImplicitCopyCtorExpr * impCpCtorExpr );
91 void postvisit( StmtExpr * stmtExpr );
92 void previsit( UniqueExpr * unqExpr );
93 void postvisit( UniqueExpr * unqExpr );
[c2931ea]94
95 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
[65660bd]96 Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
[c2931ea]97 /// true if type does not need to be copy constructed to ensure correctness
[1132b62]98 bool skipCopyConstruct( Type * type );
99 void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
[092528b]100 void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
[31f379c]101
[597db97f]102 UnqCount & unqCount; // count the number of times each unique expr ID appears
[c0714bf]103 std::unordered_set< int > vars;
[c2931ea]104 };
105
106 /// collects constructed object decls - used as a base class
[698ec72]107 struct ObjDeclCollector : public WithGuards, public WithShortCircuiting {
[62423350]108 // use ordered data structure to maintain ordering for set_difference and for consistent error messages
109 typedef std::list< ObjectDecl * > ObjectSet;
[698ec72]110 void previsit( CompoundStmt *compoundStmt );
111 void previsit( DeclStmt *stmt );
[52c14b3]112
113 // don't go into other functions
[698ec72]114 void previsit( FunctionDecl * ) { visit_children = false; }
[52c14b3]115
[c2931ea]116 protected:
117 ObjectSet curVars;
118 };
119
[6cf27a07]120 // debug
[62423350]121 template<typename ObjectSet>
122 struct PrintSet {
123 PrintSet( const ObjectSet & objs ) : objs( objs ) {}
[c2931ea]124 const ObjectSet & objs;
125 };
[62423350]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) {
[c2931ea]130 out << "{ ";
131 for ( ObjectDecl * obj : set.objs ) {
132 out << obj->get_name() << ", " ;
[adcc065]133 } // for
[c2931ea]134 out << " }";
135 return out;
136 }
137
[698ec72]138 struct LabelFinder final : public ObjDeclCollector {
[c2931ea]139 typedef std::map< Label, ObjectSet > LabelMap;
140 // map of Label -> live variables at that label
141 LabelMap vars;
142
[698ec72]143 typedef ObjDeclCollector Parent;
144 using Parent::previsit;
145 void previsit( Statement * stmt );
146
147 void previsit( CompoundStmt *compoundStmt );
148 void previsit( DeclStmt *stmt );
[c2931ea]149 };
150
[698ec72]151 struct InsertDtors final : public ObjDeclCollector, public WithStmtsToAdd {
[adcc065]152 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
153 /// (currently by FixInit)
[c2931ea]154 static void insert( std::list< Declaration * > & translationUnit );
155
156 typedef std::list< ObjectDecl * > OrderedDecls;
157 typedef std::list< OrderedDecls > OrderedDeclsStack;
158
[698ec72]159 InsertDtors( PassVisitor<LabelFinder> & finder ) : finder( finder ), labelVars( finder.pass.vars ) {}
[c2931ea]160
[698ec72]161 typedef ObjDeclCollector Parent;
162 using Parent::previsit;
[62e5546]163
[698ec72]164 void previsit( ObjectDecl * objDecl );
165 void previsit( FunctionDecl * funcDecl );
[c2931ea]166
[698ec72]167 void previsit( CompoundStmt * compoundStmt );
168 void postvisit( CompoundStmt * compoundStmt );
169 void previsit( ReturnStmt * returnStmt );
170 void previsit( BranchStmt * stmt );
[c2931ea]171 private:
172 void handleGoto( BranchStmt * stmt );
173
[698ec72]174 PassVisitor<LabelFinder> & finder;
[c2931ea]175 LabelFinder::LabelMap & labelVars;
176 OrderedDeclsStack reverseDeclOrder;
177 };
178
[0508ab3]179 class FixInit : public WithStmtsToAdd {
[c2931ea]180 public:
181 /// expand each object declaration to use its constructor after it is declared.
182 static void fixInitializers( std::list< Declaration * > &translationUnit );
183
[aff3af4]184 DeclarationWithType * postmutate( ObjectDecl *objDecl );
[72e9222]185
186 std::list< Declaration * > staticDtorDecls;
[c2931ea]187 };
188
[62e5546]189 class FixCopyCtors final : public GenPoly::PolyMutator {
[c2931ea]190 public:
[597db97f]191 FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){}
[adcc065]192 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
193 /// and destructors
[597db97f]194 static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount );
[c2931ea]195
[31f379c]196 typedef GenPoly::PolyMutator Parent;
197 using Parent::mutate;
[62e5546]198 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
[b726084]199 virtual Expression * mutate( UniqueExpr * unqExpr ) override;
[31f379c]200 virtual Expression * mutate( StmtExpr * stmtExpr ) override;
[597db97f]201
202 UnqCount & unqCount;
[c2931ea]203 };
[79970ed]204
[9a707e4e]205 struct GenStructMemberCalls final : public WithGuards, public WithShortCircuiting, public WithIndexer {
[c8dfcd3]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 );
[79970ed]210
[9a707e4e]211 void previsit( FunctionDecl * funcDecl );
212 void postvisit( FunctionDecl * funcDecl );
[79970ed]213
[9a707e4e]214 void previsit( MemberExpr * memberExpr );
215 void previsit( ApplicationExpr * appExpr );
[79970ed]216
[3906301]217 SemanticError errors;
[79970ed]218 private:
[3906301]219 template< typename... Params >
[64ac636]220 void emit( CodeLocation, const Params &... params );
[79970ed]221
222 FunctionDecl * function = 0;
[64ac636]223 std::set< DeclarationWithType * > unhandled;
224 std::map< DeclarationWithType *, CodeLocation > usedUninit;
[79970ed]225 ObjectDecl * thisParam = 0;
[c8dfcd3]226 bool isCtor = false; // true if current function is a constructor
[44f6341]227 StructDecl * structDecl = 0;
[c8dfcd3]228 };
229
230 // very simple resolver-like mutator class - used to
231 // resolve UntypedExprs that are found within newly
232 // generated constructor/destructor calls
[62e5546]233 class MutatingResolver final : public Mutator {
[c8dfcd3]234 public:
235 MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
236
[62e5546]237 using Mutator::mutate;
238 virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override;
239 virtual Expression* mutate( UntypedExpr *untypedExpr ) override;
[c8dfcd3]240
[62e5546]241 private:
[c8dfcd3]242 SymTab::Indexer & indexer;
[79970ed]243 };
[b6fe7e6]244
[62e5546]245 class FixCtorExprs final : public GenPoly::DeclMutator {
[b6fe7e6]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
[62e5546]250 using GenPoly::DeclMutator::mutate;
251 virtual Expression * mutate( ConstructorExpr * ctorExpr ) override;
[b6fe7e6]252 };
[c2931ea]253 } // namespace
[db4ecc5]254
[6cf27a07]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
[597db97f]259 UnqCount unqCount;
[b6fe7e6]260
[c0714bf]261 InsertImplicitCalls::insert( translationUnit );
262 ResolveCopyCtors::resolveImplicitCalls( translationUnit, unqCount );
[c2931ea]263 InsertDtors::insert( translationUnit );
[71f4e4f]264 FixInit::fixInitializers( translationUnit );
[c2931ea]265
[db4ecc5]266 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
[597db97f]267 FixCopyCtors::fixCopyCtors( translationUnit, unqCount );
[79970ed]268
[c8dfcd3]269 GenStructMemberCalls::generate( translationUnit );
[b6fe7e6]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 );
[db4ecc5]278 }
279
[c2931ea]280 namespace {
[c0714bf]281 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
282 PassVisitor<InsertImplicitCalls> inserter;
[c2931ea]283 mutateAll( translationUnit, inserter );
284 }
[db4ecc5]285
[c0714bf]286 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
287 PassVisitor<ResolveCopyCtors> resolver( unqCount );
[c2931ea]288 acceptAll( translationUnit, resolver );
289 }
[71f4e4f]290
[c2931ea]291 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
[aff3af4]292 PassVisitor<FixInit> fixer;
[72e9222]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 );
[aff3af4]300 translationUnit.splice( i, fixer.pass.staticDtorDecls );
[72e9222]301 } catch( SemanticError &e ) {
[138e29e]302 e.set_location( (*i)->location );
[72e9222]303 errors.append( e );
304 } // try
305 } // for
306 if ( ! errors.isEmpty() ) {
307 throw errors;
308 } // if
[c2931ea]309 }
[71f4e4f]310
[c2931ea]311 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
[698ec72]312 PassVisitor<LabelFinder> finder;
313 PassVisitor<InsertDtors> inserter( finder );
[c2931ea]314 acceptAll( translationUnit, inserter );
315 }
316
[597db97f]317 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
318 FixCopyCtors fixer( unqCount );
[c2931ea]319 mutateAll( translationUnit, fixer );
320 }
[db4ecc5]321
[c8dfcd3]322 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
[9a707e4e]323 PassVisitor<GenStructMemberCalls> warner;
[c8dfcd3]324 acceptAll( translationUnit, warner );
[79970ed]325 }
326
[b6fe7e6]327 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
328 FixCtorExprs fixer;
329 fixer.mutateDeclarationList( translationUnit );
330 }
331
[134322e]332 Expression * InsertImplicitCalls::postmutate( ApplicationExpr * appExpr ) {
[c2931ea]333 assert( appExpr );
334
335 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
[9a063c8]336 if ( LinkageSpec::isBuiltin( function->get_var()->get_linkage() ) ) {
[c2931ea]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 );
[bff227f]342 if ( CodeGen::isConstructor( funcDecl->get_name() ) && ftype->get_parameters().size() == 2 ) {
[0a81c3f]343 Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
[c2931ea]344 Type * t2 = ftype->get_parameters().back()->get_type();
[0a81c3f]345 assert( t1 );
[c2931ea]346
[0a81c3f]347 if ( ResolvExpr::typesCompatible( t1, t2, SymTab::Indexer() ) ) {
[a28bc02]348 // optimization: don't need to copy construct in order to call a copy constructor
[c2931ea]349 return appExpr;
[adcc065]350 } // if
[bff227f]351 } else if ( CodeGen::isDestructor( funcDecl->get_name() ) ) {
[c2931ea]352 // correctness: never copy construct arguments to a destructor
[845cedc]353 return appExpr;
[adcc065]354 } // if
355 } // if
356 } // if
[c2931ea]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 );
[c0714bf]361 // Move the type substitution to the new top-level, if it is attached to the appExpr.
[c2931ea]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
[c0714bf]364 // calls can be resolved.
[c2931ea]365 assert( env );
[c0714bf]366 std::swap( expr->env, appExpr->env );
[c2931ea]367 return expr;
[db4ecc5]368 }
369
[c2931ea]370 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
[ce8c12f]371 return dynamic_cast< VarArgsType * >( type ) || dynamic_cast< ReferenceType * >( type ) || GenPoly::getFunctionType( type ) || Tuples::isTtype( type );
[c2931ea]372 }
373
[65660bd]374 Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
[c2931ea]375 assert( var );
[092528b]376 // arrays are not copy constructed, so this should always be an ExprStmt
377 ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg );
[e3e16bc]378 ExprStmt * exprStmt = strict_dynamic_cast< ExprStmt * >( stmt->get_callStmt() );
[092528b]379 Expression * untyped = exprStmt->get_expr();
[c2931ea]380
381 // resolve copy constructor
[adcc065]382 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
383 // (VariableExpr and already resolved expression)
[c2931ea]384 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
[c0714bf]385 Expression * resolved = ResolvExpr::findVoidExpression( untyped, indexer );
[65660bd]386 assert( resolved );
[c2931ea]387 if ( resolved->get_env() ) {
[31f379c]388 // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
[c2931ea]389 env->add( *resolved->get_env() );
[31f379c]390 delete resolved->get_env();
391 resolved->set_env( nullptr );
[adcc065]392 } // if
[cf18eea]393
[092528b]394 delete stmt;
[c2931ea]395 return resolved;
[540de412]396 }
[db4ecc5]397
[1132b62]398 void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
[c2931ea]399 static UniqueName tempNamer("_tmp_cp");
[31f379c]400 assert( env );
401 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
[1132b62]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();
[31f379c]408 env->apply( result );
[68fe077a]409 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
[615a096]410 tmp->get_type()->set_const( false );
[1132b62]411
412 // create and resolve copy constructor
413 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
[65660bd]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 ) );
[1132b62]428 }
[c2931ea]429
[092528b]430 void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
431 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
[1132b62]432 }
433
[c0714bf]434 void ResolveCopyCtors::postvisit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
[c2931ea]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() ) {
[1132b62]441 copyConstructArg( arg, impCpCtorExpr );
[adcc065]442 } // for
[db4ecc5]443
[adcc065]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
[31f379c]446 // xxx - handle named return values?
[906e24d]447 Type * result = appExpr->get_result();
448 if ( ! result->isVoid() ) {
[1132b62]449 static UniqueName retNamer("_tmp_cp_ret");
[c2931ea]450 result = result->clone();
[31f379c]451 env->apply( result );
[68fe077a]452 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
[615a096]453 ret->get_type()->set_const( false );
[c2931ea]454 impCpCtorExpr->get_returnDecls().push_back( ret );
455 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
[0a81c3f]456 if ( ! dynamic_cast< ReferenceType * >( result ) ) {
[dc86541]457 // destructing lvalue returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
[092528b]458 destructRet( ret, impCpCtorExpr );
[dc86541]459 }
[adcc065]460 } // for
[c2931ea]461 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
[db4ecc5]462 }
463
[c0714bf]464 void ResolveCopyCtors::postvisit( StmtExpr * stmtExpr ) {
465 assert( env );
[31f379c]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 );
[68fe077a]474 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
[615a096]475 ret->get_type()->set_const( false );
[31f379c]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
[e3e16bc]482 ExprStmt * last = strict_dynamic_cast< ExprStmt * >( body->get_kids().back() );
[31f379c]483 last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) );
484
[092528b]485 stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
[31f379c]486 } // if
487 }
488
[c0714bf]489 void ResolveCopyCtors::previsit( UniqueExpr * unqExpr ) {
[597db97f]490 unqCount[ unqExpr->get_id() ]++; // count the number of unique expressions for each ID
[c0714bf]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 ) {
[141b786]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
[14a33790]511 unqExpr->set_object( new ObjectDecl( toString("_unq", unqExpr->get_id()), Type::StorageClasses(), LinkageSpec::C, nullptr, unqExpr->get_result()->clone(), nullptr ) );
[141b786]512 unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) );
513 }
514 vars.insert( unqExpr->get_id() );
515 }
516
[c2931ea]517 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
518 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
519
[e3e16bc]520 impCpCtorExpr = strict_dynamic_cast< ImplicitCopyCtorExpr * >( Parent::mutate( impCpCtorExpr ) );
[c2931ea]521 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
522 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
523 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
[845cedc]524
[c2931ea]525 // add all temporary declarations and their constructors
526 for ( ObjectDecl * obj : tempDecls ) {
527 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]528 } // for
[c2931ea]529 for ( ObjectDecl * obj : returnDecls ) {
530 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]531 } // for
[db4ecc5]532
[c2931ea]533 // add destructors after current statement
534 for ( Expression * dtor : dtors ) {
535 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
[adcc065]536 } // for
[db4ecc5]537
[c2931ea]538 // xxx - update to work with multiple return values
[c0714bf]539 ObjectDecl * returnDecl = returnDecls.empty() ? nullptr : returnDecls.front();
[c2931ea]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();
[c0714bf]548 impCpCtorExpr->set_callExpr( nullptr );
549 std::swap( impCpCtorExpr->env, callExpr->env );
550 assert( impCpCtorExpr->env == nullptr );
[c2931ea]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
[906e24d]559 assign->set_result( returnDecl->get_type()->clone() );
[c2931ea]560
561 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
[31f379c]562 // move env from callExpr to retExpr
563 retExpr->set_env( callExpr->get_env() );
564 callExpr->set_env( nullptr );
[c2931ea]565 return retExpr;
566 } else {
567 return callExpr;
[adcc065]568 } // if
[4ffdd63]569 }
[c2931ea]570
[31f379c]571 Expression * FixCopyCtors::mutate( StmtExpr * stmtExpr ) {
[65aca88]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
[e3e16bc]582 // stmtExpr = strict_dynamic_cast< StmtExpr * >( Parent::mutate( stmtExpr ) );
[31f379c]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() ) ) );
[a28bc02]598 stmtExpr->get_returnDecls().clear();
599 stmtExpr->get_dtors().clear();
[31f379c]600 }
[a28bc02]601 assert( stmtExpr->get_returnDecls().empty() );
602 assert( stmtExpr->get_dtors().empty() );
[31f379c]603 return stmtExpr;
604 }
605
[141b786]606 Expression * FixCopyCtors::mutate( UniqueExpr * unqExpr ) {
[597db97f]607 unqCount[ unqExpr->get_id() ]--;
608 static std::unordered_map< int, std::list< Statement * > > dtors;
[141b786]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() ) );
[597db97f]618 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
[edbdbe6]619 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
[597db97f]620 }
[141b786]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 }
[597db97f]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 );
[141b786]630 unqMap[unqExpr->get_id()] = unqExpr;
[edbdbe6]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 }
[141b786]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
[aff3af4]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)
[c2931ea]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() ) {
[08d5507b]655 if ( objDecl->get_storageClasses().is_static ) {
[72e9222]656 // originally wanted to take advantage of gcc nested functions, but
[f9cebb5]657 // we get memory errors with this approach. To remedy this, the static
658 // variable is hoisted when the destructor needs to be called.
[72e9222]659 //
[c2931ea]660 // generate:
[f9cebb5]661 // static T __objName_static_varN;
[72e9222]662 // void __objName_dtor_atexitN() {
[f9cebb5]663 // __dtor__...;
[72e9222]664 // }
665 // int f(...) {
666 // ...
667 // static bool __objName_uninitialized = true;
668 // if (__objName_uninitialized) {
669 // __ctor(__objName);
670 // __objName_uninitialized = false;
[f9cebb5]671 // atexit(__objName_dtor_atexitN);
[c2931ea]672 // }
[72e9222]673 // ...
[c2931ea]674 // }
675
[72e9222]676 static UniqueName dtorCallerNamer( "_dtor_atexit" );
677
678 // static bool __objName_uninitialized = true
[c2931ea]679 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
[579263a]680 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant::from_int( 1 ) ) );
[68fe077a]681 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr );
[c2931ea]682 isUninitializedVar->fixUniqueId();
683
684 // __objName_uninitialized = false;
685 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
686 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
[d56e5bc]687 setTrue->get_args().push_back( new ConstantExpr( Constant::from_int( 0 ) ) );
[c2931ea]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 );
[72e9222]699
[a4dd728]700 Statement * dtor = ctorInit->get_dtor();
[62423350]701 objDecl->set_init( nullptr );
702 ctorInit->set_ctor( nullptr );
[a4dd728]703 ctorInit->set_dtor( nullptr );
704 if ( dtor ) {
[f9cebb5]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
[a4dd728]709 Statement * dtorStmt = dtor->clone();
[f9cebb5]710
711 // void __objName_dtor_atexitN(...) {...}
[68fe077a]712 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) );
[f9cebb5]713 dtorCaller->fixUniqueId();
[c8dfcd3]714 dtorCaller->get_statements()->push_back( dtorStmt );
[f9cebb5]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.
[c8dfcd3]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.
[f9cebb5]734 static UniqueName staticNamer( "_static_var" );
[c8dfcd3]735 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
736 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
[f9cebb5]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" );
[68fe077a]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") } );
[a4dd728]742 delete ctorInit;
[f9cebb5]743 return dummy;
744 }
[c2931ea]745 } else {
[e3e16bc]746 ImplicitCtorDtorStmt * implicit = strict_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor );
[233e4d9]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 );
[62423350]755 objDecl->set_init( nullptr );
756 ctorInit->set_ctor( nullptr );
[233e4d9]757 }
[adcc065]758 } // if
[c2931ea]759 } else if ( Initializer * init = ctorInit->get_init() ) {
760 objDecl->set_init( init );
[62423350]761 ctorInit->set_init( nullptr );
[c2931ea]762 } else {
763 // no constructor and no initializer, which is okay
[62423350]764 objDecl->set_init( nullptr );
[adcc065]765 } // if
[c2931ea]766 delete ctorInit;
[adcc065]767 } // if
[c2931ea]768 return objDecl;
[db4ecc5]769 }
770
[698ec72]771 void ObjDeclCollector::previsit( CompoundStmt * ) {
772 GuardValue( curVars );
[db4ecc5]773 }
774
[698ec72]775 void ObjDeclCollector::previsit( DeclStmt * stmt ) {
[4b2589a]776 // keep track of all variables currently in scope
[c2931ea]777 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
[62423350]778 curVars.push_back( objDecl );
[adcc065]779 } // if
[db4ecc5]780 }
781
[698ec72]782 void LabelFinder::previsit( Statement * stmt ) {
[4b2589a]783 // for each label, remember the variables in scope at that label.
[c2931ea]784 for ( Label l : stmt->get_labels() ) {
785 vars[l] = curVars;
[adcc065]786 } // for
[71f4e4f]787 }
[f1e012b]788
[698ec72]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
[ec79847]800 template<typename Iterator, typename OutputIterator>
801 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
802 for ( Iterator it = begin ; it != end ; ++it ) {
[adcc065]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.
[c2931ea]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();
[adcc065]811 } // for
[f1e012b]812 }
[39786813]813
[698ec72]814 void InsertDtors::previsit( ObjectDecl * objDecl ) {
[c2931ea]815 // remember non-static destructed objects so that their destructors can be inserted later
[08d5507b]816 if ( ! objDecl->get_storageClasses().is_static ) {
[c2931ea]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();
[f9cebb5]821 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
[c2931ea]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 );
[adcc065]825 } // if
826 } // if
827 } // if
[52c14b3]828 }
829
[698ec72]830 void InsertDtors::previsit( FunctionDecl * funcDecl ) {
[52c14b3]831 // each function needs to have its own set of labels
[698ec72]832 GuardValue( labelVars );
[52c14b3]833 labelVars.clear();
[698ec72]834 maybeAccept( funcDecl->type, finder );
835 maybeAccept( funcDecl->statements, finder );
[52c14b3]836
[698ec72]837 // all labels for this function have been collected, insert destructors as appropriate via implicit recursion.
[52c14b3]838 }
839
[698ec72]840 void InsertDtors::previsit( CompoundStmt * compoundStmt ) {
[adcc065]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
[c2931ea]844 reverseDeclOrder.push_front( OrderedDecls() );
[698ec72]845 Parent::previsit( compoundStmt );
846 }
[39786813]847
[698ec72]848 void InsertDtors::postvisit( CompoundStmt * compoundStmt ) {
[0661678]849 // add destructors for the current scope that we're exiting, unless the last statement is a return, which
850 // causes unreachable code warnings
[c2931ea]851 std::list< Statement * > & statements = compoundStmt->get_kids();
[0661678]852 if ( ! statements.empty() && ! dynamic_cast< ReturnStmt * >( statements.back() ) ) {
853 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
854 }
[c2931ea]855 reverseDeclOrder.pop_front();
[39786813]856 }
857
[698ec72]858 void InsertDtors::previsit( ReturnStmt * ) {
[4b2589a]859 // return exits all scopes, so dump destructors for all scopes
[c2931ea]860 for ( OrderedDecls & od : reverseDeclOrder ) {
[698ec72]861 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAddBefore ) );
[adcc065]862 } // for
[39786813]863 }
[f1e012b]864
[adcc065]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.
[c2931ea]869 void InsertDtors::handleGoto( BranchStmt * stmt ) {
[5809461]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() );
[c2931ea]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 );
[adcc065]892 } // if
[c2931ea]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() ) {
[62423350]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
[c2931ea]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.
[62423350]907 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return needsDestructor.count( objDecl ); } );
[adcc065]908 } // for
[698ec72]909 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAddBefore ) );
[adcc065]910 } // if
[c2931ea]911 }
[39786813]912
[698ec72]913 void InsertDtors::previsit( BranchStmt * stmt ) {
[c2931ea]914 switch( stmt->get_type() ) {
[adcc065]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
[c2931ea]925 }
[79970ed]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;
[bff227f]932 return CodeGen::isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
[79970ed]933 }
934
[9a707e4e]935 void GenStructMemberCalls::previsit( FunctionDecl * funcDecl ) {
936 GuardValue( funcDecl );
937 GuardValue( unhandled );
938 GuardValue( usedUninit );
939 GuardValue( thisParam );
940 GuardValue( isCtor );
941 GuardValue( structDecl );
[64ac636]942 errors = SemanticError(); // clear previous errors
[c8dfcd3]943
944 // need to start with fresh sets
945 unhandled.clear();
946 usedUninit.clear();
[79970ed]947
948 function = funcDecl;
[bff227f]949 isCtor = CodeGen::isConstructor( function->get_name() );
[c8dfcd3]950 if ( checkWarnings( function ) ) {
951 FunctionType * type = function->get_functionType();
[79970ed]952 assert( ! type->get_parameters().empty() );
[e3e16bc]953 thisParam = strict_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
[0a81c3f]954 Type * thisType = getPointerBase( thisParam->get_type() );
955 StructInstType * structType = dynamic_cast< StructInstType * >( thisType );
[79970ed]956 if ( structType ) {
[44f6341]957 structDecl = structType->get_baseStruct();
[79970ed]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 }
[9a707e4e]967 }
968
969 void addIds( SymTab::Indexer & indexer, const std::list< DeclarationWithType * > & decls ) {
970 for ( auto d : decls ) {
971 indexer.addId( d );
972 }
973 }
[c8dfcd3]974
[9a707e4e]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 ) {
[c8dfcd3]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.
[64ac636]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" );
[79970ed]999 }
1000
[c8dfcd3]1001 if ( ! unhandled.empty() ) {
[4618319]1002 // need to explicitly re-add function parameters to the indexer in order to resolve copy constructors
[9a707e4e]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 );
[44f6341]1007
1008 // need to iterate through members in reverse in order for
1009 // ctor/dtor statements to come out in the right order
[1ba88a0]1010 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
[44f6341]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
[c8dfcd3]1018 std::list< Statement * > stmt;
[4d4882a]1019 Expression * arg2 = 0;
1020 if ( isCopyConstructor( function ) ) {
[44f6341]1021 // if copy ctor, need to pass second-param-of-this-function.field
[4d4882a]1022 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
1023 assert( params.size() == 2 );
[44f6341]1024 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
[4d4882a]1025 }
1026 InitExpander srcParam( arg2 );
[4618319]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 );
[c8dfcd3]1031
1032 assert( stmt.size() <= 1 );
1033 if ( stmt.size() == 1 ) {
1034 Statement * callStmt = stmt.front();
1035
[9a707e4e]1036 MutatingResolver resolver( indexer );
[c8dfcd3]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 ) {
[64ac636]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" );
[c8dfcd3]1047 }
1048 }
1049 }
1050 }
[64ac636]1051 if (! errors.isEmpty()) {
1052 throw errors;
1053 }
[79970ed]1054 }
1055
[4618319]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
[9a707e4e]1079 void GenStructMemberCalls::previsit( ApplicationExpr * appExpr ) {
1080 if ( ! checkWarnings( function ) ) {
1081 visit_children = false;
1082 return;
1083 }
[79970ed]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
[4618319]1090 if ( isThisExpression( firstParam, thisParam ) ) {
[79970ed]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.
[4618319]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() );
[79970ed]1099 }
1100 }
1101 }
1102 }
1103
[9a707e4e]1104 void GenStructMemberCalls::previsit( MemberExpr * memberExpr ) {
1105 if ( ! checkWarnings( function ) || ! isCtor ) {
1106 visit_children = false;
1107 return;
1108 }
[79970ed]1109
[4618319]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 } );
[79970ed]1114 }
1115 }
1116 }
[3906301]1117
1118 template< typename Visitor, typename... Params >
[64ac636]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 );
[3906301]1123 }
1124
1125 template< typename... Params >
[64ac636]1126 void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
[3906301]1127 // toggle warnings vs. errors here.
1128 // warn( params... );
[64ac636]1129 error( *this, loc, params... );
[3906301]1130 }
[c8dfcd3]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.
[33a25f9]1136 indexer.addId( objectDecl );
[c8dfcd3]1137 return objectDecl;
1138 }
1139
1140 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
[e3e16bc]1141 return strict_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
[c8dfcd3]1142 }
[b6fe7e6]1143
1144 Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
1145 static UniqueName tempNamer( "_tmp_ctor_expr" );
[f0121d7]1146 // xxx - is the size check necessary?
[906e24d]1147 assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
[b7b8674]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.
[68fe077a]1150 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
[b6fe7e6]1151 addDeclaration( tmp );
1152
[627f585]1153 // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
[e3e16bc]1154 ApplicationExpr * callExpr = strict_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
[b6fe7e6]1155 TypeSubstitution * env = ctorExpr->get_env();
1156 ctorExpr->set_callExpr( nullptr );
1157 ctorExpr->set_env( nullptr );
[8a6cf7e]1158 delete ctorExpr;
[b6fe7e6]1159
1160 Expression *& firstArg = callExpr->get_args().front();
1161
[8a6cf7e]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 ) ) );
[b6fe7e6]1191 commaExpr->set_env( env );
1192 return commaExpr;
1193 }
[c2931ea]1194 } // namespace
[71f4e4f]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.