source: src/GenPoly/Lvalue.cc @ da7fe39

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

Merge branch 'master' into references

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