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