source: src/InitTweak/FixInit.cc@ 2bfc6b2

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

Refactor FindSpecialDeclarations and associated special declarations

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