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

new-env with_gc
Last change on this file since 1ed958c3 was ff29f08, checked in by Aaron Moss <a3moss@…>, 7 years ago

Merge remote-tracking branch 'origin/master' into with_gc

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