source: src/InitTweak/FixInit.cc@ 5382492

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

save type substitution and apply it when creating temporary variables for copy construction

  • Property mode set to 100644
File size: 18.0 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
11// Last Modified By : Rob Schluntz
[5382492]12// Last Modified On : Tue Apr 26 11:35:31 2016
[ca1c11f]13// Update Count : 30
[71f4e4f]14//
15
16#include <stack>
17#include <list>
18#include "RemoveInit.h"
[db4ecc5]19#include "ResolvExpr/Resolver.h"
[845cedc]20#include "ResolvExpr/typeops.h"
[71f4e4f]21#include "SynTree/Declaration.h"
22#include "SynTree/Type.h"
23#include "SynTree/Expression.h"
24#include "SynTree/Statement.h"
25#include "SynTree/Initializer.h"
26#include "SynTree/Mutator.h"
[db4ecc5]27#include "SymTab/Indexer.h"
[71f4e4f]28#include "GenPoly/PolyMutator.h"
[cf18eea]29#include "GenPoly/GenPoly.h"
[71f4e4f]30
[845cedc]31bool ctordtorp = false;
32#define PRINT( text ) if ( ctordtorp ) { text }
33
[71f4e4f]34namespace InitTweak {
35 namespace {
36 const std::list<Label> noLabels;
[e0323a2]37 const std::list<Expression*> noDesignators;
[71f4e4f]38 }
39
[5382492]40 class InsertImplicitCalls : public GenPoly::PolyMutator {
[db4ecc5]41 public:
42 /// wrap function application expressions as ImplicitCopyCtorExpr nodes
43 /// so that it is easy to identify which function calls need their parameters
44 /// to be copy constructed
45 static void insert( std::list< Declaration * > & translationUnit );
46
47 virtual Expression * mutate( ApplicationExpr * appExpr );
48 };
49
50 class ResolveCopyCtors : public SymTab::Indexer {
51 public:
52 /// generate temporary ObjectDecls for each argument and return value of each
53 /// ImplicitCopyCtorExpr, generate/resolve copy construction expressions for each,
54 /// and generate/resolve destructors for both arguments and return value temporaries
55 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
56
57 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
58
59 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
60 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
[cf18eea]61 /// true if type does not need to be copy constructed to ensure correctness
62 bool skipCopyConstruct( Type * );
[db4ecc5]63 };
64
[71f4e4f]65 class FixInit : public GenPoly::PolyMutator {
66 public:
[db4ecc5]67 /// expand each object declaration to use its constructor after it is declared.
68 /// insert destructor calls at the appropriate places
[71f4e4f]69 static void fixInitializers( std::list< Declaration * > &translationUnit );
70
[db4ecc5]71 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
[f1e012b]72
73 virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
[39786813]74 virtual Statement * mutate( ReturnStmt * returnStmt );
75 virtual Statement * mutate( BranchStmt * branchStmt );
[5b2f5bb]76
77 private:
[39786813]78 // stack of list of statements - used to differentiate scopes
79 std::list< std::list< Statement * > > dtorStmts;
[71f4e4f]80 };
81
[db4ecc5]82 class FixCopyCtors : public GenPoly::PolyMutator {
83 public:
84 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors,
85 /// call expression, and destructors
86 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
87
88 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
89
90 private:
91 // stack of list of statements - used to differentiate scopes
92 std::list< std::list< Statement * > > dtorStmts;
93 };
94
[71f4e4f]95 void fix( std::list< Declaration * > & translationUnit ) {
[db4ecc5]96 InsertImplicitCalls::insert( translationUnit );
97 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
[71f4e4f]98 FixInit::fixInitializers( translationUnit );
[db4ecc5]99 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
100 FixCopyCtors::fixCopyCtors( translationUnit );
101 }
102
103 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
104 InsertImplicitCalls inserter;
105 mutateAll( translationUnit, inserter );
106 }
107
108 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
109 ResolveCopyCtors resolver;
110 acceptAll( translationUnit, resolver );
[71f4e4f]111 }
112
113 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
114 FixInit fixer;
115 mutateAll( translationUnit, fixer );
116 }
117
[db4ecc5]118 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
119 FixCopyCtors fixer;
120 mutateAll( translationUnit, fixer );
121 }
122
123 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
[845cedc]124 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
125 assert( appExpr );
126
[db4ecc5]127 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
128 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
129 // optimization: don't need to copy construct in order to call intrinsic functions
130 return appExpr;
[845cedc]131 } else if ( FunctionDecl * funcDecl = dynamic_cast< FunctionDecl * > ( function->get_var() ) ) {
132 FunctionType * ftype = funcDecl->get_functionType();
133 if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
134 Type * t1 = ftype->get_parameters().front()->get_type();
135 Type * t2 = ftype->get_parameters().back()->get_type();
136 PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
137 assert( ptrType );
138 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
139 // optimization: don't need to copy construct in order to call a copy constructor or
140 // assignment operator
141 return appExpr;
142 }
143 } else if ( funcDecl->get_name() == "^?{}" ) {
144 // correctness: never copy construct arguments to a destructor
145 return appExpr;
146 }
[db4ecc5]147 }
148 }
[845cedc]149 PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
150
[db4ecc5]151 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
[5382492]152 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
153 // save a copy of the type substitution onto the new node so that it is easy to find.
154 // The substitution is needed to obtain the type of temporary variables so that copy constructor
155 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
156 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
157 // saves the environment, or compute the types of temporaries here, but it's more simpler to
158 // save the environment here, and more cohesive to compute temporary variables and resolve copy
159 // constructor calls together.
160 assert( env );
161 expr->set_env( env->clone() );
162 return expr;
[db4ecc5]163 }
164
[cf18eea]165 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
166 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
167 }
168
[db4ecc5]169 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
170 assert( var );
171 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
172 untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
173 if (cpArg) untyped->get_args().push_back( cpArg );
174
175 // resolve copy constructor
176 // should only be one alternative for copy ctor and dtor expressions, since
177 // all arguments are fixed (VariableExpr and already resolved expression)
[845cedc]178 PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
[db4ecc5]179 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
180
181 assert( resolved );
182 delete untyped;
183 return resolved;
184 }
185
186 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
187 static UniqueName tempNamer("_tmp_cp");
188 static UniqueName retNamer("_tmp_cp_ret");
189
[845cedc]190 PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
191 Visitor::visit( impCpCtorExpr );
[db4ecc5]192
[845cedc]193 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
[b617e4b]194
[db4ecc5]195 // take each argument and attempt to copy construct it.
196 for ( Expression * & arg : appExpr->get_args() ) {
[5382492]197 PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
[db4ecc5]198 // xxx - need to handle tuple arguments
199 assert( ! arg->get_results().empty() );
[cf18eea]200 Type * result = arg->get_results().front();
201 if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
[5382492]202 // type may involve type variables, so apply type substitution to get temporary variable's actual type
203 result = result->clone();
204 impCpCtorExpr->get_env()->apply( result );
205 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
[b617e4b]206 tmp->get_type()->set_isConst( false );
[db4ecc5]207
208 // create and resolve copy constructor
[845cedc]209 PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
[db4ecc5]210 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
211
212 // if the chosen constructor is intrinsic, the copy is unnecessary, so
213 // don't create the temporary and don't call the copy constructor
214 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
215 assert( function );
216 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
217 // replace argument to function call with temporary
218 arg = new VariableExpr( tmp );
219 impCpCtorExpr->get_tempDecls().push_back( tmp );
220 impCpCtorExpr->get_copyCtors().push_back( cpCtor );
221 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
222 }
223 }
224
225 // each return value from the call needs to be connected with an ObjectDecl
226 // at the call site, which is initialized with the return value and is destructed
227 // later
228 // xxx - handle multiple return values
[845cedc]229 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
[db4ecc5]230 for ( Type * result : appExpr->get_results() ) {
[845cedc]231 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result->clone(), new SingleInit( callExpr ) );
[b617e4b]232 ret->get_type()->set_isConst( false );
[db4ecc5]233 impCpCtorExpr->get_returnDecls().push_back( ret );
[845cedc]234 PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
[db4ecc5]235 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
236 }
[845cedc]237 PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
[db4ecc5]238 }
239
240
241 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
[845cedc]242 PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
243
244 // assert( impCpCtorExpr->get_callExpr()->get_env() );
[db4ecc5]245 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
246 assert( impCpCtorExpr );
247
248 std::list< Expression * > & copyCtors = impCpCtorExpr->get_copyCtors();
249 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
250 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
251 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
252
253 // add all temporary declarations and their constructors
254 for ( ObjectDecl * obj : tempDecls ) {
255 assert( ! copyCtors.empty() );
256 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
257 stmtsToAdd.push_back( new ExprStmt( noLabels, copyCtors.front() ) );
258 copyCtors.pop_front();
259 }
260
261 // add destructors after current statement
262 for ( Expression * dtor : dtors ) {
263 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
264 }
265
266 // xxx - update to work with multiple return values
267 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
[845cedc]268 Expression * callExpr = impCpCtorExpr->get_callExpr();
269
270 PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
[db4ecc5]271
272 // xxx - some of these aren't necessary, and can be removed once this is stable
273 copyCtors.clear();
274 dtors.clear();
275 tempDecls.clear();
276 returnDecls.clear();
[845cedc]277 impCpCtorExpr->set_callExpr( NULL );
278 delete impCpCtorExpr;
[db4ecc5]279
280 if ( returnDecl ) {
281 // call is currently attached to first returnDecl
282 stmtsToAdd.push_back( new DeclStmt( noLabels, returnDecl ) );
283 return new VariableExpr( returnDecl );
284 } else {
285 // add call expression - if no return values, can call directly
[845cedc]286 assert( callExpr );
287 return callExpr;
[db4ecc5]288 }
289 }
290
291 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
292 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
293 // when the init is removed from the ObjectDecl
294 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
295
[71f4e4f]296 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
[f1e012b]297 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
[71f4e4f]298 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
[5b2f5bb]299 if ( Statement * ctor = ctorInit->get_ctor() ) {
[e0323a2]300 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
301 // generate:
302 // static bool __objName_uninitialized = true;
303 // if (__objName_uninitialized) {
304 // __ctor(__objName);
305 // void dtor_atexit() {
306 // __dtor(__objName);
307 // }
308 // on_exit(dtorOnExit, &__objName);
309 // __objName_uninitialized = false;
310 // }
311
312 // generate first line
313 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
314 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
315 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
316 isUninitializedVar->fixUniqueId();
317
318 // void dtor_atexit(...) {...}
319 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
320 dtorCaller->fixUniqueId();
321 dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
322
323 // on_exit(dtor_atexit);
324 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
325 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
326
327 // __objName_uninitialized = false;
328 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
329 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
330 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
331
332 // generate body of if
333 CompoundStmt * initStmts = new CompoundStmt( noLabels );
334 std::list< Statement * > & body = initStmts->get_kids();
335 body.push_back( ctor );
336 body.push_back( new DeclStmt( noLabels, dtorCaller ) );
337 body.push_back( new ExprStmt( noLabels, callAtexit ) );
338 body.push_back( new ExprStmt( noLabels, setTrue ) );
339
340 // put it all together
341 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
342 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
343 stmtsToAddAfter.push_back( ifStmt );
344 } else {
345 stmtsToAddAfter.push_back( ctor );
[39786813]346 dtorStmts.back().push_front( ctorInit->get_dtor() );
[e0323a2]347 }
[71f4e4f]348 objDecl->set_init( NULL );
349 ctorInit->set_ctor( NULL );
[5b2f5bb]350 ctorInit->set_dtor( NULL ); // xxx - only destruct when constructing? Probably not?
[71f4e4f]351 } else if ( Initializer * init = ctorInit->get_init() ) {
352 objDecl->set_init( init );
353 ctorInit->set_init( NULL );
354 } else {
[f1e012b]355 // no constructor and no initializer, which is okay
356 objDecl->set_init( NULL );
[71f4e4f]357 }
358 delete ctorInit;
359 }
360 return objDecl;
361 }
[f1e012b]362
[39786813]363 template<typename Iterator, typename OutputIterator>
364 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
365 for ( Iterator it = begin ; it != end ; ++it ) {
[f1e012b]366 // remove if instrinsic destructor statement
367 // xxx - test user manually calling intrinsic functions - what happens?
368 if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( *it ) ) {
[5b2f5bb]369 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( exprStmt->get_expr() );
370 assert( appExpr );
371 VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
372 assert( function );
373 // check for Intrinsic only - don't want to remove all overridable dtors because autogenerated dtor
374 // will call all member dtors, and some members may have a user defined dtor.
375 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
[39786813]376 // don't need to call intrinsic dtor, because it does nothing
[5b2f5bb]377 } else {
378 // non-intrinsic dtors must be called
[39786813]379 *out++ = (*it)->clone();
[f1e012b]380 }
[5b2f5bb]381 } else {
382 // could also be a compound statement with a loop, in the case of an array
[39786813]383 *out++ = (*it)->clone();
[f1e012b]384 }
385 }
[39786813]386 }
387
388
389 CompoundStmt * FixInit::mutate( CompoundStmt * compoundStmt ) {
390 // mutate statements - this will also populate dtorStmts list.
391 // don't want to dump all destructors when block is left,
392 // just the destructors associated with variables defined in this block,
393 // so push a new list to the top of the stack so that we can differentiate scopes
394 dtorStmts.push_back( std::list<Statement *>() );
395
396 compoundStmt = PolyMutator::mutate( compoundStmt );
397 std::list< Statement * > & statements = compoundStmt->get_kids();
398
399 insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( statements ) );
400
401 deleteAll( dtorStmts.back() );
402 dtorStmts.pop_back();
403 return compoundStmt;
404 }
405
406 Statement * FixInit::mutate( ReturnStmt * returnStmt ) {
407 for ( std::list< std::list< Statement * > >::reverse_iterator list = dtorStmts.rbegin(); list != dtorStmts.rend(); ++list ) {
408 insertDtors( list->begin(), list->end(), back_inserter( stmtsToAdd ) );
409 }
[db4ecc5]410 return Mutator::mutate( returnStmt );
[39786813]411 }
412
413 Statement * FixInit::mutate( BranchStmt * branchStmt ) {
[5b2f5bb]414 // TODO: adding to the end of a block isn't sufficient, since
415 // return/break/goto should trigger destructor when block is left.
[39786813]416 switch( branchStmt->get_type() ) {
417 case BranchStmt::Continue:
418 case BranchStmt::Break:
419 insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( stmtsToAdd ) );
420 break;
421 case BranchStmt::Goto:
422 // xxx
423 // if goto leaves a block, generate dtors for every block it leaves
424 // if goto is in same block but earlier statement, destruct every object that was defined after the statement
425 break;
426 default:
427 assert( false );
428 }
[db4ecc5]429 return Mutator::mutate( branchStmt );
[f1e012b]430 }
431
[39786813]432
[71f4e4f]433} // namespace InitTweak
434
435// Local Variables: //
436// tab-width: 4 //
437// mode: c++ //
438// compile-command: "make install" //
439// End: //
Note: See TracBrowser for help on using the repository browser.