source: src/GenPoly/Lvalue.cc @ 8135d4c

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

Merge branch 'master' into references

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