source: src/InitTweak/FixInit.cc@ ec8bcc4

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since ec8bcc4 was d55d7a6, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Massive change to errors to enable warnings

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