source: src/InitTweak/FixInit.cc@ 4a9ccc3

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors 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 4a9ccc3 was 092528b, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

fix copy constructing/destructing qualified argument/return temporaries

  • Property mode set to 100644
File size: 48.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 <unordered_map>
21#include <unordered_set>
22#include "InitTweak.h"
23#include "GenInit.h"
24#include "FixInit.h"
25#include "FixGlobalInit.h"
26#include "ResolvExpr/Resolver.h"
27#include "ResolvExpr/typeops.h"
28#include "SynTree/Declaration.h"
29#include "SynTree/Type.h"
30#include "SynTree/Expression.h"
31#include "SynTree/Attribute.h"
32#include "SynTree/Statement.h"
33#include "SynTree/Initializer.h"
34#include "SynTree/Mutator.h"
35#include "SymTab/Indexer.h"
36#include "SymTab/Autogen.h"
37#include "GenPoly/PolyMutator.h"
38#include "GenPoly/DeclMutator.h"
39#include "SynTree/AddStmtVisitor.h"
40#include "CodeGen/GenType.h" // for warning/error messages
41#include "Tuples/Tuples.h"
42
43bool ctordtorp = false; // print all debug
44bool ctorp = false; // print ctor debug
45bool cpctorp = false; // print copy ctor debug
46bool dtorp = false; // print dtor debug
47#define PRINT( text ) if ( ctordtorp ) { text }
48#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
49#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
50
51namespace InitTweak {
52 namespace {
53 typedef std::unordered_map< Expression *, TypeSubstitution * > EnvMap;
54
55 class InsertImplicitCalls final : public GenPoly::PolyMutator {
56 public:
57 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
58 /// function calls need their parameters to be copy constructed
59 static void insert( std::list< Declaration * > & translationUnit, EnvMap & envMap );
60
61 InsertImplicitCalls( EnvMap & envMap ) : envMap( envMap ) {}
62 typedef GenPoly::PolyMutator Parent;
63 using Parent::mutate;
64 virtual Expression * mutate( ApplicationExpr * appExpr ) override;
65 virtual Expression * mutate( StmtExpr * stmtExpr ) override;
66
67 // collects environments for relevant nodes
68 EnvMap & envMap;
69 };
70
71 class ResolveCopyCtors final : public SymTab::Indexer {
72 public:
73 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
74 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
75 /// arguments and return value temporaries
76 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap );
77
78 typedef SymTab::Indexer Parent;
79 using Parent::visit;
80
81 ResolveCopyCtors( const EnvMap & envMap ) : envMap( envMap ) {}
82
83 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
84 virtual void visit( UniqueExpr * unqExpr ) override;
85 virtual void visit( StmtExpr * stmtExpr ) override;
86
87 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
88 Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
89 /// true if type does not need to be copy constructed to ensure correctness
90 bool skipCopyConstruct( Type * type );
91 void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
92 void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
93
94 TypeSubstitution * env;
95 const EnvMap & envMap;
96 };
97
98 /// collects constructed object decls - used as a base class
99 class ObjDeclCollector : public AddStmtVisitor {
100 public:
101 typedef AddStmtVisitor Parent;
102 using Parent::visit;
103 typedef std::set< ObjectDecl * > ObjectSet;
104 virtual void visit( CompoundStmt *compoundStmt ) override;
105 virtual void visit( DeclStmt *stmt ) override;
106 protected:
107 ObjectSet curVars;
108 };
109
110 // debug
111 struct printSet {
112 typedef ObjDeclCollector::ObjectSet ObjectSet;
113 printSet( const ObjectSet & objs ) : objs( objs ) {}
114 const ObjectSet & objs;
115 };
116 std::ostream & operator<<( std::ostream & out, const printSet & set) {
117 out << "{ ";
118 for ( ObjectDecl * obj : set.objs ) {
119 out << obj->get_name() << ", " ;
120 } // for
121 out << " }";
122 return out;
123 }
124
125 class LabelFinder final : public ObjDeclCollector {
126 public:
127 typedef ObjDeclCollector Parent;
128 typedef std::map< Label, ObjectSet > LabelMap;
129 // map of Label -> live variables at that label
130 LabelMap vars;
131
132 void handleStmt( Statement * stmt );
133
134 // xxx - This needs to be done better.
135 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
136 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
137 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
138 // every specialized class knows about every new kind of statement that might be added.
139 using Parent::visit;
140 virtual void visit( CompoundStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
141 virtual void visit( ExprStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
142 virtual void visit( AsmStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
143 virtual void visit( IfStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
144 virtual void visit( WhileStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
145 virtual void visit( ForStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
146 virtual void visit( SwitchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
147 virtual void visit( CaseStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
148 virtual void visit( BranchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
149 virtual void visit( ReturnStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
150 virtual void visit( TryStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
151 virtual void visit( CatchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
152 virtual void visit( FinallyStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
153 virtual void visit( NullStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
154 virtual void visit( DeclStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
155 virtual void visit( ImplicitCtorDtorStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
156 };
157
158 class InsertDtors final : public ObjDeclCollector {
159 public:
160 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
161 /// (currently by FixInit)
162 static void insert( std::list< Declaration * > & translationUnit );
163
164 typedef ObjDeclCollector Parent;
165 typedef std::list< ObjectDecl * > OrderedDecls;
166 typedef std::list< OrderedDecls > OrderedDeclsStack;
167
168 InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
169
170 using Parent::visit;
171
172 virtual void visit( ObjectDecl * objDecl ) override;
173
174 virtual void visit( CompoundStmt * compoundStmt ) override;
175 virtual void visit( ReturnStmt * returnStmt ) override;
176 virtual void visit( BranchStmt * stmt ) override;
177 private:
178 void handleGoto( BranchStmt * stmt );
179
180 LabelFinder::LabelMap & labelVars;
181 OrderedDeclsStack reverseDeclOrder;
182 };
183
184 class FixInit final : public GenPoly::PolyMutator {
185 public:
186 /// expand each object declaration to use its constructor after it is declared.
187 static void fixInitializers( std::list< Declaration * > &translationUnit );
188
189 typedef GenPoly::PolyMutator Parent;
190 using Parent::mutate;
191 virtual DeclarationWithType * mutate( ObjectDecl *objDecl ) override;
192
193 std::list< Declaration * > staticDtorDecls;
194 };
195
196 class FixCopyCtors final : public GenPoly::PolyMutator {
197 public:
198 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
199 /// and destructors
200 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
201
202 typedef GenPoly::PolyMutator Parent;
203 using Parent::mutate;
204 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
205 virtual Expression * mutate( UniqueExpr * unqExpr ) override;
206 virtual Expression * mutate( StmtExpr * stmtExpr ) override;
207 };
208
209 class GenStructMemberCalls final : public SymTab::Indexer {
210 public:
211 typedef Indexer Parent;
212 /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
213 /// for any member that is missing a corresponding ctor/dtor call.
214 /// error if a member is used before constructed
215 static void generate( std::list< Declaration * > & translationUnit );
216
217 using Parent::visit;
218
219 virtual void visit( FunctionDecl * funcDecl ) override;
220
221 virtual void visit( MemberExpr * memberExpr ) override;
222 virtual void visit( ApplicationExpr * appExpr ) override;
223
224 SemanticError errors;
225 private:
226 void handleFirstParam( Expression * firstParam );
227 template< typename... Params >
228 void emit( const Params &... params );
229
230 FunctionDecl * function = 0;
231 std::set< DeclarationWithType * > unhandled, usedUninit;
232 ObjectDecl * thisParam = 0;
233 bool isCtor = false; // true if current function is a constructor
234 StructDecl * structDecl = 0;
235 };
236
237 // very simple resolver-like mutator class - used to
238 // resolve UntypedExprs that are found within newly
239 // generated constructor/destructor calls
240 class MutatingResolver final : public Mutator {
241 public:
242 MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
243
244 using Mutator::mutate;
245 virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override;
246 virtual Expression* mutate( UntypedExpr *untypedExpr ) override;
247
248 private:
249 SymTab::Indexer & indexer;
250 };
251
252 class FixCtorExprs final : public GenPoly::DeclMutator {
253 public:
254 /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
255 static void fix( std::list< Declaration * > & translationUnit );
256
257 using GenPoly::DeclMutator::mutate;
258 virtual Expression * mutate( ConstructorExpr * ctorExpr ) override;
259 };
260 } // namespace
261
262 void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
263 // fixes ConstructorInit for global variables. should happen before fixInitializers.
264 InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
265
266 EnvMap envMap;
267
268 InsertImplicitCalls::insert( translationUnit, envMap );
269 ResolveCopyCtors::resolveImplicitCalls( translationUnit, envMap );
270 InsertDtors::insert( translationUnit );
271 FixInit::fixInitializers( translationUnit );
272
273 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
274 FixCopyCtors::fixCopyCtors( translationUnit );
275
276 GenStructMemberCalls::generate( translationUnit );
277 // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
278 // hack in the way untyped assignments are generated, where the first argument cannot have
279 // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
280 // Thus such assignment exprs must never pushed through expression resolution (and thus should
281 // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
282 // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
283 // don't look right, and a member can be constructed more than once.
284 FixCtorExprs::fix( translationUnit );
285 }
286
287 namespace {
288 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit, EnvMap & envMap ) {
289 InsertImplicitCalls inserter( envMap );
290 mutateAll( translationUnit, inserter );
291 }
292
293 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap ) {
294 ResolveCopyCtors resolver( envMap );
295 acceptAll( translationUnit, resolver );
296 }
297
298 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
299 FixInit fixer;
300
301 // can't use mutateAll, because need to insert declarations at top-level
302 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
303 SemanticError errors;
304 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
305 try {
306 *i = maybeMutate( *i, fixer );
307 translationUnit.splice( i, fixer.staticDtorDecls );
308 } catch( SemanticError &e ) {
309 errors.append( e );
310 } // try
311 } // for
312 if ( ! errors.isEmpty() ) {
313 throw errors;
314 } // if
315 }
316
317 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
318 LabelFinder finder;
319 InsertDtors inserter( finder );
320 acceptAll( translationUnit, finder );
321 acceptAll( translationUnit, inserter );
322 }
323
324 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
325 FixCopyCtors fixer;
326 mutateAll( translationUnit, fixer );
327 }
328
329 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
330 GenStructMemberCalls warner;
331 acceptAll( translationUnit, warner );
332
333 // visitor doesn't throw so that it can collect all errors
334 if ( ! warner.errors.isEmpty() ) {
335 throw warner.errors;
336 }
337 }
338
339 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
340 FixCtorExprs fixer;
341 fixer.mutateDeclarationList( translationUnit );
342 }
343
344 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
345 appExpr = dynamic_cast< ApplicationExpr * >( Parent::mutate( appExpr ) );
346 assert( appExpr );
347
348 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
349 if ( LinkageSpec::isBuiltin( function->get_var()->get_linkage() ) ) {
350 // optimization: don't need to copy construct in order to call intrinsic functions
351 return appExpr;
352 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
353 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
354 assert( ftype );
355 if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
356 Type * t1 = ftype->get_parameters().front()->get_type();
357 Type * t2 = ftype->get_parameters().back()->get_type();
358 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( t1 );
359
360 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
361 // optimization: don't need to copy construct in order to call a copy constructor or
362 // assignment operator
363 return appExpr;
364 } // if
365 } else if ( isDestructor( funcDecl->get_name() ) ) {
366 // correctness: never copy construct arguments to a destructor
367 return appExpr;
368 } // if
369 } // if
370 } // if
371 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
372
373 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
374 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
375 // save the type substitution into the envMap so that it is easy to find.
376 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
377 // The substitution is needed to obtain the type of temporary variables so that copy constructor
378 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
379 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
380 // saves the environment, or compute the types of temporaries here, but it's much simpler to
381 // save the environment here, and more cohesive to compute temporary variables and resolve copy
382 // constructor calls together.
383 assert( env );
384 envMap[expr] = env;
385 return expr;
386 }
387
388 Expression * InsertImplicitCalls::mutate( StmtExpr * stmtExpr ) {
389 assert( env );
390 envMap[stmtExpr] = env;
391 return Parent::mutate( stmtExpr );
392 }
393
394 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
395 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type ) || Tuples::isTtype( type );
396 }
397
398 Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
399 assert( var );
400 // arrays are not copy constructed, so this should always be an ExprStmt
401 ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg );
402 ExprStmt * exprStmt = safe_dynamic_cast< ExprStmt * >( stmt->get_callStmt() );
403 Expression * untyped = exprStmt->get_expr();
404
405 // resolve copy constructor
406 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
407 // (VariableExpr and already resolved expression)
408 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
409 Expression * resolved = ResolvExpr::findVoidExpression( untyped, *this );
410 assert( resolved );
411 if ( resolved->get_env() ) {
412 // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
413 env->add( *resolved->get_env() );
414 delete resolved->get_env();
415 resolved->set_env( nullptr );
416 } // if
417
418 delete stmt;
419 return resolved;
420 }
421
422 void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
423 static UniqueName tempNamer("_tmp_cp");
424 assert( env );
425 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
426 assert( arg->has_result() );
427 Type * result = arg->get_result();
428 if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types
429
430 // type may involve type variables, so apply type substitution to get temporary variable's actual type
431 result = result->clone();
432 env->apply( result );
433 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
434 tmp->get_type()->set_isConst( false );
435
436 // create and resolve copy constructor
437 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
438 Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg );
439
440 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) {
441 // if the chosen constructor is intrinsic, the copy is unnecessary, so
442 // don't create the temporary and don't call the copy constructor
443 VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
444 assert( function );
445 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) return;
446 }
447
448 // replace argument to function call with temporary
449 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
450 impCpCtorExpr->get_tempDecls().push_back( tmp );
451 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
452 }
453
454 void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
455 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
456 }
457
458 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
459 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
460 Parent::visit( impCpCtorExpr );
461 env = envMap.at(impCpCtorExpr);
462 assert( env );
463
464 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
465
466 // take each argument and attempt to copy construct it.
467 for ( Expression * & arg : appExpr->get_args() ) {
468 copyConstructArg( arg, impCpCtorExpr );
469 } // for
470
471 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
472 // initialized with the return value and is destructed later
473 // xxx - handle named return values?
474 Type * result = appExpr->get_result();
475 if ( ! result->isVoid() ) {
476 static UniqueName retNamer("_tmp_cp_ret");
477 result = result->clone();
478 env->apply( result );
479 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
480 ret->get_type()->set_isConst( false );
481 impCpCtorExpr->get_returnDecls().push_back( ret );
482 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
483 if ( ! result->get_isLvalue() ) {
484 // destructing lvalue returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
485 destructRet( ret, impCpCtorExpr );
486 }
487 } // for
488 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
489 }
490
491 void ResolveCopyCtors::visit( StmtExpr * stmtExpr ) {
492 Parent::visit( stmtExpr );
493 env = envMap.at(stmtExpr);
494 assert( stmtExpr->get_result() );
495 Type * result = stmtExpr->get_result();
496 if ( ! result->isVoid() ) {
497 static UniqueName retNamer("_tmp_stmtexpr_ret");
498
499 // create variable that will hold the result of the stmt expr
500 result = result->clone();
501 env->apply( result );
502 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
503 ret->get_type()->set_isConst( false );
504 stmtExpr->get_returnDecls().push_front( ret );
505
506 // must have a non-empty body, otherwise it wouldn't have a result
507 CompoundStmt * body = stmtExpr->get_statements();
508 assert( ! body->get_kids().empty() );
509 // must be an ExprStmt, otherwise it wouldn't have a result
510 ExprStmt * last = safe_dynamic_cast< ExprStmt * >( body->get_kids().back() );
511 last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) );
512
513 stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
514 } // if
515
516 }
517
518 void ResolveCopyCtors::visit( UniqueExpr * unqExpr ) {
519 static std::unordered_set< int > vars;
520 if ( vars.count( unqExpr->get_id() ) ) {
521 // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
522 return;
523 }
524
525 Parent::visit( unqExpr );
526 // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
527 assert( unqExpr->get_result() );
528 if ( ImplicitCopyCtorExpr * impCpCtorExpr = dynamic_cast<ImplicitCopyCtorExpr*>( unqExpr->get_expr() ) ) {
529 // note the variable used as the result from the call
530 assert( impCpCtorExpr->get_result() && impCpCtorExpr->get_returnDecls().size() == 1 );
531 unqExpr->set_var( new VariableExpr( impCpCtorExpr->get_returnDecls().front() ) );
532 } else {
533 // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
534 unqExpr->set_object( new ObjectDecl( toString("_unq_expr_", unqExpr->get_id()), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, unqExpr->get_result()->clone(), nullptr ) );
535 unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) );
536 }
537 vars.insert( unqExpr->get_id() );
538 }
539
540 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
541 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
542
543 impCpCtorExpr = safe_dynamic_cast< ImplicitCopyCtorExpr * >( Parent::mutate( impCpCtorExpr ) );
544 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
545 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
546 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
547
548 // add all temporary declarations and their constructors
549 for ( ObjectDecl * obj : tempDecls ) {
550 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
551 } // for
552 for ( ObjectDecl * obj : returnDecls ) {
553 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
554 } // for
555
556 // add destructors after current statement
557 for ( Expression * dtor : dtors ) {
558 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
559 } // for
560
561 // xxx - update to work with multiple return values
562 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
563 Expression * callExpr = impCpCtorExpr->get_callExpr();
564
565 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
566
567 // detach fields from wrapper node so that it can be deleted without deleting too much
568 dtors.clear();
569 tempDecls.clear();
570 returnDecls.clear();
571 impCpCtorExpr->set_callExpr( NULL );
572 impCpCtorExpr->set_env( NULL );
573 delete impCpCtorExpr;
574
575 if ( returnDecl ) {
576 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
577 assign->get_args().push_back( new VariableExpr( returnDecl ) );
578 assign->get_args().push_back( callExpr );
579 // know the result type of the assignment is the type of the LHS (minus the pointer), so
580 // add that onto the assignment expression so that later steps have the necessary information
581 assign->set_result( returnDecl->get_type()->clone() );
582
583 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
584 if ( callExpr->get_result()->get_isLvalue() ) {
585 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
586 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
587 // type of the return temporary from T to T* to properly capture the return value. Then dereference
588 // the result of the comma expression, since the lvalue returning call was originally wrapped with
589 // an AddressExpr. Effectively, this turns
590 // lvalue T f();
591 // &*f();
592 // into
593 // T * f();
594 // T * tmp_cp_retN;
595 // &*(tmp_cp_retN = &*f(), tmp_cp_retN); // the first * and second & are generated here
596 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
597 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
598
599 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
600 retExpr->set_result( new PointerType( Type::Qualifiers(), retExpr->get_result() ) );
601 retExpr = UntypedExpr::createDeref( retExpr );
602 } // if
603 // move env from callExpr to retExpr
604 retExpr->set_env( callExpr->get_env() );
605 callExpr->set_env( nullptr );
606 return retExpr;
607 } else {
608 return callExpr;
609 } // if
610 }
611
612 Expression * FixCopyCtors::mutate( StmtExpr * stmtExpr ) {
613 stmtExpr = safe_dynamic_cast< StmtExpr * >( Parent::mutate( stmtExpr ) );
614 assert( stmtExpr->get_result() );
615 Type * result = stmtExpr->get_result();
616 if ( ! result->isVoid() ) {
617 for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) {
618 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
619 } // for
620 // add destructors after current statement
621 for ( Expression * dtor : stmtExpr->get_dtors() ) {
622 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
623 } // for
624 // must have a non-empty body, otherwise it wouldn't have a result
625 CompoundStmt * body = stmtExpr->get_statements();
626 assert( ! body->get_kids().empty() );
627 assert( ! stmtExpr->get_returnDecls().empty() );
628 body->get_kids().push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) );
629 }
630 stmtExpr->get_returnDecls().clear();
631 stmtExpr->get_dtors().clear();
632 return stmtExpr;
633 }
634
635 Expression * FixCopyCtors::mutate( UniqueExpr * unqExpr ) {
636 static std::unordered_map< int, UniqueExpr * > unqMap;
637 static std::unordered_set< int > addDeref;
638 // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes
639 if ( unqMap.count( unqExpr->get_id() ) ) {
640 // take data from other UniqueExpr to ensure consistency
641 delete unqExpr->get_expr();
642 unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() );
643 delete unqExpr->get_result();
644 unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
645 if ( addDeref.count( unqExpr->get_id() ) ) {
646 // other UniqueExpr was dereferenced because it was an lvalue return, so this one should be too
647 return UntypedExpr::createDeref( unqExpr );
648 }
649 return unqExpr;
650 }
651 unqExpr = safe_dynamic_cast< UniqueExpr * >( Parent::mutate( unqExpr ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
652 unqMap[unqExpr->get_id()] = unqExpr;
653 if ( UntypedExpr * deref = dynamic_cast< UntypedExpr * >( unqExpr->get_expr() ) ) {
654 // unique expression is now a dereference, because the inner expression is an lvalue returning function call.
655 // Normalize the expression by dereferencing the unique expression, rather than the inner expression
656 // (i.e. move the dereference out a level)
657 assert( getFunctionName( deref ) == "*?" );
658 unqExpr->set_expr( getCallArg( deref, 0 ) );
659 getCallArg( deref, 0 ) = unqExpr;
660 addDeref.insert( unqExpr->get_id() );
661 return deref;
662 }
663 return unqExpr;
664 }
665
666 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
667 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
668 // is removed from the ObjectDecl
669 objDecl = dynamic_cast< ObjectDecl * >( Parent::mutate( objDecl ) );
670 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
671 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
672 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
673 if ( Statement * ctor = ctorInit->get_ctor() ) {
674 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
675 // originally wanted to take advantage of gcc nested functions, but
676 // we get memory errors with this approach. To remedy this, the static
677 // variable is hoisted when the destructor needs to be called.
678 //
679 // generate:
680 // static T __objName_static_varN;
681 // void __objName_dtor_atexitN() {
682 // __dtor__...;
683 // }
684 // int f(...) {
685 // ...
686 // static bool __objName_uninitialized = true;
687 // if (__objName_uninitialized) {
688 // __ctor(__objName);
689 // __objName_uninitialized = false;
690 // atexit(__objName_dtor_atexitN);
691 // }
692 // ...
693 // }
694
695 static UniqueName dtorCallerNamer( "_dtor_atexit" );
696
697 // static bool __objName_uninitialized = true
698 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
699 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
700 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
701 isUninitializedVar->fixUniqueId();
702
703 // __objName_uninitialized = false;
704 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
705 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
706 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
707
708 // generate body of if
709 CompoundStmt * initStmts = new CompoundStmt( noLabels );
710 std::list< Statement * > & body = initStmts->get_kids();
711 body.push_back( ctor );
712 body.push_back( new ExprStmt( noLabels, setTrue ) );
713
714 // put it all together
715 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
716 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
717 stmtsToAddAfter.push_back( ifStmt );
718
719 if ( ctorInit->get_dtor() ) {
720 // if the object has a non-trivial destructor, have to
721 // hoist it and the object into the global space and
722 // call the destructor function with atexit.
723
724 Statement * dtorStmt = ctorInit->get_dtor()->clone();
725
726 // void __objName_dtor_atexitN(...) {...}
727 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
728 dtorCaller->fixUniqueId();
729 dtorCaller->get_statements()->push_back( dtorStmt );
730
731 // atexit(dtor_atexit);
732 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
733 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
734
735 body.push_back( new ExprStmt( noLabels, callAtexit ) );
736
737 // hoist variable and dtor caller decls to list of decls that will be added into global scope
738 staticDtorDecls.push_back( objDecl );
739 staticDtorDecls.push_back( dtorCaller );
740
741 // need to rename object uniquely since it now appears
742 // at global scope and there could be multiple function-scoped
743 // static variables with the same name in different functions.
744 // Note: it isn't sufficient to modify only the mangleName, because
745 // then subsequent Indexer passes can choke on seeing the object's name
746 // if another object has the same name and type. An unfortunate side-effect
747 // of renaming the object is that subsequent NameExprs may fail to resolve,
748 // but there shouldn't be any remaining past this point.
749 static UniqueName staticNamer( "_static_var" );
750 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
751 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
752
753 objDecl->set_init( NULL );
754 ctorInit->set_ctor( NULL );
755 delete ctorInit;
756
757 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
758 // create a new object which is never used
759 static UniqueName dummyNamer( "_dummy" );
760 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") } );
761 return dummy;
762 }
763 } else {
764 stmtsToAddAfter.push_back( ctor );
765 } // if
766 objDecl->set_init( NULL );
767 ctorInit->set_ctor( NULL );
768 } else if ( Initializer * init = ctorInit->get_init() ) {
769 objDecl->set_init( init );
770 ctorInit->set_init( NULL );
771 } else {
772 // no constructor and no initializer, which is okay
773 objDecl->set_init( NULL );
774 } // if
775 delete ctorInit;
776 } // if
777 return objDecl;
778 }
779
780 void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
781 std::set< ObjectDecl * > prevVars = curVars;
782 Parent::visit( compoundStmt );
783 curVars = prevVars;
784 }
785
786 void ObjDeclCollector::visit( DeclStmt *stmt ) {
787 // keep track of all variables currently in scope
788 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
789 curVars.insert( objDecl );
790 } // if
791 Parent::visit( stmt );
792 }
793
794 void LabelFinder::handleStmt( Statement * stmt ) {
795 // for each label, remember the variables in scope at that label.
796 for ( Label l : stmt->get_labels() ) {
797 vars[l] = curVars;
798 } // for
799 }
800
801 template<typename Iterator, typename OutputIterator>
802 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
803 for ( Iterator it = begin ; it != end ; ++it ) {
804 // extract destructor statement from the object decl and insert it into the output. Note that this is
805 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
806 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
807 // contain side effects.
808 ObjectDecl * objDecl = *it;
809 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
810 assert( ctorInit && ctorInit->get_dtor() );
811 *out++ = ctorInit->get_dtor()->clone();
812 } // for
813 }
814
815 void InsertDtors::visit( ObjectDecl * objDecl ) {
816 // remember non-static destructed objects so that their destructors can be inserted later
817 if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
818 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
819 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
820 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
821 Statement * dtor = ctorInit->get_dtor();
822 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
823 // don't need to call intrinsic dtor, because it does nothing, but
824 // non-intrinsic dtors must be called
825 reverseDeclOrder.front().push_front( objDecl );
826 } // if
827 } // if
828 } // if
829 Parent::visit( objDecl );
830 }
831
832 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
833 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
834 // when block is left, just the destructors associated with variables defined in this block, so push a new
835 // list to the top of the stack so that we can differentiate scopes
836 reverseDeclOrder.push_front( OrderedDecls() );
837 Parent::visit( compoundStmt );
838
839 // add destructors for the current scope that we're exiting
840 std::list< Statement * > & statements = compoundStmt->get_kids();
841 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
842 reverseDeclOrder.pop_front();
843 }
844
845 void InsertDtors::visit( ReturnStmt * returnStmt ) {
846 // return exits all scopes, so dump destructors for all scopes
847 for ( OrderedDecls & od : reverseDeclOrder ) {
848 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
849 } // for
850 }
851
852 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
853 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
854 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
855 // of the error. See C++ Reference 6.6 Jump Statements for details.
856 void InsertDtors::handleGoto( BranchStmt * stmt ) {
857 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
858 // S_L = lvars = set of objects in scope at label definition
859 // S_G = curVars = set of objects in scope at goto statement
860 ObjectSet & lvars = labelVars[ stmt->get_target() ];
861
862 DTOR_PRINT(
863 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
864 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
865 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
866 )
867
868 ObjectSet diff;
869 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
870 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
871 DTOR_PRINT(
872 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
873 )
874 if ( ! diff.empty() ) {
875 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
876 } // if
877 // S_G-S_L results in set of objects that must be destructed
878 diff.clear();
879 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
880 DTOR_PRINT(
881 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
882 )
883 if ( ! diff.empty() ) {
884 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
885 OrderedDecls ordered;
886 for ( OrderedDecls & rdo : reverseDeclOrder ) {
887 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
888 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
889 } // for
890 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
891 } // if
892 }
893
894 void InsertDtors::visit( BranchStmt * stmt ) {
895 switch( stmt->get_type() ) {
896 case BranchStmt::Continue:
897 case BranchStmt::Break:
898 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
899 // always be empty), but it serves as a small sanity check.
900 case BranchStmt::Goto:
901 handleGoto( stmt );
902 break;
903 default:
904 assert( false );
905 } // switch
906 }
907
908 bool checkWarnings( FunctionDecl * funcDecl ) {
909 // only check for warnings if the current function is a user-defined
910 // constructor or destructor
911 if ( ! funcDecl ) return false;
912 if ( ! funcDecl->get_statements() ) return false;
913 return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
914 }
915
916 void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
917 ValueGuard< FunctionDecl * > oldFunction( funcDecl );
918 ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
919 ValueGuard< std::set< DeclarationWithType * > > oldUsedUninit( usedUninit );
920 ValueGuard< ObjectDecl * > oldThisParam( thisParam );
921 ValueGuard< bool > oldIsCtor( isCtor );
922 ValueGuard< StructDecl * > oldStructDecl( structDecl );
923
924 // need to start with fresh sets
925 unhandled.clear();
926 usedUninit.clear();
927
928 function = funcDecl;
929 isCtor = isConstructor( function->get_name() );
930 if ( checkWarnings( function ) ) {
931 FunctionType * type = function->get_functionType();
932 assert( ! type->get_parameters().empty() );
933 thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
934 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
935 StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
936 if ( structType ) {
937 structDecl = structType->get_baseStruct();
938 for ( Declaration * member : structDecl->get_members() ) {
939 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
940 // record all of the struct type's members that need to be constructed or
941 // destructed by the end of the function
942 unhandled.insert( field );
943 }
944 }
945 }
946 }
947 Parent::visit( function );
948
949 // remove the unhandled objects from usedUninit, because a call is inserted
950 // to handle them - only objects that are later constructed are used uninitialized.
951 std::set< DeclarationWithType * > diff;
952 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ) );
953 for ( DeclarationWithType * member : diff ) {
954 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", member->get_name(), " used before being constructed" );
955 }
956
957 if ( ! unhandled.empty() ) {
958 // need to explicitly re-add function parameters in order to resolve copy constructors
959 enterScope();
960 maybeAccept( function->get_functionType(), *this );
961
962 // need to iterate through members in reverse in order for
963 // ctor/dtor statements to come out in the right order
964 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
965 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
966 // skip non-DWT members
967 if ( ! field ) continue;
968 // skip handled members
969 if ( ! unhandled.count( field ) ) continue;
970
971 // insert and resolve default/copy constructor call for each field that's unhandled
972 std::list< Statement * > stmt;
973 UntypedExpr * deref = UntypedExpr::createDeref( new VariableExpr( thisParam ) );
974
975 Expression * arg2 = 0;
976 if ( isCopyConstructor( function ) ) {
977 // if copy ctor, need to pass second-param-of-this-function.field
978 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
979 assert( params.size() == 2 );
980 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
981 }
982 InitExpander srcParam( arg2 );
983 SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
984
985 assert( stmt.size() <= 1 );
986 if ( stmt.size() == 1 ) {
987 Statement * callStmt = stmt.front();
988
989 MutatingResolver resolver( *this );
990 try {
991 callStmt->acceptMutator( resolver );
992 if ( isCtor ) {
993 function->get_statements()->push_front( callStmt );
994 } else {
995 // destructor statements should be added at the end
996 function->get_statements()->push_back( callStmt );
997 }
998 } catch ( SemanticError & error ) {
999 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" );
1000 }
1001 }
1002 }
1003 leaveScope();
1004 }
1005 }
1006
1007 void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
1008 if ( ! checkWarnings( function ) ) return;
1009
1010 std::string fname = getFunctionName( appExpr );
1011 if ( fname == function->get_name() ) {
1012 // call to same kind of function
1013 Expression * firstParam = appExpr->get_args().front();
1014
1015 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
1016 // if calling another constructor on thisParam, assume that function handles
1017 // all members - if it doesn't a warning will appear in that function.
1018 if ( varExpr->get_var() == thisParam ) {
1019 unhandled.clear();
1020 }
1021 } else {
1022 // if first parameter is a member expression then
1023 // remove the member from unhandled set.
1024 handleFirstParam( firstParam );
1025 }
1026 }
1027
1028 Parent::visit( appExpr );
1029 }
1030
1031 void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
1032 using namespace std;
1033 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
1034 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
1035 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1036 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1037 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1038 if ( varExpr->get_var() == thisParam ) {
1039 unhandled.erase( memberExpr->get_member() );
1040 }
1041 }
1042 }
1043 }
1044 }
1045 }
1046 }
1047
1048 void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
1049 if ( ! checkWarnings( function ) ) return;
1050 if ( ! isCtor ) return;
1051
1052 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1053 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1054 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1055 if ( varExpr->get_var() == thisParam ) {
1056 if ( unhandled.count( memberExpr->get_member() ) ) {
1057 // emit a warning because a member was used before it was constructed
1058 usedUninit.insert( memberExpr->get_member() );
1059 }
1060 }
1061 }
1062 }
1063 }
1064 Parent::visit( memberExpr );
1065 }
1066
1067 template< typename Visitor, typename... Params >
1068 void error( Visitor & v, const Params &... params ) {
1069 v.errors.append( toString( params... ) );
1070 }
1071
1072 template< typename... Params >
1073 void GenStructMemberCalls::emit( const Params &... params ) {
1074 // toggle warnings vs. errors here.
1075 // warn( params... );
1076 error( *this, params... );
1077 }
1078
1079 DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
1080 // add object to the indexer assumes that there will be no name collisions
1081 // in generated code. If this changes, add mutate methods for entities with
1082 // scope and call {enter,leave}Scope explicitly.
1083 objectDecl->accept( indexer );
1084 return objectDecl;
1085 }
1086
1087 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
1088 return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
1089 }
1090
1091 Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
1092 static UniqueName tempNamer( "_tmp_ctor_expr" );
1093 // xxx - is the size check necessary?
1094 assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
1095 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
1096 addDeclaration( tmp );
1097
1098 // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
1099 ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
1100 TypeSubstitution * env = ctorExpr->get_env();
1101 ctorExpr->set_callExpr( nullptr );
1102 ctorExpr->set_env( nullptr );
1103
1104 Expression *& firstArg = callExpr->get_args().front();
1105 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
1106 assign->get_args().push_back( new VariableExpr( tmp ) );
1107 assign->get_args().push_back( firstArg );
1108 assign->set_result( ctorExpr->get_result()->clone() );
1109 firstArg = assign;
1110
1111 CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
1112 commaExpr->set_env( env );
1113 delete ctorExpr;
1114 return commaExpr;
1115 }
1116 } // namespace
1117} // namespace InitTweak
1118
1119// Local Variables: //
1120// tab-width: 4 //
1121// mode: c++ //
1122// compile-command: "make install" //
1123// End: //
Note: See TracBrowser for help on using the repository browser.