source: src/InitTweak/GenInit.cc@ 850fda6

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 850fda6 was dcd73d1, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

add error checking for managed object's initializer depth

  • Property mode set to 100644
File size: 13.7 KB
Line 
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 : Rob Schluntz
12// Last Modified On : Fri May 13 11:37:48 2016
13// Update Count : 166
14//
15
16#include <stack>
17#include <list>
18#include "GenInit.h"
19#include "InitTweak.h"
20#include "SynTree/Declaration.h"
21#include "SynTree/Type.h"
22#include "SynTree/Expression.h"
23#include "SynTree/Statement.h"
24#include "SynTree/Initializer.h"
25#include "SynTree/Mutator.h"
26#include "SymTab/Autogen.h"
27#include "SymTab/Mangler.h"
28#include "GenPoly/PolyMutator.h"
29#include "GenPoly/DeclMutator.h"
30#include "GenPoly/ScopedSet.h"
31
32namespace InitTweak {
33 namespace {
34 const std::list<Label> noLabels;
35 const std::list<Expression *> noDesignators;
36 }
37
38 class ReturnFixer : public GenPoly::PolyMutator {
39 public:
40 /// consistently allocates a temporary variable for the return value
41 /// of a function so that anything which the resolver decides can be constructed
42 /// into the return type of a function can be returned.
43 static void makeReturnTemp( std::list< Declaration * > &translationUnit );
44
45 ReturnFixer();
46
47 virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
48
49 virtual Statement * mutate( ReturnStmt * returnStmt );
50
51 protected:
52 std::list<DeclarationWithType*> returnVals;
53 UniqueName tempNamer;
54 std::string funcName;
55 };
56
57 class CtorDtor : public GenPoly::PolyMutator {
58 public:
59 typedef GenPoly::PolyMutator Parent;
60 using Parent::mutate;
61 /// create constructor and destructor statements for object declarations.
62 /// the actual call statements will be added in after the resolver has run
63 /// so that the initializer expression is only removed if a constructor is found
64 /// and the same destructor call is inserted in all of the appropriate locations.
65 static void generateCtorDtor( std::list< Declaration * > &translationUnit );
66
67 virtual DeclarationWithType * mutate( ObjectDecl * );
68 virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
69 // should not traverse into any of these declarations to find objects
70 // that need to be constructed or destructed
71 virtual Declaration* mutate( StructDecl *aggregateDecl );
72 virtual Declaration* mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
73 virtual Declaration* mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
74 virtual Declaration* mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
75 virtual TypeDecl* mutate( TypeDecl *typeDecl ) { return typeDecl; }
76 virtual Declaration* mutate( TypedefDecl *typeDecl ) { return typeDecl; }
77
78 virtual Type * mutate( FunctionType *funcType ) { return funcType; }
79
80 virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
81
82 private:
83 // set of mangled type names for which a constructor or destructor exists in the current scope.
84 // these types require a ConstructorInit node to be generated, anything else is a POD type and thus
85 // should not have a ConstructorInit generated.
86
87 bool isManaged( ObjectDecl * objDecl ) const ; // determine if object is managed
88 void handleDWT( DeclarationWithType * dwt ); // add type to managed if ctor/dtor
89 GenPoly::ScopedSet< std::string > managedTypes;
90 bool inFunction = false;
91 };
92
93 class HoistArrayDimension : public GenPoly::DeclMutator {
94 public:
95 typedef GenPoly::DeclMutator Parent;
96
97 /// hoist dimension from array types in object declaration so that it uses a single
98 /// const variable of type size_t, so that side effecting array dimensions are only
99 /// computed once.
100 static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
101
102 private:
103 virtual DeclarationWithType * mutate( ObjectDecl * objectDecl );
104 virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
105 // should not traverse into any of these declarations to find objects
106 // that need to be constructed or destructed
107 virtual Declaration* mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
108 virtual Declaration* mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
109 virtual Declaration* mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
110 virtual Declaration* mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
111 virtual TypeDecl* mutate( TypeDecl *typeDecl ) { return typeDecl; }
112 virtual Declaration* mutate( TypedefDecl *typeDecl ) { return typeDecl; }
113
114 virtual Type* mutate( FunctionType *funcType ) { return funcType; }
115
116 void hoist( Type * type );
117
118 DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
119 bool inFunction = false;
120 };
121
122 void genInit( std::list< Declaration * > & translationUnit ) {
123 ReturnFixer::makeReturnTemp( translationUnit );
124 HoistArrayDimension::hoistArrayDimension( translationUnit );
125 CtorDtor::generateCtorDtor( translationUnit );
126 }
127
128 void ReturnFixer::makeReturnTemp( std::list< Declaration * > & translationUnit ) {
129 ReturnFixer fixer;
130 mutateAll( translationUnit, fixer );
131 }
132
133 ReturnFixer::ReturnFixer() : tempNamer( "_retVal" ) {}
134
135 Statement *ReturnFixer::mutate( ReturnStmt *returnStmt ) {
136 // update for multiple return values
137 assert( returnVals.size() == 0 || returnVals.size() == 1 );
138 // hands off if the function returns an lvalue - we don't want to allocate a temporary if a variable's address
139 // is being returned
140 if ( returnStmt->get_expr() && returnVals.size() == 1 && funcName != "?=?" && ! returnVals.front()->get_type()->get_isLvalue() ) {
141 // ensure return value is not destructed by explicitly creating
142 // an empty SingleInit node wherein maybeConstruct is false
143 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, returnVals.front()->get_type()->clone(), new ListInit( std::list<Initializer*>(), noDesignators, false ) );
144 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
145
146 // and explicitly create the constructor expression separately
147 UntypedExpr *construct = new UntypedExpr( new NameExpr( "?{}" ) );
148 construct->get_args().push_back( new AddressExpr( new VariableExpr( newObj ) ) );
149 construct->get_args().push_back( returnStmt->get_expr() );
150 stmtsToAdd.push_back(new ExprStmt(noLabels, construct));
151
152 returnStmt->set_expr( new VariableExpr( newObj ) );
153 } // if
154 return returnStmt;
155 }
156
157 DeclarationWithType* ReturnFixer::mutate( FunctionDecl *functionDecl ) {
158 ValueGuard< std::list<DeclarationWithType*> > oldReturnVals( returnVals );
159 ValueGuard< std::string > oldFuncName( funcName );
160
161 FunctionType * type = functionDecl->get_functionType();
162 returnVals = type->get_returnVals();
163 funcName = functionDecl->get_name();
164 DeclarationWithType * decl = Mutator::mutate( functionDecl );
165 return decl;
166 }
167
168 // precompute array dimension expression, because constructor generation may duplicate it,
169 // which would be incorrect if it is a side-effecting computation.
170 void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
171 HoistArrayDimension hoister;
172 hoister.mutateDeclarationList( translationUnit );
173 }
174
175 DeclarationWithType * HoistArrayDimension::mutate( ObjectDecl * objectDecl ) {
176 storageclass = objectDecl->get_storageClass();
177 DeclarationWithType * temp = Parent::mutate( objectDecl );
178 hoist( objectDecl->get_type() );
179 storageclass = DeclarationNode::NoStorageClass;
180 return temp;
181 }
182
183 void HoistArrayDimension::hoist( Type * type ) {
184 // if in function, generate const size_t var
185 static UniqueName dimensionName( "_array_dim" );
186
187 // C doesn't allow variable sized arrays at global scope or for static variables,
188 // so don't hoist dimension.
189 if ( ! inFunction ) return;
190 if ( storageclass == DeclarationNode::Static ) return;
191
192 if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
193 if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
194
195 // don't need to hoist dimension if it's a constexpr - only need to if there's potential
196 // for side effects.
197 if ( isConstExpr( arrayType->get_dimension() ) ) return;
198
199 ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageclass, LinkageSpec::C, 0, SymTab::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
200 arrayDimension->get_type()->set_isConst( true );
201
202 arrayType->set_dimension( new VariableExpr( arrayDimension ) );
203 addDeclaration( arrayDimension );
204
205 hoist( arrayType->get_base() );
206 return;
207 }
208 }
209
210 DeclarationWithType * HoistArrayDimension::mutate( FunctionDecl *functionDecl ) {
211 ValueGuard< bool > oldInFunc( inFunction );
212 inFunction = true;
213 DeclarationWithType * decl = Parent::mutate( functionDecl );
214 return decl;
215 }
216
217 void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
218 CtorDtor ctordtor;
219 mutateAll( translationUnit, ctordtor );
220 }
221
222 bool CtorDtor::isManaged( ObjectDecl * objDecl ) const {
223 Type * type = objDecl->get_type();
224 while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
225 type = at->get_base();
226 }
227 return managedTypes.find( SymTab::Mangler::mangle( type ) ) != managedTypes.end();
228 }
229
230 void CtorDtor::handleDWT( DeclarationWithType * dwt ) {
231 // if this function is a user-defined constructor or destructor, mark down the type as "managed"
232 if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && isCtorDtor( dwt->get_name() ) ) {
233 std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters();
234 assert( ! params.empty() );
235 PointerType * type = safe_dynamic_cast< PointerType * >( params.front()->get_type() );
236 managedTypes.insert( SymTab::Mangler::mangle( type->get_base() ) );
237 }
238 }
239
240 DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) {
241 handleDWT( objDecl );
242 // hands off if @=, extern, builtin, etc.
243 // if global but initializer is not constexpr, always try to construct, since this is not legal C
244 if ( ( tryConstruct( objDecl ) && isManaged( objDecl ) ) || (! inFunction && ! isConstExpr( objDecl->get_init() ) ) ) {
245 // constructed objects cannot be designated
246 if ( isDesignated( objDecl->get_init() ) ) throw SemanticError( "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.", objDecl );
247 // constructed objects should not have initializers nested too deeply
248 if ( ! checkInitDepth( objDecl ) ) throw SemanticError( "Managed object's initializer is too deep ", objDecl );
249
250 // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
251 // for each constructable object
252 std::list< Statement * > ctor;
253 std::list< Statement * > dtor;
254
255 InitExpander srcParam( objDecl->get_init() );
256 InitExpander nullParam( (Initializer *)NULL );
257 SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl );
258 SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false );
259
260 // Currently genImplicitCall produces a single Statement - a CompoundStmt
261 // which wraps everything that needs to happen. As such, it's technically
262 // possible to use a Statement ** in the above calls, but this is inherently
263 // unsafe, so instead we take the slightly less efficient route, but will be
264 // immediately informed if somehow the above assumption is broken. In this case,
265 // we could always wrap the list of statements at this point with a CompoundStmt,
266 // but it seems reasonable at the moment for this to be done by genImplicitCall
267 // itself. It is possible that genImplicitCall produces no statements (e.g. if
268 // an array type does not have a dimension). In this case, it's fine to ignore
269 // the object for the purposes of construction.
270 assert( ctor.size() == dtor.size() && ctor.size() <= 1 );
271 if ( ctor.size() == 1 ) {
272 // need to remember init expression, in case no ctors exist
273 // if ctor does exist, want to use ctor expression instead of init
274 // push this decision to the resolver
275 assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) );
276 objDecl->set_init( new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ) );
277 }
278 }
279 return Parent::mutate( objDecl );
280 }
281
282 DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
283 ValueGuard< bool > oldInFunc = inFunction;
284 inFunction = true;
285
286 handleDWT( functionDecl );
287
288 managedTypes.beginScope();
289 // go through assertions and recursively add seen ctor/dtors
290 for ( TypeDecl * tyDecl : functionDecl->get_functionType()->get_forall() ) {
291 for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) {
292 assertion = assertion->acceptMutator( *this );
293 }
294 }
295 // parameters should not be constructed and destructed, so don't mutate FunctionType
296 mutateAll( functionDecl->get_oldDecls(), *this );
297 functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
298
299 managedTypes.endScope();
300 return functionDecl;
301 }
302
303 Declaration* CtorDtor::mutate( StructDecl *aggregateDecl ) {
304 // don't construct members, but need to take note if there is a managed member,
305 // because that means that this type is also managed
306 for ( Declaration * member : aggregateDecl->get_members() ) {
307 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
308 if ( isManaged( field ) ) {
309 managedTypes.insert( SymTab::Mangler::mangle( aggregateDecl ) );
310 break;
311 }
312 }
313 }
314 return aggregateDecl;
315 }
316
317 CompoundStmt * CtorDtor::mutate( CompoundStmt * compoundStmt ) {
318 managedTypes.beginScope();
319 CompoundStmt * stmt = Parent::mutate( compoundStmt );
320 managedTypes.endScope();
321 return stmt;
322 }
323
324} // namespace InitTweak
325
326// Local Variables: //
327// tab-width: 4 //
328// mode: c++ //
329// compile-command: "make install" //
330// End: //
Note: See TracBrowser for help on using the repository browser.