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