source: src/Tuples/TupleExpansion.cc @ c43c171

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 c43c171 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
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 "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;
[6eb8948]36
37namespace Tuples {
[3c13c03]38        namespace {
[c93bc28]39                struct MemberTupleExpander final : public Mutator {
[bf32bb8]40                        typedef Mutator Parent;
[5f5083e]41                        using Parent::mutate;
42
43                        virtual Expression * mutate( UntypedMemberExpr * memberExpr ) override;
[bf32bb8]44                };
45
[9f10c4b8]46                struct UniqueExprExpander final : public WithDeclsToAdd {
47                        Expression * postmutate( UniqueExpr * unqExpr );
[141b786]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                        }
[3c13c03]56                };
57
[9f10c4b8]58                struct TupleAssignExpander {
59                        Expression * postmutate( TupleAssignExpr * tupleExpr );
[3c13c03]60                };
61
[c92c09c]62                struct TupleTypeReplacer : public WithDeclsToAdd, public WithGuards, public WithTypeSubstitution {
63                        Type * postmutate( TupleType * tupleType );
[3c13c03]64
[c92c09c]65                        void premutate( CompoundStmt * ) {
66                                GuardScope( typeMap );
[3c13c03]67                        }
68                  private:
[e6512c8]69                        ScopedMap< int, StructDecl * > typeMap;
[3c13c03]70                };
71
[c93bc28]72                struct TupleIndexExpander {
[ab904dc]73                        Expression * postmutate( TupleIndexExpr * tupleExpr );
[3c13c03]74                };
75
[9f10c4b8]76                struct TupleExprExpander final {
77                        Expression * postmutate( TupleExpr * tupleExpr );
[3c13c03]78                };
79        }
[f006f01]80
[bf32bb8]81        void expandMemberTuples( std::list< Declaration * > & translationUnit ) {
82                MemberTupleExpander expander;
83                mutateAll( translationUnit, expander );
84        }
85
[aefcc3b]86        void expandUniqueExpr( std::list< Declaration * > & translationUnit ) {
[9f10c4b8]87                PassVisitor<UniqueExprExpander> unqExpander;
88                mutateAll( translationUnit, unqExpander );
[aefcc3b]89        }
[3c13c03]90
[aefcc3b]91        void expandTuples( std::list< Declaration * > & translationUnit ) {
[9f10c4b8]92                PassVisitor<TupleAssignExpander> assnExpander;
[3c13c03]93                mutateAll( translationUnit, assnExpander );
[f006f01]94
[c92c09c]95                PassVisitor<TupleTypeReplacer> replacer;
96                mutateAll( translationUnit, replacer );
[3c13c03]97
[ab904dc]98                PassVisitor<TupleIndexExpander> idxExpander;
[3c13c03]99                mutateAll( translationUnit, idxExpander );
100
[9f10c4b8]101                PassVisitor<TupleExprExpander> exprExpander;
[3c13c03]102                mutateAll( translationUnit, exprExpander );
103        }
104
[bf32bb8]105        namespace {
106                /// given a expression representing the member and an expression representing the aggregate,
107                /// reconstructs a flattened UntypedMemberExpr with the right precedence
[64ac636]108                Expression * reconstructMemberExpr( Expression * member, Expression * aggr, CodeLocation & loc ) {
[bf32bb8]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;
[64ac636]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;
[bf32bb8]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
[64ac636]122                                UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( member, aggr->clone() );
123                                newMemberExpr->location = loc;
124                                return newMemberExpr;
[bf32bb8]125                        }
126                }
127        }
128
129        Expression * MemberTupleExpander::mutate( UntypedMemberExpr * memberExpr ) {
[907eccb]130                if ( UntypedTupleExpr * tupleExpr = dynamic_cast< UntypedTupleExpr * > ( memberExpr->get_member() ) ) {
[141b786]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
[9f10c4b8]134                        // if ( Tuples::maybeImpureIgnoreUnique( memberExpr->get_aggregate() ) ) aggr = new UniqueExpr( aggr );
[141b786]135                        aggr = new UniqueExpr( aggr );
[bf32bb8]136                        for ( Expression *& expr : tupleExpr->get_exprs() ) {
[64ac636]137                                expr = reconstructMemberExpr( expr, aggr, memberExpr->location );
138                                expr->location = memberExpr->location;
[bf32bb8]139                        }
[141b786]140                        delete aggr;
[64ac636]141                        tupleExpr->location = memberExpr->location;
[bf32bb8]142                        return tupleExpr;
143                } else {
[f0121d7]144                        // there may be a tuple expr buried in the aggregate
145                        // xxx - this is a memory leak
[64ac636]146                        UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member()->clone(), memberExpr->get_aggregate()->acceptMutator( *this ) );
147                        newMemberExpr->location = memberExpr->location;
148                        return newMemberExpr;
[bf32bb8]149                }
150        }
151
[9f10c4b8]152        Expression * UniqueExprExpander::postmutate( UniqueExpr * unqExpr ) {
[141b786]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
[9f10c4b8]162                                declsToAddBefore.push_back( unqExpr->get_object() );
[141b786]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();
[e3e16bc]170                                CommaExpr * commaExpr = strict_dynamic_cast< CommaExpr * >( expr );
[141b786]171                                assignUnq = commaExpr->get_arg1();
172                                commaExpr->set_arg1( nullptr );
173                        }
[d56e5bc]174                        ObjectDecl * finished = new ObjectDecl( toString( "_unq", id, "_finished_" ), Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new BasicType( Type::Qualifiers(), BasicType::Bool ),
[579263a]175                                                                                                        new SingleInit( new ConstantExpr( Constant::from_int( 0 ) ) ) );
[9f10c4b8]176                        declsToAddBefore.push_back( finished );
[141b786]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.
[d56e5bc]179                        Expression * assignFinished = UntypedExpr::createAssign( new VariableExpr(finished), new ConstantExpr( Constant::from_int( 1 ) ) );
[141b786]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() );
[d5556a3]183                        condExpr->set_env( maybeClone( unqExpr->get_env() ) );
[141b786]184                        decls[id] = condExpr;
[3c13c03]185                }
[141b786]186                delete unqExpr;
187                return decls[id]->clone();
[6eb8948]188        }
189
[9f10c4b8]190        Expression * TupleAssignExpander::postmutate( TupleAssignExpr * assnExpr ) {
[d5556a3]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 );
[3c13c03]196                delete assnExpr;
[d5556a3]197                return ret;
[6eb8948]198        }
199
[c92c09c]200        Type * TupleTypeReplacer::postmutate( TupleType * tupleType ) {
[e6512c8]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
[94a8123]204                        StructDecl * decl = new StructDecl( toString( "_tuple", tupleSize, "_" ) );
[f006f01]205                        decl->set_body( true );
[e6512c8]206                        for ( size_t i = 0; i < tupleSize; ++i ) {
[c92c09c]207                                TypeDecl * tyParam = new TypeDecl( toString( "tuple_param_", tupleSize, "_", i ), Type::StorageClasses(), nullptr, TypeDecl::Any );
[68fe077a]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 ) );
[d9fa60a]209                                decl->get_parameters().push_back( tyParam );
[f006f01]210                        }
[e6512c8]211                        if ( tupleSize == 0 ) {
[4c8621ac]212                                // empty structs are not standard C. Add a dummy field to empty tuples to silence warnings when a compound literal Tuple0 is created.
[68fe077a]213                                decl->get_members().push_back( new ObjectDecl( "dummy", Type::StorageClasses(), LinkageSpec::C, nullptr, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), nullptr ) );
[4c8621ac]214                        }
[e6512c8]215                        typeMap[tupleSize] = decl;
[c92c09c]216                        declsToAddBefore.push_back( decl );
[f006f01]217                }
[d9fa60a]218                Type::Qualifiers qualifiers = tupleType->get_qualifiers();
219
[e6512c8]220                StructDecl * decl = typeMap[tupleSize];
[d9fa60a]221                StructInstType * newType = new StructInstType( qualifiers, decl );
[c92c09c]222                for ( auto p : group_iterate( tupleType->get_types(), decl->get_parameters() ) ) {
223                        Type * t = std::get<0>(p);
[d9fa60a]224                        newType->get_parameters().push_back( new TypeExpr( t->clone() ) );
225                }
226                delete tupleType;
227                return newType;
[f006f01]228        }
229
[ab904dc]230        Expression * TupleIndexExpander::postmutate( TupleIndexExpr * tupleExpr ) {
231                Expression * tuple = tupleExpr->get_tuple();
[3c13c03]232                assert( tuple );
233                tupleExpr->set_tuple( nullptr );
234                unsigned int idx = tupleExpr->get_index();
[d5556a3]235                TypeSubstitution * env = tupleExpr->get_env();
236                tupleExpr->set_env( nullptr );
[3c13c03]237                delete tupleExpr;
238
[e3e16bc]239                StructInstType * type = strict_dynamic_cast< StructInstType * >( tuple->get_result() );
[3c13c03]240                StructDecl * structDecl = type->get_baseStruct();
241                assert( structDecl->get_members().size() > idx );
242                Declaration * member = *std::next(structDecl->get_members().begin(), idx);
[e3e16bc]243                MemberExpr * memExpr = new MemberExpr( strict_dynamic_cast< DeclarationWithType * >( member ), tuple );
[d5556a3]244                memExpr->set_env( env );
245                return memExpr;
[3c13c03]246        }
247
[d5556a3]248        Expression * replaceTupleExpr( Type * result, const std::list< Expression * > & exprs, TypeSubstitution * env ) {
[65660bd]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();
[d5556a3]253                        Expression * expr = new CastExpr( *iter++ );
[65660bd]254                        for ( ; iter != exprs.end(); ++iter ) {
[d5556a3]255                                expr = new CommaExpr( expr, new CastExpr( *iter ) );
[65660bd]256                        }
[d5556a3]257                        expr->set_env( env );
[65660bd]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                        }
[d5556a3]267                        Expression * expr = new CompoundLiteralExpr( result, new ListInit( inits ) );
268                        expr->set_env( env );
269                        return expr;
[3c13c03]270                }
271        }
272
[9f10c4b8]273        Expression * TupleExprExpander::postmutate( TupleExpr * tupleExpr ) {
[65660bd]274                Type * result = tupleExpr->get_result();
275                std::list< Expression * > exprs = tupleExpr->get_exprs();
276                assert( result );
[d5556a3]277                TypeSubstitution * env = tupleExpr->get_env();
[65660bd]278
[bf32bb8]279                // remove data from shell and delete it
[65660bd]280                tupleExpr->set_result( nullptr );
281                tupleExpr->get_exprs().clear();
[d5556a3]282                tupleExpr->set_env( nullptr );
[65660bd]283                delete tupleExpr;
284
[d5556a3]285                return replaceTupleExpr( result, exprs, env );
[65660bd]286        }
287
288        Type * makeTupleType( const std::list< Expression * > & exprs ) {
289                // produce the TupleType which aggregates the types of the exprs
[62423350]290                std::list< Type * > types;
291                Type::Qualifiers qualifiers( Type::Const | Type::Volatile | Type::Restrict | Type::Lvalue | Type::Atomic | Type::Mutex );
[3c13c03]292                for ( Expression * expr : exprs ) {
293                        assert( expr->get_result() );
[65660bd]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                        }
[3c13c03]298                        Type * type = expr->get_result()->clone();
[62423350]299                        types.push_back( type );
[65660bd]300                        // the qualifiers on the tuple type are the qualifiers that exist on all component types
[3c13c03]301                        qualifiers &= type->get_qualifiers();
302                } // for
[907eccb]303                if ( exprs.empty() ) qualifiers = Type::Qualifiers();
[62423350]304                return new TupleType( qualifiers, types );
[3c13c03]305        }
[65660bd]306
[8bf784a]307        TypeInstType * isTtype( Type * type ) {
308                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( type ) ) {
[0b150ec]309                        if ( inst->get_baseType() && inst->get_baseType()->get_kind() == TypeDecl::Ttype ) {
[8bf784a]310                                return inst;
311                        }
312                }
313                return nullptr;
314        }
315
[65660bd]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:
[9f10c4b8]320                        ImpurityDetector( bool ignoreUnique ) : ignoreUnique( ignoreUnique ) {}
321
[65660bd]322                        typedef Visitor Parent;
[b7b8674]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                        }
[9f10c4b8]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
[65660bd]346                        bool maybeImpure = false;
[9f10c4b8]347                        bool ignoreUnique;
[65660bd]348                };
349        } // namespace
350
351        bool maybeImpure( Expression * expr ) {
[9f10c4b8]352                ImpurityDetector detector( false );
353                expr->accept( detector );
354                return detector.maybeImpure;
355        }
356
357        bool maybeImpureIgnoreUnique( Expression * expr ) {
358                ImpurityDetector detector( true );
[65660bd]359                expr->accept( detector );
360                return detector.maybeImpure;
361        }
[6eb8948]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.