source: src/GenPoly/Lvalue.cc@ 27aca84

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 with_gc
Last change on this file since 27aca84 was a3323db1, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

add a cast to every address-of function argument and initializer [fixes #84]

  • Property mode set to 100644
File size: 21.3 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 // note: reference depth can be arbitrarily deep here, so peel off the outermost pointer/reference, not just pointer because they are effecitvely equivalent in this pass
48 VariableExpr * deref = new VariableExpr( SymTab::dereferenceOperator );
49 deref->result = new PointerType( Type::Qualifiers(), deref->result );
50 Type * base = InitTweak::getPointerBase( arg->result );
51 assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->result ).c_str() );
52 ApplicationExpr * ret = new ApplicationExpr( deref, { arg } );
53 delete ret->result;
54 ret->result = base->clone();
55 ret->result->set_lvalue( true );
56 return ret;
57 } else {
58 return UntypedExpr::createDeref( arg );
59 }
60 }
61
62 struct ReferenceConversions final : public WithStmtsToAdd {
63 Expression * postmutate( CastExpr * castExpr );
64 Expression * postmutate( AddressExpr * addrExpr );
65 };
66
67 /// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
68 struct FixIntrinsicArgs final {
69 Expression * postmutate( ApplicationExpr * appExpr );
70 };
71
72 struct FixIntrinsicResult final : public WithGuards {
73 Expression * postmutate( ApplicationExpr * appExpr );
74 void premutate( FunctionDecl * funcDecl );
75 bool inIntrinsic = false;
76 };
77
78 /// Replace reference types with pointer types
79 struct ReferenceTypeElimination final {
80 Type * postmutate( ReferenceType * refType );
81 };
82
83 /// GCC-like Generalized Lvalues (which have since been removed from GCC)
84 /// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
85 /// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
86 struct GeneralizedLvalue final : public WithVisitorRef<GeneralizedLvalue> {
87 Expression * postmutate( AddressExpr * addressExpr );
88 Expression * postmutate( MemberExpr * memExpr );
89
90 template<typename Func>
91 Expression * applyTransformation( Expression * expr, Expression * arg, Func mkExpr );
92 };
93
94 /// Removes redundant &*/*& pattern that this pass can generate
95 struct CollapseAddrDeref final {
96 Expression * postmutate( AddressExpr * addressExpr );
97 Expression * postmutate( ApplicationExpr * appExpr );
98 };
99
100 struct AddrRef final : public WithGuards, public WithVisitorRef<AddrRef>, public WithShortCircuiting {
101 void premutate( AddressExpr * addrExpr );
102 Expression * postmutate( AddressExpr * addrExpr );
103 void premutate( Expression * expr );
104 void premutate( ApplicationExpr * appExpr );
105 void premutate( SingleInit * init );
106
107 void handleNonAddr( Expression * );
108
109 bool first = true;
110 bool current = false;
111 int refDepth = 0;
112 bool addCast = false;
113 };
114 } // namespace
115
116 static bool referencesEliminated = false;
117 // used by UntypedExpr::createDeref to determine whether result type of dereference should be ReferenceType or value type.
118 bool referencesPermissable() {
119 return ! referencesEliminated;
120 }
121
122 void convertLvalue( std::list< Declaration* > & translationUnit ) {
123 PassVisitor<ReferenceConversions> refCvt;
124 PassVisitor<ReferenceTypeElimination> elim;
125 PassVisitor<GeneralizedLvalue> genLval;
126 PassVisitor<FixIntrinsicArgs> fixer;
127 PassVisitor<CollapseAddrDeref> collapser;
128 PassVisitor<AddrRef> addrRef;
129 PassVisitor<FixIntrinsicResult> intrinsicResults;
130 mutateAll( translationUnit, intrinsicResults );
131 mutateAll( translationUnit, addrRef );
132 mutateAll( translationUnit, refCvt );
133 mutateAll( translationUnit, fixer );
134 mutateAll( translationUnit, collapser );
135 mutateAll( translationUnit, genLval );
136 mutateAll( translationUnit, elim ); // last because other passes need reference types to work
137
138 // from this point forward, no other pass should create reference types.
139 referencesEliminated = true;
140 }
141
142 Expression * generalizedLvalue( Expression * expr ) {
143 PassVisitor<GeneralizedLvalue> genLval;
144 return expr->acceptMutator( genLval );
145 }
146
147 namespace {
148 // true for intrinsic function calls that return a reference
149 bool isIntrinsicReference( Expression * expr ) {
150 if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
151 std::string fname = InitTweak::getFunctionName( untyped );
152 // known intrinsic-reference prelude functions
153 return fname == "*?" || fname == "?[?]";
154 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
155 if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
156 // use type of return variable rather than expr result type, since it may have been changed to a pointer type
157 FunctionType * ftype = GenPoly::getFunctionType( func->get_type() );
158 Type * ret = ftype->returnVals.empty() ? nullptr : ftype->returnVals.front()->get_type();
159 return func->linkage == LinkageSpec::Intrinsic && dynamic_cast<ReferenceType *>( ret );
160 }
161 }
162 return false;
163 }
164
165 Expression * FixIntrinsicResult::postmutate( ApplicationExpr * appExpr ) {
166 if ( isIntrinsicReference( appExpr ) ) {
167 // eliminate reference types from intrinsic applications - now they return lvalues
168 Type * result = appExpr->result;
169 appExpr->result = result->stripReferences()->clone();
170 appExpr->result->set_lvalue( true );
171 if ( ! inIntrinsic ) {
172 // when not in an intrinsic function, add a cast to
173 // don't add cast when in an intrinsic function, since they already have the cast
174 Expression * ret = new CastExpr( appExpr, result );
175 std::swap( ret->env, appExpr->env );
176 return ret;
177 }
178 delete result;
179 }
180 return appExpr;
181 }
182
183 void FixIntrinsicResult::premutate( FunctionDecl * funcDecl ) {
184 GuardValue( inIntrinsic );
185 inIntrinsic = funcDecl->linkage == LinkageSpec::Intrinsic;
186 }
187
188 Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
189 // intrinsic functions don't really take reference-typed parameters, so they require an implicit dereference on their arguments.
190 if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
191 FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
192 assertf( ftype, "Function declaration does not have function type." );
193 // can be of differing lengths only when function is variadic
194 assertf( ftype->parameters.size() == appExpr->args.size() || ftype->isVarArgs, "ApplicationExpr args do not match formal parameter type." );
195
196
197 unsigned int i = 0;
198 const unsigned int end = ftype->parameters.size();
199 for ( auto p : unsafe_group_iterate( appExpr->args, ftype->parameters ) ) {
200 if (i == end) break;
201 Expression *& arg = std::get<0>( p );
202 Type * formal = std::get<1>( p )->get_type();
203 PRINT(
204 std::cerr << "pair<0>: " << arg << std::endl;
205 std::cerr << " -- " << arg->result << std::endl;
206 std::cerr << "pair<1>: " << formal << std::endl;
207 )
208 if ( dynamic_cast<ReferenceType*>( formal ) ) {
209 PRINT(
210 std::cerr << "===formal is reference" << std::endl;
211 )
212 // TODO: it's likely that the second condition should be ... && ! isIntrinsicReference( arg ), but this requires investigation.
213 if ( function->get_linkage() != LinkageSpec::Intrinsic && isIntrinsicReference( arg ) ) {
214 // if argument is dereference or array subscript, the result isn't REALLY a reference, but non-intrinsic functions expect a reference: take address
215
216 // NOTE: previously, this condition fixed
217 // void f(int *&);
218 // int & x = ...;
219 // f(&x);
220 // But now this is taken care of by a reference cast added by AddrRef. Need to find a new
221 // example or remove this branch.
222
223 PRINT(
224 std::cerr << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
225 )
226 arg = new AddressExpr( arg );
227 } else if ( function->get_linkage() == LinkageSpec::Intrinsic && arg->result->referenceDepth() != 0 ) {
228 // argument is a 'real' reference, but function expects a C lvalue: add a dereference to the reference-typed argument
229 PRINT(
230 std::cerr << "===is non-intrinsic arg in intrinsic call - adding deref to arg" << std::endl;
231 )
232 Type * baseType = InitTweak::getPointerBase( arg->result );
233 assertf( baseType, "parameter is reference, arg must be pointer or reference: %s", toString( arg->result ).c_str() );
234 PointerType * ptrType = new PointerType( Type::Qualifiers(), baseType->clone() );
235 delete arg->result;
236 arg->set_result( ptrType );
237 arg = mkDeref( arg );
238 assertf( arg->result->referenceDepth() == 0, "Reference types should have been eliminated from intrinsic function calls, but weren't: %s", toCString( arg->result ) );
239 }
240 }
241 ++i;
242 }
243 }
244 return appExpr;
245 }
246
247 // idea: &&&E: get outer &, inner &
248 // at inner &, record depth D of reference type of argument of &
249 // at outer &, add D derefs.
250 void AddrRef::handleNonAddr( Expression * ) {
251 // non-address-of: reset status variables:
252 // * current expr is NOT the first address-of expr in an address-of chain
253 // * next seen address-of expr IS the first in the chain.
254 GuardValue( current );
255 GuardValue( first );
256 current = false;
257 first = true;
258 }
259
260 void AddrRef::premutate( Expression * expr ) {
261 handleNonAddr( expr );
262 GuardValue( addCast );
263 addCast = false;
264 }
265
266 void AddrRef::premutate( AddressExpr * ) {
267 GuardValue( current );
268 GuardValue( first );
269 current = first; // is this the first address-of in the chain?
270 first = false; // from here out, no longer possible for next address-of to be first in chain
271 if ( current ) { // this is the outermost address-of in a chain
272 GuardValue( refDepth );
273 refDepth = 0; // set depth to 0 so that postmutate can find the innermost address-of easily
274 }
275 }
276
277 Expression * AddrRef::postmutate( AddressExpr * addrExpr ) {
278 if ( refDepth == 0 ) {
279 // this is the innermost address-of in a chain, record depth D
280 if ( ! isIntrinsicReference( addrExpr->arg ) ) {
281 // try to avoid ?[?]
282 // xxx - is this condition still necessary? intrinsicReferences should have a cast around them at this point, so I don't think this condition ever fires.
283 refDepth = addrExpr->arg->result->referenceDepth();
284 } else {
285 assertf( false, "AddrRef : address-of should not have intrinsic reference argument: %s", toCString( addrExpr->arg ) );
286 }
287 }
288 if ( current ) { // this is the outermost address-of in a chain
289 Expression * ret = addrExpr;
290 while ( refDepth ) {
291 // add one dereference for each
292 ret = mkDeref( ret );
293 refDepth--;
294 }
295
296 if ( addCast ) {
297 return new CastExpr( ret, addrExpr->result->clone() );
298 }
299 return ret;
300 }
301 return addrExpr;
302 }
303
304 void AddrRef::premutate( ApplicationExpr * appExpr ) {
305 visit_children = false;
306 GuardValue( addCast );
307 handleNonAddr( appExpr );
308 for ( Expression *& arg : appExpr->args ) {
309 // each argument with address-of requires a cast
310 addCast = true;
311 arg = arg->acceptMutator( *visitor );
312 }
313 }
314
315 void AddrRef::premutate( SingleInit * ) {
316 GuardValue( addCast );
317 // each initialization context with address-of requires a cast
318 addCast = true;
319 }
320
321
322 Expression * ReferenceConversions::postmutate( AddressExpr * addrExpr ) {
323 // Inner expression may have been lvalue to reference conversion, which becomes an address expression.
324 // In this case, remove the outer address expression and return the argument.
325 // TODO: It's possible that this might catch too much and require a more sophisticated check.
326 return addrExpr;
327 }
328
329 Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
330 // xxx - is it possible to convert directly between reference types with a different base? E.g.,
331 // int x;
332 // (double&)x;
333 // At the moment, I am working off of the assumption that this is illegal, thus the cast becomes redundant
334 // after this pass, so trash the cast altogether. If that changes, care must be taken to insert the correct
335 // pointer casts in the right places.
336
337 // Note: reference depth difference is the determining factor in what code is run, rather than whether something is
338 // reference type or not, since conversion still needs to occur when both types are references that differ in depth.
339
340 Type * destType = castExpr->result;
341 Type * srcType = castExpr->arg->result;
342 int depth1 = destType->referenceDepth();
343 int depth2 = srcType->referenceDepth();
344 int diff = depth1 - depth2;
345
346 if ( diff > 0 && ! srcType->get_lvalue() ) {
347 // rvalue to reference conversion -- introduce temporary
348 // know that reference depth of cast argument is 0, need to introduce n temporaries for reference depth of n, e.g.
349 // (int &&&)3;
350 // becomes
351 // int __ref_tmp_0 = 3;
352 // int & __ref_tmp_1 = _&_ref_tmp_0;
353 // int && __ref_tmp_2 = &__ref_tmp_1;
354 // &__ref_tmp_2;
355 // the last & comes from the remaining reference conversion code
356 SemanticWarning( castExpr->arg->location, Warning::RvalueToReferenceConversion, toCString( castExpr->arg ) );
357
358 static UniqueName tempNamer( "__ref_tmp_" );
359 ObjectDecl * temp = ObjectDecl::newObject( tempNamer.newName(), castExpr->arg->result->clone(), new SingleInit( castExpr->arg ) );
360 PRINT( std::cerr << "made temp: " << temp << std::endl; )
361 stmtsToAddBefore.push_back( new DeclStmt( temp ) );
362 for ( int i = 0; i < depth1-1; i++ ) { // xxx - maybe this should be diff-1? check how this works with reference type for srcType
363 ObjectDecl * newTemp = ObjectDecl::newObject( tempNamer.newName(), new ReferenceType( Type::Qualifiers(), temp->type->clone() ), new SingleInit( new AddressExpr( new VariableExpr( temp ) ) ) );
364 PRINT( std::cerr << "made temp" << i << ": " << newTemp << std::endl; )
365 stmtsToAddBefore.push_back( new DeclStmt( newTemp ) );
366 temp = newTemp;
367 }
368 // update diff so that remaining code works out correctly
369 castExpr->arg = new VariableExpr( temp );
370 PRINT( std::cerr << "update cast to: " << castExpr << std::endl; )
371 srcType = castExpr->arg->result;
372 depth2 = srcType->referenceDepth();
373 diff = depth1 - depth2;
374 assert( diff == 1 );
375 }
376
377 // handle conversion between different depths
378 PRINT (
379 if ( depth1 || depth2 ) {
380 std::cerr << "destType: " << destType << " / srcType: " << srcType << std::endl;
381 std::cerr << "depth: " << depth1 << " / " << depth2 << std::endl;
382 }
383 )
384 if ( diff > 0 ) {
385 // conversion to type with more depth (e.g. int & -> int &&): add address-of for each level of difference
386 Expression * ret = castExpr->arg;
387 for ( int i = 0; i < diff; ++i ) {
388 ret = new AddressExpr( ret );
389 }
390 if ( srcType->get_lvalue() && srcType->get_qualifiers() != strict_dynamic_cast<ReferenceType *>( destType )->base->get_qualifiers() ) {
391 // must keep cast if cast-to type is different from the actual type
392 castExpr->arg = ret;
393 return castExpr;
394 }
395 ret->env = castExpr->env;
396 delete ret->result;
397 ret->result = castExpr->result;
398 castExpr->env = nullptr;
399 castExpr->arg = nullptr;
400 castExpr->result = nullptr;
401 delete castExpr;
402 return ret;
403 } else if ( diff < 0 ) {
404 // conversion to type with less depth (e.g. int && -> int &): add dereferences for each level of difference
405 diff = -diff; // care only about magnitude now
406 Expression * ret = castExpr->arg;
407 for ( int i = 0; i < diff; ++i ) {
408 ret = mkDeref( ret );
409 }
410 if ( ! ResolvExpr::typesCompatibleIgnoreQualifiers( destType->stripReferences(), srcType->stripReferences(), SymTab::Indexer() ) ) {
411 // must keep cast if types are different
412 castExpr->arg = ret;
413 return castExpr;
414 }
415 ret->env = castExpr->env;
416 delete ret->result;
417 ret->result = castExpr->result;
418 ret->result->set_lvalue( true ); // ensure result is lvalue
419 castExpr->env = nullptr;
420 castExpr->arg = nullptr;
421 castExpr->result = nullptr;
422 delete castExpr;
423 return ret;
424 } else {
425 assert( diff == 0 );
426 // conversion between references of the same depth
427 return castExpr;
428 }
429 }
430
431 Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
432 Type * base = refType->base;
433 Type::Qualifiers qualifiers = refType->get_qualifiers();
434 refType->base = nullptr;
435 delete refType;
436 return new PointerType( qualifiers, base );
437 }
438
439 template<typename Func>
440 Expression * GeneralizedLvalue::applyTransformation( Expression * expr, Expression * arg, Func mkExpr ) {
441 if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( arg ) ) {
442 Expression * arg1 = commaExpr->arg1->clone();
443 Expression * arg2 = commaExpr->arg2->clone();
444 Expression * ret = new CommaExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ) );
445 ret->env = expr->env;
446 expr->env = nullptr;
447 delete expr;
448 return ret;
449 } else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( arg ) ) {
450 Expression * arg1 = condExpr->arg1->clone();
451 Expression * arg2 = condExpr->arg2->clone();
452 Expression * arg3 = condExpr->arg3->clone();
453 ConditionalExpr * ret = new ConditionalExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ), mkExpr( arg3 )->acceptMutator( *visitor ) );
454 ret->env = expr->env;
455 expr->env = nullptr;
456 delete expr;
457
458 // conditional expr type may not be either of the argument types, need to unify
459 using namespace ResolvExpr;
460 Type* commonType = nullptr;
461 TypeEnvironment newEnv;
462 AssertionSet needAssertions, haveAssertions;
463 OpenVarSet openVars;
464 unify( ret->arg2->result, ret->arg3->result, newEnv, needAssertions, haveAssertions, openVars, SymTab::Indexer(), commonType );
465 ret->result = commonType ? commonType : ret->arg2->result->clone();
466 return ret;
467 }
468 return expr;
469 }
470
471 Expression * GeneralizedLvalue::postmutate( MemberExpr * memExpr ) {
472 return applyTransformation( memExpr, memExpr->aggregate, [=]( Expression * aggr ) { return new MemberExpr( memExpr->member, aggr ); } );
473 }
474
475 Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
476 return applyTransformation( addrExpr, addrExpr->arg, []( Expression * arg ) { return new AddressExpr( arg ); } );
477 }
478
479 Expression * CollapseAddrDeref::postmutate( AddressExpr * addrExpr ) {
480 Expression * arg = addrExpr->arg;
481 if ( isIntrinsicReference( arg ) ) {
482 std::string fname = InitTweak::getFunctionName( arg );
483 if ( fname == "*?" ) {
484 Expression *& arg0 = InitTweak::getCallArg( arg, 0 );
485 Expression * ret = arg0;
486 ret->set_env( addrExpr->env );
487 arg0 = nullptr;
488 addrExpr->env = nullptr;
489 delete addrExpr;
490 return ret;
491 }
492 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * > ( arg ) ) {
493 // need to move cast to pointer type out a level since address of pointer
494 // is not valid C code (can be introduced in prior passes, e.g., InstantiateGeneric)
495 if ( InitTweak::getPointerBase( castExpr->result ) ) {
496 addrExpr->arg = castExpr->arg;
497 castExpr->arg = addrExpr;
498 castExpr->result = new PointerType( Type::Qualifiers(), castExpr->result );
499 return castExpr;
500 }
501 }
502 return addrExpr;
503 }
504
505 Expression * CollapseAddrDeref::postmutate( ApplicationExpr * appExpr ) {
506 if ( isIntrinsicReference( appExpr ) ) {
507 std::string fname = InitTweak::getFunctionName( appExpr );
508 if ( fname == "*?" ) {
509 Expression * arg = InitTweak::getCallArg( appExpr, 0 );
510 // xxx - this isn't right, because it can remove casts that should be there...
511 // while ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
512 // arg = castExpr->get_arg();
513 // }
514 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( arg ) ) {
515 Expression * ret = addrExpr->arg;
516 ret->env = appExpr->env;
517 addrExpr->arg = nullptr;
518 appExpr->env = nullptr;
519 delete appExpr;
520 return ret;
521 }
522 }
523 }
524 return appExpr;
525 }
526 } // namespace
527} // namespace GenPoly
528
529// Local Variables: //
530// tab-width: 4 //
531// mode: c++ //
532// compile-command: "make install" //
533// End: //
Note: See TracBrowser for help on using the repository browser.