source: src/InitTweak/GenInit.cc @ ac9ca96

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since ac9ca96 was ac9ca96, checked in by Rob Schluntz <rschlunt@…>, 8 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
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#include "ResolvExpr/typeops.h"
32
33namespace InitTweak {
34        namespace {
35                const std::list<Label> noLabels;
36                const std::list<Expression *> noDesignators;
37        }
38
39        class ReturnFixer : public GenPoly::PolyMutator {
40          public:
41                /// consistently allocates a temporary variable for the return value
42                /// of a function so that anything which the resolver decides can be constructed
43                /// into the return type of a function can be returned.
44                static void makeReturnTemp( std::list< Declaration * > &translationUnit );
45
46                ReturnFixer();
47
48                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
49
50                virtual Statement * mutate( ReturnStmt * returnStmt );
51
52          protected:
53                FunctionType * ftype;
54                UniqueName tempNamer;
55                std::string funcName;
56        };
57
58        class CtorDtor : public GenPoly::PolyMutator {
59          public:
60                typedef GenPoly::PolyMutator Parent;
61                using Parent::mutate;
62                /// create constructor and destructor statements for object declarations.
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.
66                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
67
68                virtual DeclarationWithType * mutate( ObjectDecl * );
69                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
70                // should not traverse into any of these declarations to find objects
71                // that need to be constructed or destructed
72                virtual Declaration* mutate( StructDecl *aggregateDecl );
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; }
78
79                virtual Type * mutate( FunctionType *funcType ) { return funcType; }
80
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
89                bool isManaged( Type * type ) const; // determine if type is managed
90                void handleDWT( DeclarationWithType * dwt ); // add type to managed if ctor/dtor
91                GenPoly::ScopedSet< std::string > managedTypes;
92                bool inFunction = false;
93        };
94
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:
105                virtual DeclarationWithType * mutate( ObjectDecl * objectDecl );
106                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
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;
121                bool inFunction = false;
122        };
123
124        void genInit( std::list< Declaration * > & translationUnit ) {
125                ReturnFixer::makeReturnTemp( translationUnit );
126                HoistArrayDimension::hoistArrayDimension( translationUnit );
127                CtorDtor::generateCtorDtor( translationUnit );
128        }
129
130        void ReturnFixer::makeReturnTemp( std::list< Declaration * > & translationUnit ) {
131                ReturnFixer fixer;
132                mutateAll( translationUnit, fixer );
133        }
134
135        ReturnFixer::ReturnFixer() : tempNamer( "_retVal" ) {}
136
137        Statement *ReturnFixer::mutate( ReturnStmt *returnStmt ) {
138                std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals();
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
142                if ( returnStmt->get_expr() && returnVals.size() == 1 && funcName != "?=?" && ! returnVals.front()->get_type()->get_isLvalue() ) {
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 ) );
146                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
147
148                        // and explicitly create the constructor expression separately
149                        UntypedExpr *construct = new UntypedExpr( new NameExpr( "?{}" ) );
150                        construct->get_args().push_back( new AddressExpr( new VariableExpr( newObj ) ) );
151                        construct->get_args().push_back( returnStmt->get_expr() );
152                        stmtsToAdd.push_back(new ExprStmt(noLabels, construct));
153
154                        returnStmt->set_expr( new VariableExpr( newObj ) );
155                } // if
156                return returnStmt;
157        }
158
159        DeclarationWithType* ReturnFixer::mutate( FunctionDecl *functionDecl ) {
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 );
170                ValueGuard< std::string > oldFuncName( funcName );
171
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                }
180                funcName = functionDecl->get_name();
181                DeclarationWithType * decl = Mutator::mutate( functionDecl );
182                return decl;
183        }
184
185        // precompute array dimension expression, because constructor generation may duplicate it,
186        // which would be incorrect if it is a side-effecting computation.
187        void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
188                HoistArrayDimension hoister;
189                hoister.mutateDeclarationList( translationUnit );
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 ) {
201                // if in function, generate const size_t var
202                static UniqueName dimensionName( "_array_dim" );
203
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 ) ) {
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        }
226
227        DeclarationWithType * HoistArrayDimension::mutate( FunctionDecl *functionDecl ) {
228                ValueGuard< bool > oldInFunc( inFunction );
229                inFunction = true;
230                DeclarationWithType * decl = Parent::mutate( functionDecl );
231                return decl;
232        }
233
234        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
235                CtorDtor ctordtor;
236                mutateAll( translationUnit, ctordtor );
237        }
238
239        bool CtorDtor::isManaged( Type * type ) const {
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                }
246                return managedTypes.find( SymTab::Mangler::mangle( type ) ) != managedTypes.end();
247        }
248
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                }
254                return isManaged( type );
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
267        DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) {
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 );
274                        // constructed objects should not have initializers nested too deeply
275                        if ( ! checkInitDepth( objDecl ) ) throw SemanticError( "Managed object's initializer is too deep ", objDecl );
276
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 ) {
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
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() ) );
304                        }
305                }
306                return Parent::mutate( objDecl );
307        }
308
309        DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
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
317                for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) {
318                        for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) {
319                                assertion = assertion->acceptMutator( *this );
320                        }
321                }
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 ) );
325
326                managedTypes.endScope();
327                return functionDecl;
328        }
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
351} // namespace InitTweak
352
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.