source: src/InitTweak/FixInit.cc@ 3c09d47

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 3c09d47 was 8135d4c, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Merge branch 'master' into references

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