source: src/InitTweak/FixInit.cc@ acdfb45

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 acdfb45 was 33a25f9, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Remove visitor feature from Indexer

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