source: src/GenPoly/Lvalue.cc@ 5af7306

new-env with_gc
Last change on this file since 5af7306 was 68f9c43, checked in by Aaron Moss <a3moss@…>, 8 years ago

First pass at delete removal

  • Property mode set to 100644
File size: 19.4 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// Lvalue.cc --
8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Mar 17 09:11:18 2017
13// Update Count : 5
14//
15
16#include <cassert> // for strict_dynamic_cast
17#include <string> // for string
18
19#include "Common/PassVisitor.h"
20#include "GenPoly.h" // for isPolyType
21#include "Lvalue.h"
22
23#include "Parser/LinkageSpec.h" // for Spec, isBuiltin, Intrinsic
24#include "ResolvExpr/TypeEnvironment.h" // for AssertionSet, OpenVarSet
25#include "ResolvExpr/Unify.h" // for unify
26#include "ResolvExpr/typeops.h"
27#include "SymTab/Autogen.h"
28#include "SymTab/Indexer.h" // for Indexer
29#include "SynTree/Declaration.h" // for Declaration, FunctionDecl
30#include "SynTree/Expression.h" // for Expression, ConditionalExpr
31#include "SynTree/Mutator.h" // for mutateAll, Mutator
32#include "SynTree/Statement.h" // for ReturnStmt, Statement (ptr o...
33#include "SynTree/Type.h" // for PointerType, Type, FunctionType
34#include "SynTree/Visitor.h" // for Visitor, acceptAll
35
36#if 0
37#define PRINT(x) x
38#else
39#define PRINT(x)
40#endif
41
42namespace GenPoly {
43 namespace {
44 // TODO: fold this into the general createDeref function??
45 Expression * mkDeref( Expression * arg ) {
46 if ( SymTab::dereferenceOperator ) {
47 VariableExpr * deref = new VariableExpr( SymTab::dereferenceOperator );
48 deref->result = new PointerType( Type::Qualifiers(), deref->result );
49 Type * base = InitTweak::getPointerBase( arg->result );
50 assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->result ).c_str() );
51 ApplicationExpr * ret = new ApplicationExpr( deref, { arg } );
52 ret->result = base->clone();
53 ret->result->set_lvalue( true );
54 return ret;
55 } else {
56 return UntypedExpr::createDeref( arg );
57 }
58 }
59
60 struct ReferenceConversions final {
61 Expression * postmutate( CastExpr * castExpr );
62 Expression * postmutate( AddressExpr * addrExpr );
63 };
64
65 /// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
66 struct FixIntrinsicArgs final {
67 Expression * postmutate( ApplicationExpr * appExpr );
68 };
69
70 struct FixIntrinsicResult final : public WithGuards {
71 Expression * postmutate( ApplicationExpr * appExpr );
72 void premutate( FunctionDecl * funcDecl );
73 bool inIntrinsic = false;
74 };
75
76 /// Replace reference types with pointer types
77 struct ReferenceTypeElimination final {
78 Type * postmutate( ReferenceType * refType );
79 };
80
81 /// GCC-like Generalized Lvalues (which have since been removed from GCC)
82 /// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
83 /// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
84 struct GeneralizedLvalue final : public WithVisitorRef<GeneralizedLvalue> {
85 Expression * postmutate( AddressExpr * addressExpr );
86 Expression * postmutate( MemberExpr * memExpr );
87
88 template<typename Func>
89 Expression * applyTransformation( Expression * expr, Expression * arg, Func mkExpr );
90 };
91
92 /// Removes redundant &*/*& pattern that this pass can generate
93 struct CollapseAddrDeref final {
94 Expression * postmutate( AddressExpr * addressExpr );
95 Expression * postmutate( ApplicationExpr * appExpr );
96 };
97
98 struct AddrRef final : public WithGuards {
99 void premutate( AddressExpr * addrExpr );
100 Expression * postmutate( AddressExpr * addrExpr );
101 void premutate( Expression * expr );
102
103 bool first = true;
104 bool current = false;
105 int refDepth = 0;
106 };
107 } // namespace
108
109 static bool referencesEliminated = false;
110 // used by UntypedExpr::createDeref to determine whether result type of dereference should be ReferenceType or value type.
111 bool referencesPermissable() {
112 return ! referencesEliminated;
113 }
114
115 void convertLvalue( std::list< Declaration* >& translationUnit ) {
116 PassVisitor<ReferenceConversions> refCvt;
117 PassVisitor<ReferenceTypeElimination> elim;
118 PassVisitor<GeneralizedLvalue> genLval;
119 PassVisitor<FixIntrinsicArgs> fixer;
120 PassVisitor<CollapseAddrDeref> collapser;
121 PassVisitor<AddrRef> addrRef;
122 PassVisitor<FixIntrinsicResult> intrinsicResults;
123 mutateAll( translationUnit, intrinsicResults );
124 mutateAll( translationUnit, addrRef );
125 mutateAll( translationUnit, refCvt );
126 mutateAll( translationUnit, fixer );
127 mutateAll( translationUnit, collapser );
128 mutateAll( translationUnit, genLval );
129 mutateAll( translationUnit, elim ); // last because other passes need reference types to work
130
131 // from this point forward, no other pass should create reference types.
132 referencesEliminated = true;
133 }
134
135 Expression * generalizedLvalue( Expression * expr ) {
136 PassVisitor<GeneralizedLvalue> genLval;
137 return expr->acceptMutator( genLval );
138 }
139
140 namespace {
141 // true for intrinsic function calls that return a reference
142 bool isIntrinsicReference( Expression * expr ) {
143 if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
144 std::string fname = InitTweak::getFunctionName( untyped );
145 // known intrinsic-reference prelude functions
146 return fname == "*?" || fname == "?[?]";
147 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
148 if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
149 // use type of return variable rather than expr result type, since it may have been changed to a pointer type
150 FunctionType * ftype = GenPoly::getFunctionType( func->get_type() );
151 Type * ret = ftype->get_returnVals().empty() ? nullptr : ftype->get_returnVals().front()->get_type();
152 return func->get_linkage() == LinkageSpec::Intrinsic && dynamic_cast<ReferenceType *>( ret );
153 }
154 }
155 return false;
156 }
157
158 Expression * FixIntrinsicResult::postmutate( ApplicationExpr * appExpr ) {
159 if ( isIntrinsicReference( appExpr ) ) {
160 // eliminate reference types from intrinsic applications - now they return lvalues
161 Type * result = appExpr->get_result();
162 appExpr->set_result( result->stripReferences()->clone() );
163 appExpr->get_result()->set_lvalue( true );
164 if ( ! inIntrinsic ) {
165 // when not in an intrinsic function, add a cast to
166 // don't add cast when in an intrinsic function, since they already have the cast
167 Expression * ret = new CastExpr( appExpr, result );
168 ret->set_env( appExpr->get_env() );
169 appExpr->set_env( nullptr );
170 return ret;
171 }
172 }
173 return appExpr;
174 }
175
176 void FixIntrinsicResult::premutate( FunctionDecl * funcDecl ) {
177 GuardValue( inIntrinsic );
178 inIntrinsic = funcDecl->linkage == LinkageSpec::Intrinsic;
179 }
180
181 Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
182 // intrinsic functions don't really take reference-typed parameters, so they require an implicit dereference on their arguments.
183 if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
184 FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
185 assertf( ftype, "Function declaration does not have function type." );
186 // can be of differing lengths only when function is variadic
187 assertf( ftype->get_parameters().size() == appExpr->get_args().size() || ftype->get_isVarArgs(), "ApplicationExpr args do not match formal parameter type." );
188
189
190 unsigned int i = 0;
191 const unsigned int end = ftype->get_parameters().size();
192 for ( auto p : unsafe_group_iterate( appExpr->get_args(), ftype->get_parameters() ) ) {
193 if (i == end) break;
194 Expression *& arg = std::get<0>( p );
195 Type * formal = std::get<1>( p )->get_type();
196 PRINT(
197 std::cerr << "pair<0>: " << arg << std::endl;
198 std::cerr << "pair<1>: " << formal << std::endl;
199 )
200 if ( dynamic_cast<ReferenceType*>( formal ) ) {
201 if ( isIntrinsicReference( arg ) ) { // do not combine conditions, because that changes the meaning of the else if
202 if ( function->get_linkage() != LinkageSpec::Intrinsic ) { // intrinsic functions that turn pointers into references
203 // if argument is dereference or array subscript, the result isn't REALLY a reference, so it's not necessary to fix the argument
204 PRINT(
205 std::cerr << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
206 )
207 arg = new AddressExpr( arg );
208 }
209 } else if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
210 // std::cerr << "===adding deref to arg" << std::endl;
211 // if the parameter is a reference, add a dereference to the reference-typed argument.
212 Type * baseType = InitTweak::getPointerBase( arg->get_result() );
213 assertf( baseType, "parameter is reference, arg must be pointer or reference: %s", toString( arg->get_result() ).c_str() );
214 arg->set_result( new PointerType{ Type::Qualifiers(), baseType->clone() } );
215 arg = mkDeref( arg );
216 }
217 }
218 ++i;
219 }
220 }
221 return appExpr;
222 }
223
224 // idea: &&&E: get outer &, inner &
225 // at inner &, record depth D of reference type
226 // at outer &, add D derefs.
227 void AddrRef::premutate( Expression * ) {
228 GuardValue( current );
229 GuardValue( first );
230 current = false;
231 first = true;
232 }
233
234 void AddrRef::premutate( AddressExpr * ) {
235 GuardValue( current );
236 GuardValue( first );
237 current = first;
238 first = false;
239 if ( current ) {
240 GuardValue( refDepth );
241 refDepth = 0;
242 }
243 }
244
245 Expression * AddrRef::postmutate( AddressExpr * addrExpr ) {
246 if ( refDepth == 0 ) {
247 if ( ! isIntrinsicReference( addrExpr->get_arg() ) ) {
248 // try to avoid ?[?]
249 refDepth = addrExpr->get_arg()->get_result()->referenceDepth();
250 }
251 }
252 if ( current ) {
253 Expression * ret = addrExpr;
254 while ( refDepth ) {
255 ret = mkDeref( ret );
256 refDepth--;
257 }
258 return ret;
259 }
260 return addrExpr;
261 }
262
263 Expression * ReferenceConversions::postmutate( AddressExpr * addrExpr ) {
264 // Inner expression may have been lvalue to reference conversion, which becomes an address expression.
265 // In this case, remove the outer address expression and return the argument.
266 // TODO: It's possible that this might catch too much and require a more sophisticated check.
267 return addrExpr;
268 }
269
270 Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
271 // xxx - is it possible to convert directly between reference types with a different base? E.g.,
272 // int x;
273 // (double&)x;
274 // At the moment, I am working off of the assumption that this is illegal, thus the cast becomes redundant
275 // after this pass, so trash the cast altogether. If that changes, care must be taken to insert the correct
276 // pointer casts in the right places.
277
278 // conversion to reference type
279 if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_result() ) ) {
280 (void)refType;
281 if ( ReferenceType * otherRef = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
282 // nothing to do if casting from reference to reference.
283 (void)otherRef;
284 PRINT( std::cerr << "convert reference to reference -- nop" << std::endl; )
285 if ( isIntrinsicReference( castExpr->get_arg() ) ) {
286 Expression * callExpr = castExpr->get_arg();
287 PRINT(
288 std::cerr << "but arg is deref -- &" << std::endl;
289 std::cerr << callExpr << std::endl;
290 )
291 callExpr = new AddressExpr( callExpr ); // this doesn't work properly for multiple casts
292 callExpr->set_result( refType->clone() );
293 // move environment out to new top-level
294 callExpr->set_env( castExpr->get_env() );
295 castExpr->set_arg( nullptr );
296 castExpr->set_env( nullptr );
297 return callExpr;
298 }
299 int depth1 = refType->referenceDepth();
300 int depth2 = otherRef->referenceDepth();
301 int diff = depth1-depth2;
302 if ( diff == 0 ) {
303 // conversion between references of the same depth
304 assertf( depth1 == depth2, "non-intrinsic reference with cast of reference to reference not yet supported: %d %d %s", depth1, depth2, toString( castExpr ).c_str() );
305 PRINT( std::cerr << castExpr << std::endl; )
306 return castExpr;
307 } else if ( diff < 0 ) {
308 // conversion from reference to reference with less depth (e.g. int && -> int &): add dereferences
309 Expression * ret = castExpr->arg;
310 for ( int i = 0; i < diff; ++i ) {
311 ret = mkDeref( ret );
312 }
313 ret->env = castExpr->env;
314 ret->result = castExpr->result;
315 ret->result->set_lvalue( true ); // ensure result is lvalue
316 castExpr->env = nullptr;
317 castExpr->arg = nullptr;
318 castExpr->result = nullptr;
319 return ret;
320 } else if ( diff > 0 ) {
321 // conversion from reference to reference with more depth (e.g. int & -> int &&): add address-of
322 Expression * ret = castExpr->arg;
323 for ( int i = 0; i < diff; ++i ) {
324 ret = new AddressExpr( ret );
325 }
326 ret->env = castExpr->env;
327 ret->result = castExpr->result;
328 castExpr->env = nullptr;
329 castExpr->arg = nullptr;
330 castExpr->result = nullptr;
331 return ret;
332 }
333
334 assertf( depth1 == depth2, "non-intrinsic reference with cast of reference to reference not yet supported: %d %d %s", depth1, depth2, toString( castExpr ).c_str() );
335 PRINT( std::cerr << castExpr << std::endl; )
336 return castExpr;
337 } else if ( castExpr->arg->result->get_lvalue() ) {
338 // conversion from lvalue to reference
339 // xxx - keep cast, but turn into pointer cast??
340 // xxx - memory
341 PRINT(
342 std::cerr << "convert lvalue to reference -- &" << std::endl;
343 std::cerr << castExpr->arg << std::endl;
344 )
345 AddressExpr * ret = new AddressExpr( castExpr->arg );
346 if ( refType->base->get_qualifiers() != castExpr->arg->result->get_qualifiers() ) {
347 // must keep cast if cast-to type is different from the actual type
348 castExpr->arg = ret;
349 return castExpr;
350 }
351 ret->env = castExpr->env;
352 ret->result = castExpr->result;
353 castExpr->env = nullptr;
354 castExpr->arg = nullptr;
355 castExpr->result = nullptr;
356 return ret;
357 } else {
358 // rvalue to reference conversion -- introduce temporary
359 }
360 assertf( false, "Only conversions to reference from lvalue are currently supported: %s", toString( castExpr ).c_str() );
361 } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->arg->result ) ) {
362 (void)refType;
363 // conversion from reference to rvalue
364 PRINT(
365 std::cerr << "convert reference to rvalue -- *" << std::endl;
366 std::cerr << "was = " << castExpr << std::endl;
367 )
368 Expression * ret = castExpr->arg;
369 TypeSubstitution * env = castExpr->env;
370 castExpr->set_env( nullptr );
371 if ( ! isIntrinsicReference( ret ) ) {
372 // dereference if not already dereferenced
373 ret = mkDeref( ret );
374 }
375 if ( ResolvExpr::typesCompatibleIgnoreQualifiers( castExpr->result, castExpr->arg->result->stripReferences(), SymTab::Indexer() ) ) {
376 // can remove cast if types are compatible, changing expression type to value type
377 ret->result = castExpr->result->clone();
378 ret->result->set_lvalue( true ); // ensure result is lvalue
379 castExpr->arg = nullptr;
380 } else {
381 // must keep cast if types are different
382 castExpr->arg = ret;
383 ret = castExpr;
384 }
385 ret->set_env( env );
386 PRINT( std::cerr << "now: " << ret << std::endl; )
387 return ret;
388 }
389 return castExpr;
390 }
391
392 Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
393 Type * base = refType->get_base();
394 Type::Qualifiers qualifiers = refType->get_qualifiers();
395 refType->set_base( nullptr );
396 return new PointerType( qualifiers, base );
397 }
398
399 template<typename Func>
400 Expression * GeneralizedLvalue::applyTransformation( Expression * expr, Expression * arg, Func mkExpr ) {
401 if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( arg ) ) {
402 Expression * arg1 = commaExpr->get_arg1()->clone();
403 Expression * arg2 = commaExpr->get_arg2()->clone();
404 Expression * ret = new CommaExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ) );
405 ret->set_env( expr->get_env() );
406 expr->set_env( nullptr );
407 return ret;
408 } else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( arg ) ) {
409 Expression * arg1 = condExpr->get_arg1()->clone();
410 Expression * arg2 = condExpr->get_arg2()->clone();
411 Expression * arg3 = condExpr->get_arg3()->clone();
412 ConditionalExpr * ret = new ConditionalExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ), mkExpr( arg3 )->acceptMutator( *visitor ) );
413 ret->set_env( expr->get_env() );
414 expr->set_env( nullptr );
415
416 // conditional expr type may not be either of the argument types, need to unify
417 using namespace ResolvExpr;
418 Type* commonType = nullptr;
419 TypeEnvironment newEnv;
420 AssertionSet needAssertions, haveAssertions;
421 OpenVarSet openVars;
422 unify( ret->get_arg2()->get_result(), ret->get_arg3()->get_result(), newEnv, needAssertions, haveAssertions, openVars, SymTab::Indexer(), commonType );
423 ret->set_result( commonType ? commonType : ret->get_arg2()->get_result()->clone() );
424 return ret;
425 }
426 return expr;
427 }
428
429 Expression * GeneralizedLvalue::postmutate( MemberExpr * memExpr ) {
430 return applyTransformation( memExpr, memExpr->get_aggregate(), [=]( Expression * aggr ) { return new MemberExpr( memExpr->get_member(), aggr ); } );
431 }
432
433 Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
434 return applyTransformation( addrExpr, addrExpr->get_arg(), []( Expression * arg ) { return new AddressExpr( arg ); } );
435 }
436
437 Expression * CollapseAddrDeref::postmutate( AddressExpr * addrExpr ) {
438 Expression * arg = addrExpr->get_arg();
439 if ( isIntrinsicReference( arg ) ) {
440 std::string fname = InitTweak::getFunctionName( arg );
441 if ( fname == "*?" ) {
442 Expression *& arg0 = InitTweak::getCallArg( arg, 0 );
443 Expression * ret = arg0;
444 ret->set_env( addrExpr->get_env() );
445 arg0 = nullptr;
446 addrExpr->set_env( nullptr );
447 return ret;
448 }
449 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * > ( arg ) ) {
450 // need to move cast to pointer type out a level since address of pointer
451 // is not valid C code (can be introduced in prior passes, e.g., InstantiateGeneric)
452 if ( InitTweak::getPointerBase( castExpr->result ) ) {
453 addrExpr->arg = castExpr->arg;
454 castExpr->arg = addrExpr;
455 castExpr->result = new PointerType( Type::Qualifiers(), castExpr->result );
456 return castExpr;
457 }
458 }
459 return addrExpr;
460 }
461
462 Expression * CollapseAddrDeref::postmutate( ApplicationExpr * appExpr ) {
463 if ( isIntrinsicReference( appExpr ) ) {
464 std::string fname = InitTweak::getFunctionName( appExpr );
465 if ( fname == "*?" ) {
466 Expression * arg = InitTweak::getCallArg( appExpr, 0 );
467 // xxx - this isn't right, because it can remove casts that should be there...
468 // while ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
469 // arg = castExpr->get_arg();
470 // }
471 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( arg ) ) {
472 Expression * ret = addrExpr->get_arg();
473 ret->set_env( appExpr->get_env() );
474 addrExpr->set_arg( nullptr );
475 appExpr->set_env( nullptr );
476 return ret;
477 }
478 }
479 }
480 return appExpr;
481 }
482 } // namespace
483} // namespace GenPoly
484
485// Local Variables: //
486// tab-width: 4 //
487// mode: c++ //
488// compile-command: "make install" //
489// End: //
Note: See TracBrowser for help on using the repository browser.