source: src/Tuples/TupleExpansion.cc @ e4d829b

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

major effort on designations, works in many cases

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