source: src/Tuples/TupleExpansion.cc @ ba54f7d

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 ba54f7d was e3e16bc, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Renamed safe_dynamic_cast to strict_dynamic_cast

  • Property mode set to 100644
File size: 14.7 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 : Wed Jun 21 17:35:04 2017
13// Update Count     : 19
14//
15
16#include <stddef.h>               // for size_t
17#include <cassert>                // for assert
18#include <list>                   // for list
19
20#include "Common/PassVisitor.h"   // for PassVisitor, WithDeclsToAdd, WithGu...
21#include "Common/ScopedMap.h"     // for ScopedMap
22#include "Common/utility.h"       // for CodeLocation
23#include "GenPoly/DeclMutator.h"  // for DeclMutator
24#include "InitTweak/InitTweak.h"  // for getFunction
25#include "Parser/LinkageSpec.h"   // for Spec, C, Intrinsic
26#include "SynTree/Constant.h"     // for Constant
27#include "SynTree/Declaration.h"  // for StructDecl, DeclarationWithType
28#include "SynTree/Expression.h"   // for UntypedMemberExpr, Expression, Uniq...
29#include "SynTree/Label.h"        // for operator==, Label
30#include "SynTree/Mutator.h"      // for Mutator
31#include "SynTree/Type.h"         // for Type, Type::Qualifiers, TupleType
32#include "SynTree/Visitor.h"      // for Visitor
33
34class CompoundStmt;
35class TypeSubstitution;
36
37namespace Tuples {
38        namespace {
39                struct MemberTupleExpander final : public Mutator {
40                        typedef Mutator Parent;
41                        using Parent::mutate;
42
43                        virtual Expression * mutate( UntypedMemberExpr * memberExpr ) override;
44                };
45
46                struct UniqueExprExpander final : public WithDeclsToAdd {
47                        Expression * postmutate( UniqueExpr * unqExpr );
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                struct TupleAssignExpander {
59                        Expression * postmutate( TupleAssignExpr * tupleExpr );
60                };
61
62                struct TupleTypeReplacer : public WithDeclsToAdd, public WithGuards, public WithTypeSubstitution {
63                        Type * postmutate( TupleType * tupleType );
64
65                        void premutate( CompoundStmt * ) {
66                                GuardScope( typeMap );
67                        }
68                  private:
69                        ScopedMap< int, StructDecl * > typeMap;
70                };
71
72                struct TupleIndexExpander {
73                        Expression * postmutate( TupleIndexExpr * tupleExpr );
74                };
75
76                struct TupleExprExpander final {
77                        Expression * postmutate( TupleExpr * tupleExpr );
78                };
79        }
80
81        void expandMemberTuples( std::list< Declaration * > & translationUnit ) {
82                MemberTupleExpander expander;
83                mutateAll( translationUnit, expander );
84        }
85
86        void expandUniqueExpr( std::list< Declaration * > & translationUnit ) {
87                PassVisitor<UniqueExprExpander> unqExpander;
88                mutateAll( translationUnit, unqExpander );
89        }
90
91        void expandTuples( std::list< Declaration * > & translationUnit ) {
92                PassVisitor<TupleAssignExpander> assnExpander;
93                mutateAll( translationUnit, assnExpander );
94
95                PassVisitor<TupleTypeReplacer> replacer;
96                mutateAll( translationUnit, replacer );
97
98                PassVisitor<TupleIndexExpander> idxExpander;
99                mutateAll( translationUnit, idxExpander );
100
101                PassVisitor<TupleExprExpander> exprExpander;
102                mutateAll( translationUnit, exprExpander );
103        }
104
105        namespace {
106                /// given a expression representing the member and an expression representing the aggregate,
107                /// reconstructs a flattened UntypedMemberExpr with the right precedence
108                Expression * reconstructMemberExpr( Expression * member, Expression * aggr, CodeLocation & loc ) {
109                        if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * >( member ) ) {
110                                // construct a new UntypedMemberExpr with the correct structure , and recursively
111                                // expand that member expression.
112                                MemberTupleExpander expander;
113                                UntypedMemberExpr * inner = new UntypedMemberExpr( memberExpr->get_aggregate(), aggr->clone() );
114                                UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member(), inner );
115                                inner->location = newMemberExpr->location = loc;
116                                memberExpr->set_member(nullptr);
117                                memberExpr->set_aggregate(nullptr);
118                                delete memberExpr;
119                                return newMemberExpr->acceptMutator( expander );
120                        } else {
121                                // not a member expression, so there is nothing to do but attach and return
122                                UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( member, aggr->clone() );
123                                newMemberExpr->location = loc;
124                                return newMemberExpr;
125                        }
126                }
127        }
128
129        Expression * MemberTupleExpander::mutate( UntypedMemberExpr * memberExpr ) {
130                if ( UntypedTupleExpr * tupleExpr = dynamic_cast< UntypedTupleExpr * > ( memberExpr->get_member() ) ) {
131                        Expression * aggr = memberExpr->get_aggregate()->clone()->acceptMutator( *this );
132                        // aggregate expressions which might be impure must be wrapped in unique expressions
133                        // 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
134                        // if ( Tuples::maybeImpureIgnoreUnique( memberExpr->get_aggregate() ) ) aggr = new UniqueExpr( aggr );
135                        aggr = new UniqueExpr( aggr );
136                        for ( Expression *& expr : tupleExpr->get_exprs() ) {
137                                expr = reconstructMemberExpr( expr, aggr, memberExpr->location );
138                                expr->location = memberExpr->location;
139                        }
140                        delete aggr;
141                        tupleExpr->location = memberExpr->location;
142                        return tupleExpr;
143                } else {
144                        // there may be a tuple expr buried in the aggregate
145                        // xxx - this is a memory leak
146                        UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member()->clone(), memberExpr->get_aggregate()->acceptMutator( *this ) );
147                        newMemberExpr->location = memberExpr->location;
148                        return newMemberExpr;
149                }
150        }
151
152        Expression * UniqueExprExpander::postmutate( UniqueExpr * unqExpr ) {
153                const int id = unqExpr->get_id();
154
155                // on first time visiting a unique expr with a particular ID, generate the expression that replaces all UniqueExprs with that ID,
156                // and lookup on subsequent hits. This ensures that all unique exprs with the same ID reference the same variable.
157                if ( ! decls.count( id ) ) {
158                        Expression * assignUnq;
159                        Expression * var = unqExpr->get_var();
160                        if ( unqExpr->get_object() ) {
161                                // an object was generated to represent this unique expression -- it should be added to the list of declarations now
162                                declsToAddBefore.push_back( unqExpr->get_object() );
163                                unqExpr->set_object( nullptr );
164                                // steal the expr from the unqExpr
165                                assignUnq = UntypedExpr::createAssign( unqExpr->get_var()->clone(), unqExpr->get_expr() );
166                                unqExpr->set_expr( nullptr );
167                        } else {
168                                // steal the already generated assignment to var from the unqExpr - this has been generated by FixInit
169                                Expression * expr = unqExpr->get_expr();
170                                CommaExpr * commaExpr = strict_dynamic_cast< CommaExpr * >( expr );
171                                assignUnq = commaExpr->get_arg1();
172                                commaExpr->set_arg1( nullptr );
173                        }
174                        ObjectDecl * finished = new ObjectDecl( toString( "_unq", id, "_finished_" ), Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new BasicType( Type::Qualifiers(), BasicType::Bool ),
175                                                                                                        new SingleInit( new ConstantExpr( Constant::from_int( 0 ) ) ) );
176                        declsToAddBefore.push_back( finished );
177                        // (finished ? _unq_expr_N : (_unq_expr_N = <unqExpr->get_expr()>, finished = 1, _unq_expr_N))
178                        // This pattern ensures that each unique expression is evaluated once, regardless of evaluation order of the generated C code.
179                        Expression * assignFinished = UntypedExpr::createAssign( new VariableExpr(finished), new ConstantExpr( Constant::from_int( 1 ) ) );
180                        ConditionalExpr * condExpr = new ConditionalExpr( new VariableExpr( finished ), var->clone(),
181                                new CommaExpr( new CommaExpr( assignUnq, assignFinished ), var->clone() ) );
182                        condExpr->set_result( var->get_result()->clone() );
183                        condExpr->set_env( maybeClone( unqExpr->get_env() ) );
184                        decls[id] = condExpr;
185                }
186                delete unqExpr;
187                return decls[id]->clone();
188        }
189
190        Expression * TupleAssignExpander::postmutate( TupleAssignExpr * assnExpr ) {
191                StmtExpr * ret = assnExpr->get_stmtExpr();
192                assnExpr->set_stmtExpr( nullptr );
193                // move env to StmtExpr
194                ret->set_env( assnExpr->get_env() );
195                assnExpr->set_env( nullptr );
196                delete assnExpr;
197                return ret;
198        }
199
200        Type * TupleTypeReplacer::postmutate( TupleType * tupleType ) {
201                unsigned tupleSize = tupleType->size();
202                if ( ! typeMap.count( tupleSize ) ) {
203                        // generate struct type to replace tuple type based on the number of components in the tuple
204                        StructDecl * decl = new StructDecl( toString( "_tuple", tupleSize, "_" ) );
205                        decl->set_body( true );
206                        for ( size_t i = 0; i < tupleSize; ++i ) {
207                                TypeDecl * tyParam = new TypeDecl( toString( "tuple_param_", tupleSize, "_", i ), Type::StorageClasses(), nullptr, TypeDecl::Any );
208                                decl->get_members().push_back( new ObjectDecl( toString("field_", i ), Type::StorageClasses(), LinkageSpec::C, nullptr, new TypeInstType( Type::Qualifiers(), tyParam->get_name(), tyParam ), nullptr ) );
209                                decl->get_parameters().push_back( tyParam );
210                        }
211                        if ( tupleSize == 0 ) {
212                                // empty structs are not standard C. Add a dummy field to empty tuples to silence warnings when a compound literal Tuple0 is created.
213                                decl->get_members().push_back( new ObjectDecl( "dummy", Type::StorageClasses(), LinkageSpec::C, nullptr, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), nullptr ) );
214                        }
215                        typeMap[tupleSize] = decl;
216                        declsToAddBefore.push_back( decl );
217                }
218                Type::Qualifiers qualifiers = tupleType->get_qualifiers();
219
220                StructDecl * decl = typeMap[tupleSize];
221                StructInstType * newType = new StructInstType( qualifiers, decl );
222                for ( auto p : group_iterate( tupleType->get_types(), decl->get_parameters() ) ) {
223                        Type * t = std::get<0>(p);
224                        newType->get_parameters().push_back( new TypeExpr( t->clone() ) );
225                }
226                delete tupleType;
227                return newType;
228        }
229
230        Expression * TupleIndexExpander::postmutate( TupleIndexExpr * tupleExpr ) {
231                Expression * tuple = tupleExpr->get_tuple();
232                assert( tuple );
233                tupleExpr->set_tuple( nullptr );
234                unsigned int idx = tupleExpr->get_index();
235                TypeSubstitution * env = tupleExpr->get_env();
236                tupleExpr->set_env( nullptr );
237                delete tupleExpr;
238
239                StructInstType * type = strict_dynamic_cast< StructInstType * >( tuple->get_result() );
240                StructDecl * structDecl = type->get_baseStruct();
241                assert( structDecl->get_members().size() > idx );
242                Declaration * member = *std::next(structDecl->get_members().begin(), idx);
243                MemberExpr * memExpr = new MemberExpr( strict_dynamic_cast< DeclarationWithType * >( member ), tuple );
244                memExpr->set_env( env );
245                return memExpr;
246        }
247
248        Expression * replaceTupleExpr( Type * result, const std::list< Expression * > & exprs, TypeSubstitution * env ) {
249                if ( result->isVoid() ) {
250                        // void result - don't need to produce a value for cascading - just output a chain of comma exprs
251                        assert( ! exprs.empty() );
252                        std::list< Expression * >::const_iterator iter = exprs.begin();
253                        Expression * expr = new CastExpr( *iter++ );
254                        for ( ; iter != exprs.end(); ++iter ) {
255                                expr = new CommaExpr( expr, new CastExpr( *iter ) );
256                        }
257                        expr->set_env( env );
258                        return expr;
259                } else {
260                        // typed tuple expression - produce a compound literal which performs each of the expressions
261                        // as a distinct part of its initializer - the produced compound literal may be used as part of
262                        // another expression
263                        std::list< Initializer * > inits;
264                        for ( Expression * expr : exprs ) {
265                                inits.push_back( new SingleInit( expr ) );
266                        }
267                        Expression * expr = new CompoundLiteralExpr( result, new ListInit( inits ) );
268                        expr->set_env( env );
269                        return expr;
270                }
271        }
272
273        Expression * TupleExprExpander::postmutate( TupleExpr * tupleExpr ) {
274                Type * result = tupleExpr->get_result();
275                std::list< Expression * > exprs = tupleExpr->get_exprs();
276                assert( result );
277                TypeSubstitution * env = tupleExpr->get_env();
278
279                // remove data from shell and delete it
280                tupleExpr->set_result( nullptr );
281                tupleExpr->get_exprs().clear();
282                tupleExpr->set_env( nullptr );
283                delete tupleExpr;
284
285                return replaceTupleExpr( result, exprs, env );
286        }
287
288        Type * makeTupleType( const std::list< Expression * > & exprs ) {
289                // produce the TupleType which aggregates the types of the exprs
290                std::list< Type * > types;
291                Type::Qualifiers qualifiers( Type::Const | Type::Volatile | Type::Restrict | Type::Lvalue | Type::Atomic | Type::Mutex );
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                                return new VoidType( Type::Qualifiers() );
297                        }
298                        Type * type = expr->get_result()->clone();
299                        types.push_back( type );
300                        // the qualifiers on the tuple type are the qualifiers that exist on all component types
301                        qualifiers &= type->get_qualifiers();
302                } // for
303                if ( exprs.empty() ) qualifiers = Type::Qualifiers();
304                return new TupleType( qualifiers, types );
305        }
306
307        TypeInstType * isTtype( Type * type ) {
308                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( type ) ) {
309                        if ( inst->get_baseType() && inst->get_baseType()->get_kind() == TypeDecl::Ttype ) {
310                                return inst;
311                        }
312                }
313                return nullptr;
314        }
315
316        namespace {
317                /// 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
318                class ImpurityDetector : public Visitor {
319                public:
320                        ImpurityDetector( bool ignoreUnique ) : ignoreUnique( ignoreUnique ) {}
321
322                        typedef Visitor Parent;
323                        virtual void visit( ApplicationExpr * appExpr ) {
324                                if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
325                                        if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
326                                                if ( function->get_name() == "*?" || function->get_name() == "?[?]" ) {
327                                                        // intrinsic dereference, subscript are pure, but need to recursively look for impurity
328                                                        Parent::visit( appExpr );
329                                                        return;
330                                                }
331                                        }
332                                }
333                                maybeImpure = true;
334                        }
335                        virtual void visit( UntypedExpr * ) { maybeImpure = true; }
336                        virtual void visit( UniqueExpr * unq ) {
337                                if ( ignoreUnique ) {
338                                        // bottom out at unique expression.
339                                        // The existence of a unique expression doesn't change the purity of an expression.
340                                        // That is, even if the wrapped expression is impure, the wrapper protects the rest of the expression.
341                                        return;
342                                }
343                                maybeAccept( unq->expr, *this );
344                        }
345
346                        bool maybeImpure = false;
347                        bool ignoreUnique;
348                };
349        } // namespace
350
351        bool maybeImpure( Expression * expr ) {
352                ImpurityDetector detector( false );
353                expr->accept( detector );
354                return detector.maybeImpure;
355        }
356
357        bool maybeImpureIgnoreUnique( Expression * expr ) {
358                ImpurityDetector detector( true );
359                expr->accept( detector );
360                return detector.maybeImpure;
361        }
362} // namespace Tuples
363
364// Local Variables: //
365// tab-width: 4 //
366// mode: c++ //
367// compile-command: "make install" //
368// End: //
Note: See TracBrowser for help on using the repository browser.