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 | // GenInit.cc -- |
---|
8 | // |
---|
9 | // Author : Rob Schluntz |
---|
10 | // Created On : Mon May 18 07:44:20 2015 |
---|
11 | // Last Modified By : Andrew Beach |
---|
12 | // Last Modified On : Mon Oct 25 13:53:00 2021 |
---|
13 | // Update Count : 186 |
---|
14 | // |
---|
15 | #include "GenInit.h" |
---|
16 | |
---|
17 | #include <stddef.h> // for NULL |
---|
18 | #include <algorithm> // for any_of |
---|
19 | #include <cassert> // for assert, strict_dynamic_cast, assertf |
---|
20 | #include <deque> |
---|
21 | #include <iterator> // for back_inserter, inserter, back_inse... |
---|
22 | #include <list> // for _List_iterator, list |
---|
23 | |
---|
24 | #include "AST/Decl.hpp" |
---|
25 | #include "AST/Init.hpp" |
---|
26 | #include "AST/Pass.hpp" |
---|
27 | #include "AST/Node.hpp" |
---|
28 | #include "AST/Stmt.hpp" |
---|
29 | #include "CompilationState.h" |
---|
30 | #include "CodeGen/OperatorTable.h" |
---|
31 | #include "Common/PassVisitor.h" // for PassVisitor, WithGuards, WithShort... |
---|
32 | #include "Common/SemanticError.h" // for SemanticError |
---|
33 | #include "Common/UniqueName.h" // for UniqueName |
---|
34 | #include "Common/utility.h" // for ValueGuard, maybeClone |
---|
35 | #include "GenPoly/GenPoly.h" // for getFunctionType, isPolyType |
---|
36 | #include "GenPoly/ScopedSet.h" // for ScopedSet, ScopedSet<>::const_iter... |
---|
37 | #include "InitTweak.h" // for isConstExpr, InitExpander, checkIn... |
---|
38 | #include "ResolvExpr/Resolver.h" |
---|
39 | #include "SymTab/Autogen.h" // for genImplicitCall |
---|
40 | #include "SymTab/Mangler.h" // for Mangler |
---|
41 | #include "SynTree/LinkageSpec.h" // for isOverridable, C |
---|
42 | #include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType |
---|
43 | #include "SynTree/Expression.h" // for VariableExpr, UntypedExpr, Address... |
---|
44 | #include "SynTree/Initializer.h" // for ConstructorInit, SingleInit, Initi... |
---|
45 | #include "SynTree/Label.h" // for Label |
---|
46 | #include "SynTree/Mutator.h" // for mutateAll |
---|
47 | #include "SynTree/Statement.h" // for CompoundStmt, ImplicitCtorDtorStmt |
---|
48 | #include "SynTree/Type.h" // for Type, ArrayType, Type::Qualifiers |
---|
49 | #include "SynTree/Visitor.h" // for acceptAll, maybeAccept |
---|
50 | #include "Tuples/Tuples.h" // for maybeImpure |
---|
51 | #include "Validate/FindSpecialDecls.h" // for SizeType |
---|
52 | |
---|
53 | namespace InitTweak { |
---|
54 | namespace { |
---|
55 | const std::list<Label> noLabels; |
---|
56 | const std::list<Expression *> noDesignators; |
---|
57 | } |
---|
58 | |
---|
59 | struct ReturnFixer : public WithStmtsToAdd, public WithGuards { |
---|
60 | /// consistently allocates a temporary variable for the return value |
---|
61 | /// of a function so that anything which the resolver decides can be constructed |
---|
62 | /// into the return type of a function can be returned. |
---|
63 | static void makeReturnTemp( std::list< Declaration * > &translationUnit ); |
---|
64 | |
---|
65 | void premutate( FunctionDecl *functionDecl ); |
---|
66 | void premutate( ReturnStmt * returnStmt ); |
---|
67 | |
---|
68 | protected: |
---|
69 | FunctionType * ftype = nullptr; |
---|
70 | std::string funcName; |
---|
71 | }; |
---|
72 | |
---|
73 | struct CtorDtor : public WithGuards, public WithShortCircuiting, public WithVisitorRef<CtorDtor> { |
---|
74 | /// create constructor and destructor statements for object declarations. |
---|
75 | /// the actual call statements will be added in after the resolver has run |
---|
76 | /// so that the initializer expression is only removed if a constructor is found |
---|
77 | /// and the same destructor call is inserted in all of the appropriate locations. |
---|
78 | static void generateCtorDtor( std::list< Declaration * > &translationUnit ); |
---|
79 | |
---|
80 | void previsit( ObjectDecl * ); |
---|
81 | void previsit( FunctionDecl *functionDecl ); |
---|
82 | |
---|
83 | // should not traverse into any of these declarations to find objects |
---|
84 | // that need to be constructed or destructed |
---|
85 | void previsit( StructDecl *aggregateDecl ); |
---|
86 | void previsit( AggregateDecl * ) { visit_children = false; } |
---|
87 | void previsit( NamedTypeDecl * ) { visit_children = false; } |
---|
88 | void previsit( FunctionType * ) { visit_children = false; } |
---|
89 | |
---|
90 | void previsit( CompoundStmt * compoundStmt ); |
---|
91 | |
---|
92 | private: |
---|
93 | // set of mangled type names for which a constructor or destructor exists in the current scope. |
---|
94 | // these types require a ConstructorInit node to be generated, anything else is a POD type and thus |
---|
95 | // should not have a ConstructorInit generated. |
---|
96 | |
---|
97 | ManagedTypes managedTypes; |
---|
98 | bool inFunction = false; |
---|
99 | }; |
---|
100 | |
---|
101 | struct HoistArrayDimension final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards, public WithIndexer { |
---|
102 | /// hoist dimension from array types in object declaration so that it uses a single |
---|
103 | /// const variable of type size_t, so that side effecting array dimensions are only |
---|
104 | /// computed once. |
---|
105 | static void hoistArrayDimension( std::list< Declaration * > & translationUnit ); |
---|
106 | |
---|
107 | void premutate( ObjectDecl * objectDecl ); |
---|
108 | DeclarationWithType * postmutate( ObjectDecl * objectDecl ); |
---|
109 | void premutate( FunctionDecl *functionDecl ); |
---|
110 | // should not traverse into any of these declarations to find objects |
---|
111 | // that need to be constructed or destructed |
---|
112 | void premutate( AggregateDecl * ) { visit_children = false; } |
---|
113 | void premutate( NamedTypeDecl * ) { visit_children = false; } |
---|
114 | void premutate( FunctionType * ) { visit_children = false; } |
---|
115 | |
---|
116 | // need this so that enumerators are added to the indexer, due to premutate(AggregateDecl *) |
---|
117 | void premutate( EnumDecl * ) {} |
---|
118 | |
---|
119 | void hoist( Type * type ); |
---|
120 | |
---|
121 | Type::StorageClasses storageClasses; |
---|
122 | bool inFunction = false; |
---|
123 | }; |
---|
124 | |
---|
125 | struct HoistArrayDimension_NoResolve final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards { |
---|
126 | /// hoist dimension from array types in object declaration so that it uses a single |
---|
127 | /// const variable of type size_t, so that side effecting array dimensions are only |
---|
128 | /// computed once. |
---|
129 | static void hoistArrayDimension( std::list< Declaration * > & translationUnit ); |
---|
130 | |
---|
131 | void premutate( ObjectDecl * objectDecl ); |
---|
132 | DeclarationWithType * postmutate( ObjectDecl * objectDecl ); |
---|
133 | void premutate( FunctionDecl *functionDecl ); |
---|
134 | // should not traverse into any of these declarations to find objects |
---|
135 | // that need to be constructed or destructed |
---|
136 | void premutate( AggregateDecl * ) { visit_children = false; } |
---|
137 | void premutate( NamedTypeDecl * ) { visit_children = false; } |
---|
138 | void premutate( FunctionType * ) { visit_children = false; } |
---|
139 | |
---|
140 | void hoist( Type * type ); |
---|
141 | |
---|
142 | Type::StorageClasses storageClasses; |
---|
143 | bool inFunction = false; |
---|
144 | }; |
---|
145 | |
---|
146 | void genInit( std::list< Declaration * > & translationUnit ) { |
---|
147 | if (!useNewAST) { |
---|
148 | HoistArrayDimension::hoistArrayDimension( translationUnit ); |
---|
149 | } |
---|
150 | else { |
---|
151 | HoistArrayDimension_NoResolve::hoistArrayDimension( translationUnit ); |
---|
152 | } |
---|
153 | fixReturnStatements( translationUnit ); |
---|
154 | |
---|
155 | if (!useNewAST) { |
---|
156 | CtorDtor::generateCtorDtor( translationUnit ); |
---|
157 | } |
---|
158 | } |
---|
159 | |
---|
160 | void fixReturnStatements( std::list< Declaration * > & translationUnit ) { |
---|
161 | PassVisitor<ReturnFixer> fixer; |
---|
162 | mutateAll( translationUnit, fixer ); |
---|
163 | } |
---|
164 | |
---|
165 | void ReturnFixer::premutate( ReturnStmt *returnStmt ) { |
---|
166 | std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals(); |
---|
167 | assert( returnVals.size() == 0 || returnVals.size() == 1 ); |
---|
168 | // hands off if the function returns a reference - we don't want to allocate a temporary if a variable's address |
---|
169 | // is being returned |
---|
170 | if ( returnStmt->expr && returnVals.size() == 1 && isConstructable( returnVals.front()->get_type() ) ) { |
---|
171 | // explicitly construct the return value using the return expression and the retVal object |
---|
172 | assertf( returnVals.front()->name != "", "Function %s has unnamed return value\n", funcName.c_str() ); |
---|
173 | |
---|
174 | ObjectDecl * retVal = strict_dynamic_cast< ObjectDecl * >( returnVals.front() ); |
---|
175 | if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( returnStmt->expr ) ) { |
---|
176 | // return statement has already been mutated - don't need to do it again |
---|
177 | if ( varExpr->var == retVal ) return; |
---|
178 | } |
---|
179 | Statement * stmt = genCtorDtor( "?{}", retVal, returnStmt->expr ); |
---|
180 | assertf( stmt, "ReturnFixer: genCtorDtor returned nullptr: %s / %s", toString( retVal ).c_str(), toString( returnStmt->expr ).c_str() ); |
---|
181 | stmtsToAddBefore.push_back( stmt ); |
---|
182 | |
---|
183 | // return the retVal object |
---|
184 | returnStmt->expr = new VariableExpr( returnVals.front() ); |
---|
185 | } // if |
---|
186 | } |
---|
187 | |
---|
188 | void ReturnFixer::premutate( FunctionDecl *functionDecl ) { |
---|
189 | GuardValue( ftype ); |
---|
190 | GuardValue( funcName ); |
---|
191 | |
---|
192 | ftype = functionDecl->type; |
---|
193 | funcName = functionDecl->name; |
---|
194 | } |
---|
195 | |
---|
196 | // precompute array dimension expression, because constructor generation may duplicate it, |
---|
197 | // which would be incorrect if it is a side-effecting computation. |
---|
198 | void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) { |
---|
199 | PassVisitor<HoistArrayDimension> hoister; |
---|
200 | mutateAll( translationUnit, hoister ); |
---|
201 | } |
---|
202 | |
---|
203 | void HoistArrayDimension::premutate( ObjectDecl * objectDecl ) { |
---|
204 | GuardValue( storageClasses ); |
---|
205 | storageClasses = objectDecl->get_storageClasses(); |
---|
206 | } |
---|
207 | |
---|
208 | DeclarationWithType * HoistArrayDimension::postmutate( ObjectDecl * objectDecl ) { |
---|
209 | hoist( objectDecl->get_type() ); |
---|
210 | return objectDecl; |
---|
211 | } |
---|
212 | |
---|
213 | void HoistArrayDimension::hoist( Type * type ) { |
---|
214 | // if in function, generate const size_t var |
---|
215 | static UniqueName dimensionName( "_array_dim" ); |
---|
216 | |
---|
217 | // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension. |
---|
218 | if ( ! inFunction ) return; |
---|
219 | if ( storageClasses.is_static ) return; |
---|
220 | |
---|
221 | if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) { |
---|
222 | if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist? |
---|
223 | |
---|
224 | // need to resolve array dimensions in order to accurately determine if constexpr |
---|
225 | ResolvExpr::findSingleExpression( arrayType->dimension, Validate::SizeType->clone(), indexer ); |
---|
226 | // array is variable-length when the dimension is not constexpr |
---|
227 | arrayType->isVarLen = ! isConstExpr( arrayType->dimension ); |
---|
228 | // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects. |
---|
229 | // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve |
---|
230 | // still try to detect constant expressions |
---|
231 | if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return; |
---|
232 | |
---|
233 | ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) ); |
---|
234 | arrayDimension->get_type()->set_const( true ); |
---|
235 | |
---|
236 | arrayType->set_dimension( new VariableExpr( arrayDimension ) ); |
---|
237 | declsToAddBefore.push_back( arrayDimension ); |
---|
238 | |
---|
239 | hoist( arrayType->get_base() ); |
---|
240 | return; |
---|
241 | } |
---|
242 | } |
---|
243 | |
---|
244 | void HoistArrayDimension::premutate( FunctionDecl * ) { |
---|
245 | GuardValue( inFunction ); |
---|
246 | inFunction = true; |
---|
247 | } |
---|
248 | |
---|
249 | // precompute array dimension expression, because constructor generation may duplicate it, |
---|
250 | // which would be incorrect if it is a side-effecting computation. |
---|
251 | void HoistArrayDimension_NoResolve::hoistArrayDimension( std::list< Declaration * > & translationUnit ) { |
---|
252 | PassVisitor<HoistArrayDimension_NoResolve> hoister; |
---|
253 | mutateAll( translationUnit, hoister ); |
---|
254 | } |
---|
255 | |
---|
256 | void HoistArrayDimension_NoResolve::premutate( ObjectDecl * objectDecl ) { |
---|
257 | GuardValue( storageClasses ); |
---|
258 | storageClasses = objectDecl->get_storageClasses(); |
---|
259 | } |
---|
260 | |
---|
261 | DeclarationWithType * HoistArrayDimension_NoResolve::postmutate( ObjectDecl * objectDecl ) { |
---|
262 | hoist( objectDecl->get_type() ); |
---|
263 | return objectDecl; |
---|
264 | } |
---|
265 | |
---|
266 | void HoistArrayDimension_NoResolve::hoist( Type * type ) { |
---|
267 | // if in function, generate const size_t var |
---|
268 | static UniqueName dimensionName( "_array_dim" ); |
---|
269 | |
---|
270 | // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension. |
---|
271 | if ( ! inFunction ) return; |
---|
272 | if ( storageClasses.is_static ) return; |
---|
273 | |
---|
274 | if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) { |
---|
275 | if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist? |
---|
276 | // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects. |
---|
277 | // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve |
---|
278 | // still try to detect constant expressions |
---|
279 | if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return; |
---|
280 | |
---|
281 | ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) ); |
---|
282 | arrayDimension->get_type()->set_const( true ); |
---|
283 | |
---|
284 | arrayType->set_dimension( new VariableExpr( arrayDimension ) ); |
---|
285 | declsToAddBefore.push_back( arrayDimension ); |
---|
286 | |
---|
287 | hoist( arrayType->get_base() ); |
---|
288 | return; |
---|
289 | } |
---|
290 | } |
---|
291 | |
---|
292 | void HoistArrayDimension_NoResolve::premutate( FunctionDecl * ) { |
---|
293 | GuardValue( inFunction ); |
---|
294 | inFunction = true; |
---|
295 | } |
---|
296 | |
---|
297 | namespace { |
---|
298 | |
---|
299 | # warning Remove the _New suffix after the conversion is complete. |
---|
300 | struct HoistArrayDimension_NoResolve_New final : |
---|
301 | public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting, |
---|
302 | public ast::WithGuards, public ast::WithConstTranslationUnit, |
---|
303 | public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New> { |
---|
304 | void previsit( const ast::ObjectDecl * decl ); |
---|
305 | const ast::DeclWithType * postvisit( const ast::ObjectDecl * decl ); |
---|
306 | // Do not look for objects inside there declarations (and type). |
---|
307 | void previsit( const ast::AggregateDecl * ) { visit_children = false; } |
---|
308 | void previsit( const ast::NamedTypeDecl * ) { visit_children = false; } |
---|
309 | void previsit( const ast::FunctionType * ) { visit_children = false; } |
---|
310 | |
---|
311 | const ast::Type * hoist( const ast::Type * type ); |
---|
312 | |
---|
313 | ast::Storage::Classes storageClasses; |
---|
314 | }; |
---|
315 | |
---|
316 | void HoistArrayDimension_NoResolve_New::previsit( |
---|
317 | const ast::ObjectDecl * decl ) { |
---|
318 | GuardValue( storageClasses ) = decl->storage; |
---|
319 | } |
---|
320 | |
---|
321 | const ast::DeclWithType * HoistArrayDimension_NoResolve_New::postvisit( |
---|
322 | const ast::ObjectDecl * objectDecl ) { |
---|
323 | return mutate_field( objectDecl, &ast::ObjectDecl::type, |
---|
324 | hoist( objectDecl->type ) ); |
---|
325 | } |
---|
326 | |
---|
327 | const ast::Type * HoistArrayDimension_NoResolve_New::hoist( |
---|
328 | const ast::Type * type ) { |
---|
329 | static UniqueName dimensionName( "_array_dim" ); |
---|
330 | |
---|
331 | if ( !isInFunction() || storageClasses.is_static ) { |
---|
332 | return type; |
---|
333 | } |
---|
334 | |
---|
335 | if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) { |
---|
336 | if ( nullptr == arrayType->dimension ) { |
---|
337 | return type; |
---|
338 | } |
---|
339 | |
---|
340 | if ( !Tuples::maybeImpure( arrayType->dimension ) ) { |
---|
341 | return type; |
---|
342 | } |
---|
343 | |
---|
344 | ast::ptr<ast::Type> dimType = transUnit().global.sizeType; |
---|
345 | assert( dimType ); |
---|
346 | add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) ); |
---|
347 | |
---|
348 | ast::ObjectDecl * arrayDimension = new ast::ObjectDecl( |
---|
349 | arrayType->dimension->location, |
---|
350 | dimensionName.newName(), |
---|
351 | dimType, |
---|
352 | new ast::SingleInit( |
---|
353 | arrayType->dimension->location, |
---|
354 | arrayType->dimension |
---|
355 | ) |
---|
356 | ); |
---|
357 | |
---|
358 | ast::ArrayType * mutType = ast::mutate( arrayType ); |
---|
359 | mutType->dimension = new ast::VariableExpr( |
---|
360 | arrayDimension->location, arrayDimension ); |
---|
361 | declsToAddBefore.push_back( arrayDimension ); |
---|
362 | |
---|
363 | mutType->base = hoist( mutType->base ); |
---|
364 | return mutType; |
---|
365 | } |
---|
366 | return type; |
---|
367 | } |
---|
368 | |
---|
369 | struct ReturnFixer_New final : |
---|
370 | public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting { |
---|
371 | void previsit( const ast::FunctionDecl * decl ); |
---|
372 | const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt ); |
---|
373 | private: |
---|
374 | const ast::FunctionDecl * funcDecl = nullptr; |
---|
375 | }; |
---|
376 | |
---|
377 | void ReturnFixer_New::previsit( const ast::FunctionDecl * decl ) { |
---|
378 | if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false; |
---|
379 | GuardValue( funcDecl ) = decl; |
---|
380 | } |
---|
381 | |
---|
382 | const ast::ReturnStmt * ReturnFixer_New::previsit( |
---|
383 | const ast::ReturnStmt * stmt ) { |
---|
384 | auto & returns = funcDecl->returns; |
---|
385 | assert( returns.size() < 2 ); |
---|
386 | // Hands off if the function returns a reference. |
---|
387 | // Don't allocate a temporary if the address is returned. |
---|
388 | if ( stmt->expr && 1 == returns.size() ) { |
---|
389 | ast::ptr<ast::DeclWithType> retDecl = returns.front(); |
---|
390 | if ( isConstructable( retDecl->get_type() ) ) { |
---|
391 | // Explicitly construct the return value using the return |
---|
392 | // expression and the retVal object. |
---|
393 | assertf( "" != retDecl->name, |
---|
394 | "Function %s has unnamed return value.\n", |
---|
395 | funcDecl->name.c_str() ); |
---|
396 | |
---|
397 | auto retVal = retDecl.strict_as<ast::ObjectDecl>(); |
---|
398 | if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) { |
---|
399 | // Check if the return statement is already set up. |
---|
400 | if ( varExpr->var == retVal ) return stmt; |
---|
401 | } |
---|
402 | ast::ptr<ast::Stmt> ctorStmt = genCtorDtor( |
---|
403 | retVal->location, "?{}", retVal, stmt->expr ); |
---|
404 | assertf( ctorStmt, |
---|
405 | "ReturnFixer: genCtorDtor returned nullptr: %s / %s", |
---|
406 | toString( retVal ).c_str(), |
---|
407 | toString( stmt->expr ).c_str() ); |
---|
408 | stmtsToAddBefore.push_back( ctorStmt ); |
---|
409 | |
---|
410 | // Return the retVal object. |
---|
411 | ast::ReturnStmt * mutStmt = ast::mutate( stmt ); |
---|
412 | mutStmt->expr = new ast::VariableExpr( |
---|
413 | stmt->location, retDecl ); |
---|
414 | return mutStmt; |
---|
415 | } |
---|
416 | } |
---|
417 | return stmt; |
---|
418 | } |
---|
419 | |
---|
420 | } // namespace |
---|
421 | |
---|
422 | void genInit( ast::TranslationUnit & transUnit ) { |
---|
423 | ast::Pass<HoistArrayDimension_NoResolve_New>::run( transUnit ); |
---|
424 | ast::Pass<ReturnFixer_New>::run( transUnit ); |
---|
425 | } |
---|
426 | |
---|
427 | void fixReturnStatements( ast::TranslationUnit & transUnit ) { |
---|
428 | ast::Pass<ReturnFixer_New>::run( transUnit ); |
---|
429 | } |
---|
430 | |
---|
431 | void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) { |
---|
432 | PassVisitor<CtorDtor> ctordtor; |
---|
433 | acceptAll( translationUnit, ctordtor ); |
---|
434 | } |
---|
435 | |
---|
436 | bool ManagedTypes::isManaged( Type * type ) const { |
---|
437 | // references are never constructed |
---|
438 | if ( dynamic_cast< ReferenceType * >( type ) ) return false; |
---|
439 | // need to clear and reset qualifiers when determining if a type is managed |
---|
440 | ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() ); |
---|
441 | type->get_qualifiers() = Type::Qualifiers(); |
---|
442 | if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) { |
---|
443 | // tuple is also managed if any of its components are managed |
---|
444 | if ( std::any_of( tupleType->types.begin(), tupleType->types.end(), [&](Type * type) { return isManaged( type ); }) ) { |
---|
445 | return true; |
---|
446 | } |
---|
447 | } |
---|
448 | // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable) |
---|
449 | return managedTypes.find( SymTab::Mangler::mangleConcrete( type ) ) != managedTypes.end() || GenPoly::isPolyType( type ); |
---|
450 | } |
---|
451 | |
---|
452 | bool ManagedTypes::isManaged( ObjectDecl * objDecl ) const { |
---|
453 | Type * type = objDecl->get_type(); |
---|
454 | while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) { |
---|
455 | // must always construct VLAs with an initializer, since this is an error in C |
---|
456 | if ( at->isVarLen && objDecl->init ) return true; |
---|
457 | type = at->get_base(); |
---|
458 | } |
---|
459 | return isManaged( type ); |
---|
460 | } |
---|
461 | |
---|
462 | // why is this not just on FunctionDecl? |
---|
463 | void ManagedTypes::handleDWT( DeclarationWithType * dwt ) { |
---|
464 | // if this function is a user-defined constructor or destructor, mark down the type as "managed" |
---|
465 | if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && CodeGen::isCtorDtor( dwt->get_name() ) ) { |
---|
466 | std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters(); |
---|
467 | assert( ! params.empty() ); |
---|
468 | Type * type = InitTweak::getPointerBase( params.front()->get_type() ); |
---|
469 | assert( type ); |
---|
470 | managedTypes.insert( SymTab::Mangler::mangleConcrete( type ) ); |
---|
471 | } |
---|
472 | } |
---|
473 | |
---|
474 | void ManagedTypes::handleStruct( StructDecl * aggregateDecl ) { |
---|
475 | // don't construct members, but need to take note if there is a managed member, |
---|
476 | // because that means that this type is also managed |
---|
477 | for ( Declaration * member : aggregateDecl->get_members() ) { |
---|
478 | if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) { |
---|
479 | if ( isManaged( field ) ) { |
---|
480 | // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that |
---|
481 | // polymorphic constructors make generic types managed types |
---|
482 | StructInstType inst( Type::Qualifiers(), aggregateDecl ); |
---|
483 | managedTypes.insert( SymTab::Mangler::mangleConcrete( &inst ) ); |
---|
484 | break; |
---|
485 | } |
---|
486 | } |
---|
487 | } |
---|
488 | } |
---|
489 | |
---|
490 | void ManagedTypes::beginScope() { managedTypes.beginScope(); } |
---|
491 | void ManagedTypes::endScope() { managedTypes.endScope(); } |
---|
492 | |
---|
493 | bool ManagedTypes_new::isManaged( const ast::Type * type ) const { |
---|
494 | // references are never constructed |
---|
495 | if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false; |
---|
496 | if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) { |
---|
497 | // tuple is also managed if any of its components are managed |
---|
498 | for (auto & component : tupleType->types) { |
---|
499 | if (isManaged(component)) return true; |
---|
500 | } |
---|
501 | } |
---|
502 | // need to clear and reset qualifiers when determining if a type is managed |
---|
503 | // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() ); |
---|
504 | auto tmp = shallowCopy(type); |
---|
505 | tmp->qualifiers = {}; |
---|
506 | // delete tmp at return |
---|
507 | ast::ptr<ast::Type> guard = tmp; |
---|
508 | // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable) |
---|
509 | return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp ); |
---|
510 | } |
---|
511 | |
---|
512 | bool ManagedTypes_new::isManaged( const ast::ObjectDecl * objDecl ) const { |
---|
513 | const ast::Type * type = objDecl->type; |
---|
514 | while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) { |
---|
515 | // must always construct VLAs with an initializer, since this is an error in C |
---|
516 | if ( at->isVarLen && objDecl->init ) return true; |
---|
517 | type = at->base; |
---|
518 | } |
---|
519 | return isManaged( type ); |
---|
520 | } |
---|
521 | |
---|
522 | void ManagedTypes_new::handleDWT( const ast::DeclWithType * dwt ) { |
---|
523 | // if this function is a user-defined constructor or destructor, mark down the type as "managed" |
---|
524 | if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) { |
---|
525 | auto & params = GenPoly::getFunctionType( dwt->get_type())->params; |
---|
526 | assert( ! params.empty() ); |
---|
527 | // Type * type = InitTweak::getPointerBase( params.front() ); |
---|
528 | // assert( type ); |
---|
529 | managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
530 | } |
---|
531 | } |
---|
532 | |
---|
533 | void ManagedTypes_new::handleStruct( const ast::StructDecl * aggregateDecl ) { |
---|
534 | // don't construct members, but need to take note if there is a managed member, |
---|
535 | // because that means that this type is also managed |
---|
536 | for ( auto & member : aggregateDecl->members ) { |
---|
537 | if ( auto field = member.as<ast::ObjectDecl>() ) { |
---|
538 | if ( isManaged( field ) ) { |
---|
539 | // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that |
---|
540 | // polymorphic constructors make generic types managed types |
---|
541 | ast::StructInstType inst( aggregateDecl ); |
---|
542 | managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
543 | break; |
---|
544 | } |
---|
545 | } |
---|
546 | } |
---|
547 | } |
---|
548 | |
---|
549 | void ManagedTypes_new::beginScope() { managedTypes.beginScope(); } |
---|
550 | void ManagedTypes_new::endScope() { managedTypes.endScope(); } |
---|
551 | |
---|
552 | ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg ) { |
---|
553 | // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor |
---|
554 | assertf( objDecl, "genCtorDtor passed null objDecl" ); |
---|
555 | std::list< Statement * > stmts; |
---|
556 | InitExpander_old srcParam( maybeClone( arg ) ); |
---|
557 | SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl ); |
---|
558 | assert( stmts.size() <= 1 ); |
---|
559 | return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr; |
---|
560 | |
---|
561 | } |
---|
562 | |
---|
563 | ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) { |
---|
564 | assertf(objDecl, "genCtorDtor passed null objDecl"); |
---|
565 | InitExpander_new srcParam(arg); |
---|
566 | return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl); |
---|
567 | } |
---|
568 | |
---|
569 | ConstructorInit * genCtorInit( ObjectDecl * objDecl ) { |
---|
570 | // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor |
---|
571 | // for each constructable object |
---|
572 | std::list< Statement * > ctor; |
---|
573 | std::list< Statement * > dtor; |
---|
574 | |
---|
575 | InitExpander_old srcParam( objDecl->get_init() ); |
---|
576 | InitExpander_old nullParam( (Initializer *)NULL ); |
---|
577 | SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl ); |
---|
578 | SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false ); |
---|
579 | |
---|
580 | // Currently genImplicitCall produces a single Statement - a CompoundStmt |
---|
581 | // which wraps everything that needs to happen. As such, it's technically |
---|
582 | // possible to use a Statement ** in the above calls, but this is inherently |
---|
583 | // unsafe, so instead we take the slightly less efficient route, but will be |
---|
584 | // immediately informed if somehow the above assumption is broken. In this case, |
---|
585 | // we could always wrap the list of statements at this point with a CompoundStmt, |
---|
586 | // but it seems reasonable at the moment for this to be done by genImplicitCall |
---|
587 | // itself. It is possible that genImplicitCall produces no statements (e.g. if |
---|
588 | // an array type does not have a dimension). In this case, it's fine to ignore |
---|
589 | // the object for the purposes of construction. |
---|
590 | assert( ctor.size() == dtor.size() && ctor.size() <= 1 ); |
---|
591 | if ( ctor.size() == 1 ) { |
---|
592 | // need to remember init expression, in case no ctors exist |
---|
593 | // if ctor does exist, want to use ctor expression instead of init |
---|
594 | // push this decision to the resolver |
---|
595 | assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) ); |
---|
596 | return new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ); |
---|
597 | } |
---|
598 | return nullptr; |
---|
599 | } |
---|
600 | |
---|
601 | void CtorDtor::previsit( ObjectDecl * objDecl ) { |
---|
602 | managedTypes.handleDWT( objDecl ); |
---|
603 | // hands off if @=, extern, builtin, etc. |
---|
604 | // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C |
---|
605 | if ( tryConstruct( objDecl ) && ( managedTypes.isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) { |
---|
606 | // constructed objects cannot be designated |
---|
607 | if ( isDesignated( objDecl->get_init() ) ) SemanticError( objDecl, "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.\n" ); |
---|
608 | // constructed objects should not have initializers nested too deeply |
---|
609 | if ( ! checkInitDepth( objDecl ) ) SemanticError( objDecl, "Managed object's initializer is too deep " ); |
---|
610 | |
---|
611 | objDecl->set_init( genCtorInit( objDecl ) ); |
---|
612 | } |
---|
613 | } |
---|
614 | |
---|
615 | void CtorDtor::previsit( FunctionDecl *functionDecl ) { |
---|
616 | visit_children = false; // do not try and construct parameters or forall parameters |
---|
617 | GuardValue( inFunction ); |
---|
618 | inFunction = true; |
---|
619 | |
---|
620 | managedTypes.handleDWT( functionDecl ); |
---|
621 | |
---|
622 | GuardScope( managedTypes ); |
---|
623 | // go through assertions and recursively add seen ctor/dtors |
---|
624 | for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) { |
---|
625 | for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) { |
---|
626 | managedTypes.handleDWT( assertion ); |
---|
627 | } |
---|
628 | } |
---|
629 | |
---|
630 | maybeAccept( functionDecl->get_statements(), *visitor ); |
---|
631 | } |
---|
632 | |
---|
633 | void CtorDtor::previsit( StructDecl *aggregateDecl ) { |
---|
634 | visit_children = false; // do not try to construct and destruct aggregate members |
---|
635 | |
---|
636 | managedTypes.handleStruct( aggregateDecl ); |
---|
637 | } |
---|
638 | |
---|
639 | void CtorDtor::previsit( CompoundStmt * ) { |
---|
640 | GuardScope( managedTypes ); |
---|
641 | } |
---|
642 | |
---|
643 | ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) { |
---|
644 | // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each |
---|
645 | // constructable object |
---|
646 | InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr }; |
---|
647 | ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl); |
---|
648 | |
---|
649 | ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall( |
---|
650 | srcParam, dstParam, loc, "?{}", objDecl ); |
---|
651 | ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall( |
---|
652 | nullParam, dstParam, loc, "^?{}", objDecl, |
---|
653 | SymTab::LoopBackward ); |
---|
654 | |
---|
655 | // check that either both ctor and dtor are present, or neither |
---|
656 | assert( (bool)ctor == (bool)dtor ); |
---|
657 | |
---|
658 | if ( ctor ) { |
---|
659 | // need to remember init expression, in case no ctors exist. If ctor does exist, want to |
---|
660 | // use ctor expression instead of init. |
---|
661 | ctor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
662 | dtor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
663 | |
---|
664 | return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init }; |
---|
665 | } |
---|
666 | |
---|
667 | return nullptr; |
---|
668 | } |
---|
669 | |
---|
670 | } // namespace InitTweak |
---|
671 | |
---|
672 | // Local Variables: // |
---|
673 | // tab-width: 4 // |
---|
674 | // mode: c++ // |
---|
675 | // compile-command: "make install" // |
---|
676 | // End: // |
---|