source: src/InitTweak/FixInit.cc@ cb91437

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 cb91437 was 233e4d9, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

simplify generated code by collapsing intrinsic constructor calls into C-style initializers

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