source: src/Tuples/TupleExpansion.cc@ 65deb18

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 65deb18 was c470ada, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Transfer code location of tuple type to generated tuple struct

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