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

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 4e22d7d was 6dfa2e1, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Do not attempt to construct/destruct StmtExprs of non-constructable types

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