source: src/InitTweak/GenInit.cc @ 5f98ce5

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 5f98ce5 was 5f98ce5, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

hoist non-constexpr array dimension into const variable in case of side effects

  • Property mode set to 100644
File size: 11.4 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 "GenPoly/PolyMutator.h"
28#include "GenPoly/DeclMutator.h"
29
30namespace InitTweak {
31        namespace {
32                const std::list<Label> noLabels;
33                const std::list<Expression *> noDesignators;
34        }
35
36        class ReturnFixer : public GenPoly::PolyMutator {
37          public:
38                /// consistently allocates a temporary variable for the return value
39                /// of a function so that anything which the resolver decides can be constructed
40                /// into the return type of a function can be returned.
41                static void makeReturnTemp( std::list< Declaration * > &translationUnit );
42
43                ReturnFixer();
44
45                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
46
47                virtual Statement * mutate( ReturnStmt * returnStmt );
48
49          protected:
50                std::list<DeclarationWithType*> returnVals;
51                UniqueName tempNamer;
52                std::string funcName;
53        };
54
55        class CtorDtor : public GenPoly::PolyMutator {
56          public:
57                /// create constructor and destructor statements for object declarations.
58                /// the actual call statements will be added in after the resolver has run
59                /// so that the initializer expression is only removed if a constructor is found
60                /// and the same destructor call is inserted in all of the appropriate locations.
61                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
62
63                CtorDtor() : inFunction( false ) {}
64
65                virtual DeclarationWithType * mutate( ObjectDecl * );
66                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
67                // should not traverse into any of these declarations to find objects
68                // that need to be constructed or destructed
69                virtual Declaration* mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
70                virtual Declaration* mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
71                virtual Declaration* mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
72                virtual Declaration* mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
73                virtual TypeDecl* mutate( TypeDecl *typeDecl ) { return typeDecl; }
74                virtual Declaration* mutate( TypedefDecl *typeDecl ) { return typeDecl; }
75
76                virtual Type * mutate( FunctionType *funcType ) { return funcType; }
77
78          protected:
79                bool inFunction;
80        };
81
82        class HoistArrayDimension : public GenPoly::DeclMutator {
83          public:
84                typedef GenPoly::DeclMutator Parent;
85
86                /// hoist dimension from array types in object declaration so that it uses a single
87                /// const variable of type size_t, so that side effecting array dimensions are only
88                /// computed once.
89                static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
90
91          private:
92                DeclarationWithType * mutate( ObjectDecl * objectDecl );
93                // should not traverse into any of these declarations to find objects
94                // that need to be constructed or destructed
95                virtual Declaration* mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
96                virtual Declaration* mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
97                virtual Declaration* mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
98                virtual Declaration* mutate( TraitDecl *aggregateDecl ) { return aggregateDecl; }
99                virtual TypeDecl* mutate( TypeDecl *typeDecl ) { return typeDecl; }
100                virtual Declaration* mutate( TypedefDecl *typeDecl ) { return typeDecl; }
101
102                virtual Type* mutate( FunctionType *funcType ) { return funcType; }
103
104                void hoist( Type * type );
105
106                DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass;
107        };
108
109        void genInit( std::list< Declaration * > & translationUnit ) {
110                ReturnFixer::makeReturnTemp( translationUnit );
111                HoistArrayDimension::hoistArrayDimension( translationUnit );
112                CtorDtor::generateCtorDtor( translationUnit );
113        }
114
115        void ReturnFixer::makeReturnTemp( std::list< Declaration * > & translationUnit ) {
116                ReturnFixer fixer;
117                mutateAll( translationUnit, fixer );
118        }
119
120        ReturnFixer::ReturnFixer() : tempNamer( "_retVal" ) {}
121
122        Statement *ReturnFixer::mutate( ReturnStmt *returnStmt ) {
123                // update for multiple return values
124                assert( returnVals.size() == 0 || returnVals.size() == 1 );
125                // hands off if the function returns an lvalue - we don't want to allocate a temporary if a variable's address
126                // is being returned
127                if ( returnStmt->get_expr() && returnVals.size() == 1 && funcName != "?=?" && ! returnVals.front()->get_type()->get_isLvalue() ) {
128                        // ensure return value is not destructed by explicitly creating
129                        // an empty SingleInit node wherein maybeConstruct is false
130                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, returnVals.front()->get_type()->clone(), new ListInit( std::list<Initializer*>(), noDesignators, false ) );
131                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
132
133                        // and explicitly create the constructor expression separately
134                        UntypedExpr *construct = new UntypedExpr( new NameExpr( "?{}" ) );
135                        construct->get_args().push_back( new AddressExpr( new VariableExpr( newObj ) ) );
136                        construct->get_args().push_back( returnStmt->get_expr() );
137                        stmtsToAdd.push_back(new ExprStmt(noLabels, construct));
138
139                        returnStmt->set_expr( new VariableExpr( newObj ) );
140                } // if
141                return returnStmt;
142        }
143
144        DeclarationWithType* ReturnFixer::mutate( FunctionDecl *functionDecl ) {
145                std::list<DeclarationWithType*> oldReturnVals = returnVals;
146                std::string oldFuncName = funcName;
147
148                FunctionType * type = functionDecl->get_functionType();
149                returnVals = type->get_returnVals();
150                funcName = functionDecl->get_name();
151                DeclarationWithType * decl = Mutator::mutate( functionDecl );
152                returnVals = oldReturnVals;
153                funcName = oldFuncName;
154                return decl;
155        }
156
157        void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
158                HoistArrayDimension hoister;
159                mutateAll( translationUnit, hoister );
160        }
161
162        DeclarationWithType * HoistArrayDimension::mutate( ObjectDecl * objectDecl ) {
163                storageclass = objectDecl->get_storageClass();
164                DeclarationWithType * temp = Parent::mutate( objectDecl );
165                hoist( objectDecl->get_type() );
166                storageclass = DeclarationNode::NoStorageClass;
167                return temp;
168        }
169
170        void HoistArrayDimension::hoist( Type * type ) {
171                static UniqueName dimensionName( "_array_dim" );
172                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
173                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
174
175                        // don't need to hoist dimension if it's a constexpr - only need to if there's potential
176                        // for side effects.
177                        if ( isConstExpr( arrayType->get_dimension() ) ) return;
178
179                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageclass, LinkageSpec::C, 0, SymTab::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
180                        arrayDimension->get_type()->set_isConst( true );
181
182                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
183                        addDeclaration( arrayDimension );
184
185                        hoist( arrayType->get_base() );
186                        return;
187                }
188        }
189
190        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
191                CtorDtor ctordtor;
192                mutateAll( translationUnit, ctordtor );
193        }
194
195        namespace {
196                Expression * makeCtorDtorExpr( std::string name, ObjectDecl * objDecl, std::list< Expression * > args ) {
197                        UntypedExpr * expr = new UntypedExpr( new NameExpr( name ) );
198                        expr->get_args().push_back( new AddressExpr( new VariableExpr( objDecl ) ) );
199                        expr->get_args().splice( expr->get_args().end(), args );
200                        return expr;
201                }
202        }
203
204        DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) {
205                // hands off if designated or if @=
206                if ( tryConstruct( objDecl ) ) {
207                        if ( inFunction ) {
208                                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
209                                        // call into makeArrayFunction from validate.cc to generate calls to ctor/dtor for each element of array
210                                        // TODO: walk initializers and generate appropriate ctor if element has initializer.
211                                        // Initializer could be nested (depends on the depth of the array type on the object)
212
213                                        std::list< Expression * > args = makeInitList( objDecl->get_init() );
214                                        if ( args.empty() ) {
215                                                std::list< Statement * > ctor;
216                                                std::list< Statement * > dtor;
217
218                                                SymTab::genImplicitCall( NULL, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl );
219                                                SymTab::genImplicitCall( NULL, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false );
220
221                                                // Currently genArrayCall produces a single Statement - a CompoundStmt
222                                                // which  wraps everything that needs to happen. As such, it's technically
223                                                // possible to use a Statement ** in the above calls, but this is inherently
224                                                // unsafe, so instead we take the slightly less efficient route, but will be
225                                                // immediately informed if somehow the above assumption is broken. In this case,
226                                                // we could always wrap the list of statements at this point with a CompoundStmt,
227                                                // but it seems reasonable at the moment for this to be done by genArrayCall
228                                                // itself
229                                                assert( ctor.size() == 1 && dynamic_cast< ImplicitCtorDtorStmt * >( ctor.front() ) );
230                                                assert( dtor.size() == 1 && dynamic_cast< ImplicitCtorDtorStmt * >( dtor.front() ) );
231                                                objDecl->set_init( new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ) );
232                                        } else {
233                                                // array came with an initializer list: initialize each element
234                                                // may have more initializers than elements in the array - need to check at each index that
235                                                // we haven't exceeded size. This requires precomputing the size because it might be a side-effecting
236                                                // computation.
237                                                // may have fewer initializers than elements in the array - need to default construct
238                                                // remaining elements.
239                                                // might be able to merge this with the case above.
240
241                                        }
242                                } else {
243                                        // it's sufficient to attempt to call the ctor/dtor for the given object and its initializer
244                                        Expression * ctor = makeCtorDtorExpr( "?{}", objDecl, makeInitList( objDecl->get_init() ) );
245                                        Expression * dtor = makeCtorDtorExpr( "^?{}", objDecl, std::list< Expression * >() );
246
247                                        // need to remember init expression, in case no ctors exist
248                                        // if ctor does exist, want to use ctor expression instead of init
249                                        // push this decision to the resolver
250                                        ExprStmt * ctorStmt = new ExprStmt( noLabels, ctor );
251                                        ExprStmt * dtorStmt = new ExprStmt( noLabels, dtor );
252                                        objDecl->set_init( new ConstructorInit( new ImplicitCtorDtorStmt( ctorStmt ), new ImplicitCtorDtorStmt( dtorStmt ), objDecl->get_init() ) );
253                                }
254                        }
255                }
256                return Mutator::mutate( objDecl );
257        }
258
259        DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
260                // parameters should not be constructed and destructed, so don't mutate FunctionType
261                bool oldInFunc = inFunction;
262                mutateAll( functionDecl->get_oldDecls(), *this );
263                inFunction = true;
264                functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
265                inFunction = oldInFunc;
266                return functionDecl;
267        }
268} // namespace InitTweak
269
270// Local Variables: //
271// tab-width: 4 //
272// mode: c++ //
273// compile-command: "make install" //
274// End: //
Note: See TracBrowser for help on using the repository browser.