source: src/Tuples/TupleExpansion.cc@ 641c3d0

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

Big push on designations and initialization: works with generic types, tuples, arrays, tests pass.
Refactor guard_value_impl.
Add list of declarations to TupleType.

  • Property mode set to 100644
File size: 14.2 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 <iterator>
17#include <iostream>
18#include <cassert>
19#include "Tuples.h"
20#include "Common/PassVisitor.h"
21#include "Common/ScopedMap.h"
22#include "GenPoly/DeclMutator.h"
23#include "InitTweak/GenInit.h"
24#include "InitTweak/InitTweak.h"
25#include "ResolvExpr/typeops.h"
26#include "SymTab/Mangler.h"
27#include "SynTree/Declaration.h"
28#include "SynTree/Expression.h"
29#include "SynTree/Initializer.h"
30#include "SynTree/Mutator.h"
31#include "SynTree/Statement.h"
32#include "SynTree/Type.h"
33
34namespace Tuples {
35 namespace {
36 class MemberTupleExpander final : public Mutator {
37 public:
38 typedef Mutator Parent;
39 using Parent::mutate;
40
41 virtual Expression * mutate( UntypedMemberExpr * memberExpr ) override;
42 };
43
44 class UniqueExprExpander final : public GenPoly::DeclMutator {
45 public:
46 typedef GenPoly::DeclMutator Parent;
47 using Parent::mutate;
48
49 virtual Expression * mutate( UniqueExpr * unqExpr ) override;
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 }
58 };
59
60 class TupleAssignExpander : public Mutator {
61 public:
62 typedef Mutator Parent;
63 using Parent::mutate;
64
65 virtual Expression * mutate( TupleAssignExpr * tupleExpr );
66 };
67
68 class TupleTypeReplacer : public GenPoly::DeclMutator {
69 public:
70 typedef GenPoly::DeclMutator Parent;
71 using Parent::mutate;
72
73 virtual Type * mutate( TupleType * tupleType ) override;
74
75 virtual CompoundStmt * mutate( CompoundStmt * stmt ) override {
76 typeMap.beginScope();
77 stmt = Parent::mutate( stmt );
78 typeMap.endScope();
79 return stmt;
80 }
81 private:
82 ScopedMap< int, StructDecl * > typeMap;
83 };
84
85 class TupleIndexExpander {
86 public:
87 Expression * postmutate( TupleIndexExpr * tupleExpr );
88 };
89
90 class TupleExprExpander final : public Mutator {
91 public:
92 typedef Mutator Parent;
93 using Parent::mutate;
94
95 virtual Expression * mutate( TupleExpr * tupleExpr ) override;
96 };
97 }
98
99 void expandMemberTuples( std::list< Declaration * > & translationUnit ) {
100 MemberTupleExpander expander;
101 mutateAll( translationUnit, expander );
102 }
103
104 void expandUniqueExpr( std::list< Declaration * > & translationUnit ) {
105 UniqueExprExpander unqExpander;
106 unqExpander.mutateDeclarationList( translationUnit );
107 }
108
109 void expandTuples( std::list< Declaration * > & translationUnit ) {
110 TupleAssignExpander assnExpander;
111 mutateAll( translationUnit, assnExpander );
112
113 TupleTypeReplacer replacer;
114 replacer.mutateDeclarationList( translationUnit );
115
116 PassVisitor<TupleIndexExpander> idxExpander;
117 mutateAll( translationUnit, idxExpander );
118
119 TupleExprExpander exprExpander;
120 mutateAll( translationUnit, exprExpander );
121 }
122
123 namespace {
124 /// given a expression representing the member and an expression representing the aggregate,
125 /// reconstructs a flattened UntypedMemberExpr with the right precedence
126 Expression * reconstructMemberExpr( Expression * member, Expression * aggr, CodeLocation & loc ) {
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;
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;
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
140 UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( member, aggr->clone() );
141 newMemberExpr->location = loc;
142 return newMemberExpr;
143 }
144 }
145 }
146
147 Expression * MemberTupleExpander::mutate( UntypedMemberExpr * memberExpr ) {
148 if ( UntypedTupleExpr * tupleExpr = dynamic_cast< UntypedTupleExpr * > ( memberExpr->get_member() ) ) {
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 );
154 for ( Expression *& expr : tupleExpr->get_exprs() ) {
155 expr = reconstructMemberExpr( expr, aggr, memberExpr->location );
156 expr->location = memberExpr->location;
157 }
158 delete aggr;
159 tupleExpr->location = memberExpr->location;
160 return tupleExpr;
161 } else {
162 // there may be a tuple expr buried in the aggregate
163 // xxx - this is a memory leak
164 UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member()->clone(), memberExpr->get_aggregate()->acceptMutator( *this ) );
165 newMemberExpr->location = memberExpr->location;
166 return newMemberExpr;
167 }
168 }
169
170 Expression * UniqueExprExpander::mutate( UniqueExpr * unqExpr ) {
171 unqExpr = safe_dynamic_cast< UniqueExpr * > ( Parent::mutate( unqExpr ) );
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 ObjectDecl * finished = new ObjectDecl( toString( "_unq", id, "_finished_" ), Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new BasicType( Type::Qualifiers(), BasicType::Bool ),
194 new SingleInit( new ConstantExpr( Constant::from_int( 0 ) ) ) );
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::from_int( 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() );
202 condExpr->set_env( maybeClone( unqExpr->get_env() ) );
203 decls[id] = condExpr;
204 }
205 delete unqExpr;
206 return decls[id]->clone();
207 }
208
209 Expression * TupleAssignExpander::mutate( TupleAssignExpr * assnExpr ) {
210 assnExpr = safe_dynamic_cast< TupleAssignExpr * >( Parent::mutate( assnExpr ) );
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 );
216 delete assnExpr;
217 return ret;
218 }
219
220 Type * TupleTypeReplacer::mutate( TupleType * tupleType ) {
221 tupleType = safe_dynamic_cast< TupleType * > ( Parent::mutate( tupleType ) );
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
225 StructDecl * decl = new StructDecl( toString( "_tuple", tupleSize, "_" ) );
226 decl->set_body( true );
227 for ( size_t i = 0; i < tupleSize; ++i ) {
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 ) );
230 decl->get_parameters().push_back( tyParam );
231 }
232 if ( tupleSize == 0 ) {
233 // empty structs are not standard C. Add a dummy field to empty tuples to silence warnings when a compound literal Tuple0 is created.
234 decl->get_members().push_back( new ObjectDecl( "dummy", Type::StorageClasses(), LinkageSpec::C, nullptr, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), nullptr ) );
235 }
236 typeMap[tupleSize] = decl;
237 addDeclaration( decl );
238 }
239 Type::Qualifiers qualifiers = tupleType->get_qualifiers();
240
241 StructDecl * decl = typeMap[tupleSize];
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;
248 }
249
250 Expression * TupleIndexExpander::postmutate( TupleIndexExpr * tupleExpr ) {
251 Expression * tuple = tupleExpr->get_tuple();
252 assert( tuple );
253 tupleExpr->set_tuple( nullptr );
254 unsigned int idx = tupleExpr->get_index();
255 TypeSubstitution * env = tupleExpr->get_env();
256 tupleExpr->set_env( nullptr );
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);
263 MemberExpr * memExpr = new MemberExpr( safe_dynamic_cast< DeclarationWithType * >( member ), tuple );
264 memExpr->set_env( env );
265 return memExpr;
266 }
267
268 Expression * replaceTupleExpr( Type * result, const std::list< Expression * > & exprs, TypeSubstitution * env ) {
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();
273 Expression * expr = new CastExpr( *iter++ );
274 for ( ; iter != exprs.end(); ++iter ) {
275 expr = new CommaExpr( expr, new CastExpr( *iter ) );
276 }
277 expr->set_env( env );
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 }
287 Expression * expr = new CompoundLiteralExpr( result, new ListInit( inits ) );
288 expr->set_env( env );
289 return expr;
290 }
291 }
292
293 Expression * TupleExprExpander::mutate( TupleExpr * tupleExpr ) {
294 // recursively expand sub-tuple-expressions
295 tupleExpr = safe_dynamic_cast<TupleExpr *>(Parent::mutate(tupleExpr));
296 Type * result = tupleExpr->get_result();
297 std::list< Expression * > exprs = tupleExpr->get_exprs();
298 assert( result );
299 TypeSubstitution * env = tupleExpr->get_env();
300
301 // remove data from shell and delete it
302 tupleExpr->set_result( nullptr );
303 tupleExpr->get_exprs().clear();
304 tupleExpr->set_env( nullptr );
305 delete tupleExpr;
306
307 return replaceTupleExpr( result, exprs, env );
308 }
309
310 Type * makeTupleType( const std::list< Expression * > & exprs ) {
311 // produce the TupleType which aggregates the types of the exprs
312 std::list< Type * > types;
313 Type::Qualifiers qualifiers( Type::Const | Type::Volatile | Type::Restrict | Type::Lvalue | Type::Atomic | Type::Mutex );
314 for ( Expression * expr : exprs ) {
315 assert( expr->get_result() );
316 if ( expr->get_result()->isVoid() ) {
317 // if the type of any expr is void, the type of the entire tuple is void
318 return new VoidType( Type::Qualifiers() );
319 }
320 Type * type = expr->get_result()->clone();
321 types.push_back( type );
322 // the qualifiers on the tuple type are the qualifiers that exist on all component types
323 qualifiers &= type->get_qualifiers();
324 } // for
325 if ( exprs.empty() ) qualifiers = Type::Qualifiers();
326 return new TupleType( qualifiers, types );
327 }
328
329 TypeInstType * isTtype( Type * type ) {
330 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( type ) ) {
331 if ( inst->get_baseType() && inst->get_baseType()->get_kind() == TypeDecl::Ttype ) {
332 return inst;
333 }
334 }
335 return nullptr;
336 }
337
338 namespace {
339 /// 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
340 class ImpurityDetector : public Visitor {
341 public:
342 typedef Visitor Parent;
343 virtual void visit( ApplicationExpr * appExpr ) {
344 if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
345 if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
346 if ( function->get_name() == "*?" || function->get_name() == "?[?]" ) {
347 // intrinsic dereference, subscript are pure, but need to recursively look for impurity
348 Parent::visit( appExpr );
349 return;
350 }
351 }
352 }
353 maybeImpure = true;
354 }
355 virtual void visit( __attribute__((unused)) UntypedExpr * untypedExpr ) { maybeImpure = true; }
356 bool maybeImpure = false;
357 };
358 } // namespace
359
360 bool maybeImpure( Expression * expr ) {
361 ImpurityDetector detector;
362 expr->accept( detector );
363 return detector.maybeImpure;
364 }
365} // namespace Tuples
366
367// Local Variables: //
368// tab-width: 4 //
369// mode: c++ //
370// compile-command: "make install" //
371// End: //
Note: See TracBrowser for help on using the repository browser.