source: src/InitTweak/FixInit.cc@ e33f321

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 e33f321 was 8bf784a, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

name mangling for ttype, fix SynTree operator<< to work with nullptr, add isTtype check, ttype variables are automatically "sized"

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