source: src/GenPoly/Lvalue.cc @ 9236060

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

Merge branch 'master' into references

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