source: src/InitTweak/RemoveInit.cc @ 972e6f7

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

separate Autogen from Validate, call default ctor/dtors on array elements

  • Property mode set to 100644
File size: 10.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// RemoveInit.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 : Tue Feb 09 15:12:29 2016
13// Update Count     : 166
14//
15
16#include <stack>
17#include <list>
18#include "RemoveInit.h"
19#include "SynTree/Declaration.h"
20#include "SynTree/Type.h"
21#include "SynTree/Expression.h"
22#include "SynTree/Statement.h"
23#include "SynTree/Initializer.h"
24#include "SynTree/Mutator.h"
25#include "SymTab/Autogen.h"
26#include "GenPoly/PolyMutator.h"
27
28namespace InitTweak {
29        namespace {
30                const std::list<Label> noLabels;
31        }
32
33        class RemoveInit : public GenPoly::PolyMutator {
34          public:
35                /// removes and replaces initialization for polymorphic value objects
36                /// with assignment (TODO: constructor) statements.
37                /// also consistently allocates a temporary variable for the return value
38                /// of a function so that anything which the resolver decides can be assigned
39                /// into the return type of a function can be returned.
40                static void removeInitializers( std::list< Declaration * > &translationUnit );
41
42                RemoveInit();
43                virtual ObjectDecl * mutate( ObjectDecl *objDecl );
44                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
45
46                virtual Statement * mutate( ReturnStmt * returnStmt );
47
48          protected:
49                std::list<DeclarationWithType*> returnVals;
50                UniqueName tempNamer;
51                std::string funcName;
52        };
53
54        class CtorDtor : public GenPoly::PolyMutator {
55          public:
56                /// create constructor and destructor statements for object declarations.
57                /// Destructors are inserted directly into the code, whereas constructors
58                /// will be added in after the resolver has run so that the initializer expression
59                /// is only removed if a constructor is found
60                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
61
62                CtorDtor() : inFunction( false ) {}
63
64                virtual ObjectDecl * mutate( ObjectDecl * );
65                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
66                virtual Declaration* mutate( StructDecl *aggregateDecl );
67                virtual Declaration* mutate( UnionDecl *aggregateDecl );
68                virtual Declaration* mutate( EnumDecl *aggregateDecl );
69                virtual Declaration* mutate( ContextDecl *aggregateDecl );
70                virtual TypeDecl* mutate( TypeDecl *typeDecl );
71                virtual Declaration* mutate( TypedefDecl *typeDecl );
72
73                virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
74
75          protected:
76                bool inFunction;
77
78                // to be added before block ends - use push_front so order is correct
79                std::list< Statement * > destructorStmts;
80        };
81
82        void tweak( std::list< Declaration * > & translationUnit ) {
83                RemoveInit::removeInitializers( translationUnit );
84                CtorDtor::generateCtorDtor( translationUnit );
85        }
86
87        void RemoveInit::removeInitializers( std::list< Declaration * > & translationUnit ) {
88                RemoveInit remover;
89                mutateAll( translationUnit, remover );
90        }
91
92        RemoveInit::RemoveInit() : tempNamer( "_retVal" ) {}
93
94        // in the case where an object has an initializer and a polymorphic type, insert an assignment immediately after the
95        // declaration. This will (seemingly) cause the later phases to do the right thing with the assignment
96        ObjectDecl *RemoveInit::mutate( ObjectDecl *objDecl ) {
97                if (objDecl->get_init() && dynamic_cast<TypeInstType*>(objDecl->get_type())) {
98                        if (SingleInit * single = dynamic_cast<SingleInit*>(objDecl->get_init())) {
99                                // xxx this can be more complicated - consider ListInit
100                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?{}" ) );
101                                assign->get_args().push_back( new AddressExpr (new NameExpr( objDecl->get_name() ) ) );
102                                assign->get_args().push_back( single->get_value()->clone() );
103                                stmtsToAddAfter.push_back(new ExprStmt(noLabels, assign));
104                        } // if
105                } // if
106                return objDecl;
107        }
108
109        Statement *RemoveInit::mutate( ReturnStmt *returnStmt ) {
110                // update for multiple return values
111                assert( returnVals.size() == 0 || returnVals.size() == 1 );
112                // hands off if the function returns an lvalue - we don't want to allocate a temporary if a variable's address
113                // is being returned
114                // xxx - this should construct rather than assign
115                if ( returnStmt->get_expr() && returnVals.size() == 1 && funcName != "?=?" && ! returnVals.front()->get_type()->get_isLvalue()  ) {
116                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, returnVals.front()->get_type()->clone(), 0 );
117                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
118
119                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
120                        assign->get_args().push_back( new AddressExpr (new NameExpr( newObj->get_name() ) ) );
121                        assign->get_args().push_back( returnStmt->get_expr() );
122                        stmtsToAdd.push_back(new ExprStmt(noLabels, assign));
123
124                        returnStmt->set_expr( new VariableExpr( newObj ) );
125                } // if
126                return returnStmt;
127        }
128
129        DeclarationWithType* RemoveInit::mutate( FunctionDecl *functionDecl ) {
130                std::list<DeclarationWithType*> oldReturnVals = returnVals;
131                std::string oldFuncName = funcName;
132
133                FunctionType * type = functionDecl->get_functionType();
134                returnVals = type->get_returnVals();
135                funcName = functionDecl->get_name();
136                DeclarationWithType * decl = Mutator::mutate( functionDecl );
137                returnVals = oldReturnVals;
138                funcName = oldFuncName;
139                return decl;
140        }
141
142
143        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
144                CtorDtor ctordtor;
145                mutateAll( translationUnit, ctordtor );
146        }
147
148        namespace {
149                bool tryConstruct( ObjectDecl * objDecl ) {
150                        // xxx - handle designations
151                        return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
152                                (objDecl->get_init() == NULL ||
153                                ( objDecl->get_init() != NULL && objDecl->get_init()->get_maybeConstructed() ));
154                }
155
156                Expression * makeCtorDtorExpr( std::string name, ObjectDecl * objDecl, std::list< Expression * > args ) {
157                        UntypedExpr * expr = new UntypedExpr( new NameExpr( name ) );
158                        expr->get_args().push_back( new AddressExpr( new VariableExpr( objDecl ) ) );
159                        expr->get_args().splice( expr->get_args().end(), args );
160                        return expr;
161                }
162
163                class InitExpander : public Visitor {
164                  public:
165                  InitExpander() {}
166                  // ~InitExpander() {}
167                        virtual void visit( SingleInit * singleInit );
168                        virtual void visit( ListInit * listInit );
169                        std::list< Expression * > argList;
170                };
171
172                void InitExpander::visit( SingleInit * singleInit ) {
173                        argList.push_back( singleInit->get_value()->clone() );
174                }
175
176                void InitExpander::visit( ListInit * listInit ) {
177                        // xxx - for now, assume no nested list inits
178                        std::list<Initializer*>::iterator it = listInit->begin_initializers();
179                        for ( ; it != listInit->end_initializers(); ++it ) {
180                                (*it)->accept( *this );
181                        }
182                }
183
184                std::list< Expression * > makeInitList( Initializer * init ) {
185                        InitExpander expander;
186                        maybeAccept( init, expander );
187                        return expander.argList;
188                }
189        }
190
191        ObjectDecl * CtorDtor::mutate( ObjectDecl * objDecl ) {
192                // hands off if designated or if @=
193                if ( tryConstruct( objDecl ) ) {
194                        if ( inFunction ) {
195                                if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
196                                        // call into makeArrayFunction from validate.cc to generate calls to ctor/dtor for each element of array
197                                        // TODO: walk initializer and generate appropriate copy ctor if element has initializer
198                                        SymTab::makeArrayFunction( NULL, new VariableExpr( objDecl ), at, "?{}", back_inserter( stmtsToAddAfter ) );
199                                        SymTab::makeArrayFunction( NULL, new VariableExpr( objDecl ), at, "^?{}", front_inserter( destructorStmts ), false );
200                                } else {
201                                        // it's sufficient to attempt to call the ctor/dtor for the given object and its initializer
202                                        Expression * ctor = makeCtorDtorExpr( "?{}", objDecl, makeInitList( objDecl->get_init() ) );
203                                        Expression * dtor = makeCtorDtorExpr( "^?{}", objDecl, std::list< Expression * >() );
204
205                                        // need to remember init expression, in case no ctors exist
206                                        // if ctor does exist, want to use ctor expression instead of init
207                                        // push this decision to the resolver
208                                        objDecl->set_init( new ConstructorInit( ctor, objDecl->get_init() ) );
209                                        destructorStmts.push_front( new ExprStmt( noLabels, dtor ) );
210                                }
211                        } else {
212                                // xxx - find a way to construct/destruct globals
213                                // hack: implicit "static" initialization routine for each struct type? or something similar?
214                                // --ties into module system
215                                // this can be done by mangling main and replacing it with our own main which calls each
216                                // module initialization routine in some decided order (order given in link command?)
217                                // and finally calls mangled main
218                        }
219                }
220                return objDecl;
221        }
222
223        DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) {
224                // parameters should not be constructed and destructed, so don't mutate FunctionType
225                bool oldInFunc = inFunction;
226                mutateAll( functionDecl->get_oldDecls(), *this );
227                inFunction = true;
228                functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
229                inFunction = oldInFunc;
230                return functionDecl;
231        }
232
233        CompoundStmt * CtorDtor::mutate( CompoundStmt * compoundStmt ) {
234                // don't want to dump all destructors when block is left,
235                // just the destructors associated with variables defined in this block
236                std::list< Statement * > oldDestructorStmts = destructorStmts;
237                destructorStmts = std::list<Statement *>();
238
239                CompoundStmt * ret = PolyMutator::mutate( compoundStmt );
240                std::list< Statement * > &statements = ret->get_kids();
241                if ( ! destructorStmts.empty() ) {
242                        // TODO: adding to the end of a block isn't sufficient, since
243                        // return/break/goto should trigger destructor when block is left.
244                        statements.splice( statements.end(), destructorStmts );
245                } // if
246
247                destructorStmts = oldDestructorStmts;
248                return ret;
249        }
250
251        // should not traverse into any of these declarations to find objects
252        // that need to be constructed or destructed
253        Declaration* CtorDtor::mutate( StructDecl *aggregateDecl ) { return aggregateDecl; }
254        Declaration* CtorDtor::mutate( UnionDecl *aggregateDecl ) { return aggregateDecl; }
255        Declaration* CtorDtor::mutate( EnumDecl *aggregateDecl ) { return aggregateDecl; }
256        Declaration* CtorDtor::mutate( ContextDecl *aggregateDecl ) { return aggregateDecl; }
257        TypeDecl* CtorDtor::mutate( TypeDecl *typeDecl ) { return typeDecl; }
258        Declaration* CtorDtor::mutate( TypedefDecl *typeDecl ) { return typeDecl; }
259
260} // namespace InitTweak
261
262// Local Variables: //
263// tab-width: 4 //
264// mode: c++ //
265// compile-command: "make install" //
266// End: //
Note: See TracBrowser for help on using the repository browser.