source: src/InitTweak/FixInit.cc@ 837ce06

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

Fix cleanup function generation to always generate monomorphic functions

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