source: src/GenPoly/Lvalue.cpp@ 1b39705

Last change on this file since 1b39705 was 00f89a6, checked in by Fangren Yu <f37yu@…>, 11 months ago

attempt to fix const reference conversion

  • Property mode set to 100644
File size: 23.8 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.cpp -- Clean up lvalues and remove references.
8//
9// Author : Andrew Beach
10// Created On : Thu Sep 15 14:08:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Aug 12 18:07:00 2024
13// Update Count : 1
14//
15
16#include "Lvalue.hpp"
17
18#include <set>
19#include <iostream>
20
21#include "AST/Copy.hpp" // for deepCopy
22#include "AST/Expr.hpp"
23#include "AST/Inspect.hpp"
24#include "AST/LinkageSpec.hpp" // for Linkage
25#include "AST/Pass.hpp"
26#include "Common/SemanticError.hpp" // for SemanticWarning
27#include "Common/ToString.hpp" // for toCString
28#include "Common/UniqueName.hpp" // for UniqueName
29#include "GenPoly/GenPoly.hpp" // for genFunctionType
30#include "ResolvExpr/Typeops.hpp" // for typesCompatible
31#include "ResolvExpr/Unify.hpp" // for unify
32
33#if 0
34#define PRINT(x) x
35#else
36#define PRINT(x)
37#endif
38
39namespace GenPoly {
40
41namespace {
42
43/// Intrinsic functions that return references now instead return lvalues.
44struct FixIntrinsicResults final : public ast::WithGuards {
45 enum {
46 NoSkip,
47 Skip,
48 SkipInProgress,
49 } skip = NoSkip;
50
51 void previsit( ast::AsmExpr const * ) {
52 GuardValue( skip ) = Skip;
53 }
54 void previsit( ast::ApplicationExpr const * ) {
55 GuardValue( skip ) = (skip == Skip) ? SkipInProgress : NoSkip;
56 }
57
58 ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
59 void previsit( ast::FunctionDecl const * decl );
60 bool inIntrinsic = false;
61};
62
63/// Add de-references around address-of operations on reference types.
64struct AddressRef final :
65 public ast::WithConstTranslationUnit,
66 public ast::WithGuards,
67 public ast::WithShortCircuiting,
68 public ast::WithVisitorRef<AddressRef> {
69 void previsit( ast::AddressExpr const * expr );
70 ast::Expr const * postvisit( ast::AddressExpr const * expr );
71 void previsit( ast::Expr const * expr );
72 ast::ApplicationExpr const * previsit( ast::ApplicationExpr const * expr );
73 void previsit( ast::SingleInit const * init );
74
75 void handleNonAddr( ast::Expr const * expr );
76
77 bool first = true;
78 bool current = false;
79 bool addCast = false;
80 int refDepth = 0;
81};
82
83/// Handles casts between references and pointers,
84/// creating temporaries for the conversion.
85struct ReferenceConversions final :
86 public ast::WithConstTranslationUnit,
87 public ast::WithGuards, public ast::WithStmtsToAdd<> {
88 ast::Expr const * postvisit( ast::CastExpr const * expr );
89 ast::Expr const * postvisit( ast::AddressExpr const * expr );
90};
91
92/// Intrinsic functions that take reference parameters don't actually do.
93/// Their reference arguments must be implicity dereferenced.
94/// TODO Also appears to contain redundent code with AddressRef
95struct FixIntrinsicArgs final :
96 public ast::WithConstTranslationUnit {
97 ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
98};
99
100/// Removes redundant &* / *& patterns that may be generated.
101struct CollapseAddressDeref final {
102 ast::Expr const * postvisit( ast::AddressExpr const * expr );
103 ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
104};
105
106/// GCC-like Generalized Lvalues (which have since been removed from GCC).
107/// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
108/// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
109struct GeneralizedLvalue final :
110 public ast::WithVisitorRef<GeneralizedLvalue> {
111 ast::Expr const * postvisit( ast::AddressExpr const * expr );
112 ast::Expr const * postvisit( ast::MemberExpr const * expr );
113
114 template<typename Node, typename Func>
115 ast::Expr const * applyTransformation(
116 Node const * expr, ast::ptr<ast::Expr> Node::*field, Func mkExpr );
117};
118
119/// Replace all reference types with pointer types.
120struct ReferenceTypeElimination final {
121 ast::SizeofExpr const * previsit( ast::SizeofExpr const * expr );
122 ast::AlignofExpr const * previsit( ast::AlignofExpr const * expr );
123 ast::Type const * postvisit( ast::ReferenceType const * type );
124};
125
126/// True for intrinsic function calls that return an lvalue in C.
127bool isIntrinsicReference( ast::Expr const * expr ) {
128 // The known intrinsic-reference prelude functions.
129 static std::set<std::string> const lvalueFunctions = { "*?", "?[?]" };
130 if ( auto untyped = dynamic_cast<ast::UntypedExpr const *>( expr ) ) {
131 std::string fname = ast::getFunctionName( untyped );
132 return lvalueFunctions.count( fname );
133 } else if ( auto app = dynamic_cast<ast::ApplicationExpr const *>( expr ) ) {
134 if ( auto func = ast::getFunction( app ) ) {
135 return func->linkage == ast::Linkage::Intrinsic
136 && lvalueFunctions.count( func->name );
137 }
138 }
139 return false;
140}
141
142// A maybe typed variant of the createDeref function (only UntypedExpr).
143ast::Expr * mkDeref(
144 ast::TranslationGlobal const & global, ast::Expr const * arg ) {
145 if ( global.dereference ) {
146 // Note: Reference depth can be arbitrarily deep here,
147 // so peel off the outermost pointer/reference, not just
148 // pointer because they are effecitvely equivalent in this pass
149 ast::VariableExpr * deref = new ast::VariableExpr(
150 arg->location, global.dereference );
151 deref->result = new ast::PointerType( deref->result );
152 ast::Type const * base = ast::getPointerBase( arg->result );
153 assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->result ).c_str() );
154 ast::ApplicationExpr * ret =
155 new ast::ApplicationExpr( arg->location, deref, { arg } );
156 ret->result = ast::deepCopy( base );
157 return ret;
158 } else {
159 return ast::UntypedExpr::createDeref( arg->location, arg );
160 }
161}
162
163ast::Expr const * FixIntrinsicResults::postvisit(
164 ast::ApplicationExpr const * expr ) {
165
166 if ( skip == SkipInProgress || !isIntrinsicReference( expr ) ) {
167 return expr;
168 }
169 // Eliminate reference types from intrinsic applications
170 // now they return lvalues.
171 ast::ptr<ast::ReferenceType> result =
172 expr->result.strict_as<ast::ReferenceType>();
173 expr = ast::mutate_field( expr, &ast::ApplicationExpr::result,
174 ast::deepCopy( result->base ) );
175 if ( inIntrinsic ) {
176 return expr;
177 }
178 // When not in an intrinsic function, add a cast to don't add cast when
179 // in an intrinsic function, since they already have the cast.
180 auto * ret = new ast::CastExpr( expr->location, expr, result.get() );
181 ret->env = expr->env;
182 return ret;
183}
184
185void FixIntrinsicResults::previsit( ast::FunctionDecl const * decl ) {
186 GuardValue( inIntrinsic ) = decl->linkage == ast::Linkage::Intrinsic;
187}
188
189void AddressRef::previsit( ast::AddressExpr const * ) {
190 // Is this the first address-of in the chain?
191 GuardValue( current ) = first;
192 // Later references will not be for next address-of to be first in chain.
193 GuardValue( first ) = false;
194 // If is the outermost address-of in a chain:
195 if ( current ) {
196 // Set depth to 0 so that postvisit can
197 // find the innermost address-of easily.
198 GuardValue( refDepth ) = 0;
199 }
200}
201
202ast::Expr const * AddressRef::postvisit( ast::AddressExpr const * expr ) {
203 PRINT( std::cerr << "addr ref at " << expr << std::endl; )
204 if ( 0 == refDepth ) {
205 PRINT( std::cerr << "depth 0, get new depth..." << std::endl; )
206 // Is this the innermost address-of in a chain? record depth D.
207 if ( isIntrinsicReference( expr->arg ) ) {
208 assertf( false, "AddrRef : address-of should not have intrinsic reference argument: %s", toCString( expr->arg ) );
209 } else {
210 // try to avoid ?[?]
211 // TODO is this condition still necessary? intrinsicReferences
212 // should have a cast around them at this point, so I don't think
213 // this condition ever fires.
214 refDepth = expr->arg->result->referenceDepth();
215 PRINT( std::cerr << "arg not intrinsic reference, new depth is: " << refDepth << std::endl; )
216 }
217 }
218 if ( current ) {
219 PRINT( std::cerr << "current, depth is: " << refDepth << std::endl; )
220 ast::Expr const * ret = expr;
221 while ( refDepth ) {
222 // Add one dereference for each address-of in the chain.
223 ret = mkDeref( transUnit().global, ret );
224 --refDepth;
225 }
226
227 // if addrExpr depth is 0, then the result is a pointer because the
228 // arg was depth 1 and not lvalue. This means the dereference result
229 // is not a reference, is lvalue, and one less pointer depth than the
230 // addrExpr. Thus the cast is meaningless.
231 // TODO: One thing to double check is whether it is possible for the
232 // types to differ outside of the single pointer level (i.e. can the
233 // base type of addrExpr differ from the type of addrExpr-arg?). If
234 // so then the cast might need to be added, conditional on a more
235 // sophisticated check.
236 if ( addCast && 0 != expr->result->referenceDepth() ) {
237 PRINT( std::cerr << "adding cast to " << expr->result << std::endl; )
238 return new ast::CastExpr( expr->location,
239 ret, ast::deepCopy( expr->result ) );
240 }
241 return ret;
242 }
243 PRINT( std::cerr << "not current..." << std::endl; )
244 return expr;
245}
246
247void AddressRef::previsit( ast::Expr const * expr ) {
248 handleNonAddr( expr );
249 GuardValue( addCast ) = false;
250}
251
252// So we want to skip traversing to the head?
253ast::ApplicationExpr const * AddressRef::previsit(
254 ast::ApplicationExpr const * expr ) {
255 visit_children = false;
256 GuardValue( addCast );
257 handleNonAddr( expr );
258 auto mutExpr = ast::mutate( expr );
259 for ( ast::ptr<ast::Expr> & arg : mutExpr->args ) {
260 addCast = true;
261 arg = arg->accept( *visitor );
262 }
263 return mutExpr;
264}
265
266void AddressRef::previsit( ast::SingleInit const * ) {
267 // Each initialization context with address-of requires a cast.
268 GuardValue( addCast ) = true;
269}
270
271// idea: &&&E: get outer &, inner &
272// at inner &, record depth D of reference type of argument of &.
273// at auter &, add D derefs.
274void AddressRef::handleNonAddr( ast::Expr const * ) {
275 // non-address-of: reset status variables:
276 // * current expr is NOT the first address-of expr in an address-of chain.
277 // * next seen address-of expr IS the first in the chain.
278 GuardValue( current ) = false;
279 GuardValue( first ) = true;
280}
281
282ast::Expr const * ReferenceConversions::postvisit(
283 ast::CastExpr const * expr ) {
284 // TODO: Is it possible to convert directly between reference types with
285 // a different base. e.g.
286 // int x;
287 // (double&)x;
288 // At the moment, I (who?) am working off of the assumption that this is
289 // illegal, thus the cast becomes redundant after this pass, so trash the
290 // cast altogether. If that changes, care must be taken to insert the
291 // correct pointer casts in the right places.
292
293 // Note: reference depth difference is the determining factor in what
294 // code is run, rather than whether something is reference type or not,
295 // since conversion still needs to occur when both types are references
296 // that differ in depth.
297 ast::Type const * dstType = expr->result.get();
298 ast::Type const * srcType = expr->arg->result.get();
299 assertf( dstType, "Cast to no type in: %s", toCString( expr ) );
300 assertf( srcType, "Cast from no type in: %s", toCString( expr ) );
301 int dstDepth = dstType->referenceDepth();
302 int srcDepth = srcType->referenceDepth();
303 int diff = dstDepth - srcDepth;
304
305 if ( 0 < diff && !expr->arg->get_lvalue() ) {
306 // rvalue to reference conversion -- introduce temporary
307 // know that reference depth of cast argument is 0
308 // (int &&&)3;
309 // becomes
310 // int __ref_tmp_0 = 3;
311 // int & __ref_tmp_1 = &__ref_tmp_0;
312 // int && __ref_tmp_2 = &__ref_tmp_1;
313 // &__ref_tmp_2;
314 // The last & comes from the remaining reference conversion code.
315 SemanticWarning( expr->arg->location,
316 Warning::RvalueToReferenceConversion, toCString( expr->arg ) );
317
318
319 // allowing conversion in the rvalue to const ref case
320 // use the referenced-to type to create temp variables
321 ast::Type const * targetType = dstType;
322 for (int i = 0; i < diff; ++i) targetType = (strict_dynamic_cast<ast::ReferenceType const *>(targetType))->base;
323
324 static UniqueName tmpNamer( "__ref_tmp_" );
325 ast::ObjectDecl * tmp = new ast::ObjectDecl( expr->arg->location,
326 tmpNamer.newName(),
327 // ast::deepCopy( expr->arg->result ),
328 ast::deepCopy (targetType),
329 new ast::SingleInit( expr->arg->location, expr->arg ) );
330 PRINT( std::cerr << "make tmp: " << tmp << std::endl; )
331 stmtsToAddBefore.push_back( new ast::DeclStmt( tmp->location, tmp ) );
332 for ( int i = 0 ; i < dstDepth - 1 ; ++i ) {
333 ast::ObjectDecl * newTmp = new ast::ObjectDecl( tmp->location,
334 tmpNamer.newName(),
335 new ast::ReferenceType( ast::deepCopy( tmp->type ) ),
336 new ast::SingleInit( tmp->location,
337 new ast::AddressExpr( tmp->location,
338 new ast::VariableExpr( tmp->location, tmp ) ) ) );
339 PRINT( std::cerr << "make tmp: " << i << ": " << newTmp << std::endl; )
340 stmtsToAddBefore.push_back(
341 new ast::DeclStmt( newTmp->location, newTmp ) );
342 tmp = newTmp;
343 }
344 // Update diff so that remaining code works out correctly.
345 expr = ast::mutate_field( expr, &ast::CastExpr::arg,
346 new ast::VariableExpr( tmp->location, tmp ) );
347 PRINT( std::cerr << "update cast to: " << expr << std::endl; )
348 srcType = expr->arg->result;
349 srcDepth = srcType->referenceDepth();
350 diff = dstDepth - srcDepth;
351 assert( 1 == diff );
352 }
353
354 // Handle conversion between different depths.
355 PRINT(
356 if ( dstDepth || srcDepth ) {
357 std::cerr << "dstType: " << dstType << " / srcType: " << srcType << '\n';
358 std::cerr << "depth: " << dstDepth << " / " << srcDepth << std::endl;
359 }
360 )
361 // Conversion to type with more depth/more references.
362 // Add address-of for each level of difference.
363 if ( 0 < diff ) {
364 ast::Expr * ret = ast::mutate( expr->arg.get() );
365 for ( int i = 0 ; i < diff ; ++i ) {
366 ret = new ast::AddressExpr( ret->location, ret );
367 }
368 if ( expr->arg->get_lvalue() &&
369 !ResolvExpr::typesCompatible(
370 srcType,
371 strict_dynamic_cast<ast::ReferenceType const *>( dstType )->base ) ) {
372 // Must keep cast if cast-to type is different from the actual type.
373 return ast::mutate_field( expr, &ast::CastExpr::arg, ret );
374 }
375 ret->env = expr->env;
376 ret->result = expr->result;
377 return ret;
378 // Conversion to type with less depth/fewer references.
379 // Add dereferences for each level of difference.
380 } else if ( diff < 0 ) {
381 ast::Expr * ret = ast::mutate( expr->arg.get() );
382 for ( int i = 0 ; i < -diff ; ++i ) {
383 ret = mkDeref( transUnit().global, ret );
384 }
385 // Must keep cast if types are different.
386 if ( !ResolvExpr::typesCompatibleIgnoreQualifiers(
387 dstType->stripReferences(),
388 srcType->stripReferences() ) ) {
389 return ast::mutate_field( expr, &ast::CastExpr::arg, ret );
390 }
391 ret->env = expr->env;
392 ret->result = expr->result;
393 // The result must be an lvalue.
394 assert( ret->get_lvalue() );
395 return ret;
396 // Conversion with the same depth.
397 } else {
398 assert( 0 == diff );
399 // Remove useless generated casts.
400 if ( expr->isGenerated == ast::GeneratedFlag::GeneratedCast &&
401 ResolvExpr::typesCompatible(
402 expr->result,
403 expr->arg->result ) ) {
404 PRINT(
405 std::cerr << "types are compatible, removing cast: " << expr << '\n';
406 std::cerr << "-- " << expr->result << '\n';
407 std::cerr << "-- " << expr->arg->result << std::endl;
408 )
409 auto argAsEnum = expr->arg.as<ast::EnumInstType>();
410 auto resultAsEnum = expr->result.as<ast::EnumInstType>();
411 if (argAsEnum && resultAsEnum) {
412 if (argAsEnum->base->name != resultAsEnum->base->name) {
413 return expr;
414 }
415 }
416 return ast::mutate_field( expr->arg.get(),
417 &ast::Expr::env, expr->env.get() );
418 }
419 return expr;
420 }
421}
422
423ast::Expr const * ReferenceConversions::postvisit(
424 ast::AddressExpr const * expr ) {
425 // Inner expression may have been lvalue to reference conversion, which
426 // becomes an address expression. In this case, remove the outer address
427 // expression and return the argument.
428 // TODO: It's possible that this might catch too much and require a more
429 // sophisticated check. TODO What check are we talking about here?
430 return expr;
431}
432
433ast::Expr const * FixIntrinsicArgs::postvisit(
434 ast::ApplicationExpr const * expr ) {
435 // Intrinsic functions don't really take reference-typed parameters,
436 // so they require an implicit dereference on their arguments.
437 auto function = ast::getFunction( expr );
438 if ( function == nullptr ) {
439 return expr;
440 }
441
442 ast::FunctionType const * ftype = GenPoly::getFunctionType( function->get_type() );
443 assertf( ftype, "Function declaration does not have function type." );
444 // Can be of different lengths only when function is variadic.
445 assertf( ftype->params.size() == expr->args.size() || ftype->isVarArgs,
446 "ApplicationExpr args do not match formal parameter type." );
447 assertf( ftype->params.size() <= expr->args.size(),
448 "Cannot have more parameters than arguments." );
449
450 unsigned int i = 0;
451 unsigned int const end = ftype->params.size();
452
453 // This is used to make sure we get a zip on shortests.
454 if ( end == i ) return expr;
455
456 // This mutate could be redundent, but it is simpler this way.
457 auto mutExpr = ast::mutate( expr );
458
459 for ( auto pair : unsafe_group_iterate( mutExpr->args, ftype->params ) ) {
460 ast::ptr<ast::Expr> & arg = std::get<0>( pair );
461 ast::ptr<ast::Type> const & formal = std::get<1>( pair );
462 PRINT(
463 std::cerr << "pair<0>: " << arg.get() << std::endl;
464 std::cerr << " -- " << arg->result << std::endl;
465 std::cerr << "pair<1>: " << formal << std::endl;
466 )
467 //if ( dynamic_cast<ast::ReferenceType const *>( formal.get() ) ) {
468 if ( formal.as<ast::ReferenceType>() ) {
469 PRINT( std::cerr << "===formal is reference" << std::endl; )
470 // TODO: It's likely that the second condition should be
471 // `... && ! isIntrinsicReference( arg )`, but this requires
472 // investigation.
473
474 if ( ast::Linkage::Intrinsic != function->linkage
475 && isIntrinsicReference( arg ) ) {
476 // Needed for definition of prelude functions, etc.
477 // If argument is dereference or array subscript, the result
478 // isn't REALLY a reference, but non-intrinsic functions
479 // expect a reference: take address
480
481 // TODO: OK, so this should be cut?!
482 // NODE: Previously, this condition fixed
483 // void f(int *&);
484 // int & x = ...;
485 // f(&x);
486 // But now this is taken care of by a reference cast added by
487 // AddressRef. Need to find a new example or remove this
488 // branch.
489 PRINT(
490 std::cerr << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
491 )
492 arg = new ast::AddressExpr( arg->location, arg );
493 } else if ( ast::Linkage::Intrinsic == function->linkage
494 && arg->result->referenceDepth() != 0 ) {
495 // Argument is a 'real' reference, but function expects a C
496 // lvalue: Add a dereference to the reference-typed argument.
497 PRINT(
498 std::cerr << "===is non-intrinsic arg in intrinsic call - adding deref to arg" << std::endl;
499 )
500 ast::Type const * base = ast::getPointerBase( arg->result );
501 assertf( base, "parameter is reference, arg must be pointer or reference: %s", toString( arg->result ).c_str() );
502 ast::PointerType * ptr = new ast::PointerType( ast::deepCopy( base ) );
503 arg = ast::mutate_field( arg.get(),
504 &ast::ApplicationExpr::result, ptr );
505 arg = mkDeref( transUnit().global, arg );
506 }
507 }
508 ++i;
509 if ( end == i ) break;
510 }
511 return mutExpr;
512}
513
514ast::Expr const * CollapseAddressDeref::postvisit(
515 ast::AddressExpr const * expr ) {
516 ast::Expr const * arg = expr->arg;
517 if ( isIntrinsicReference( arg ) ) {
518 std::string fname = ast::getFunctionName( arg );
519 if ( fname == "*?" ) {
520 ast::Expr const * arg0 = ast::getCallArg( arg, 0 );
521 ast::Expr * ret = ast::mutate( arg0 );
522 ret->env = expr->env;
523 return ret;
524 }
525 } else if ( auto cast = dynamic_cast<ast::CastExpr const *>( arg ) ) {
526 // Need to move cast to pointer type out a level since address of
527 // pointer is not valid C code (can be introduced in prior passes,
528 // e.g., InstantiateGeneric)
529 if ( ast::getPointerBase( cast->result ) ) {
530 auto mutExpr = ast::mutate( expr );
531 auto mutCast = strict_dynamic_cast<ast::CastExpr *>(
532 ast::mutate( mutExpr->arg.release() ) );
533 mutExpr->arg = mutCast->arg;
534 mutCast->arg = mutExpr;
535 mutCast->result = new ast::PointerType( mutCast->result );
536 return mutCast;
537 }
538 }
539 return expr;
540}
541
542ast::Expr const * CollapseAddressDeref::postvisit(
543 ast::ApplicationExpr const * expr ) {
544 if ( isIntrinsicReference( expr ) ) {
545 std::string fname = ast::getFunctionName( expr );
546 if ( fname == "*?" ) {
547 assert( 1 == expr->args.size() );
548 ast::Expr const * arg = ast::getCallArg( expr, 0 );
549 // xxx - this isn't right, because it can remove casts that
550 // should be there...
551 // while ( auto cast = dynamic_cast< ast::CastExpr const * >( arg ) ) {
552 // arg = cast->arg;
553 // }
554 if ( auto addr = dynamic_cast<ast::AddressExpr const *>( arg ) ) {
555 return ast::mutate_field( addr->arg.get(),
556 &ast::Expr::env, expr->env.get() );
557 }
558 }
559 }
560 return expr;
561}
562
563ast::Expr const * GeneralizedLvalue::postvisit(
564 ast::AddressExpr const * expr ) {
565 return applyTransformation( expr, &ast::AddressExpr::arg,
566 []( ast::Expr const * arg ) {
567 return new ast::AddressExpr( arg->location, arg );
568 }
569 );
570}
571
572ast::Expr const * GeneralizedLvalue::postvisit(
573 ast::MemberExpr const * expr ) {
574 return applyTransformation( expr, &ast::MemberExpr::aggregate,
575 [expr]( ast::Expr const * aggr ) {
576 return new ast::MemberExpr( aggr->location, expr->member, aggr );
577 }
578 );
579}
580
581template<typename Node, typename Func>
582ast::Expr const * GeneralizedLvalue::applyTransformation(
583 Node const * expr, ast::ptr<ast::Expr> Node::*field, Func mkExpr ) {
584 ast::ptr<ast::Expr> const & arg = expr->*field;
585 if ( auto commaArg = arg.as<ast::CommaExpr>() ) {
586 ast::Expr const * arg1 = ast::deepCopy( commaArg->arg1 );
587 ast::Expr const * arg2 = ast::deepCopy( commaArg->arg2 );
588 ast::Expr const * ret = new ast::CommaExpr(
589 commaArg->location, arg1, mkExpr( arg2 )->accept( *visitor ) );
590 return ret;
591 } else if ( auto condArg = arg.as<ast::ConditionalExpr>() ) {
592 ast::Expr const * arg1 = ast::deepCopy( condArg->arg1 );
593 ast::Expr const * arg2 = ast::deepCopy( condArg->arg2 );
594 ast::Expr const * arg3 = ast::deepCopy( condArg->arg3 );
595 ast::ConditionalExpr * ret = new ast::ConditionalExpr(
596 condArg->location, arg1, mkExpr( arg2 )->accept( *visitor ),
597 mkExpr( arg3 )->accept( *visitor ) );
598
599 // Conditional expr type may not be either of the arguments,
600 // so unify to get the result.
601 // TODO: Maybe I could create a wrapper for this.
602 ast::ptr<ast::Type> common = nullptr;
603 ast::TypeEnvironment newEnv;
604 ast::AssertionSet needAssertions, haveAssertions;
605 ast::OpenVarSet openVars;
606 ResolvExpr::unify( ret->arg2->result, ret->arg3->result, newEnv,
607 needAssertions, haveAssertions, openVars, common );
608 ret->result = common ? common : ast::deepCopy( ret->arg2->result );
609 return ret;
610 }
611 return expr;
612}
613
614ast::SizeofExpr const * ReferenceTypeElimination::previsit(
615 ast::SizeofExpr const * expr ) {
616 return ast::mutate_field( expr, &ast::SizeofExpr::type,
617 expr->type->stripReferences() );
618}
619
620ast::AlignofExpr const * ReferenceTypeElimination::previsit(
621 ast::AlignofExpr const * expr ) {
622 return ast::mutate_field( expr, &ast::AlignofExpr::type,
623 expr->type->stripReferences() );
624}
625
626ast::Type const * ReferenceTypeElimination::postvisit(
627 ast::ReferenceType const * type ) {
628 return new ast::PointerType( type->base, type->qualifiers );
629}
630
631} // namespace
632
633// Stored elsewhere (Lvalue2, initially false):
634extern bool referencesEliminated;
635
636void convertLvalue( ast::TranslationUnit & translationUnit ) {
637 ast::Pass<FixIntrinsicResults>::run( translationUnit );
638 ast::Pass<AddressRef>::run( translationUnit );
639 ast::Pass<ReferenceConversions>::run( translationUnit );
640 ast::Pass<FixIntrinsicArgs>::run( translationUnit );
641 ast::Pass<CollapseAddressDeref>::run( translationUnit );
642 ast::Pass<GeneralizedLvalue>::run( translationUnit );
643 // Last because other passes need reference types to work.
644 ast::Pass<ReferenceTypeElimination>::run( translationUnit );
645 // From this point forward, nothing should create reference types.
646 referencesEliminated = true;
647}
648
649ast::Expr const * generalizedLvalue( ast::Expr const * expr ) {
650 ast::Pass<GeneralizedLvalue> visitor;
651 return expr->accept( visitor );
652}
653
654} // namespace GenPoly
655
656// Local Variables: //
657// tab-width: 4 //
658// mode: c++ //
659// compile-command: "make install" //
660// End: //
Note: See TracBrowser for help on using the repository browser.