source: src/InitTweak/GenInit.cc@ ac9ca96

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 ac9ca96 was ac9ca96, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

consider tuples managed if a tuple constructor is declared, combine environments in tuple assignment

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