source: src/InitTweak/FixInit.cc@ fa463f1

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 stuck-waitfor-destruct with_gc
Last change on this file since fa463f1 was 3906301, checked in by Rob Schluntz <rschlunt@…>, 10 years ago

change constructor warnings into errors and update the test output

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