source: src/InitTweak/FixInit.cc@ 9dbf7c8

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 9dbf7c8 was be151bf, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Minor cleanup in InsertImplicitCalls and augment assert in strict_dynamic_cast

  • Property mode set to 100644
File size: 50.9 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// FixInit.h --
8//
9// Author : Rob Schluntz
10// Created On : Wed Jan 13 16:29:30 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : 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/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 );
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 // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
263 // hack in the way untyped assignments are generated, where the first argument cannot have
264 // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
265 // Thus such assignment exprs must never pushed through expression resolution (and thus should
266 // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
267 // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
268 // don't look right, and a member can be constructed more than once.
269 FixCtorExprs::fix( translationUnit );
270 }
271
272 namespace {
273 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
274 PassVisitor<InsertImplicitCalls> inserter;
275 mutateAll( translationUnit, inserter );
276 }
277
278 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
279 PassVisitor<ResolveCopyCtors> resolver( unqCount );
280 acceptAll( translationUnit, resolver );
281 }
282
283 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
284 PassVisitor<FixInit> fixer;
285
286 // can't use mutateAll, because need to insert declarations at top-level
287 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
288 SemanticError errors;
289 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
290 try {
291 maybeMutate( *i, fixer );
292 translationUnit.splice( i, fixer.pass.staticDtorDecls );
293 } catch( SemanticError &e ) {
294 e.set_location( (*i)->location );
295 errors.append( e );
296 } // try
297 } // for
298 if ( ! errors.isEmpty() ) {
299 throw errors;
300 } // if
301 }
302
303 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
304 PassVisitor<LabelFinder> finder;
305 PassVisitor<InsertDtors> inserter( finder );
306 acceptAll( translationUnit, inserter );
307 }
308
309 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
310 PassVisitor<FixCopyCtors> fixer( unqCount );
311 mutateAll( translationUnit, fixer );
312 }
313
314 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
315 PassVisitor<GenStructMemberCalls> warner;
316 acceptAll( translationUnit, warner );
317 }
318
319 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
320 PassVisitor<FixCtorExprs> fixer;
321 mutateAll( translationUnit, fixer );
322 }
323
324 Expression * InsertImplicitCalls::postmutate( ApplicationExpr * appExpr ) {
325 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
326 if ( function->var->linkage.is_builtin ) {
327 // optimization: don't need to copy construct in order to call intrinsic functions
328 return appExpr;
329 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
330 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
331 assertf( ftype, "Function call without function type: %s", toString( funcDecl ).c_str() );
332 if ( CodeGen::isConstructor( funcDecl->get_name() ) && ftype->parameters.size() == 2 ) {
333 Type * t1 = getPointerBase( ftype->parameters.front()->get_type() );
334 Type * t2 = ftype->parameters.back()->get_type();
335 assert( t1 );
336
337 if ( ResolvExpr::typesCompatible( t1, t2, SymTab::Indexer() ) ) {
338 // optimization: don't need to copy construct in order to call a copy constructor
339 return appExpr;
340 } // if
341 } else if ( CodeGen::isDestructor( funcDecl->get_name() ) ) {
342 // correctness: never copy construct arguments to a destructor
343 return appExpr;
344 } // if
345 } // if
346 } // if
347 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
348
349 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
350 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
351 // Move the type substitution to the new top-level, if it is attached to the appExpr.
352 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
353 // The substitution is needed to obtain the type of temporary variables so that copy constructor
354 // calls can be resolved.
355 assert( env );
356 std::swap( expr->env, appExpr->env );
357 return expr;
358 }
359
360 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) { return ! isConstructable( type ); }
361
362 Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
363 assert( var );
364 // arrays are not copy constructed, so this should always be an ExprStmt
365 ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg );
366 ExprStmt * exprStmt = strict_dynamic_cast< ExprStmt * >( stmt->get_callStmt() );
367 Expression * resolved = exprStmt->expr;
368 exprStmt->expr = nullptr; // take ownership of 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 " << resolved << std::endl; )
374 ResolvExpr::findVoidExpression( resolved, 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 delete stmt;
383 return resolved;
384 }
385
386 void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
387 static UniqueName tempNamer("_tmp_cp");
388 assert( env );
389 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
390 assert( arg->result );
391 Type * result = arg->get_result();
392 if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types
393
394 // type may involve type variables, so apply type substitution to get temporary variable's actual type
395 result = result->clone();
396 env->apply( result );
397 ObjectDecl * tmp = ObjectDecl::newObject( "__tmp", result, nullptr );
398 tmp->get_type()->set_const( false );
399
400 // create and resolve copy constructor
401 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
402 Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg );
403
404 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) {
405 // if the chosen constructor is intrinsic, the copy is unnecessary, so
406 // don't create the temporary and don't call the copy constructor
407 VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
408 assert( function );
409 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) return;
410 }
411
412 // set a unique name for the temporary once it's certain the call is necessary
413 tmp->name = tempNamer.newName();
414
415 // replace argument to function call with temporary
416 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
417 impCpCtorExpr->get_tempDecls().push_back( tmp );
418 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
419 }
420
421 void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
422 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
423 }
424
425 void ResolveCopyCtors::postvisit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
426 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
427
428 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
429
430 // take each argument and attempt to copy construct it.
431 for ( Expression * & arg : appExpr->get_args() ) {
432 copyConstructArg( arg, impCpCtorExpr );
433 } // for
434
435 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
436 // initialized with the return value and is destructed later
437 // xxx - handle named return values?
438 Type * result = appExpr->get_result();
439 if ( ! result->isVoid() ) {
440 static UniqueName retNamer("_tmp_cp_ret");
441 result = result->clone();
442 env->apply( result );
443 ObjectDecl * ret = ObjectDecl::newObject( retNamer.newName(), result, nullptr );
444 ret->get_type()->set_const( false );
445 impCpCtorExpr->get_returnDecls().push_back( ret );
446 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
447 if ( ! dynamic_cast< ReferenceType * >( result ) ) {
448 // destructing reference returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
449 destructRet( ret, impCpCtorExpr );
450 }
451 } // for
452 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
453 }
454
455 void ResolveCopyCtors::postvisit( StmtExpr * stmtExpr ) {
456 assert( env );
457 assert( stmtExpr->get_result() );
458 Type * result = stmtExpr->get_result();
459 if ( ! result->isVoid() ) {
460 static UniqueName retNamer("_tmp_stmtexpr_ret");
461
462 // create variable that will hold the result of the stmt expr
463 result = result->clone();
464 env->apply( result );
465 ObjectDecl * ret = ObjectDecl::newObject( retNamer.newName(), result, nullptr );
466 ret->get_type()->set_const( false );
467 stmtExpr->get_returnDecls().push_front( ret );
468
469 // must have a non-empty body, otherwise it wouldn't have a result
470 CompoundStmt * body = stmtExpr->get_statements();
471 assert( ! body->get_kids().empty() );
472 // must be an ExprStmt, otherwise it wouldn't have a result
473 ExprStmt * last = strict_dynamic_cast< ExprStmt * >( body->get_kids().back() );
474 last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) );
475
476 stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
477 } // if
478 }
479
480 void ResolveCopyCtors::previsit( UniqueExpr * unqExpr ) {
481 unqCount[ unqExpr->get_id() ]++; // count the number of unique expressions for each ID
482 if ( vars.count( unqExpr->get_id() ) ) {
483 // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
484 visit_children = false;
485 }
486 }
487
488 void ResolveCopyCtors::postvisit( UniqueExpr * unqExpr ) {
489 if ( vars.count( unqExpr->get_id() ) ) {
490 // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
491 return;
492 }
493
494 // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
495 assert( unqExpr->get_result() );
496 if ( ImplicitCopyCtorExpr * impCpCtorExpr = dynamic_cast<ImplicitCopyCtorExpr*>( unqExpr->get_expr() ) ) {
497 // note the variable used as the result from the call
498 assert( impCpCtorExpr->get_result() && impCpCtorExpr->get_returnDecls().size() == 1 );
499 unqExpr->set_var( new VariableExpr( impCpCtorExpr->get_returnDecls().front() ) );
500 } else {
501 // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
502 unqExpr->set_object( ObjectDecl::newObject( toString("_unq", unqExpr->get_id()), unqExpr->get_result()->clone(), nullptr ) );
503 unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) );
504 }
505 vars.insert( unqExpr->get_id() );
506 }
507
508 Expression * FixCopyCtors::postmutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
509 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
510
511 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
512 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
513 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
514
515 // add all temporary declarations and their constructors
516 for ( ObjectDecl * obj : tempDecls ) {
517 stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) );
518 } // for
519 for ( ObjectDecl * obj : returnDecls ) {
520 stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) );
521 } // for
522
523 // add destructors after current statement
524 for ( Expression * dtor : dtors ) {
525 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
526 } // for
527
528 ObjectDecl * returnDecl = returnDecls.empty() ? nullptr : returnDecls.front();
529 Expression * callExpr = impCpCtorExpr->get_callExpr();
530
531 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
532
533 // detach fields from wrapper node so that it can be deleted without deleting too much
534 dtors.clear();
535 tempDecls.clear();
536 returnDecls.clear();
537 impCpCtorExpr->set_callExpr( nullptr );
538 std::swap( impCpCtorExpr->env, callExpr->env );
539 assert( impCpCtorExpr->env == nullptr );
540 delete impCpCtorExpr;
541
542 if ( returnDecl ) {
543 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
544 assign->get_args().push_back( new VariableExpr( returnDecl ) );
545 assign->get_args().push_back( callExpr );
546 // know the result type of the assignment is the type of the LHS (minus the pointer), so
547 // add that onto the assignment expression so that later steps have the necessary information
548 assign->set_result( returnDecl->get_type()->clone() );
549
550 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
551 // move env from callExpr to retExpr
552 std::swap( retExpr->env, callExpr->env );
553 return retExpr;
554 } else {
555 return callExpr;
556 } // if
557 }
558
559 void FixCopyCtors::premutate( StmtExpr * stmtExpr ) {
560 // function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression,
561 // since temporaries can be shared across sub-expressions, e.g.
562 // [A, A] f();
563 // g([A] x, [A] y);
564 // g(f());
565 // f is executed once, so the return temporary is shared across the tuple constructors for x and y.
566 // Explicitly mutating children instead of mutating the inner compound statment forces the temporaries to be added
567 // to the outer context, rather than inside of the statement expression.
568 visit_children = false;
569 std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
570 for ( Statement *& stmt : stmts ) {
571 stmt = stmt->acceptMutator( *visitor );
572 } // for
573 assert( stmtExpr->get_result() );
574 Type * result = stmtExpr->get_result();
575 if ( ! result->isVoid() ) {
576 for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) {
577 stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) );
578 } // for
579 // add destructors after current statement
580 for ( Expression * dtor : stmtExpr->get_dtors() ) {
581 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
582 } // for
583 // must have a non-empty body, otherwise it wouldn't have a result
584 assert( ! stmts.empty() );
585 assert( ! stmtExpr->get_returnDecls().empty() );
586 stmts.push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) );
587 stmtExpr->get_returnDecls().clear();
588 stmtExpr->get_dtors().clear();
589 }
590 assert( stmtExpr->get_returnDecls().empty() );
591 assert( stmtExpr->get_dtors().empty() );
592 }
593
594 void FixCopyCtors::premutate( UniqueExpr * unqExpr ) {
595 visit_children = false;
596 unqCount[ unqExpr->get_id() ]--;
597 static std::unordered_map< int, std::list< Statement * > > dtors;
598 static std::unordered_map< int, UniqueExpr * > unqMap;
599 // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes
600 if ( unqMap.count( unqExpr->get_id() ) ) {
601 // take data from other UniqueExpr to ensure consistency
602 delete unqExpr->get_expr();
603 unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() );
604 delete unqExpr->get_result();
605 unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
606 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
607 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
608 }
609 return;
610 }
611 PassVisitor<FixCopyCtors> fixer( unqCount );
612 unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
613 stmtsToAddBefore.splice( stmtsToAddBefore.end(), fixer.pass.stmtsToAddBefore );
614 unqMap[unqExpr->get_id()] = unqExpr;
615 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
616 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
617 } else { // remember dtors for last instance of unique expr
618 dtors[ unqExpr->get_id() ] = fixer.pass.stmtsToAddAfter;
619 }
620 return;
621 }
622
623 DeclarationWithType * FixInit::postmutate( ObjectDecl *objDecl ) {
624 // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postmutate)
625 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
626 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
627 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
628 if ( Statement * ctor = ctorInit->get_ctor() ) {
629 if ( objDecl->get_storageClasses().is_static ) {
630 // originally wanted to take advantage of gcc nested functions, but
631 // we get memory errors with this approach. To remedy this, the static
632 // variable is hoisted when the destructor needs to be called.
633 //
634 // generate:
635 // static T __objName_static_varN;
636 // void __objName_dtor_atexitN() {
637 // __dtor__...;
638 // }
639 // int f(...) {
640 // ...
641 // static bool __objName_uninitialized = true;
642 // if (__objName_uninitialized) {
643 // __ctor(__objName);
644 // __objName_uninitialized = false;
645 // atexit(__objName_dtor_atexitN);
646 // }
647 // ...
648 // }
649
650 static UniqueName dtorCallerNamer( "_dtor_atexit" );
651
652 // static bool __objName_uninitialized = true
653 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
654 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant::from_int( 1 ) ) );
655 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr );
656 isUninitializedVar->fixUniqueId();
657
658 // __objName_uninitialized = false;
659 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
660 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
661 setTrue->get_args().push_back( new ConstantExpr( Constant::from_int( 0 ) ) );
662
663 // generate body of if
664 CompoundStmt * initStmts = new CompoundStmt( noLabels );
665 std::list< Statement * > & body = initStmts->get_kids();
666 body.push_back( ctor );
667 body.push_back( new ExprStmt( noLabels, setTrue ) );
668
669 // put it all together
670 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
671 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
672 stmtsToAddAfter.push_back( ifStmt );
673
674 Statement * dtor = ctorInit->get_dtor();
675 objDecl->set_init( nullptr );
676 ctorInit->set_ctor( nullptr );
677 ctorInit->set_dtor( nullptr );
678 if ( dtor ) {
679 // if the object has a non-trivial destructor, have to
680 // hoist it and the object into the global space and
681 // call the destructor function with atexit.
682
683 Statement * dtorStmt = dtor->clone();
684
685 // void __objName_dtor_atexitN(...) {...}
686 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) );
687 dtorCaller->fixUniqueId();
688 dtorCaller->get_statements()->push_back( dtorStmt );
689
690 // atexit(dtor_atexit);
691 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
692 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
693
694 body.push_back( new ExprStmt( noLabels, callAtexit ) );
695
696 // hoist variable and dtor caller decls to list of decls that will be added into global scope
697 staticDtorDecls.push_back( objDecl );
698 staticDtorDecls.push_back( dtorCaller );
699
700 // need to rename object uniquely since it now appears
701 // at global scope and there could be multiple function-scoped
702 // static variables with the same name in different functions.
703 // Note: it isn't sufficient to modify only the mangleName, because
704 // then subsequent Indexer passes can choke on seeing the object's name
705 // if another object has the same name and type. An unfortunate side-effect
706 // of renaming the object is that subsequent NameExprs may fail to resolve,
707 // but there shouldn't be any remaining past this point.
708 static UniqueName staticNamer( "_static_var" );
709 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
710 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
711
712 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
713 // create a new object which is never used
714 static UniqueName dummyNamer( "_dummy" );
715 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") } );
716 delete ctorInit;
717 return dummy;
718 }
719 } else {
720 ImplicitCtorDtorStmt * implicit = strict_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor );
721 ExprStmt * ctorStmt = dynamic_cast< ExprStmt * >( implicit->callStmt );
722 ApplicationExpr * ctorCall = nullptr;
723 if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->expr )) && ctorCall->get_args().size() == 2 ) {
724 // clean up intrinsic copy constructor calls by making them into SingleInits
725 objDecl->init = new SingleInit( ctorCall->args.back() );
726 ctorCall->args.pop_back();
727 } else {
728 stmtsToAddAfter.push_back( ctor );
729 objDecl->init = nullptr;
730 ctorInit->ctor = nullptr;
731 }
732 } // if
733 } else if ( Initializer * init = ctorInit->init ) {
734 objDecl->init = init;
735 ctorInit->init = nullptr;
736 } else {
737 // no constructor and no initializer, which is okay
738 objDecl->init = nullptr;
739 } // if
740 delete ctorInit;
741 } // if
742 return objDecl;
743 }
744
745 void ObjDeclCollector::previsit( CompoundStmt * ) {
746 GuardValue( curVars );
747 }
748
749 void ObjDeclCollector::previsit( DeclStmt * stmt ) {
750 // keep track of all variables currently in scope
751 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
752 curVars.push_back( objDecl );
753 } // if
754 }
755
756 void LabelFinder::previsit( Statement * stmt ) {
757 // for each label, remember the variables in scope at that label.
758 for ( Label l : stmt->get_labels() ) {
759 vars[l] = curVars;
760 } // for
761 }
762
763 void LabelFinder::previsit( CompoundStmt * stmt ) {
764 previsit( (Statement *)stmt );
765 Parent::previsit( stmt );
766 }
767
768 void LabelFinder::previsit( DeclStmt * stmt ) {
769 previsit( (Statement *)stmt );
770 Parent::previsit( stmt );
771 }
772
773
774 template<typename Iterator, typename OutputIterator>
775 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
776 for ( Iterator it = begin ; it != end ; ++it ) {
777 // extract destructor statement from the object decl and insert it into the output. Note that this is
778 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
779 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
780 // contain side effects.
781 ObjectDecl * objDecl = *it;
782 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
783 assert( ctorInit && ctorInit->get_dtor() );
784 *out++ = ctorInit->get_dtor()->clone();
785 } // for
786 }
787
788 void InsertDtors::previsit( ObjectDecl * objDecl ) {
789 // remember non-static destructed objects so that their destructors can be inserted later
790 if ( ! objDecl->get_storageClasses().is_static ) {
791 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
792 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
793 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
794 Statement * dtor = ctorInit->get_dtor();
795 // don't need to call intrinsic dtor, because it does nothing, but
796 // non-intrinsic dtors must be called
797 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
798 // set dtor location to the object's location for error messages
799 ctorInit->dtor->location = objDecl->location;
800 reverseDeclOrder.front().push_front( objDecl );
801 } // if
802 } // if
803 } // if
804 }
805
806 void InsertDtors::previsit( FunctionDecl * funcDecl ) {
807 // each function needs to have its own set of labels
808 GuardValue( labelVars );
809 labelVars.clear();
810 // LabelFinder does not recurse into FunctionDecl, so need to visit
811 // its children manually.
812 maybeAccept( funcDecl->type, finder );
813 maybeAccept( funcDecl->statements, finder );
814
815 // all labels for this function have been collected, insert destructors as appropriate via implicit recursion.
816 }
817
818 void InsertDtors::previsit( CompoundStmt * compoundStmt ) {
819 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
820 // when block is left, just the destructors associated with variables defined in this block, so push a new
821 // list to the top of the stack so that we can differentiate scopes
822 reverseDeclOrder.push_front( OrderedDecls() );
823 Parent::previsit( compoundStmt );
824 }
825
826 void InsertDtors::postvisit( CompoundStmt * compoundStmt ) {
827 // add destructors for the current scope that we're exiting, unless the last statement is a return, which
828 // causes unreachable code warnings
829 std::list< Statement * > & statements = compoundStmt->get_kids();
830 if ( ! statements.empty() && ! dynamic_cast< ReturnStmt * >( statements.back() ) ) {
831 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
832 }
833 reverseDeclOrder.pop_front();
834 }
835
836 void InsertDtors::previsit( ReturnStmt * ) {
837 // return exits all scopes, so dump destructors for all scopes
838 for ( OrderedDecls & od : reverseDeclOrder ) {
839 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAddBefore ) );
840 } // for
841 }
842
843 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
844 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
845 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
846 // of the error. See C++ Reference 6.6 Jump Statements for details.
847 void InsertDtors::handleGoto( BranchStmt * stmt ) {
848 // can't do anything for computed goto
849 if ( stmt->computedTarget ) return;
850
851 assertf( stmt->get_target() != "", "BranchStmt missing a label: %s", toString( stmt ).c_str() );
852 // S_L = lvars = set of objects in scope at label definition
853 // S_G = curVars = set of objects in scope at goto statement
854 ObjectSet & lvars = labelVars[ stmt->get_target() ];
855
856 DTOR_PRINT(
857 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
858 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
859 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
860 )
861
862 ObjectSet diff;
863 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
864 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
865 DTOR_PRINT(
866 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
867 )
868 if ( ! diff.empty() ) {
869 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
870 } // if
871 // S_G-S_L results in set of objects that must be destructed
872 diff.clear();
873 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
874 DTOR_PRINT(
875 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
876 )
877 if ( ! diff.empty() ) {
878 // create an auxilliary set for fast lookup -- can't make diff a set, because diff ordering should be consistent for error messages.
879 std::unordered_set<ObjectDecl *> needsDestructor( diff.begin(), diff.end() );
880
881 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
882 OrderedDecls ordered;
883 for ( OrderedDecls & rdo : reverseDeclOrder ) {
884 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
885 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return needsDestructor.count( objDecl ); } );
886 } // for
887 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAddBefore ) );
888 } // if
889 }
890
891 void InsertDtors::previsit( BranchStmt * stmt ) {
892 switch( stmt->get_type() ) {
893 case BranchStmt::Continue:
894 case BranchStmt::Break:
895 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
896 // always be empty), but it serves as a small sanity check.
897 case BranchStmt::Goto:
898 handleGoto( stmt );
899 break;
900 default:
901 assert( false );
902 } // switch
903 }
904
905 bool checkWarnings( FunctionDecl * funcDecl ) {
906 // only check for warnings if the current function is a user-defined
907 // constructor or destructor
908 if ( ! funcDecl ) return false;
909 if ( ! funcDecl->get_statements() ) return false;
910 return CodeGen::isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
911 }
912
913 void addIds( SymTab::Indexer & indexer, const std::list< DeclarationWithType * > & decls ) {
914 for ( auto d : decls ) {
915 indexer.addId( d );
916 }
917 }
918
919 void addTypes( SymTab::Indexer & indexer, const std::list< TypeDecl * > & tds ) {
920 for ( auto td : tds ) {
921 indexer.addType( td );
922 addIds( indexer, td->assertions );
923 }
924 }
925
926 void GenStructMemberCalls::previsit( FunctionDecl * funcDecl ) {
927 GuardValue( function );
928 GuardValue( unhandled );
929 GuardValue( usedUninit );
930 GuardValue( thisParam );
931 GuardValue( isCtor );
932 GuardValue( structDecl );
933 errors = SemanticError(); // clear previous errors
934
935 // need to start with fresh sets
936 unhandled.clear();
937 usedUninit.clear();
938
939 function = funcDecl;
940 isCtor = CodeGen::isConstructor( function->get_name() );
941 if ( checkWarnings( function ) ) {
942 FunctionType * type = function->get_functionType();
943 assert( ! type->get_parameters().empty() );
944 thisParam = strict_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
945 Type * thisType = getPointerBase( thisParam->get_type() );
946 StructInstType * structType = dynamic_cast< StructInstType * >( thisType );
947 if ( structType ) {
948 structDecl = structType->get_baseStruct();
949 for ( Declaration * member : structDecl->get_members() ) {
950 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
951 // record all of the struct type's members that need to be constructed or
952 // destructed by the end of the function
953 unhandled.insert( field );
954 }
955 }
956 }
957 }
958 }
959
960 void GenStructMemberCalls::postvisit( FunctionDecl * funcDecl ) {
961 // remove the unhandled objects from usedUninit, because a call is inserted
962 // to handle them - only objects that are later constructed are used uninitialized.
963 std::map< DeclarationWithType *, CodeLocation > diff;
964 // need the comparator since usedUninit and unhandled have different types
965 struct comp_t {
966 typedef decltype(usedUninit)::value_type usedUninit_t;
967 typedef decltype(unhandled)::value_type unhandled_t;
968 bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
969 bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
970 } comp;
971 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
972 for ( auto p : diff ) {
973 DeclarationWithType * member = p.first;
974 CodeLocation loc = p.second;
975 // xxx - make error message better by also tracking the location that the object is constructed at?
976 emit( loc, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", member->get_name(), " used before being constructed" );
977 }
978
979 if ( ! unhandled.empty() ) {
980 // need to explicitly re-add function parameters to the indexer in order to resolve copy constructors
981 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this]() { indexer.leaveScope(); } );
982 addTypes( indexer, function->type->forall );
983 addIds( indexer, function->type->returnVals );
984 addIds( indexer, function->type->parameters );
985
986 // need to iterate through members in reverse in order for
987 // ctor/dtor statements to come out in the right order
988 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
989 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
990 // skip non-DWT members
991 if ( ! field ) continue;
992 // skip non-constructable members
993 if ( ! tryConstruct( field ) ) continue;
994 // skip handled members
995 if ( ! unhandled.count( field ) ) continue;
996
997 // insert and resolve default/copy constructor call for each field that's unhandled
998 std::list< Statement * > stmt;
999 Expression * arg2 = 0;
1000 if ( isCopyConstructor( function ) ) {
1001 // if copy ctor, need to pass second-param-of-this-function.field
1002 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
1003 assert( params.size() == 2 );
1004 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
1005 }
1006 InitExpander srcParam( arg2 );
1007 // cast away reference type and construct field.
1008 Expression * thisExpr = new CastExpr( new VariableExpr( thisParam ), thisParam->get_type()->stripReferences()->clone() );
1009 Expression * memberDest = new MemberExpr( field, thisExpr );
1010 SymTab::genImplicitCall( srcParam, memberDest, function->get_name(), back_inserter( stmt ), field, isCtor );
1011
1012 assert( stmt.size() <= 1 );
1013 if ( stmt.size() == 1 ) {
1014 Statement * callStmt = stmt.front();
1015
1016 MutatingResolver resolver( indexer );
1017 try {
1018 callStmt->acceptMutator( resolver );
1019 if ( isCtor ) {
1020 function->get_statements()->push_front( callStmt );
1021 } else {
1022 // destructor statements should be added at the end
1023 function->get_statements()->push_back( callStmt );
1024 }
1025 } catch ( SemanticError & error ) {
1026 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" );
1027 }
1028 }
1029 }
1030 }
1031 if (! errors.isEmpty()) {
1032 throw errors;
1033 }
1034 }
1035
1036 /// true if expr is effectively just the 'this' parameter
1037 bool isThisExpression( Expression * expr, DeclarationWithType * thisParam ) {
1038 // TODO: there are more complicated ways to pass 'this' to a constructor, e.g. &*, *&, etc.
1039 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
1040 return varExpr->get_var() == thisParam;
1041 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * > ( expr ) ) {
1042 return isThisExpression( castExpr->get_arg(), thisParam );
1043 }
1044 return false;
1045 }
1046
1047 /// returns a MemberExpr if expr is effectively just member access on the 'this' parameter, else nullptr
1048 MemberExpr * isThisMemberExpr( Expression * expr, DeclarationWithType * thisParam ) {
1049 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
1050 if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) {
1051 return memberExpr;
1052 }
1053 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
1054 return isThisMemberExpr( castExpr->get_arg(), thisParam );
1055 }
1056 return nullptr;
1057 }
1058
1059 void GenStructMemberCalls::previsit( ApplicationExpr * appExpr ) {
1060 if ( ! checkWarnings( function ) ) {
1061 visit_children = false;
1062 return;
1063 }
1064
1065 std::string fname = getFunctionName( appExpr );
1066 if ( fname == function->get_name() ) {
1067 // call to same kind of function
1068 Expression * firstParam = appExpr->get_args().front();
1069
1070 if ( isThisExpression( firstParam, thisParam ) ) {
1071 // if calling another constructor on thisParam, assume that function handles
1072 // all members - if it doesn't a warning will appear in that function.
1073 unhandled.clear();
1074 } else if ( MemberExpr * memberExpr = isThisMemberExpr( firstParam, thisParam ) ) {
1075 // if first parameter is a member expression on the this parameter,
1076 // then remove the member from unhandled set.
1077 if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) {
1078 unhandled.erase( memberExpr->get_member() );
1079 }
1080 }
1081 }
1082 }
1083
1084 void GenStructMemberCalls::previsit( MemberExpr * memberExpr ) {
1085 if ( ! checkWarnings( function ) || ! isCtor ) {
1086 visit_children = false;
1087 return;
1088 }
1089
1090 if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) {
1091 if ( unhandled.count( memberExpr->get_member() ) ) {
1092 // emit a warning because a member was used before it was constructed
1093 usedUninit.insert( { memberExpr->get_member(), memberExpr->location } );
1094 }
1095 }
1096 }
1097
1098 template< typename Visitor, typename... Params >
1099 void error( Visitor & v, CodeLocation loc, const Params &... params ) {
1100 SemanticError err( toString( params... ) );
1101 err.set_location( loc );
1102 v.errors.append( err );
1103 }
1104
1105 template< typename... Params >
1106 void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
1107 // toggle warnings vs. errors here.
1108 // warn( params... );
1109 error( *this, loc, params... );
1110 }
1111
1112 DeclarationWithType * MutatingResolver::mutate( ObjectDecl * objectDecl ) {
1113 // add object to the indexer assumes that there will be no name collisions
1114 // in generated code. If this changes, add mutate methods for entities with
1115 // scope and call {enter,leave}Scope explicitly.
1116 indexer.addId( objectDecl );
1117 return objectDecl;
1118 }
1119
1120 Expression * MutatingResolver::mutate( UntypedExpr * untypedExpr ) {
1121 Expression * newExpr = untypedExpr;
1122 ResolvExpr::findVoidExpression( newExpr, indexer );
1123 return newExpr;
1124 }
1125
1126 Expression * FixCtorExprs::postmutate( ConstructorExpr * ctorExpr ) {
1127 static UniqueName tempNamer( "_tmp_ctor_expr" );
1128 // xxx - is the size check necessary?
1129 assert( ctorExpr->result && ctorExpr->get_result()->size() == 1 );
1130
1131 // 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.
1132 ObjectDecl * tmp = ObjectDecl::newObject( tempNamer.newName(), ctorExpr->get_result()->clone(), nullptr );
1133 declsToAddBefore.push_back( tmp );
1134
1135 // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
1136 ApplicationExpr * callExpr = strict_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
1137 TypeSubstitution * env = ctorExpr->get_env();
1138 ctorExpr->set_callExpr( nullptr );
1139 ctorExpr->set_env( nullptr );
1140 delete ctorExpr;
1141
1142 // build assignment and replace constructor's first argument with new temporary
1143 Expression *& firstArg = callExpr->get_args().front();
1144 Expression * assign = new UntypedExpr( new NameExpr( "?=?" ), { new AddressExpr( new VariableExpr( tmp ) ), new AddressExpr( firstArg ) } );
1145 firstArg = new VariableExpr( tmp );
1146
1147 // resolve assignment and dispose of new env
1148 ResolvExpr::findVoidExpression( assign, indexer );
1149 delete assign->env;
1150 assign->env = nullptr;
1151
1152 // for constructor expr:
1153 // T x;
1154 // x{};
1155 // results in:
1156 // T x;
1157 // T & tmp;
1158 // &tmp = &x, ?{}(tmp), tmp
1159 CommaExpr * commaExpr = new CommaExpr( assign, new CommaExpr( callExpr, new VariableExpr( tmp ) ) );
1160 commaExpr->set_env( env );
1161 return commaExpr;
1162 }
1163 } // namespace
1164} // namespace InitTweak
1165
1166// Local Variables: //
1167// tab-width: 4 //
1168// mode: c++ //
1169// compile-command: "make install" //
1170// End: //
Note: See TracBrowser for help on using the repository browser.