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.cpp -- Generate initializers, and other stuff. |
---|
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.hpp" |
---|
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.hpp" |
---|
30 | #include "CodeGen/OperatorTable.hpp" |
---|
31 | #include "Common/SemanticError.hpp" // for SemanticError |
---|
32 | #include "Common/ToString.hpp" // for toCString |
---|
33 | #include "Common/UniqueName.hpp" // for UniqueName |
---|
34 | #include "GenPoly/GenPoly.hpp" // for getFunctionType, isPolyType |
---|
35 | #include "GenPoly/ScopedSet.hpp" // for ScopedSet, ScopedSet<>::const_iter... |
---|
36 | #include "InitTweak.hpp" // for isConstExpr, InitExpander, checkIn... |
---|
37 | #include "ResolvExpr/Resolver.hpp" |
---|
38 | #include "SymTab/GenImplicitCall.hpp" // for genImplicitCall |
---|
39 | #include "SymTab/Mangler.hpp" // for Mangler |
---|
40 | #include "Tuples/Tuples.hpp" // for maybeImpure |
---|
41 | |
---|
42 | namespace InitTweak { |
---|
43 | |
---|
44 | namespace { |
---|
45 | |
---|
46 | // Outer pass finds declarations, for their type could wrap a type that needs hoisting |
---|
47 | struct HoistArrayDimension_NoResolve final : |
---|
48 | public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting, |
---|
49 | public ast::WithGuards, public ast::WithConstTranslationUnit, |
---|
50 | public ast::WithVisitorRef<HoistArrayDimension_NoResolve>, |
---|
51 | public ast::WithSymbolTableX<ast::SymbolTable::ErrorDetection::IgnoreErrors> { |
---|
52 | |
---|
53 | // Inner pass looks within a type, for a part that depends on an expression |
---|
54 | struct HoistDimsFromTypes final : |
---|
55 | public ast::WithShortCircuiting, public ast::WithGuards { |
---|
56 | |
---|
57 | HoistArrayDimension_NoResolve * outer; |
---|
58 | HoistDimsFromTypes( HoistArrayDimension_NoResolve * outer ) : outer(outer) {} |
---|
59 | |
---|
60 | // Only intended for visiting through types. |
---|
61 | // Tolerate, and short-circuit at, the dimension expression of an array type. |
---|
62 | // (We'll operate on the dimension expression of an array type directly |
---|
63 | // from the parent type, not by visiting through it) |
---|
64 | // Look inside type exprs. |
---|
65 | void previsit( const ast::Node * ) { |
---|
66 | assert( false && "unsupported node type" ); |
---|
67 | }; |
---|
68 | const ast::Expr * allowedExpr = nullptr; |
---|
69 | void previsit( const ast::Type * ) { |
---|
70 | GuardValue( allowedExpr ) = nullptr; |
---|
71 | } |
---|
72 | void previsit( const ast::ArrayType * t ) { |
---|
73 | GuardValue( allowedExpr ) = t->dimension.get(); |
---|
74 | } |
---|
75 | void previsit( const ast::PointerType * t ) { |
---|
76 | GuardValue( allowedExpr ) = t->dimension.get(); |
---|
77 | } |
---|
78 | void previsit( const ast::TypeofType * t ) { |
---|
79 | GuardValue( allowedExpr ) = t->expr.get(); |
---|
80 | } |
---|
81 | void previsit( const ast::Expr * e ) { |
---|
82 | assert( e == allowedExpr && |
---|
83 | "only expecting to visit exprs that are dimension exprs or typeof(-) inner exprs" ); |
---|
84 | |
---|
85 | // Skip the tolerated expressions |
---|
86 | visit_children = false; |
---|
87 | } |
---|
88 | void previsit( const ast::TypeExpr * ) {} |
---|
89 | |
---|
90 | const ast::Type * postvisit( |
---|
91 | const ast::ArrayType * arrayType ) { |
---|
92 | static UniqueName dimensionName( "_array_dim" ); |
---|
93 | |
---|
94 | if ( nullptr == arrayType->dimension ) { // if no dimension is given, don't presume to invent one |
---|
95 | return arrayType; |
---|
96 | } |
---|
97 | |
---|
98 | // find size_t; use it as the type for a dim expr |
---|
99 | ast::ptr<ast::Type> dimType = outer->transUnit().global.sizeType; |
---|
100 | assert( dimType ); |
---|
101 | add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) ); |
---|
102 | |
---|
103 | // Special-case handling: leave the user's dimension expression alone |
---|
104 | // - requires the user to have followed a careful convention |
---|
105 | // - may apply to extremely simple applications, but only as windfall |
---|
106 | // - users of advanced applications will be following the convention on purpose |
---|
107 | // - CFA maintainers must protect the criteria against leaving too much alone |
---|
108 | |
---|
109 | // Actual leave-alone cases following are conservative approximations of "cannot vary" |
---|
110 | |
---|
111 | // Leave alone: literals and enum constants |
---|
112 | if ( dynamic_cast< const ast::ConstantExpr * >( arrayType->dimension.get() ) ) { |
---|
113 | return arrayType; |
---|
114 | } |
---|
115 | |
---|
116 | // Leave alone: direct use of an object declared to be const |
---|
117 | const ast::NameExpr * dimn = dynamic_cast< const ast::NameExpr * >( arrayType->dimension.get() ); |
---|
118 | if ( dimn ) { |
---|
119 | std::vector<ast::SymbolTable::IdData> dimnDefs = outer->symtab.lookupId( dimn->name ); |
---|
120 | if ( dimnDefs.size() == 1 ) { |
---|
121 | const ast::DeclWithType * dimnDef = dimnDefs[0].id.get(); |
---|
122 | assert( dimnDef && "symbol table binds a name to nothing" ); |
---|
123 | const ast::ObjectDecl * dimOb = dynamic_cast< const ast::ObjectDecl * >( dimnDef ); |
---|
124 | if( dimOb ) { |
---|
125 | const ast::Type * dimTy = dimOb->type.get(); |
---|
126 | assert( dimTy && "object declaration bearing no type" ); |
---|
127 | // must not hoist some: size_t |
---|
128 | // must hoist all: pointers and references |
---|
129 | // the analysis is conservative; BasicType is a simple approximation |
---|
130 | if ( dynamic_cast< const ast::BasicType * >( dimTy ) || |
---|
131 | dynamic_cast< const ast::SueInstType<ast::EnumDecl> * >( dimTy ) ) { |
---|
132 | if ( dimTy->is_const() ) { |
---|
133 | // The dimension is certainly re-evaluable, giving the same answer each time. |
---|
134 | // Our user might be hoping to write the array type in multiple places, having them unify. |
---|
135 | // Leave the type alone. |
---|
136 | |
---|
137 | // We believe the new criterion leaves less alone than the old criterion. |
---|
138 | // Thus, the old criterion should have left the current case alone. |
---|
139 | // Catch cases that weren't thought through. |
---|
140 | assert( !Tuples::maybeImpure( arrayType->dimension ) ); |
---|
141 | |
---|
142 | return arrayType; |
---|
143 | } |
---|
144 | }; |
---|
145 | } |
---|
146 | } |
---|
147 | } |
---|
148 | |
---|
149 | // Leave alone: any sizeof expression (answer cannot vary during current lexical scope) |
---|
150 | const ast::SizeofExpr * sz = dynamic_cast< const ast::SizeofExpr * >( arrayType->dimension.get() ); |
---|
151 | if ( sz ) { |
---|
152 | return arrayType; |
---|
153 | } |
---|
154 | |
---|
155 | // General-case handling: change the array-type's dim expr (hoist the user-given content out of the type) |
---|
156 | // - always safe |
---|
157 | // - user-unnoticeable in common applications (benign noise in -CFA output) |
---|
158 | // - may annoy a responsible user of advanced applications (but they can work around) |
---|
159 | // - protects against misusing advanced features |
---|
160 | // |
---|
161 | // The hoist, by example, is: |
---|
162 | // FROM USER: float a[ rand() ]; |
---|
163 | // TO GCC: const size_t __len_of_a = rand(); float a[ __len_of_a ]; |
---|
164 | |
---|
165 | ast::ObjectDecl * arrayDimension = new ast::ObjectDecl( |
---|
166 | arrayType->dimension->location, |
---|
167 | dimensionName.newName(), |
---|
168 | dimType, |
---|
169 | new ast::SingleInit( |
---|
170 | arrayType->dimension->location, |
---|
171 | arrayType->dimension |
---|
172 | ) |
---|
173 | ); |
---|
174 | |
---|
175 | ast::ArrayType * mutType = ast::mutate( arrayType ); |
---|
176 | mutType->dimension = new ast::VariableExpr( |
---|
177 | arrayDimension->location, arrayDimension ); |
---|
178 | outer->declsToAddBefore.push_back( arrayDimension ); |
---|
179 | |
---|
180 | return mutType; |
---|
181 | } // postvisit( const ast::ArrayType * ) |
---|
182 | }; // struct HoistDimsFromTypes |
---|
183 | |
---|
184 | ast::Storage::Classes storageClasses; |
---|
185 | void previsit( |
---|
186 | const ast::ObjectDecl * decl ) { |
---|
187 | GuardValue( storageClasses ) = decl->storage; |
---|
188 | } |
---|
189 | |
---|
190 | const ast::DeclWithType * postvisit( |
---|
191 | const ast::ObjectDecl * objectDecl ) { |
---|
192 | |
---|
193 | if ( !isInFunction() || storageClasses.is_static ) { |
---|
194 | return objectDecl; |
---|
195 | } |
---|
196 | |
---|
197 | const ast::Type * mid = objectDecl->type; |
---|
198 | |
---|
199 | ast::Pass<HoistDimsFromTypes> hoist{this}; |
---|
200 | const ast::Type * result = mid->accept( hoist ); |
---|
201 | |
---|
202 | return mutate_field( objectDecl, &ast::ObjectDecl::type, result ); |
---|
203 | } |
---|
204 | }; |
---|
205 | |
---|
206 | struct ReturnFixer final : |
---|
207 | public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting { |
---|
208 | void previsit( const ast::FunctionDecl * decl ); |
---|
209 | const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt ); |
---|
210 | private: |
---|
211 | const ast::FunctionDecl * funcDecl = nullptr; |
---|
212 | }; |
---|
213 | |
---|
214 | void ReturnFixer::previsit( const ast::FunctionDecl * decl ) { |
---|
215 | if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false; |
---|
216 | GuardValue( funcDecl ) = decl; |
---|
217 | } |
---|
218 | |
---|
219 | const ast::ReturnStmt * ReturnFixer::previsit( |
---|
220 | const ast::ReturnStmt * stmt ) { |
---|
221 | auto & returns = funcDecl->returns; |
---|
222 | assert( returns.size() < 2 ); |
---|
223 | // Hands off if the function returns a reference. |
---|
224 | // Don't allocate a temporary if the address is returned. |
---|
225 | if ( stmt->expr && 1 == returns.size() ) { |
---|
226 | ast::ptr<ast::DeclWithType> retDecl = returns.front(); |
---|
227 | if ( isConstructable( retDecl->get_type() ) ) { |
---|
228 | // Explicitly construct the return value using the return |
---|
229 | // expression and the retVal object. |
---|
230 | assertf( "" != retDecl->name, |
---|
231 | "Function %s has unnamed return value.\n", |
---|
232 | funcDecl->name.c_str() ); |
---|
233 | |
---|
234 | auto retVal = retDecl.strict_as<ast::ObjectDecl>(); |
---|
235 | if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) { |
---|
236 | // Check if the return statement is already set up. |
---|
237 | if ( varExpr->var == retVal ) return stmt; |
---|
238 | } |
---|
239 | const ast::Stmt * ctorStmt = genCtorDtor( |
---|
240 | retVal->location, "?{}", retVal, stmt->expr ); |
---|
241 | assertf( ctorStmt, |
---|
242 | "ReturnFixer: genCtorDtor returned nullptr: %s / %s", |
---|
243 | toString( retVal ).c_str(), |
---|
244 | toString( stmt->expr ).c_str() ); |
---|
245 | stmtsToAddBefore.push_back( ctorStmt ); |
---|
246 | |
---|
247 | // Return the retVal object. |
---|
248 | ast::ReturnStmt * mutStmt = ast::mutate( stmt ); |
---|
249 | mutStmt->expr = new ast::VariableExpr( |
---|
250 | stmt->location, retDecl ); |
---|
251 | return mutStmt; |
---|
252 | } |
---|
253 | } |
---|
254 | return stmt; |
---|
255 | } |
---|
256 | |
---|
257 | } // namespace |
---|
258 | |
---|
259 | void genInit( ast::TranslationUnit & transUnit ) { |
---|
260 | ast::Pass<HoistArrayDimension_NoResolve>::run( transUnit ); |
---|
261 | ast::Pass<ReturnFixer>::run( transUnit ); |
---|
262 | } |
---|
263 | |
---|
264 | void fixReturnStatements( ast::TranslationUnit & transUnit ) { |
---|
265 | ast::Pass<ReturnFixer>::run( transUnit ); |
---|
266 | } |
---|
267 | |
---|
268 | bool ManagedTypes::isManaged( const ast::Type * type ) const { |
---|
269 | // references are never constructed |
---|
270 | if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false; |
---|
271 | if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) { |
---|
272 | // tuple is also managed if any of its components are managed |
---|
273 | for (auto & component : tupleType->types) { |
---|
274 | if (isManaged(component)) return true; |
---|
275 | } |
---|
276 | } |
---|
277 | // need to clear and reset qualifiers when determining if a type is managed |
---|
278 | auto tmp = shallowCopy(type); |
---|
279 | tmp->qualifiers = {}; |
---|
280 | // delete tmp at return |
---|
281 | ast::ptr<ast::Type> guard = tmp; |
---|
282 | // 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) |
---|
283 | return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp ); |
---|
284 | } |
---|
285 | |
---|
286 | bool ManagedTypes::isManaged( const ast::ObjectDecl * objDecl ) const { |
---|
287 | const ast::Type * type = objDecl->type; |
---|
288 | while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) { |
---|
289 | // must always construct VLAs with an initializer, since this is an error in C |
---|
290 | if ( at->isVarLen && objDecl->init ) return true; |
---|
291 | type = at->base; |
---|
292 | } |
---|
293 | return isManaged( type ); |
---|
294 | } |
---|
295 | |
---|
296 | void ManagedTypes::handleDWT( const ast::DeclWithType * dwt ) { |
---|
297 | // if this function is a user-defined constructor or destructor, mark down the type as "managed" |
---|
298 | if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) { |
---|
299 | auto & params = GenPoly::getFunctionType( dwt->get_type())->params; |
---|
300 | assert( ! params.empty() ); |
---|
301 | // Type * type = InitTweak::getPointerBase( params.front() ); |
---|
302 | // assert( type ); |
---|
303 | managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
304 | } |
---|
305 | } |
---|
306 | |
---|
307 | void ManagedTypes::handleStruct( const ast::StructDecl * aggregateDecl ) { |
---|
308 | // don't construct members, but need to take note if there is a managed member, |
---|
309 | // because that means that this type is also managed |
---|
310 | for ( auto & member : aggregateDecl->members ) { |
---|
311 | if ( auto field = member.as<ast::ObjectDecl>() ) { |
---|
312 | if ( isManaged( field ) ) { |
---|
313 | // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that |
---|
314 | // polymorphic constructors make generic types managed types |
---|
315 | ast::StructInstType inst( aggregateDecl ); |
---|
316 | managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
317 | break; |
---|
318 | } |
---|
319 | } |
---|
320 | } |
---|
321 | } |
---|
322 | |
---|
323 | void ManagedTypes::beginScope() { managedTypes.beginScope(); } |
---|
324 | void ManagedTypes::endScope() { managedTypes.endScope(); } |
---|
325 | |
---|
326 | const ast::Stmt * genCtorDtor( const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg ) { |
---|
327 | assertf(objDecl, "genCtorDtor passed null objDecl"); |
---|
328 | InitExpander srcParam(arg); |
---|
329 | return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl); |
---|
330 | } |
---|
331 | |
---|
332 | ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) { |
---|
333 | // Call genImplicitCall to generate calls to ctor/dtor for each constructable object. |
---|
334 | InitExpander srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr }; |
---|
335 | ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl); |
---|
336 | |
---|
337 | ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall( |
---|
338 | srcParam, dstParam, loc, "?{}", objDecl ); |
---|
339 | ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall( |
---|
340 | nullParam, dstParam, loc, "^?{}", objDecl, |
---|
341 | SymTab::LoopBackward ); |
---|
342 | |
---|
343 | // check that either both ctor and dtor are present, or neither |
---|
344 | assert( (bool)ctor == (bool)dtor ); |
---|
345 | |
---|
346 | if ( ctor ) { |
---|
347 | // need to remember init expression, in case no ctors exist. If ctor does exist, want to |
---|
348 | // use ctor expression instead of init. |
---|
349 | ctor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
350 | dtor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
351 | |
---|
352 | return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init }; |
---|
353 | } |
---|
354 | |
---|
355 | return nullptr; |
---|
356 | } |
---|
357 | |
---|
358 | } // namespace InitTweak |
---|
359 | |
---|
360 | // Local Variables: // |
---|
361 | // tab-width: 4 // |
---|
362 | // mode: c++ // |
---|
363 | // compile-command: "make install" // |
---|
364 | // End: // |
---|