source: src/InitTweak/GenInit.cc @ 6cf27a07

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

reorganize global init so that it is simpler and generates less unnecessary code

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