source: src/InitTweak/FixInit.cc@ 1bc749f

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum stuck-waitfor-destruct
Last change on this file since 1bc749f was 1bc749f, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Insert cleanup attribute for implicitly generated destructors of local variables

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