source: src/InitTweak/FixInit.cc@ 540b275

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox memory 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 540b275 was adcc065, checked in by Peter A. Buhr <pabuhr@…>, 9 years ago

add labelled break to if statement, update comment formatting, add random number test

  • Property mode set to 100644
File size: 27.2 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// FixInit.h --
8//
9// Author : Rob Schluntz
10// Created On : Wed Jan 13 16:29:30 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Jul 6 17:34:46 2016
13// Update Count : 33
14//
15
16#include <stack>
17#include <list>
18#include <iterator>
19#include <algorithm>
20#include "FixInit.h"
21#include "InitTweak.h"
22#include "ResolvExpr/Resolver.h"
23#include "ResolvExpr/typeops.h"
24#include "SynTree/Declaration.h"
25#include "SynTree/Type.h"
26#include "SynTree/Expression.h"
27#include "SynTree/Statement.h"
28#include "SynTree/Initializer.h"
29#include "SynTree/Mutator.h"
30#include "SymTab/Indexer.h"
31#include "GenPoly/PolyMutator.h"
32#include "SynTree/AddStmtVisitor.h"
33
34bool ctordtorp = false;
35bool ctorp = false;
36bool cpctorp = false;
37bool dtorp = false;
38#define PRINT( text ) if ( ctordtorp ) { text }
39#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
40#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
41
42namespace InitTweak {
43 namespace {
44 const std::list<Label> noLabels;
45 const std::list<Expression*> noDesignators;
46
47 class InsertImplicitCalls : public GenPoly::PolyMutator {
48 public:
49 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
50 /// function calls need their parameters to be copy constructed
51 static void insert( std::list< Declaration * > & translationUnit );
52
53 virtual Expression * mutate( ApplicationExpr * appExpr );
54 };
55
56 class ResolveCopyCtors : public SymTab::Indexer {
57 public:
58 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
59 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
60 /// arguments and return value temporaries
61 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
62
63 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
64
65 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
66 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
67 /// true if type does not need to be copy constructed to ensure correctness
68 bool skipCopyConstruct( Type * );
69 private:
70 TypeSubstitution * env;
71 };
72
73 /// collects constructed object decls - used as a base class
74 class ObjDeclCollector : public AddStmtVisitor {
75 public:
76 typedef AddStmtVisitor Parent;
77 using Parent::visit;
78 typedef std::set< ObjectDecl * > ObjectSet;
79 virtual void visit( CompoundStmt *compoundStmt );
80 virtual void visit( DeclStmt *stmt );
81 protected:
82 ObjectSet curVars;
83 };
84
85 struct printSet {
86 typedef ObjDeclCollector::ObjectSet ObjectSet;
87 printSet( const ObjectSet & objs ) : objs( objs ) {}
88 const ObjectSet & objs;
89 };
90 std::ostream & operator<<( std::ostream & out, const printSet & set) {
91 out << "{ ";
92 for ( ObjectDecl * obj : set.objs ) {
93 out << obj->get_name() << ", " ;
94 } // for
95 out << " }";
96 return out;
97 }
98
99 class LabelFinder : public ObjDeclCollector {
100 public:
101 typedef ObjDeclCollector Parent;
102 typedef std::map< Label, ObjectSet > LabelMap;
103 // map of Label -> live variables at that label
104 LabelMap vars;
105
106 void handleStmt( Statement * stmt );
107
108 // xxx - This needs to be done better.
109 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
110 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
111 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
112 // every specialized class knows about every new kind of statement that might be added.
113 virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
114 virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
115 virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
116 virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
117 virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
118 virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
119 virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
120 virtual void visit( ChooseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
121 virtual void visit( FallthruStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
122 virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
123 virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
124 virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
125 virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
126 virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
127 virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
128 virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
129 virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
130 virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
131 };
132
133 class InsertDtors : public ObjDeclCollector {
134 public:
135 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
136 /// (currently by FixInit)
137 static void insert( std::list< Declaration * > & translationUnit );
138
139 typedef ObjDeclCollector Parent;
140 typedef std::list< ObjectDecl * > OrderedDecls;
141 typedef std::list< OrderedDecls > OrderedDeclsStack;
142
143 InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
144
145 virtual void visit( ObjectDecl * objDecl );
146
147 virtual void visit( CompoundStmt * compoundStmt );
148 virtual void visit( ReturnStmt * returnStmt );
149 virtual void visit( BranchStmt * stmt );
150 private:
151 void handleGoto( BranchStmt * stmt );
152
153 LabelFinder::LabelMap & labelVars;
154 OrderedDeclsStack reverseDeclOrder;
155 };
156
157 class FixInit : public GenPoly::PolyMutator {
158 public:
159 /// expand each object declaration to use its constructor after it is declared.
160 static void fixInitializers( std::list< Declaration * > &translationUnit );
161
162 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
163 };
164
165 class FixCopyCtors : public GenPoly::PolyMutator {
166 public:
167 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
168 /// and destructors
169 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
170
171 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
172 };
173 } // namespace
174
175 void fix( std::list< Declaration * > & translationUnit ) {
176 InsertImplicitCalls::insert( translationUnit );
177 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
178 InsertDtors::insert( translationUnit );
179 FixInit::fixInitializers( translationUnit );
180
181 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
182 FixCopyCtors::fixCopyCtors( translationUnit );
183 }
184
185 namespace {
186 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
187 InsertImplicitCalls inserter;
188 mutateAll( translationUnit, inserter );
189 }
190
191 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
192 ResolveCopyCtors resolver;
193 acceptAll( translationUnit, resolver );
194 }
195
196 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
197 FixInit fixer;
198 mutateAll( translationUnit, fixer );
199 }
200
201 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
202 LabelFinder finder;
203 InsertDtors inserter( finder );
204 acceptAll( translationUnit, finder );
205 acceptAll( translationUnit, inserter );
206 }
207
208 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
209 FixCopyCtors fixer;
210 mutateAll( translationUnit, fixer );
211 }
212
213 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
214 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
215 assert( appExpr );
216
217 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
218 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
219 // optimization: don't need to copy construct in order to call intrinsic functions
220 return appExpr;
221 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
222 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
223 assert( ftype );
224 if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
225 Type * t1 = ftype->get_parameters().front()->get_type();
226 Type * t2 = ftype->get_parameters().back()->get_type();
227 PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
228 assert( ptrType );
229
230 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
231 // optimization: don't need to copy construct in order to call a copy constructor or
232 // assignment operator
233 return appExpr;
234 } // if
235 } else if ( funcDecl->get_name() == "^?{}" ) {
236 // correctness: never copy construct arguments to a destructor
237 return appExpr;
238 } // if
239 } // if
240 } // if
241 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
242
243 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
244 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
245 // save the type substitution onto the new node so that it is easy to find.
246 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
247 // The substitution is needed to obtain the type of temporary variables so that copy constructor
248 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
249 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
250 // saves the environment, or compute the types of temporaries here, but it's much simpler to
251 // save the environment here, and more cohesive to compute temporary variables and resolve copy
252 // constructor calls together.
253 assert( env );
254 expr->set_env( env );
255 return expr;
256 }
257
258 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
259 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
260 }
261
262 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
263 assert( var );
264 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
265 untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
266 if (cpArg) untyped->get_args().push_back( cpArg );
267
268 // resolve copy constructor
269 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
270 // (VariableExpr and already resolved expression)
271 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
272 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
273 if ( resolved->get_env() ) {
274 env->add( *resolved->get_env() );
275 } // if
276
277 assert( resolved );
278 delete untyped;
279 return resolved;
280 }
281
282 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
283 static UniqueName tempNamer("_tmp_cp");
284 static UniqueName retNamer("_tmp_cp_ret");
285
286 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
287 Visitor::visit( impCpCtorExpr );
288 env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
289
290 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
291
292 // take each argument and attempt to copy construct it.
293 for ( Expression * & arg : appExpr->get_args() ) {
294 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
295 // xxx - need to handle tuple arguments
296 assert( ! arg->get_results().empty() );
297 Type * result = arg->get_results().front();
298 if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
299 // type may involve type variables, so apply type substitution to get temporary variable's actual type
300 result = result->clone();
301 impCpCtorExpr->get_env()->apply( result );
302 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
303 tmp->get_type()->set_isConst( false );
304
305 // create and resolve copy constructor
306 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
307 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
308
309 // if the chosen constructor is intrinsic, the copy is unnecessary, so
310 // don't create the temporary and don't call the copy constructor
311 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
312 assert( function );
313 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
314 // replace argument to function call with temporary
315 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
316 impCpCtorExpr->get_tempDecls().push_back( tmp );
317 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
318 } // if
319 } // for
320
321 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
322 // initialized with the return value and is destructed later
323 // xxx - handle multiple return values
324 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
325 // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
326 // level. Trying to pass that environment along.
327 callExpr->set_env( impCpCtorExpr->get_env()->clone() );
328 for ( Type * result : appExpr->get_results() ) {
329 result = result->clone();
330 impCpCtorExpr->get_env()->apply( result );
331 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
332 ret->get_type()->set_isConst( false );
333 impCpCtorExpr->get_returnDecls().push_back( ret );
334 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
335 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
336 } // for
337 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
338 }
339
340
341 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
342 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
343
344 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
345 assert( impCpCtorExpr );
346
347 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
348 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
349 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
350
351 // add all temporary declarations and their constructors
352 for ( ObjectDecl * obj : tempDecls ) {
353 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
354 } // for
355 for ( ObjectDecl * obj : returnDecls ) {
356 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
357 } // for
358
359 // add destructors after current statement
360 for ( Expression * dtor : dtors ) {
361 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
362 } // for
363
364 // xxx - update to work with multiple return values
365 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
366 Expression * callExpr = impCpCtorExpr->get_callExpr();
367
368 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
369
370 // detach fields from wrapper node so that it can be deleted without deleting too much
371 dtors.clear();
372 tempDecls.clear();
373 returnDecls.clear();
374 impCpCtorExpr->set_callExpr( NULL );
375 impCpCtorExpr->set_env( NULL );
376 delete impCpCtorExpr;
377
378 if ( returnDecl ) {
379 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
380 assign->get_args().push_back( new VariableExpr( returnDecl ) );
381 assign->get_args().push_back( callExpr );
382 // know the result type of the assignment is the type of the LHS (minus the pointer), so
383 // add that onto the assignment expression so that later steps have the necessary information
384 assign->add_result( returnDecl->get_type()->clone() );
385
386 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
387 if ( callExpr->get_results().front()->get_isLvalue() ) {
388 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
389 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
390 // type of the return temporary from T to T* to properly capture the return value. Then dereference
391 // the result of the comma expression, since the lvalue returning call was originally wrapped with
392 // an AddressExpr. Effectively, this turns
393 // lvalue T f();
394 // &*f()
395 // into
396 // T * tmp_cp_retN;
397 // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
398 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
399 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
400
401 Type * resultType = returnDecl->get_type()->clone();
402 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
403 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
404 deref->get_args().push_back( retExpr );
405 deref->add_result( resultType );
406 retExpr = deref;
407 } // if
408 // xxx - might need to set env on retExpr...
409 // retExpr->set_env( env->clone() );
410 return retExpr;
411 } else {
412 return callExpr;
413 } // if
414 }
415
416 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
417 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
418 // is removed from the ObjectDecl
419 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
420
421 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
422 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
423 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
424 if ( Statement * ctor = ctorInit->get_ctor() ) {
425 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
426 // generate:
427 // static bool __objName_uninitialized = true;
428 // if (__objName_uninitialized) {
429 // __ctor(__objName);
430 // void dtor_atexit() {
431 // __dtor(__objName);
432 // }
433 // on_exit(dtorOnExit, &__objName);
434 // __objName_uninitialized = false;
435 // }
436
437 // generate first line
438 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
439 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
440 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
441 isUninitializedVar->fixUniqueId();
442
443 // void dtor_atexit(...) {...}
444 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
445 dtorCaller->fixUniqueId();
446 dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor()->clone() );
447
448 // on_exit(dtor_atexit);
449 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
450 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
451
452 // __objName_uninitialized = false;
453 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
454 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
455 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
456
457 // generate body of if
458 CompoundStmt * initStmts = new CompoundStmt( noLabels );
459 std::list< Statement * > & body = initStmts->get_kids();
460 body.push_back( ctor );
461 body.push_back( new DeclStmt( noLabels, dtorCaller ) );
462 body.push_back( new ExprStmt( noLabels, callAtexit ) );
463 body.push_back( new ExprStmt( noLabels, setTrue ) );
464
465 // put it all together
466 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
467 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
468 stmtsToAddAfter.push_back( ifStmt );
469 } else {
470 stmtsToAddAfter.push_back( ctor );
471 } // if
472 objDecl->set_init( NULL );
473 ctorInit->set_ctor( NULL );
474 } else if ( Initializer * init = ctorInit->get_init() ) {
475 objDecl->set_init( init );
476 ctorInit->set_init( NULL );
477 } else {
478 // no constructor and no initializer, which is okay
479 objDecl->set_init( NULL );
480 } // if
481 delete ctorInit;
482 } // if
483 return objDecl;
484 }
485
486 void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
487 std::set< ObjectDecl * > prevVars = curVars;
488 Parent::visit( compoundStmt );
489 curVars = prevVars;
490 }
491
492 void ObjDeclCollector::visit( DeclStmt *stmt ) {
493 // keep track of all variables currently in scope
494 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
495 curVars.insert( objDecl );
496 } // if
497 Parent::visit( stmt );
498 }
499
500 void LabelFinder::handleStmt( Statement * stmt ) {
501 // for each label, remember the variables in scope at that label.
502 for ( Label l : stmt->get_labels() ) {
503 vars[l] = curVars;
504 } // for
505 }
506
507 template<typename Iterator, typename OutputIterator>
508 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
509 for ( Iterator it = begin ; it != end ; ++it ) {
510 // extract destructor statement from the object decl and insert it into the output. Note that this is
511 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
512 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
513 // contain side effects.
514 ObjectDecl * objDecl = *it;
515 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
516 assert( ctorInit && ctorInit->get_dtor() );
517 *out++ = ctorInit->get_dtor()->clone();
518 } // for
519 }
520
521 void InsertDtors::visit( ObjectDecl * objDecl ) {
522 // remember non-static destructed objects so that their destructors can be inserted later
523 if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
524 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
525 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
526 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
527 Statement * dtor = ctorInit->get_dtor();
528 if ( dtor && ! isInstrinsicSingleArgCallStmt( dtor ) ) {
529 // don't need to call intrinsic dtor, because it does nothing, but
530 // non-intrinsic dtors must be called
531 reverseDeclOrder.front().push_front( objDecl );
532 } // if
533 } // if
534 } // if
535 Parent::visit( objDecl );
536 }
537
538 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
539 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
540 // when block is left, just the destructors associated with variables defined in this block, so push a new
541 // list to the top of the stack so that we can differentiate scopes
542 reverseDeclOrder.push_front( OrderedDecls() );
543 Parent::visit( compoundStmt );
544
545 // add destructors for the current scope that we're exiting
546 std::list< Statement * > & statements = compoundStmt->get_kids();
547 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
548 reverseDeclOrder.pop_front();
549 }
550
551 void InsertDtors::visit( ReturnStmt * returnStmt ) {
552 // return exits all scopes, so dump destructors for all scopes
553 for ( OrderedDecls & od : reverseDeclOrder ) {
554 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
555 } // for
556 }
557
558 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
559 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
560 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
561 // of the error. See C++ Reference 6.6 Jump Statements for details.
562 void InsertDtors::handleGoto( BranchStmt * stmt ) {
563 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
564 // S_L = lvars = set of objects in scope at label definition
565 // S_G = curVars = set of objects in scope at goto statement
566 ObjectSet & lvars = labelVars[ stmt->get_target() ];
567
568 DTOR_PRINT(
569 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
570 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
571 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
572 )
573
574 ObjectSet diff;
575 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
576 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
577 DTOR_PRINT(
578 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
579 )
580 if ( ! diff.empty() ) {
581 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
582 } // if
583 // S_G-S_L results in set of objects that must be destructed
584 diff.clear();
585 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
586 DTOR_PRINT(
587 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
588 )
589 if ( ! diff.empty() ) {
590 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
591 OrderedDecls ordered;
592 for ( OrderedDecls & rdo : reverseDeclOrder ) {
593 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
594 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
595 } // for
596 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
597 } // if
598 }
599
600 void InsertDtors::visit( BranchStmt * stmt ) {
601 switch( stmt->get_type() ) {
602 case BranchStmt::Continue:
603 case BranchStmt::Break:
604 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
605 // always be empty), but it serves as a small sanity check.
606 case BranchStmt::Goto:
607 handleGoto( stmt );
608 break;
609 default:
610 assert( false );
611 } // switch
612 }
613 } // namespace
614} // namespace InitTweak
615
616// Local Variables: //
617// tab-width: 4 //
618// mode: c++ //
619// compile-command: "make install" //
620// End: //
Note: See TracBrowser for help on using the repository browser.