source: src/InitTweak/FixInit.cc@ e491159

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor 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 e491159 was 486341f, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

add option to CodeGen to output unmangled name, add ctorWarnings test

  • Property mode set to 100644
File size: 34.9 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 : Tue Jul 12 17:41:15 2016
13// Update Count : 34
14//
15
16#include <stack>
17#include <list>
18#include <iterator>
19#include <algorithm>
20#include "InitTweak.h"
21#include "FixInit.h"
22#include "FixGlobalInit.h"
23#include "ResolvExpr/Resolver.h"
24#include "ResolvExpr/typeops.h"
25#include "SynTree/Declaration.h"
26#include "SynTree/Type.h"
27#include "SynTree/Expression.h"
28#include "SynTree/Attribute.h"
29#include "SynTree/Statement.h"
30#include "SynTree/Initializer.h"
31#include "SynTree/Mutator.h"
32#include "SymTab/Indexer.h"
33#include "GenPoly/PolyMutator.h"
34#include "SynTree/AddStmtVisitor.h"
35#include "CodeGen/GenType.h" // for warnings
36
37bool ctordtorp = false;
38bool ctorp = false;
39bool cpctorp = false;
40bool dtorp = false;
41#define PRINT( text ) if ( ctordtorp ) { text }
42#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
43#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
44
45namespace InitTweak {
46 namespace {
47 const std::list<Label> noLabels;
48 const std::list<Expression*> noDesignators;
49
50 class InsertImplicitCalls : public GenPoly::PolyMutator {
51 public:
52 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
53 /// function calls need their parameters to be copy constructed
54 static void insert( std::list< Declaration * > & translationUnit );
55
56 virtual Expression * mutate( ApplicationExpr * appExpr );
57 };
58
59 class ResolveCopyCtors : public SymTab::Indexer {
60 public:
61 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
62 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
63 /// arguments and return value temporaries
64 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
65
66 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
67
68 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
69 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
70 /// true if type does not need to be copy constructed to ensure correctness
71 bool skipCopyConstruct( Type * );
72 private:
73 TypeSubstitution * env;
74 };
75
76 /// collects constructed object decls - used as a base class
77 class ObjDeclCollector : public AddStmtVisitor {
78 public:
79 typedef AddStmtVisitor Parent;
80 using Parent::visit;
81 typedef std::set< ObjectDecl * > ObjectSet;
82 virtual void visit( CompoundStmt *compoundStmt );
83 virtual void visit( DeclStmt *stmt );
84 protected:
85 ObjectSet curVars;
86 };
87
88 // debug
89 struct printSet {
90 typedef ObjDeclCollector::ObjectSet ObjectSet;
91 printSet( const ObjectSet & objs ) : objs( objs ) {}
92 const ObjectSet & objs;
93 };
94 std::ostream & operator<<( std::ostream & out, const printSet & set) {
95 out << "{ ";
96 for ( ObjectDecl * obj : set.objs ) {
97 out << obj->get_name() << ", " ;
98 } // for
99 out << " }";
100 return out;
101 }
102
103 class LabelFinder : public ObjDeclCollector {
104 public:
105 typedef ObjDeclCollector Parent;
106 typedef std::map< Label, ObjectSet > LabelMap;
107 // map of Label -> live variables at that label
108 LabelMap vars;
109
110 void handleStmt( Statement * stmt );
111
112 // xxx - This needs to be done better.
113 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
114 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
115 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
116 // every specialized class knows about every new kind of statement that might be added.
117 virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
118 virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
119 virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
120 virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
121 virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
122 virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
123 virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
124 virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
125 virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
126 virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
127 virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
128 virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
129 virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
130 virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
131 virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
132 virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
133 };
134
135 class InsertDtors : public ObjDeclCollector {
136 public:
137 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
138 /// (currently by FixInit)
139 static void insert( std::list< Declaration * > & translationUnit );
140
141 typedef ObjDeclCollector Parent;
142 typedef std::list< ObjectDecl * > OrderedDecls;
143 typedef std::list< OrderedDecls > OrderedDeclsStack;
144
145 InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
146
147 virtual void visit( ObjectDecl * objDecl );
148
149 virtual void visit( CompoundStmt * compoundStmt );
150 virtual void visit( ReturnStmt * returnStmt );
151 virtual void visit( BranchStmt * stmt );
152 private:
153 void handleGoto( BranchStmt * stmt );
154
155 LabelFinder::LabelMap & labelVars;
156 OrderedDeclsStack reverseDeclOrder;
157 };
158
159 class FixInit : public GenPoly::PolyMutator {
160 public:
161 /// expand each object declaration to use its constructor after it is declared.
162 static void fixInitializers( std::list< Declaration * > &translationUnit );
163
164 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
165
166 std::list< Declaration * > staticDtorDecls;
167 };
168
169 class FixCopyCtors : public GenPoly::PolyMutator {
170 public:
171 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
172 /// and destructors
173 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
174
175 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
176 };
177
178 class WarnStructMembers : public Visitor {
179 public:
180 typedef Visitor Parent;
181 /// warn if a user-defined constructor or destructor is missing calls for
182 /// a struct member or if a member is used before constructed
183 static void warnings( std::list< Declaration * > & translationUnit );
184
185 virtual void visit( FunctionDecl * funcDecl );
186
187 virtual void visit( MemberExpr * memberExpr );
188 virtual void visit( ApplicationExpr * appExpr );
189
190 private:
191 void handleFirstParam( Expression * firstParam );
192
193 FunctionDecl * function = 0;
194 std::set< DeclarationWithType * > unhandled;
195 ObjectDecl * thisParam = 0;
196 };
197 } // namespace
198
199 void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
200 // fixes ConstructorInit for global variables. should happen before fixInitializers.
201 InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
202
203 InsertImplicitCalls::insert( translationUnit );
204 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
205 InsertDtors::insert( translationUnit );
206 FixInit::fixInitializers( translationUnit );
207
208 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
209 FixCopyCtors::fixCopyCtors( translationUnit );
210
211 WarnStructMembers::warnings( translationUnit );
212 }
213
214 namespace {
215 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
216 InsertImplicitCalls inserter;
217 mutateAll( translationUnit, inserter );
218 }
219
220 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
221 ResolveCopyCtors resolver;
222 acceptAll( translationUnit, resolver );
223 }
224
225 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
226 FixInit fixer;
227
228 // can't use mutateAll, because need to insert declarations at top-level
229 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
230 SemanticError errors;
231 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
232 try {
233 *i = maybeMutate( *i, fixer );
234 translationUnit.splice( i, fixer.staticDtorDecls );
235 } catch( SemanticError &e ) {
236 errors.append( e );
237 } // try
238 } // for
239 if ( ! errors.isEmpty() ) {
240 throw errors;
241 } // if
242 }
243
244 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
245 LabelFinder finder;
246 InsertDtors inserter( finder );
247 acceptAll( translationUnit, finder );
248 acceptAll( translationUnit, inserter );
249 }
250
251 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
252 FixCopyCtors fixer;
253 mutateAll( translationUnit, fixer );
254 }
255
256 void WarnStructMembers::warnings( std::list< Declaration * > & translationUnit ) {
257 if ( true ) { // fix this condition to skip this pass if warnings aren't enabled
258 WarnStructMembers warner;
259 acceptAll( translationUnit, warner );
260 }
261 }
262
263 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
264 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
265 assert( appExpr );
266
267 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
268 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
269 // optimization: don't need to copy construct in order to call intrinsic functions
270 return appExpr;
271 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
272 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
273 assert( ftype );
274 if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
275 Type * t1 = ftype->get_parameters().front()->get_type();
276 Type * t2 = ftype->get_parameters().back()->get_type();
277 PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
278 assert( ptrType );
279
280 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
281 // optimization: don't need to copy construct in order to call a copy constructor or
282 // assignment operator
283 return appExpr;
284 } // if
285 } else if ( isDestructor( funcDecl->get_name() ) ) {
286 // correctness: never copy construct arguments to a destructor
287 return appExpr;
288 } // if
289 } // if
290 } // if
291 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
292
293 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
294 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
295 // save the type substitution onto the new node so that it is easy to find.
296 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
297 // The substitution is needed to obtain the type of temporary variables so that copy constructor
298 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
299 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
300 // saves the environment, or compute the types of temporaries here, but it's much simpler to
301 // save the environment here, and more cohesive to compute temporary variables and resolve copy
302 // constructor calls together.
303 assert( env );
304 expr->set_env( env );
305 return expr;
306 }
307
308 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
309 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
310 }
311
312 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
313 assert( var );
314 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
315 untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
316 if (cpArg) untyped->get_args().push_back( cpArg->clone() );
317
318 // resolve copy constructor
319 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
320 // (VariableExpr and already resolved expression)
321 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
322 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
323 if ( resolved->get_env() ) {
324 env->add( *resolved->get_env() );
325 } // if
326
327 assert( resolved );
328 delete untyped;
329 return resolved;
330 }
331
332 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
333 static UniqueName tempNamer("_tmp_cp");
334 static UniqueName retNamer("_tmp_cp_ret");
335
336 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
337 Visitor::visit( impCpCtorExpr );
338 env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
339
340 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
341
342 // take each argument and attempt to copy construct it.
343 for ( Expression * & arg : appExpr->get_args() ) {
344 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
345 // xxx - need to handle tuple arguments
346 assert( ! arg->get_results().empty() );
347 Type * result = arg->get_results().front();
348 if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
349 // type may involve type variables, so apply type substitution to get temporary variable's actual type
350 result = result->clone();
351 impCpCtorExpr->get_env()->apply( result );
352 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
353 tmp->get_type()->set_isConst( false );
354
355 // create and resolve copy constructor
356 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
357 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
358
359 // if the chosen constructor is intrinsic, the copy is unnecessary, so
360 // don't create the temporary and don't call the copy constructor
361 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
362 assert( function );
363 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
364 // replace argument to function call with temporary
365 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
366 impCpCtorExpr->get_tempDecls().push_back( tmp );
367 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
368 } // if
369 } // for
370
371 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
372 // initialized with the return value and is destructed later
373 // xxx - handle multiple return values
374 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
375 // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
376 // level. Trying to pass that environment along.
377 callExpr->set_env( impCpCtorExpr->get_env()->clone() );
378 for ( Type * result : appExpr->get_results() ) {
379 result = result->clone();
380 impCpCtorExpr->get_env()->apply( result );
381 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
382 ret->get_type()->set_isConst( false );
383 impCpCtorExpr->get_returnDecls().push_back( ret );
384 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
385 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
386 } // for
387 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
388 }
389
390
391 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
392 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
393
394 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
395 assert( impCpCtorExpr );
396
397 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
398 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
399 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
400
401 // add all temporary declarations and their constructors
402 for ( ObjectDecl * obj : tempDecls ) {
403 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
404 } // for
405 for ( ObjectDecl * obj : returnDecls ) {
406 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
407 } // for
408
409 // add destructors after current statement
410 for ( Expression * dtor : dtors ) {
411 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
412 } // for
413
414 // xxx - update to work with multiple return values
415 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
416 Expression * callExpr = impCpCtorExpr->get_callExpr();
417
418 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
419
420 // detach fields from wrapper node so that it can be deleted without deleting too much
421 dtors.clear();
422 tempDecls.clear();
423 returnDecls.clear();
424 impCpCtorExpr->set_callExpr( NULL );
425 impCpCtorExpr->set_env( NULL );
426 delete impCpCtorExpr;
427
428 if ( returnDecl ) {
429 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
430 assign->get_args().push_back( new VariableExpr( returnDecl ) );
431 assign->get_args().push_back( callExpr );
432 // know the result type of the assignment is the type of the LHS (minus the pointer), so
433 // add that onto the assignment expression so that later steps have the necessary information
434 assign->add_result( returnDecl->get_type()->clone() );
435
436 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
437 if ( callExpr->get_results().front()->get_isLvalue() ) {
438 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
439 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
440 // type of the return temporary from T to T* to properly capture the return value. Then dereference
441 // the result of the comma expression, since the lvalue returning call was originally wrapped with
442 // an AddressExpr. Effectively, this turns
443 // lvalue T f();
444 // &*f()
445 // into
446 // T * tmp_cp_retN;
447 // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
448 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
449 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
450
451 Type * resultType = returnDecl->get_type()->clone();
452 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
453 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
454 deref->get_args().push_back( retExpr );
455 deref->add_result( resultType );
456 retExpr = deref;
457 } // if
458 // xxx - might need to set env on retExpr...
459 // retExpr->set_env( env->clone() );
460 return retExpr;
461 } else {
462 return callExpr;
463 } // if
464 }
465
466 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
467 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
468 // is removed from the ObjectDecl
469 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
470
471 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
472 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
473 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
474 if ( Statement * ctor = ctorInit->get_ctor() ) {
475 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
476 // originally wanted to take advantage of gcc nested functions, but
477 // we get memory errors with this approach. To remedy this, the static
478 // variable is hoisted when the destructor needs to be called.
479 //
480 // generate:
481 // static T __objName_static_varN;
482 // void __objName_dtor_atexitN() {
483 // __dtor__...;
484 // }
485 // int f(...) {
486 // ...
487 // static bool __objName_uninitialized = true;
488 // if (__objName_uninitialized) {
489 // __ctor(__objName);
490 // __objName_uninitialized = false;
491 // atexit(__objName_dtor_atexitN);
492 // }
493 // ...
494 // }
495
496 static UniqueName dtorCallerNamer( "_dtor_atexit" );
497
498 // static bool __objName_uninitialized = true
499 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
500 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
501 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
502 isUninitializedVar->fixUniqueId();
503
504 // __objName_uninitialized = false;
505 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
506 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
507 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
508
509 // generate body of if
510 CompoundStmt * initStmts = new CompoundStmt( noLabels );
511 std::list< Statement * > & body = initStmts->get_kids();
512 body.push_back( ctor );
513 body.push_back( new ExprStmt( noLabels, setTrue ) );
514
515 // put it all together
516 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
517 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
518 stmtsToAddAfter.push_back( ifStmt );
519
520 if ( ctorInit->get_dtor() ) {
521 // if the object has a non-trivial destructor, have to
522 // hoist it and the object into the global space and
523 // call the destructor function with atexit.
524
525 Statement * dtorStmt = ctorInit->get_dtor()->clone();
526
527 // void __objName_dtor_atexitN(...) {...}
528 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
529 dtorCaller->fixUniqueId();
530 dtorCaller->get_statements()->get_kids().push_back( dtorStmt );
531
532 // atexit(dtor_atexit);
533 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
534 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
535
536 body.push_back( new ExprStmt( noLabels, callAtexit ) );
537
538 // hoist variable and dtor caller decls to list of decls that will be added into global scope
539 staticDtorDecls.push_back( objDecl );
540 staticDtorDecls.push_back( dtorCaller );
541
542 // need to rename object uniquely since it now appears
543 // at global scope and there could be multiple function-scoped
544 // static variables with the same name in different functions.
545 static UniqueName staticNamer( "_static_var" );
546 objDecl->set_mangleName( objDecl->get_mangleName() + staticNamer.newName() );
547
548 objDecl->set_init( NULL );
549 ctorInit->set_ctor( NULL );
550 delete ctorInit;
551
552 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
553 // create a new object which is never used
554 static UniqueName dummyNamer( "_dummy" );
555 ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), DeclarationNode::Static, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
556 return dummy;
557 }
558 } else {
559 stmtsToAddAfter.push_back( ctor );
560 } // if
561 objDecl->set_init( NULL );
562 ctorInit->set_ctor( NULL );
563 } else if ( Initializer * init = ctorInit->get_init() ) {
564 objDecl->set_init( init );
565 ctorInit->set_init( NULL );
566 } else {
567 // no constructor and no initializer, which is okay
568 objDecl->set_init( NULL );
569 } // if
570 delete ctorInit;
571 } // if
572 return objDecl;
573 }
574
575 void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
576 std::set< ObjectDecl * > prevVars = curVars;
577 Parent::visit( compoundStmt );
578 curVars = prevVars;
579 }
580
581 void ObjDeclCollector::visit( DeclStmt *stmt ) {
582 // keep track of all variables currently in scope
583 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
584 curVars.insert( objDecl );
585 } // if
586 Parent::visit( stmt );
587 }
588
589 void LabelFinder::handleStmt( Statement * stmt ) {
590 // for each label, remember the variables in scope at that label.
591 for ( Label l : stmt->get_labels() ) {
592 vars[l] = curVars;
593 } // for
594 }
595
596 template<typename Iterator, typename OutputIterator>
597 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
598 for ( Iterator it = begin ; it != end ; ++it ) {
599 // extract destructor statement from the object decl and insert it into the output. Note that this is
600 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
601 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
602 // contain side effects.
603 ObjectDecl * objDecl = *it;
604 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
605 assert( ctorInit && ctorInit->get_dtor() );
606 *out++ = ctorInit->get_dtor()->clone();
607 } // for
608 }
609
610 void InsertDtors::visit( ObjectDecl * objDecl ) {
611 // remember non-static destructed objects so that their destructors can be inserted later
612 if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
613 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
614 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
615 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
616 Statement * dtor = ctorInit->get_dtor();
617 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
618 // don't need to call intrinsic dtor, because it does nothing, but
619 // non-intrinsic dtors must be called
620 reverseDeclOrder.front().push_front( objDecl );
621 } // if
622 } // if
623 } // if
624 Parent::visit( objDecl );
625 }
626
627 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
628 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
629 // when block is left, just the destructors associated with variables defined in this block, so push a new
630 // list to the top of the stack so that we can differentiate scopes
631 reverseDeclOrder.push_front( OrderedDecls() );
632 Parent::visit( compoundStmt );
633
634 // add destructors for the current scope that we're exiting
635 std::list< Statement * > & statements = compoundStmt->get_kids();
636 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
637 reverseDeclOrder.pop_front();
638 }
639
640 void InsertDtors::visit( ReturnStmt * returnStmt ) {
641 // return exits all scopes, so dump destructors for all scopes
642 for ( OrderedDecls & od : reverseDeclOrder ) {
643 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
644 } // for
645 }
646
647 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
648 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
649 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
650 // of the error. See C++ Reference 6.6 Jump Statements for details.
651 void InsertDtors::handleGoto( BranchStmt * stmt ) {
652 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
653 // S_L = lvars = set of objects in scope at label definition
654 // S_G = curVars = set of objects in scope at goto statement
655 ObjectSet & lvars = labelVars[ stmt->get_target() ];
656
657 DTOR_PRINT(
658 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
659 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
660 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
661 )
662
663 ObjectSet diff;
664 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
665 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
666 DTOR_PRINT(
667 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
668 )
669 if ( ! diff.empty() ) {
670 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
671 } // if
672 // S_G-S_L results in set of objects that must be destructed
673 diff.clear();
674 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
675 DTOR_PRINT(
676 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
677 )
678 if ( ! diff.empty() ) {
679 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
680 OrderedDecls ordered;
681 for ( OrderedDecls & rdo : reverseDeclOrder ) {
682 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
683 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
684 } // for
685 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
686 } // if
687 }
688
689 void InsertDtors::visit( BranchStmt * stmt ) {
690 switch( stmt->get_type() ) {
691 case BranchStmt::Continue:
692 case BranchStmt::Break:
693 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
694 // always be empty), but it serves as a small sanity check.
695 case BranchStmt::Goto:
696 handleGoto( stmt );
697 break;
698 default:
699 assert( false );
700 } // switch
701 }
702
703 bool checkWarnings( FunctionDecl * funcDecl ) {
704 // only check for warnings if the current function is a user-defined
705 // constructor or destructor
706 if ( ! funcDecl ) return false;
707 if ( ! funcDecl->get_statements() ) return false;
708 return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
709 }
710
711 void WarnStructMembers::visit( FunctionDecl * funcDecl ) {
712 WarnStructMembers old = *this;
713 *this = WarnStructMembers();
714
715 function = funcDecl;
716 if ( checkWarnings( funcDecl ) ) {
717 FunctionType * type = funcDecl->get_functionType();
718 assert( ! type->get_parameters().empty() );
719 thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
720 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
721 StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
722 if ( structType ) {
723 StructDecl * structDecl = structType->get_baseStruct();
724 for ( Declaration * member : structDecl->get_members() ) {
725 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
726 // record all of the struct type's members that need to be constructed or
727 // destructed by the end of the function
728 unhandled.insert( field );
729 }
730 }
731 }
732 }
733 Parent::visit( funcDecl );
734
735 for ( DeclarationWithType * member : unhandled ) {
736 // emit a warning for each unhandled member
737 warn( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", member ", member->get_name(), " may not have been ", isConstructor( funcDecl->get_name() ) ? "constructed" : "destructed" );
738 }
739
740 *this = old;
741 }
742
743 void WarnStructMembers::visit( ApplicationExpr * appExpr ) {
744 if ( ! checkWarnings( function ) ) return;
745
746 std::string fname = getFunctionName( appExpr );
747 if ( fname == function->get_name() ) {
748 // call to same kind of function
749 Expression * firstParam = appExpr->get_args().front();
750
751 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
752 // if calling another constructor on thisParam, assume that function handles
753 // all members - if it doesn't a warning will appear in that function.
754 if ( varExpr->get_var() == thisParam ) {
755 unhandled.clear();
756 }
757 } else {
758 // if first parameter is a member expression then
759 // remove the member from unhandled set.
760 handleFirstParam( firstParam );
761 }
762 } else if ( fname == "?=?" && isIntrinsicCallExpr( appExpr ) ) {
763 // forgive use of intrinsic assignment to construct, since instrinsic constructors
764 // codegen as assignment anyway.
765 assert( appExpr->get_args().size() == 2 );
766 handleFirstParam( appExpr->get_args().front() );
767 }
768
769 Parent::visit( appExpr );
770 }
771
772 void WarnStructMembers::handleFirstParam( Expression * firstParam ) {
773 using namespace std;
774 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
775 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
776 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
777 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
778 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
779 if ( varExpr->get_var() == thisParam ) {
780 unhandled.erase( memberExpr->get_member() );
781 }
782 }
783 }
784 }
785 }
786 }
787 }
788
789 void WarnStructMembers::visit( MemberExpr * memberExpr ) {
790 if ( ! checkWarnings( function ) ) return;
791 if ( ! isConstructor( function->get_name() ) ) return;
792
793 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
794 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
795 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
796 if ( varExpr->get_var() == thisParam ) {
797 if ( unhandled.count( memberExpr->get_member() ) ) {
798 // emit a warning because a member was used before it was constructed
799 warn( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", member ", memberExpr->get_member()->get_name(), " used before being constructed" );
800 }
801 }
802 }
803 }
804 }
805 Parent::visit( memberExpr );
806 }
807 } // namespace
808} // namespace InitTweak
809
810// Local Variables: //
811// tab-width: 4 //
812// mode: c++ //
813// compile-command: "make install" //
814// End: //
Note: See TracBrowser for help on using the repository browser.