source: src/Tuples/TupleExpansion.cc@ 6fa409e

new-env
Last change on this file since 6fa409e was cdc4d43, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fix leftover delete from last merge

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