source: src/GenPoly/Lvalue.cc @ 8a6cf7e

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 8a6cf7e was 8a6cf7e, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Fix various reference features.

  • Eliminate multiple address-ofs resulting from &(T&) [address-of reference-cast].
  • Keep rvalue cast if reference base type is incompatible with rvalue type.
  • Keep pointer qualifiers when eliminating reference types.
  • Add VariableExpr::functionPointer helper function to create variable expressions with function pointer type.
  • Change ConstructorExpr? translation so that it temporarily generates a 'fake' assignment operator rather than use UntypedExpr?, so that the correct transformations occur in the Lvalue pass. This is a hack that can be fixed once PassVisitor? properly supports Indexer.
  • Property mode set to 100644
File size: 13.5 KB
RevLine 
[51587aa]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//
[906e24d]7// Lvalue.cc --
[51587aa]8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
[01aeade]11// Last Modified By : Peter A. Buhr
[615a096]12// Last Modified On : Fri Mar 17 09:11:18 2017
13// Update Count     : 5
[51587aa]14//
[51b7345]15
16#include <cassert>
17
18#include "Lvalue.h"
19
[02ad3f5]20#include "GenPoly.h"
21
[51b7345]22#include "SynTree/Declaration.h"
23#include "SynTree/Type.h"
24#include "SynTree/Expression.h"
25#include "SynTree/Statement.h"
26#include "SynTree/Visitor.h"
27#include "SynTree/Mutator.h"
28#include "SymTab/Indexer.h"
[9a34b5a]29#include "SymTab/Autogen.h"
[51b7345]30#include "ResolvExpr/Resolver.h"
31#include "ResolvExpr/typeops.h"
32
[d3b7937]33#include "Common/UniqueName.h"
34#include "Common/utility.h"
[ce8c12f]35#include "InitTweak/InitTweak.h"
[51b7345]36
[1d776fd]37#include "Common/PassVisitor.h"
38
39// need to be careful about polymorphic references... e.g. in *? (___operator_deref__A0_1_0_0__Fd0_Pd0_intrinsic___1)
40// the variable is automatically dereferenced and this causes errors dereferencing void*.
41
[cb43451]42#if 0
43#define PRINT(x) x
44#else
45#define PRINT(x)
46#endif
47
[51b7345]48namespace GenPoly {
[01aeade]49        namespace {
[9a34b5a]50                // TODO: fold this into the general createDeref function??
51                Expression * mkDeref( Expression * arg ) {
52                        if ( SymTab::dereferenceOperator ) {
53                                VariableExpr * deref = new VariableExpr( SymTab::dereferenceOperator );
54                                deref->set_result( new PointerType( Type::Qualifiers(), deref->get_result() ) );
55                                Type * base = InitTweak::getPointerBase( arg->get_result() );
56                                assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->get_result() ).c_str() );
57                                ApplicationExpr * ret = new ApplicationExpr( deref, { arg } );
58                                delete ret->get_result();
59                                ret->set_result( new ReferenceType( Type::Qualifiers(), base->clone() ) );
60                                return ret;
61                        } else {
62                                return UntypedExpr::createDeref( arg );
63                        }
64                }
65
[1d776fd]66                struct ReferenceConversions final {
67                        Expression * postmutate( CastExpr * castExpr );
[8a6cf7e]68                        Expression * postmutate( AddressExpr * addrExpr );
[01aeade]69                };
70
[1d776fd]71                /// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
72                struct FixIntrinsicArgs final {
73                        Expression * postmutate( ApplicationExpr *appExpr );
74                };
75
76
77                /// Replace reference types with pointer types
78                struct ReferenceTypeElimination final {
79                        Type * postmutate( ReferenceType * refType );
[01aeade]80                };
[b6fd751]81
82                /// GCC-like Generalized Lvalues (which have since been removed from GCC)
83                /// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
84                /// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
[d335627]85                struct GeneralizedLvalue final : public WithVisitorRef<GeneralizedLvalue> {
[1d776fd]86                        Expression * postmutate( AddressExpr * addressExpr );
[b6fd751]87                };
[cb43451]88
89                /// Removes redundant &*/*& pattern that this pass can generate
90                struct CollapseAddrDeref final {
91                        Expression * postmutate( AddressExpr * addressExpr );
92                        Expression * postmutate( ApplicationExpr * appExpr );
93                };
[01aeade]94        } // namespace
95
96        void convertLvalue( std::list< Declaration* >& translationUnit ) {
[1d776fd]97                std::cerr << "convertLvalue" << std::endl;
98                PassVisitor<ReferenceConversions> refCvt;
99                PassVisitor<ReferenceTypeElimination> elim;
100                PassVisitor<GeneralizedLvalue> genLval;
101                PassVisitor<FixIntrinsicArgs> fixer;
[cb43451]102                PassVisitor<CollapseAddrDeref> collapser;
[1d776fd]103                mutateAll( translationUnit, refCvt );
104                mutateAll( translationUnit, fixer );
[b6fd751]105                mutateAll( translationUnit, genLval );
[cb43451]106                mutateAll( translationUnit, collapser );
[8a6cf7e]107                mutateAll( translationUnit, elim );  // last because other passes need reference types to work
[01aeade]108        }
109
110        namespace {
[8a6cf7e]111                // true for intrinsic function calls that return a reference
[1d776fd]112                bool isIntrinsicReference( Expression * expr ) {
[8a6cf7e]113                        if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
114                                std::string fname = InitTweak::getFunctionName( untyped );
115                                // known intrinsic-reference prelude functions
116                                return fname == "*?" || fname == "?[?]";
[1d776fd]117                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
118                                if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
[8a6cf7e]119                                        // use type of return variable rather than expr result type, since it may have been changed to a pointer type
120                                        FunctionType * ftype = GenPoly::getFunctionType( func->get_type() );
121                                        Type * ret = ftype->get_returnVals().empty() ? nullptr : ftype->get_returnVals().front()->get_type();
122                                        return func->get_linkage() == LinkageSpec::Intrinsic && dynamic_cast<ReferenceType *>( ret );
[1d776fd]123                                }
[ce8c12f]124                        }
[1d776fd]125                        return false;
[ce8c12f]126                }
127
[cb43451]128                // xxx - might need to & every * (or every * that is an arg to non-intrinsic function??)
[1d776fd]129                Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
[9a34b5a]130                        // intrinsic functions don't really take reference-typed parameters, so they require an implicit dereference on their arguments.
[1d776fd]131                        if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
[d335627]132                                FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
133                                assertf( ftype, "Function declaration does not have function type." );
134                                // can be of differing lengths only when function is variadic
135                                assertf( ftype->get_parameters().size() == appExpr->get_args().size() || ftype->get_isVarArgs(), "ApplicationExpr args do not match formal parameter type." );
136                                unsigned int i = 0;
137                                const unsigned int end = ftype->get_parameters().size();
138                                for ( auto p : unsafe_group_iterate( appExpr->get_args(), ftype->get_parameters() ) ) {
139                                        if (i == end) break;
140                                        Expression *& arg = std::get<0>( p );
141                                        Type * formal = std::get<1>( p )->get_type();
142                                        PRINT(
143                                                std::cerr << "pair<0>: " << arg << std::endl;
144                                                std::cerr << "pair<1>: " << formal << std::endl;
145                                        )
146                                        if ( dynamic_cast<ReferenceType*>( formal ) ) {
147                                                if ( isIntrinsicReference( arg ) ) {
148                                                        if ( function->get_linkage() != LinkageSpec::Intrinsic ) { // intrinsic functions that turn pointers into references
149                                                                // if argument is dereference or array subscript, the result isn't REALLY a reference, so it's not necessary to fix the argument
150                                                                PRINT( std::cerr << "is intrinsic arg in non-intrinsic call - adding address" << std::endl; )
151                                                                arg = new AddressExpr( arg );
152                                                        }
153                                                } else if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
154                                                        // if the parameter is a reference, add a dereference to the reference-typed argument.
155                                                        Type * baseType = InitTweak::getPointerBase( arg->get_result() );
156                                                        assertf( baseType, "parameter is reference, arg must be pointer or reference: %s", toString( arg->get_result() ) );
157                                                        PointerType * ptrType = new PointerType( Type::Qualifiers(), baseType->clone() );
158                                                        delete arg->get_result();
159                                                        arg->set_result( ptrType );
160                                                        arg = mkDeref( arg );
[1d776fd]161                                                }
162                                        }
[d335627]163                                        ++i;
[baba5d8]164                                }
[1d776fd]165                        }
166                        return appExpr;
[01aeade]167                }
168
[8a6cf7e]169                Expression * ReferenceConversions::postmutate( AddressExpr * addrExpr ) {
170                        // Inner expression may have been lvalue to reference conversion, which becomes an address expression.
171                        // In this case, remove the outer address expression and return the argument.
172                        // TODO: It's possible that this might catch too much and require a more sophisticated check.
173                        if ( dynamic_cast<AddressExpr*>( addrExpr->get_arg() ) ) {
174                                Expression * arg = addrExpr->get_arg();
175                                arg->set_env( addrExpr->get_env() );
176                                addrExpr->set_arg( nullptr );
177                                addrExpr->set_env( nullptr );
178                                delete addrExpr;
179                                return arg;
180                        }
181                        return addrExpr;
182                }
183
[1d776fd]184                Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
[9a34b5a]185                        // xxx - is it possible to convert directly between reference types with a different base? E.g.,
186                        //   int x;
187                        //   (double&)x;
188                        // At the moment, I am working off of the assumption that this is illegal, thus the cast becomes redundant
189                        // after this pass, so trash the cast altogether. If that changes, care must be taken to insert the correct
190                        // pointer casts in the right places.
191
[1d776fd]192                        // conversion to reference type
193                        if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_result() ) ) {
194                                (void)refType;
195                                if ( ReferenceType * otherRef = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
196                                        // nothing to do if casting from reference to reference.
197                                        (void)otherRef;
[cb43451]198                                        PRINT( std::cerr << "convert reference to reference -- nop" << std::endl; )
[1d776fd]199                                        if ( isIntrinsicReference( castExpr->get_arg() ) ) {
200                                                Expression * callExpr = castExpr->get_arg();
[cb43451]201                                                PRINT(
202                                                        std::cerr << "but arg is deref -- &" << std::endl;
203                                                        std::cerr << callExpr << std::endl;
204                                                )
[1d776fd]205                                                // move environment out to new top-level
206                                                callExpr->set_env( castExpr->get_env() );
[9a34b5a]207                                                castExpr->set_arg( nullptr );
[1d776fd]208                                                castExpr->set_env( nullptr );
[9a34b5a]209                                                delete castExpr;
[1d776fd]210                                                return callExpr;
211                                        }
[9a34b5a]212                                        assertf( false, "non-intrinsic reference with cast of reference to reference not yet supported: ", toString( castExpr ) );
[cb43451]213                                        PRINT( std::cerr << castExpr << std::endl; )
[1d776fd]214                                        return castExpr;
215                                } else if ( castExpr->get_arg()->get_result()->get_lvalue() ) {
216                                        // conversion from lvalue to reference
217                                        // xxx - keep cast, but turn into pointer cast??
218                                        // xxx - memory
[cb43451]219                                        PRINT(
220                                                std::cerr << "convert lvalue to reference -- &" << std::endl;
221                                                std::cerr << castExpr->get_arg() << std::endl;
222                                        )
223                                        AddressExpr * ret = new AddressExpr( castExpr->get_arg() );
224                                        if ( refType->get_base()->get_qualifiers() != castExpr->get_arg()->get_result()->get_qualifiers() ) {
225                                                // must keep cast if cast-to type is different from the actual type
226                                                castExpr->set_arg( ret );
227
228                                                return castExpr;
229                                        }
[9a34b5a]230                                        ret->set_env( castExpr->get_env() );
231                                        castExpr->set_env( nullptr );
232                                        castExpr->set_arg( nullptr );
233                                        delete castExpr;
234                                        return ret;
[01aeade]235                                } else {
[1d776fd]236                                        // rvalue to reference conversion -- introduce temporary
237                                }
238                                assertf( false, "Only conversions to reference from lvalue are currently supported: %s", toString( castExpr ).c_str() );
239                        } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
[d335627]240                                (void)refType;
[9a34b5a]241                                // conversion from reference to rvalue
[8a6cf7e]242                                PRINT(
243                                        std::cerr << "convert reference to rvalue -- *" << std::endl;
244                                        std::cerr << "was = " << castExpr << std::endl;
245                                )
[9191a8e]246                                Expression * ret = castExpr->get_arg();
[8a6cf7e]247                                TypeSubstitution * env = castExpr->get_env();
248                                castExpr->set_env( nullptr );
[9191a8e]249                                if ( ! isIntrinsicReference( ret ) ) {
250                                        // dereference if not already dereferenced
251                                        ret = mkDeref( ret );
252                                }
[8a6cf7e]253                                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( castExpr->get_result(), castExpr->get_arg()->get_result()->stripReferences(), SymTab::Indexer() ) ) {
254                                        // can remove cast if types are compatible
255                                        castExpr->set_arg( nullptr );
256                                        delete castExpr;
257                                } else {
258                                        // must keep cast if types are different
259                                        castExpr->set_arg( ret );
260                                        ret = castExpr;
261                                }
262                                ret->set_env( env );
[9191a8e]263                                PRINT( std::cerr << "now: " << ret << std::endl; )
264                                return ret;
[1d776fd]265                        }
266                        return castExpr;
[01aeade]267                }
[b6fd751]268
[1d776fd]269                Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
270                        Type * base = refType->get_base();
[8a6cf7e]271                        Type::Qualifiers qualifiers = refType->get_qualifiers();
[1d776fd]272                        refType->set_base( nullptr );
273                        delete refType;
[8a6cf7e]274                        return new PointerType( qualifiers, base );
[ce8c12f]275                }
276
[1d776fd]277                Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
[b6fd751]278                        if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( addrExpr->get_arg() ) ) {
279                                Expression * arg1 = commaExpr->get_arg1()->clone();
280                                Expression * arg2 = commaExpr->get_arg2()->clone();
281                                delete addrExpr;
[d335627]282                                return new CommaExpr( arg1, (new AddressExpr( arg2 ))->acceptMutator( *visitor ) );
[b6fd751]283                        } else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( addrExpr->get_arg() ) ) {
284                                Expression * arg1 = condExpr->get_arg1()->clone();
285                                Expression * arg2 = condExpr->get_arg2()->clone();
286                                Expression * arg3 = condExpr->get_arg3()->clone();
287                                delete addrExpr;
[d335627]288                                return new ConditionalExpr( arg1, (new AddressExpr( arg2 ))->acceptMutator( *visitor ), (new AddressExpr( arg3 ))->acceptMutator( *visitor ) );
[b6fd751]289                        }
290                        return addrExpr;
291                }
[cb43451]292
293                Expression * CollapseAddrDeref::postmutate( AddressExpr * addressExpr ) {
294                        Expression * arg = addressExpr->get_arg();
295                        if ( isIntrinsicReference( arg ) ) {
296                                std::string fname = InitTweak::getFunctionName( arg );
297                                if ( fname == "*?" ) {
298                                        Expression *& arg0 = InitTweak::getCallArg( arg, 0 );
299                                        Expression * ret = arg0;
300                                        ret->set_env( addressExpr->get_env() );
301                                        arg0 = nullptr;
302                                        addressExpr->set_env( nullptr );
303                                        delete addressExpr;
304                                        return ret;
305                                }
306                        }
307                        return addressExpr;
308                }
309
310                Expression * CollapseAddrDeref::postmutate( ApplicationExpr * appExpr ) {
311                        if ( isIntrinsicReference( appExpr ) ) {
312                                std::string fname = InitTweak::getFunctionName( appExpr );
313                                if ( fname == "*?" ) {
314                                        Expression * arg = InitTweak::getCallArg( appExpr, 0 );
315                                        // xxx - this isn't right, because it can remove casts that should be there...
316                                        // while ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
317                                        //      arg = castExpr->get_arg();
318                                        // }
319                                        if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( arg ) ) {
320                                                Expression * ret = addrExpr->get_arg();
321                                                ret->set_env( appExpr->get_env() );
322                                                addrExpr->set_arg( nullptr );
323                                                appExpr->set_env( nullptr );
324                                                delete appExpr;
325                                                return ret;
326                                        }
327                                }
328                        }
329                        return appExpr;
330                }
[01aeade]331        } // namespace
[51b7345]332} // namespace GenPoly
[01aeade]333
[51587aa]334// Local Variables: //
335// tab-width: 4 //
336// mode: c++ //
337// compile-command: "make install" //
338// End: //
Note: See TracBrowser for help on using the repository browser.