source: src/Tuples/TupleExpansion.cc @ 8d7bef2

new-envwith_gc
Last change on this file since 8d7bef2 was 68f9c43, checked in by Aaron Moss <a3moss@…>, 6 years ago

First pass at delete removal

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