source: src/InitTweak/FixInit.cc@ c4d80cb

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

Remove AddStmtVisitor

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