source: src/InitTweak/FixInit.cc@ 7cddf77

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

Merge branch 'fix-bug-geninit'

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