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