source: src/Tuples/TupleExpansion.cc@ 4b1c8da

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 4b1c8da was 7030dab, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Merge branch 'master' into new-ast

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