source: src/InitTweak/FixInit.cc@ fea7ca7

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 fea7ca7 was fea7ca7, checked in by Rob Schluntz <rschlunt@…>, 10 years ago

Account for lvalue returning functions in FixCopyCtor, removed ConditionalExpr, CommaExpr, Logical Expr mutates from Specialize, added before box debug flag

  • Property mode set to 100644
File size: 19.5 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 : Rob Schluntz
12// Last Modified On : Fri Apr 29 12:25:40 2016
13// Update Count : 30
14//
15
16#include <stack>
17#include <list>
18#include "FixInit.h"
19#include "ResolvExpr/Resolver.h"
20#include "ResolvExpr/typeops.h"
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"
27#include "SymTab/Indexer.h"
28#include "GenPoly/PolyMutator.h"
29#include "GenPoly/GenPoly.h"
30
31bool ctordtorp = false;
32#define PRINT( text ) if ( ctordtorp ) { text }
33
34namespace InitTweak {
35 namespace {
36 const std::list<Label> noLabels;
37 const std::list<Expression*> noDesignators;
38 }
39
40 class InsertImplicitCalls : public GenPoly::PolyMutator {
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 );
61 /// true if type does not need to be copy constructed to ensure correctness
62 bool skipCopyConstruct( Type * );
63 };
64
65 class FixInit : public GenPoly::PolyMutator {
66 public:
67 /// expand each object declaration to use its constructor after it is declared.
68 /// insert destructor calls at the appropriate places
69 static void fixInitializers( std::list< Declaration * > &translationUnit );
70
71 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
72
73 virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
74 virtual Statement * mutate( ReturnStmt * returnStmt );
75 virtual Statement * mutate( BranchStmt * branchStmt );
76
77 private:
78 // stack of list of statements - used to differentiate scopes
79 std::list< std::list< Statement * > > dtorStmts;
80 };
81
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
95 void fix( std::list< Declaration * > & translationUnit ) {
96 InsertImplicitCalls::insert( translationUnit );
97 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
98 FixInit::fixInitializers( translationUnit );
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 );
111 }
112
113 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
114 FixInit fixer;
115 mutateAll( translationUnit, fixer );
116 }
117
118 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
119 FixCopyCtors fixer;
120 mutateAll( translationUnit, fixer );
121 }
122
123 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
124 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
125 assert( appExpr );
126
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;
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 }
147 }
148 }
149 PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
150
151 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
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;
163 }
164
165 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
166 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
167 }
168
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)
178 PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
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
190 PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
191 Visitor::visit( impCpCtorExpr );
192
193 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
194
195 // take each argument and attempt to copy construct it.
196 for ( Expression * & arg : appExpr->get_args() ) {
197 PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
198 // xxx - need to handle tuple arguments
199 assert( ! arg->get_results().empty() );
200 Type * result = arg->get_results().front();
201 if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
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 );
206 tmp->get_type()->set_isConst( false );
207
208 // create and resolve copy constructor
209 PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
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 CommaExpr( cpCtor, new VariableExpr( tmp ) );
219 impCpCtorExpr->get_tempDecls().push_back( tmp );
220 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
221 }
222 }
223
224 // each return value from the call needs to be connected with an ObjectDecl
225 // at the call site, which is initialized with the return value and is destructed
226 // later
227 // xxx - handle multiple return values
228 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
229 // xxx - is this right? callExpr may not have the right environment, because it was attached
230 // at a higher level. Trying to pass that environment along.
231 callExpr->set_env( impCpCtorExpr->get_env()->clone() );
232 for ( Type * result : appExpr->get_results() ) {
233 result = result->clone();
234 impCpCtorExpr->get_env()->apply( result );
235 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
236 ret->get_type()->set_isConst( false );
237 impCpCtorExpr->get_returnDecls().push_back( ret );
238 PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
239 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
240 }
241 PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
242 }
243
244
245 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
246 PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
247
248 // assert( impCpCtorExpr->get_callExpr()->get_env() );
249 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
250 assert( impCpCtorExpr );
251
252 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
253 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
254 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
255
256 // add all temporary declarations and their constructors
257 for ( ObjectDecl * obj : tempDecls ) {
258 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
259 }
260 for ( ObjectDecl * obj : returnDecls ) {
261 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
262 }
263
264 // add destructors after current statement
265 for ( Expression * dtor : dtors ) {
266 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
267 }
268
269 // xxx - update to work with multiple return values
270 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
271 Expression * callExpr = impCpCtorExpr->get_callExpr();
272
273 PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
274
275 // xxx - some of these aren't necessary, and can be removed once this is stable
276 dtors.clear();
277 tempDecls.clear();
278 returnDecls.clear();
279 impCpCtorExpr->set_callExpr( NULL );
280 delete impCpCtorExpr;
281
282 if ( returnDecl ) {
283 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
284 assign->get_args().push_back( new VariableExpr( returnDecl ) );
285 assign->get_args().push_back( callExpr );
286 // know the result type of the assignment is the type of the LHS (minus the pointer), so
287 // add that onto the assignment expression so that later steps have the necessary information
288 assign->add_result( returnDecl->get_type()->clone() );
289
290 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
291 if ( callExpr->get_results().front()->get_isLvalue() ) {
292 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any
293 // lvalue returning non-intrinsic function. Add an AddressExpr to the call to negate
294 // the derefence and change the type of the return temporary from T to T* to properly
295 // capture the return value. Then dereference the result of the comma expression, since
296 // the lvalue returning call was originally wrapped with an AddressExpr.
297 // Effectively, this turns
298 // lvalue T f();
299 // &*f()
300 // into
301 // T * tmp_cp_retN;
302 // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
303 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
304 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
305
306 Type * resultType = returnDecl->get_type()->clone();
307 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
308 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
309 deref->get_args().push_back( retExpr );
310 deref->add_result( resultType );
311 retExpr = deref;
312 }
313 return retExpr;
314 } else {
315 return callExpr;
316 }
317 }
318
319 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
320 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
321 // when the init is removed from the ObjectDecl
322 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
323
324 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
325 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
326 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
327 if ( Statement * ctor = ctorInit->get_ctor() ) {
328 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
329 // generate:
330 // static bool __objName_uninitialized = true;
331 // if (__objName_uninitialized) {
332 // __ctor(__objName);
333 // void dtor_atexit() {
334 // __dtor(__objName);
335 // }
336 // on_exit(dtorOnExit, &__objName);
337 // __objName_uninitialized = false;
338 // }
339
340 // generate first line
341 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
342 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
343 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
344 isUninitializedVar->fixUniqueId();
345
346 // void dtor_atexit(...) {...}
347 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
348 dtorCaller->fixUniqueId();
349 dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
350
351 // on_exit(dtor_atexit);
352 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
353 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
354
355 // __objName_uninitialized = false;
356 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
357 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
358 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
359
360 // generate body of if
361 CompoundStmt * initStmts = new CompoundStmt( noLabels );
362 std::list< Statement * > & body = initStmts->get_kids();
363 body.push_back( ctor );
364 body.push_back( new DeclStmt( noLabels, dtorCaller ) );
365 body.push_back( new ExprStmt( noLabels, callAtexit ) );
366 body.push_back( new ExprStmt( noLabels, setTrue ) );
367
368 // put it all together
369 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
370 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
371 stmtsToAddAfter.push_back( ifStmt );
372 } else {
373 stmtsToAddAfter.push_back( ctor );
374 dtorStmts.back().push_front( ctorInit->get_dtor() );
375 }
376 objDecl->set_init( NULL );
377 ctorInit->set_ctor( NULL );
378 ctorInit->set_dtor( NULL ); // xxx - only destruct when constructing? Probably not?
379 } else if ( Initializer * init = ctorInit->get_init() ) {
380 objDecl->set_init( init );
381 ctorInit->set_init( NULL );
382 } else {
383 // no constructor and no initializer, which is okay
384 objDecl->set_init( NULL );
385 }
386 delete ctorInit;
387 }
388 return objDecl;
389 }
390
391 template<typename Iterator, typename OutputIterator>
392 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
393 for ( Iterator it = begin ; it != end ; ++it ) {
394 // remove if instrinsic destructor statement
395 // xxx - test user manually calling intrinsic functions - what happens?
396 if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( *it ) ) {
397 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( exprStmt->get_expr() );
398 assert( appExpr );
399 VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
400 assert( function );
401 // check for Intrinsic only - don't want to remove all overridable dtors because autogenerated dtor
402 // will call all member dtors, and some members may have a user defined dtor.
403 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
404 // don't need to call intrinsic dtor, because it does nothing
405 } else {
406 // non-intrinsic dtors must be called
407 *out++ = (*it)->clone();
408 }
409 } else {
410 // could also be a compound statement with a loop, in the case of an array
411 *out++ = (*it)->clone();
412 }
413 }
414 }
415
416
417 CompoundStmt * FixInit::mutate( CompoundStmt * compoundStmt ) {
418 // mutate statements - this will also populate dtorStmts list.
419 // don't want to dump all destructors when block is left,
420 // just the destructors associated with variables defined in this block,
421 // so push a new list to the top of the stack so that we can differentiate scopes
422 dtorStmts.push_back( std::list<Statement *>() );
423
424 compoundStmt = PolyMutator::mutate( compoundStmt );
425 std::list< Statement * > & statements = compoundStmt->get_kids();
426
427 insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( statements ) );
428
429 deleteAll( dtorStmts.back() );
430 dtorStmts.pop_back();
431 return compoundStmt;
432 }
433
434 Statement * FixInit::mutate( ReturnStmt * returnStmt ) {
435 for ( std::list< std::list< Statement * > >::reverse_iterator list = dtorStmts.rbegin(); list != dtorStmts.rend(); ++list ) {
436 insertDtors( list->begin(), list->end(), back_inserter( stmtsToAdd ) );
437 }
438 return Mutator::mutate( returnStmt );
439 }
440
441 Statement * FixInit::mutate( BranchStmt * branchStmt ) {
442 // TODO: adding to the end of a block isn't sufficient, since
443 // return/break/goto should trigger destructor when block is left.
444 switch( branchStmt->get_type() ) {
445 case BranchStmt::Continue:
446 case BranchStmt::Break:
447 insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( stmtsToAdd ) );
448 break;
449 case BranchStmt::Goto:
450 // xxx
451 // if goto leaves a block, generate dtors for every block it leaves
452 // if goto is in same block but earlier statement, destruct every object that was defined after the statement
453 break;
454 default:
455 assert( false );
456 }
457 return Mutator::mutate( branchStmt );
458 }
459
460
461} // namespace InitTweak
462
463// Local Variables: //
464// tab-width: 4 //
465// mode: c++ //
466// compile-command: "make install" //
467// End: //
Note: See TracBrowser for help on using the repository browser.