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

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 4ae2364 was 933f32f, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Merge branch 'master' into cleanup-dtors

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