source: src/Tuples/TupleExpansion.cc @ 9a063c8

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 9a063c8 was 5f5083e, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fixed a few warnings in tuples

  • Property mode set to 100644
File size: 12.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// TupleAssignment.cc --
8//
9// Author           : Rodolfo G. Esteves
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon May 18 15:02:53 2015
13// Update Count     : 2
14//
15
16#include <iterator>
17#include <iostream>
18#include <cassert>
19#include "Tuples.h"
20#include "GenPoly/DeclMutator.h"
21#include "SynTree/Mutator.h"
22#include "SynTree/Statement.h"
23#include "SynTree/Declaration.h"
24#include "SynTree/Type.h"
25#include "SynTree/Expression.h"
26#include "SynTree/Initializer.h"
27#include "SymTab/Mangler.h"
28#include "Common/ScopedMap.h"
29#include "ResolvExpr/typeops.h"
30#include "InitTweak/GenInit.h"
31
32namespace Tuples {
33        namespace {
34                class MemberTupleExpander final : public Mutator {
35                public:
36                        typedef Mutator Parent;
37                        using Parent::mutate;
38
39                        virtual Expression * mutate( UntypedMemberExpr * memberExpr ) override;
40                };
41
42                class UniqueExprExpander final : public GenPoly::DeclMutator {
43                public:
44                        typedef GenPoly::DeclMutator Parent;
45                        using Parent::mutate;
46
47                        virtual Expression * mutate( UniqueExpr * unqExpr ) override;
48
49                        std::map< int, Expression * > decls; // not vector, because order added may not be increasing order
50
51                        ~UniqueExprExpander() {
52                                for ( std::pair<const int, Expression *> & p : decls ) {
53                                        delete p.second;
54                                }
55                        }
56                };
57
58                class TupleAssignExpander : public Mutator {
59                public:
60                        typedef Mutator Parent;
61                        using Parent::mutate;
62
63                        virtual Expression * mutate( TupleAssignExpr * tupleExpr );
64                };
65
66                class TupleTypeReplacer : public GenPoly::DeclMutator {
67                  public:
68                        typedef GenPoly::DeclMutator Parent;
69                        using Parent::mutate;
70
71                        virtual Type * mutate( TupleType * tupleType ) override;
72
73                        virtual CompoundStmt * mutate( CompoundStmt * stmt ) override {
74                                typeMap.beginScope();
75                                stmt = Parent::mutate( stmt );
76                                typeMap.endScope();
77                                return stmt;
78                        }
79                  private:
80                        ScopedMap< std::string, StructDecl * > typeMap;
81                };
82
83                class TupleIndexExpander final : public Mutator {
84                public:
85                        typedef Mutator Parent;
86                        using Parent::mutate;
87
88                        virtual Expression * mutate( TupleIndexExpr * tupleExpr ) override;
89                };
90
91                class TupleExprExpander final : public Mutator {
92                public:
93                        typedef Mutator Parent;
94                        using Parent::mutate;
95                       
96                        virtual Expression * mutate( TupleExpr * tupleExpr ) override;
97                };
98        }
99
100        void expandMemberTuples( std::list< Declaration * > & translationUnit ) {
101                MemberTupleExpander expander;
102                mutateAll( translationUnit, expander );
103        }
104
105        void expandUniqueExpr( std::list< Declaration * > & translationUnit ) {
106                UniqueExprExpander unqExpander;
107                unqExpander.mutateDeclarationList( translationUnit );
108        }
109
110        void expandTuples( std::list< Declaration * > & translationUnit ) {
111                TupleAssignExpander assnExpander;
112                mutateAll( translationUnit, assnExpander );
113
114                TupleTypeReplacer replacer;
115                replacer.mutateDeclarationList( translationUnit );
116
117                TupleIndexExpander idxExpander;
118                mutateAll( translationUnit, idxExpander );
119
120                TupleExprExpander exprExpander;
121                mutateAll( translationUnit, exprExpander );
122        }
123
124        namespace {
125                /// given a expression representing the member and an expression representing the aggregate,
126                /// reconstructs a flattened UntypedMemberExpr with the right precedence
127                Expression * reconstructMemberExpr( Expression * member, Expression * aggr ) {
128                        if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * >( member ) ) {
129                                // construct a new UntypedMemberExpr with the correct structure , and recursively
130                                // expand that member expression.
131                                MemberTupleExpander expander;
132                                UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member(), new UntypedMemberExpr( memberExpr->get_aggregate(), aggr->clone() ) );
133
134                                memberExpr->set_member(nullptr);
135                                memberExpr->set_aggregate(nullptr);
136                                delete memberExpr;
137                                return newMemberExpr->acceptMutator( expander );
138                        } else {
139                                // not a member expression, so there is nothing to do but attach and return
140                                return new UntypedMemberExpr( member, aggr->clone() );
141                        }
142                }
143        }
144
145        Expression * MemberTupleExpander::mutate( UntypedMemberExpr * memberExpr ) {
146                if ( TupleExpr * tupleExpr = dynamic_cast< TupleExpr * > ( memberExpr->get_member() ) ) {
147                        Expression * aggr = memberExpr->get_aggregate()->clone()->acceptMutator( *this );
148                        // aggregate expressions which might be impure must be wrapped in unique expressions
149                        // xxx - if there's a member-tuple expression nested in the aggregate, this currently generates the wrong code if a UniqueExpr is not used, and it's purely an optimization to remove the UniqueExpr
150                        // if ( Tuples::maybeImpure( memberExpr->get_aggregate() ) ) aggr = new UniqueExpr( aggr );
151                        aggr = new UniqueExpr( aggr );
152                        for ( Expression *& expr : tupleExpr->get_exprs() ) {
153                                expr = reconstructMemberExpr( expr, aggr );
154                        }
155                        delete aggr;
156                        return tupleExpr;
157                } else {
158                        // there may be a tuple expr buried in the aggregate
159                        // xxx - this is a memory leak
160                        return new UntypedMemberExpr( memberExpr->get_member()->clone(), memberExpr->get_aggregate()->acceptMutator( *this ) );
161                }
162        }
163
164        Expression * UniqueExprExpander::mutate( UniqueExpr * unqExpr ) {
165                unqExpr = safe_dynamic_cast< UniqueExpr * > ( Parent::mutate( unqExpr ) );
166                const int id = unqExpr->get_id();
167
168                // on first time visiting a unique expr with a particular ID, generate the expression that replaces all UniqueExprs with that ID,
169                // and lookup on subsequent hits. This ensures that all unique exprs with the same ID reference the same variable.
170                if ( ! decls.count( id ) ) {
171                        Expression * assignUnq;
172                        Expression * var = unqExpr->get_var();
173                        if ( unqExpr->get_object() ) {
174                                // an object was generated to represent this unique expression -- it should be added to the list of declarations now
175                                addDeclaration( unqExpr->get_object() );
176                                unqExpr->set_object( nullptr );
177                                // steal the expr from the unqExpr
178                                assignUnq = UntypedExpr::createAssign( unqExpr->get_var()->clone(), unqExpr->get_expr() );
179                                unqExpr->set_expr( nullptr );
180                        } else {
181                                // steal the already generated assignment to var from the unqExpr - this has been generated by FixInit
182                                Expression * expr = unqExpr->get_expr();
183                                CommaExpr * commaExpr = safe_dynamic_cast< CommaExpr * >( expr );
184                                assignUnq = commaExpr->get_arg1();
185                                commaExpr->set_arg1( nullptr );
186                        }
187                        BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
188                        ObjectDecl * finished = new ObjectDecl( toString( "_unq_expr_finished_", id ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, nullptr, new BasicType( Type::Qualifiers(), BasicType::Bool ), new SingleInit( new ConstantExpr( Constant( boolType->clone(), "0" ) ), noDesignators ) );
189                        addDeclaration( finished );
190                        // (finished ? _unq_expr_N : (_unq_expr_N = <unqExpr->get_expr()>, finished = 1, _unq_expr_N))
191                        // This pattern ensures that each unique expression is evaluated once, regardless of evaluation order of the generated C code.
192                        Expression * assignFinished = UntypedExpr::createAssign( new VariableExpr(finished), new ConstantExpr( Constant( boolType->clone(), "1" ) ) );
193                        ConditionalExpr * condExpr = new ConditionalExpr( new VariableExpr( finished ), var->clone(),
194                                new CommaExpr( new CommaExpr( assignUnq, assignFinished ), var->clone() ) );
195                        condExpr->set_result( var->get_result()->clone() );
196                        decls[id] = condExpr;
197                }
198                delete unqExpr;
199                return decls[id]->clone();
200        }
201
202        Expression * TupleAssignExpander::mutate( TupleAssignExpr * assnExpr ) {
203                assnExpr = safe_dynamic_cast< TupleAssignExpr * >( Parent::mutate( assnExpr ) );
204                CompoundStmt * compoundStmt = new CompoundStmt( noLabels );
205                std::list< Statement * > & stmts = compoundStmt->get_kids();
206                for ( ObjectDecl * obj : assnExpr->get_tempDecls() ) {
207                        stmts.push_back( new DeclStmt( noLabels, obj ) );
208                }
209                TupleExpr * tupleExpr = new TupleExpr( assnExpr->get_assigns() );
210                assert( tupleExpr->get_result() );
211                stmts.push_back( new ExprStmt( noLabels, tupleExpr ) );
212                assnExpr->get_tempDecls().clear();
213                assnExpr->get_assigns().clear();
214                delete assnExpr;
215                return new StmtExpr( compoundStmt );
216        }
217
218        Type * TupleTypeReplacer::mutate( TupleType * tupleType ) {
219                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
220                TupleType * newType = safe_dynamic_cast< TupleType * > ( Parent::mutate( tupleType ) );
221                if ( ! typeMap.count( mangleName ) ) {
222                        // generate struct type to replace tuple type
223                        StructDecl * decl = new StructDecl( "_tuple_type_" + mangleName );
224                        decl->set_body( true );
225                        int cnt = 0;
226                        for ( Type * t : *newType ) {
227                                decl->get_members().push_back( new ObjectDecl( toString("field_", cnt++), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, t->clone(), nullptr ) );
228                        }
229                        typeMap[mangleName] = decl;
230                        addDeclaration( decl );
231                }
232                Type::Qualifiers qualifiers = newType->get_qualifiers();
233                delete newType;
234                return new StructInstType( qualifiers, typeMap[mangleName] );
235        }
236
237        Expression * TupleIndexExpander::mutate( TupleIndexExpr * tupleExpr ) {
238                Expression * tuple = maybeMutate( tupleExpr->get_tuple(), *this );
239                assert( tuple );
240                tupleExpr->set_tuple( nullptr );
241                unsigned int idx = tupleExpr->get_index();
242                delete tupleExpr;
243
244                StructInstType * type = safe_dynamic_cast< StructInstType * >( tuple->get_result() );
245                StructDecl * structDecl = type->get_baseStruct();
246                assert( structDecl->get_members().size() > idx );
247                Declaration * member = *std::next(structDecl->get_members().begin(), idx);
248                return new MemberExpr( safe_dynamic_cast< DeclarationWithType * >( member ), tuple );
249        }
250
251        Expression * replaceTupleExpr( Type * result, const std::list< Expression * > & exprs ) {
252                if ( result->isVoid() ) {
253                        // void result - don't need to produce a value for cascading - just output a chain of comma exprs
254                        assert( ! exprs.empty() );
255                        std::list< Expression * >::const_iterator iter = exprs.begin();
256                        Expression * expr = *iter++;
257                        for ( ; iter != exprs.end(); ++iter ) {
258                                expr = new CommaExpr( expr, *iter );
259                        }
260                        return expr;
261                } else {
262                        // typed tuple expression - produce a compound literal which performs each of the expressions
263                        // as a distinct part of its initializer - the produced compound literal may be used as part of
264                        // another expression
265                        std::list< Initializer * > inits;
266                        for ( Expression * expr : exprs ) {
267                                inits.push_back( new SingleInit( expr ) );
268                        }
269                        return new CompoundLiteralExpr( result, new ListInit( inits ) );
270                }
271        }
272
273        Expression * TupleExprExpander::mutate( TupleExpr * tupleExpr ) {
274                // recursively expand sub-tuple-expressions
275                tupleExpr = safe_dynamic_cast<TupleExpr *>(Parent::mutate(tupleExpr));
276                Type * result = tupleExpr->get_result();
277                std::list< Expression * > exprs = tupleExpr->get_exprs();
278                assert( result );
279
280                // remove data from shell and delete it
281                tupleExpr->set_result( nullptr );
282                tupleExpr->get_exprs().clear();
283                delete tupleExpr;
284
285                return replaceTupleExpr( result, exprs );
286        }
287
288        Type * makeTupleType( const std::list< Expression * > & exprs ) {
289                // produce the TupleType which aggregates the types of the exprs
290                TupleType *tupleType = new TupleType( Type::Qualifiers(true, true, true, true, true, false) );
291                Type::Qualifiers &qualifiers = tupleType->get_qualifiers();
292                for ( Expression * expr : exprs ) {
293                        assert( expr->get_result() );
294                        if ( expr->get_result()->isVoid() ) {
295                                // if the type of any expr is void, the type of the entire tuple is void
296                                delete tupleType;
297                                return new VoidType( Type::Qualifiers() );
298                        }
299                        Type * type = expr->get_result()->clone();
300                        tupleType->get_types().push_back( type );
301                        // the qualifiers on the tuple type are the qualifiers that exist on all component types
302                        qualifiers &= type->get_qualifiers();
303                } // for
304                return tupleType;
305        }
306
307        namespace {
308                /// determines if impurity (read: side-effects) may exist in a piece of code. Currently gives a very crude approximation, wherein any function call expression means the code may be impure
309                class ImpurityDetector : public Visitor {
310                public:
311                        typedef Visitor Parent;
312                        virtual void visit( ApplicationExpr * appExpr ) { maybeImpure = true;   }
313                        virtual void visit( UntypedExpr * untypedExpr ) { maybeImpure = true; }
314                        bool maybeImpure = false;
315                };
316        } // namespace
317
318        bool maybeImpure( Expression * expr ) {
319                ImpurityDetector detector;
320                expr->accept( detector );
321                return detector.maybeImpure;
322        }
323} // namespace Tuples
324
325// Local Variables: //
326// tab-width: 4 //
327// mode: c++ //
328// compile-command: "make install" //
329// End: //
Note: See TracBrowser for help on using the repository browser.