source: src/GenPoly/InstantiateGeneric.cc @ ada4575

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since ada4575 was 27aca84, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Mark dtype-static casts as non-generated so they persist until Box

  • Property mode set to 100644
File size: 23.3 KB
RevLine 
[ea5daeb]1//
2// Cforall Version 1.0.0 Copyright (C) 2016 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// InstantiateGeneric.cc --
8//
9// Author           : Aaron B. Moss
10// Created On       : Thu Aug 04 18:33:00 2016
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Thu Aug 04 18:33:00 2016
13// Update Count     : 1
14//
15#include "InstantiateGeneric.h"
16
[08fc48f]17#include <cassert>                     // for assertf, assert
18#include <iterator>                    // for back_inserter, inserter
19#include <list>                        // for list, _List_const_iterator
20#include <utility>                     // for move, pair
21#include <vector>                      // for vector
22
[1393df07]23#include "CodeGen/OperatorTable.h"
[08fc48f]24#include "Common/PassVisitor.h"        // for PassVisitor, WithDeclsToAdd
25#include "Common/ScopedMap.h"          // for ScopedMap
26#include "Common/UniqueName.h"         // for UniqueName
27#include "Common/utility.h"            // for deleteAll, cloneAll
28#include "GenPoly.h"                   // for isPolyType, typesPolyCompatible
[1393df07]29#include "InitTweak/InitTweak.h"
[b95fe40]30#include "ResolvExpr/typeops.h"
[08fc48f]31#include "ScopedSet.h"                 // for ScopedSet, ScopedSet<>::iterator
32#include "ScrubTyVars.h"               // for ScrubTyVars
33#include "SynTree/Declaration.h"       // for StructDecl, UnionDecl, TypeDecl
34#include "SynTree/Expression.h"        // for TypeExpr, Expression
35#include "SynTree/Mutator.h"           // for mutateAll
36#include "SynTree/Type.h"              // for StructInstType, UnionInstType
37#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
38#include "SynTree/Visitor.h"           // for acceptAll
[2a7b3ca]39
[ea5daeb]40
41namespace GenPoly {
42
43        /// Abstracts type equality for a list of parameter types
44        struct TypeList {
45                TypeList() : params() {}
46                TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
47                TypeList( std::list< Type* > &&_params ) : params( _params ) {}
48
49                TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
50                TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
51
52                /// Extracts types from a list of TypeExpr*
53                TypeList( const std::list< TypeExpr* >& _params ) : params() {
54                        for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
55                                params.push_back( (*param)->get_type()->clone() );
56                        }
57                }
58
59                TypeList& operator= ( const TypeList &that ) {
60                        deleteAll( params );
61
62                        params.clear();
63                        cloneAll( that.params, params );
64
65                        return *this;
66                }
67
68                TypeList& operator= ( TypeList &&that ) {
69                        deleteAll( params );
70
71                        params = std::move( that.params );
72
73                        return *this;
74                }
75
76                ~TypeList() { deleteAll( params ); }
77
78                bool operator== ( const TypeList& that ) const {
79                        if ( params.size() != that.params.size() ) return false;
80
81                        for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
[5a3ac84]82                                if ( ! typesPolyCompatible( *it, *jt ) ) return false;
[ea5daeb]83                        }
84                        return true;
85                }
86
87                std::list< Type* > params;  ///< Instantiation parameters
88        };
[e491159]89
[ea5daeb]90        /// Maps a key and a TypeList to the some value, accounting for scope
91        template< typename Key, typename Value >
92        class InstantiationMap {
93                /// Wraps value for a specific (Key, TypeList) combination
94                typedef std::pair< TypeList, Value* > Instantiation;
95                /// List of TypeLists paired with their appropriate values
96                typedef std::vector< Instantiation > ValueList;
97                /// Underlying map type; maps keys to a linear list of corresponding TypeLists and values
98                typedef ScopedMap< Key*, ValueList > InnerMap;
99
100                InnerMap instantiations;  ///< instantiations
101
102        public:
103                /// Starts a new scope
104                void beginScope() { instantiations.beginScope(); }
105
106                /// Ends a scope
107                void endScope() { instantiations.endScope(); }
108
109                /// Gets the value for the (key, typeList) pair, returns NULL on none such.
110                Value *lookup( Key *key, const std::list< TypeExpr* >& params ) const {
111                        TypeList typeList( params );
112
113                        // scan scopes for matches to the key
114                        for ( typename InnerMap::const_iterator insts = instantiations.find( key ); insts != instantiations.end(); insts = instantiations.findNext( insts, key ) ) {
115                                for ( typename ValueList::const_reverse_iterator inst = insts->second.rbegin(); inst != insts->second.rend(); ++inst ) {
116                                        if ( inst->first == typeList ) return inst->second;
117                                }
118                        }
119                        // no matching instantiations found
120                        return 0;
121                }
122
123                /// Adds a value for a (key, typeList) pair to the current scope
124                void insert( Key *key, const std::list< TypeExpr* > &params, Value *value ) {
[e58dfb9]125                        auto it = instantiations.findAt( instantiations.currentScope(), key );
126                        if ( it == instantiations.end() ) {
127                                instantiations.insert( key, ValueList{ Instantiation{ TypeList( params ), value } } );
128                        } else {
129                                it->second.push_back( Instantiation{ TypeList( params ), value } );
130                        }
[ea5daeb]131                }
132        };
[3bb195cb]133
134        /// Possible options for a given specialization of a generic type
135        enum class genericType {
136                dtypeStatic,  ///< Concrete instantiation based solely on {d,f}type-to-void conversions
137                concrete,     ///< Concrete instantiation requiring at least one parameter type
138                dynamic       ///< No concrete instantiation
139        };
140
141        genericType& operator |= ( genericType& gt, const genericType& ht ) {
142                switch ( gt ) {
143                case genericType::dtypeStatic:
144                        gt = ht;
145                        break;
146                case genericType::concrete:
147                        if ( ht == genericType::dynamic ) { gt = genericType::dynamic; }
148                        break;
149                case genericType::dynamic:
150                        // nothing possible
151                        break;
152                }
153                return gt;
154        }
[e491159]155
[b95fe40]156        /// Add cast to dtype-static member expressions so that type information is not lost in GenericInstantiator
[1393df07]157        struct FixDtypeStatic final : public WithGuards, public WithVisitorRef<FixDtypeStatic>, public WithShortCircuiting, public WithStmtsToAdd {
[b95fe40]158                Expression * postmutate( MemberExpr * memberExpr );
159
[1393df07]160                void premutate( ApplicationExpr * appExpr );
161                void premutate( AddressExpr * addrExpr );
162
[b95fe40]163                template<typename AggrInst>
164                Expression * fixMemberExpr( AggrInst * inst, MemberExpr * memberExpr );
[1393df07]165
166                bool isLvalueArg = false;
[b95fe40]167        };
168
[ea5daeb]169        /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
[2a7b3ca]170        struct GenericInstantiator final : public WithTypeSubstitution, public WithDeclsToAdd, public WithVisitorRef<GenericInstantiator>, public WithGuards {
[ea5daeb]171                /// Map of (generic type, parameter list) pairs to concrete type instantiations
172                InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
[3bb195cb]173                /// Set of types which are dtype-only generic (and therefore have static layout)
174                ScopedSet< AggregateDecl* > dtypeStatics;
[ea5daeb]175                /// Namer for concrete types
176                UniqueName typeNamer;
[2a7b3ca]177                /// Should not make use of type environment to replace types of function parameter and return values.
178                bool inFunctionType = false;
[f6582243]179                /// Index of current member, used to recreate MemberExprs with the member from an instantiation
180                int memberIndex = -1;
[2a7b3ca]181                GenericInstantiator() : instantiations(), dtypeStatics(), typeNamer("_conc_") {}
182
183                Type* postmutate( StructInstType *inst );
184                Type* postmutate( UnionInstType *inst );
[ea5daeb]185
[f6582243]186                // fix MemberExprs to use the member from the instantiation
187                void premutate( MemberExpr * memberExpr );
188                Expression * postmutate( MemberExpr * memberExpr );
189
190                void premutate( FunctionType * ) {
[2a7b3ca]191                        GuardValue( inFunctionType );
192                        inFunctionType = true;
193                }
[ea5daeb]194
[2a7b3ca]195                void beginScope();
196                void endScope();
[ea5daeb]197        private:
198                /// Wrap instantiation lookup for structs
199                StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
200                /// Wrap instantiation lookup for unions
201                UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
202                /// Wrap instantiation insertion for structs
203                void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
204                /// Wrap instantiation insertion for unions
205                void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
[3bb195cb]206
[b940dc71]207                void replaceParametersWithConcrete( std::list< Expression* >& params );
208                Type *replaceWithConcrete( Type *type, bool doClone );
209
[3bb195cb]210                /// Strips a dtype-static aggregate decl of its type parameters, marks it as stripped
211                void stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs );
[ea5daeb]212        };
213
214        void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
[b95fe40]215                PassVisitor<FixDtypeStatic> fixer;
[2a7b3ca]216                PassVisitor<GenericInstantiator> instantiator;
[b95fe40]217
[4e7a4e6]218                mutateAll( translationUnit, fixer );
[2a7b3ca]219                mutateAll( translationUnit, instantiator );
[ea5daeb]220        }
221
[b95fe40]222        bool isDtypeStatic( const std::list< TypeDecl* >& baseParams ) {
223                return std::all_of( baseParams.begin(), baseParams.end(), []( TypeDecl * td ) { return ! td->isComplete(); } );
224        }
225
[3bb195cb]226        /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
227        /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
[ea5daeb]228        genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
229                genericType gt = genericType::dtypeStatic;
230
231                // substitute concrete types for given parameters, and incomplete types for placeholders
232                std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
233                std::list< Expression* >::const_iterator param = params.begin();
234                for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
235                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
236                        assert(paramType && "Aggregate parameters should be type expressions");
[e491159]237
[0bfaf80]238                        if ( (*baseParam)->isComplete() ) {
[87c3bef]239                                // substitute parameter for complete (otype or sized dtype) type
[5a3ac84]240                                if ( isPolyType( paramType->get_type() ) ) {
241                                        // substitute polymorphic parameter type in to generic type
[87c3bef]242                                        out.push_back( paramType->clone() );
[5a3ac84]243                                        gt = genericType::dynamic;
244                                } else {
245                                        // normalize possibly dtype-static parameter type
[6db9dab]246                                        out.push_back( new TypeExpr{
[5a3ac84]247                                                ScrubTyVars::scrubAll( paramType->get_type()->clone() ) } );
248                                        gt |= genericType::concrete;
[87c3bef]249                                }
[0bfaf80]250                        } else switch ( (*baseParam)->get_kind() ) {
251                                case TypeDecl::Dtype:
252                                        // can pretend that any incomplete dtype is `void`
253                                        out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
254                                        break;
255                                case TypeDecl::Ftype:
256                                        // can pretend that any ftype is `void (*)(void)`
257                                        out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
258                                        break;
259                                case TypeDecl::Ttype:
260                                        assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
261                                        break;
[f0ecf9b]262                                default:
263                                        assertf( false, "Unhandled type parameter kind" );
[0bfaf80]264                                        break;
[ea5daeb]265                        }
266                }
267
[b2daebd4]268                assertf( baseParam == baseParams.end() && param == params.end(), "Type parameters should match type variables" );
[ea5daeb]269                return gt;
270        }
271
272        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
273        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
274                                                        std::list< Declaration* >& out ) {
275                // substitute types into new members
276                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
277                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
278                        Declaration *newMember = (*member)->clone();
279                        subs.apply(newMember);
280                        out.push_back( newMember );
281                }
282        }
283
[3bb195cb]284        /// Substitutes types of members according to baseParams => typeSubs, working in-place
285        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
286                // substitute types into new members
287                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
288                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
289                        subs.apply(*member);
290                }
291        }
292
[f18a711]293        /// Strips the instances's type parameters
294        void stripInstParams( ReferenceToType *inst ) {
[3bb195cb]295                deleteAll( inst->get_parameters() );
296                inst->get_parameters().clear();
297        }
[e491159]298
[3bb195cb]299        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
300                substituteMembers( base->get_members(), baseParams, typeSubs );
301
[760ba67]302                // xxx - can't delete type parameters because they may have assertions that are used
303                // deleteAll( baseParams );
[3bb195cb]304                baseParams.clear();
[e491159]305
[3bb195cb]306                dtypeStatics.insert( base );
307        }
308
[b940dc71]309        /// xxx - more or less copied from box -- these should be merged with those somehow...
310        void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
311                for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
312                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
313                        assertf(paramType, "Aggregate parameters should be type expressions");
314                        paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
315                }
316        }
317
318        Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
319                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
[2a7b3ca]320                        if ( env && ! inFunctionType ) {
[b940dc71]321                                Type *concrete = env->lookup( typeInst->get_name() );
322                                if ( concrete ) {
323                                        return concrete->clone();
324                                }
325                                else return typeInst->clone();
326                        }
327                } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
328                        if ( doClone ) {
329                                structType = structType->clone();
330                        }
331                        replaceParametersWithConcrete( structType->get_parameters() );
332                        return structType;
333                } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
334                        if ( doClone ) {
335                                unionType = unionType->clone();
336                        }
337                        replaceParametersWithConcrete( unionType->get_parameters() );
338                        return unionType;
339                }
340                return type;
341        }
342
343
[2a7b3ca]344        Type* GenericInstantiator::postmutate( StructInstType *inst ) {
[ea5daeb]345                // exit early if no need for further mutation
346                if ( inst->get_parameters().empty() ) return inst;
347
[b940dc71]348                // need to replace type variables to ensure that generic types are instantiated for the return values of polymorphic functions (in particular, for thunks, because they are not [currently] copy constructed).
349                replaceWithConcrete( inst, false );
350
[3bb195cb]351                // check for an already-instantiatiated dtype-static type
[f18a711]352                if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
353                        stripInstParams( inst );
354                        return inst;
355                }
[e491159]356
[ea5daeb]357                // check if type can be concretely instantiated; put substitutions into typeSubs
[b940dc71]358                assertf( inst->get_baseParameters(), "Base struct has parameters" );
[ea5daeb]359                std::list< TypeExpr* > typeSubs;
360                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
361                switch ( gt ) {
[3bb195cb]362                case genericType::dtypeStatic:
363                        stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
[f18a711]364                        stripInstParams( inst );
[3bb195cb]365                        break;
[e491159]366
[3bb195cb]367                case genericType::concrete: {
[ea5daeb]368                        // make concrete instantiation of generic type
369                        StructDecl *concDecl = lookup( inst, typeSubs );
370                        if ( ! concDecl ) {
371                                // set concDecl to new type, insert type declaration into statements to add
372                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]373                                concDecl->set_body( inst->get_baseStruct()->has_body() );
[5a3ac84]374                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
[c7a3081]375                                insert( inst, typeSubs, concDecl ); // must insert before recursion
[2a7b3ca]376                                concDecl->acceptMutator( *visitor ); // recursively instantiate members
377                                declsToAddBefore.push_back( concDecl ); // must occur before declaration is added so that member instantiations appear first
[ea5daeb]378                        }
379                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
380                        newInst->set_baseStruct( concDecl );
381
382                        delete inst;
383                        inst = newInst;
384                        break;
385                }
386
387                case genericType::dynamic:
388                        // do nothing
389                        break;
390                }
391
392                deleteAll( typeSubs );
393                return inst;
394        }
395
[2a7b3ca]396        Type* GenericInstantiator::postmutate( UnionInstType *inst ) {
[ea5daeb]397                // exit early if no need for further mutation
398                if ( inst->get_parameters().empty() ) return inst;
[3bb195cb]399
400                // check for an already-instantiatiated dtype-static type
[f18a711]401                if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
402                        stripInstParams( inst );
403                        return inst;
404                }
[ea5daeb]405
406                // check if type can be concretely instantiated; put substitutions into typeSubs
[3bb195cb]407                assert( inst->get_baseParameters() && "Base union has parameters" );
[ea5daeb]408                std::list< TypeExpr* > typeSubs;
409                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
410                switch ( gt ) {
[3bb195cb]411                case genericType::dtypeStatic:
412                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
[f18a711]413                        stripInstParams( inst );
[3bb195cb]414                        break;
[e491159]415
[ea5daeb]416                case genericType::concrete:
417                {
418                        // make concrete instantiation of generic type
419                        UnionDecl *concDecl = lookup( inst, typeSubs );
420                        if ( ! concDecl ) {
421                                // set concDecl to new type, insert type declaration into statements to add
422                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]423                                concDecl->set_body( inst->get_baseUnion()->has_body() );
[ea5daeb]424                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
[c7a3081]425                                insert( inst, typeSubs, concDecl ); // must insert before recursion
[2a7b3ca]426                                concDecl->acceptMutator( *visitor ); // recursively instantiate members
427                                declsToAddBefore.push_back( concDecl ); // must occur before declaration is added so that member instantiations appear first
[ea5daeb]428                        }
429                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
430                        newInst->set_baseUnion( concDecl );
431
432                        delete inst;
433                        inst = newInst;
434                        break;
435                }
436                case genericType::dynamic:
437                        // do nothing
438                        break;
439                }
440
441                deleteAll( typeSubs );
442                return inst;
443        }
444
[f6582243]445        namespace {
446                bool isGenericType( Type * t ) {
447                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( t ) ) {
448                                return ! inst->parameters.empty();
449                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
450                                return ! inst->parameters.empty();
451                        }
452                        return false;
453                }
454        }
455
456        void GenericInstantiator::premutate( MemberExpr * memberExpr ) {
457                GuardValue( memberIndex );
458                memberIndex = -1;
459                if ( isGenericType( memberExpr->aggregate->result ) ) {
460                        // find the location of the member
[373d0b5]461                        AggregateDecl * aggr = memberExpr->aggregate->result->getAggr();
[f6582243]462                        std::list< Declaration * > & members = aggr->members;
463                        memberIndex = std::distance( members.begin(), std::find( members.begin(), members.end(), memberExpr->member ) );
464                        assertf( memberIndex < (int)members.size(), "Could not find member %s in generic type %s", toString( memberExpr->member ).c_str(), toString( memberExpr->aggregate ).c_str() );
465                }
466        }
467
468        Expression * GenericInstantiator::postmutate( MemberExpr * memberExpr ) {
469                if ( memberIndex != -1 ) {
470                        // using the location from the generic type, find the member in the instantiation and rebuild the member expression
[373d0b5]471                        AggregateDecl * aggr = memberExpr->aggregate->result->getAggr();
[f6582243]472                        assertf( memberIndex < (int)aggr->members.size(), "Instantiation somehow has fewer members than the generic type." );
473                        Declaration * member = *std::next( aggr->members.begin(), memberIndex );
474                        assertf( member->name == memberExpr->member->name, "Instantiation has different member order than the generic type. %s / %s", toString( member ).c_str(), toString( memberExpr->member ).c_str() );
[e3e16bc]475                        DeclarationWithType * field = strict_dynamic_cast< DeclarationWithType * >( member );
[f6582243]476                        MemberExpr * ret = new MemberExpr( field, memberExpr->aggregate->clone() );
[c20b0fea]477                        ResolvExpr::adjustExprType( ret->result ); // pointer decay
[f6582243]478                        std::swap( ret->env, memberExpr->env );
479                        delete memberExpr;
480                        return ret;
481                }
482                return memberExpr;
483        }
484
[2a7b3ca]485        void GenericInstantiator::beginScope() {
[ea5daeb]486                instantiations.beginScope();
[3bb195cb]487                dtypeStatics.beginScope();
[ea5daeb]488        }
489
[2a7b3ca]490        void GenericInstantiator::endScope() {
[ea5daeb]491                instantiations.endScope();
[3bb195cb]492                dtypeStatics.endScope();
[ea5daeb]493        }
494
[b95fe40]495        template< typename AggrInst >
496        Expression * FixDtypeStatic::fixMemberExpr( AggrInst * inst, MemberExpr * memberExpr ) {
497                // need to cast dtype-static member expressions to their actual type before that type is erased.
[27aca84]498                // NOTE: the casts here have the third argument (isGenerated) set to false so that these casts persist until Box, where they are needed.
[b95fe40]499                auto & baseParams = *inst->get_baseParameters();
500                if ( isDtypeStatic( baseParams ) ) {
501                        if ( ! ResolvExpr::typesCompatible( memberExpr->result, memberExpr->member->get_type(), SymTab::Indexer() ) ) {
[1393df07]502                                // type of member and type of expression differ
503                                Type * concType = memberExpr->result->clone();
504                                if ( isLvalueArg ) {
505                                        // result must be C lvalue, so make a new reference variable with the correct actual type to replace the member expression
506                                        //   forall(dtype T)
507                                        //   struct Ptr {
508                                        //     T * x
509                                        //   };
510                                        //   Ptr(int) p;
511                                        //   int i;
512                                        //   p.x = &i;
513                                        // becomes
514                                        //   int *& _dtype_static_member_0 = (int **)&p.x;
515                                        //   _dtype_static_member_0 = &i;
516                                        // Note: this currently creates more temporaries than is strictly necessary, since it does not check for duplicate uses of the same member expression.
517                                        static UniqueName tmpNamer( "_dtype_static_member_" );
[27aca84]518                                        Expression * init = new CastExpr( new AddressExpr( memberExpr ), new PointerType( Type::Qualifiers(), concType->clone() ), false );
[1393df07]519                                        ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), new ReferenceType( Type::Qualifiers(), concType ), new SingleInit( init ) );
[ba3706f]520                                        stmtsToAddBefore.push_back( new DeclStmt( tmp ) );
[1393df07]521                                        return new VariableExpr( tmp );
522                                } else {
523                                        // can simply add a cast to actual type
[27aca84]524                                        return new CastExpr( memberExpr, concType, false );
[1393df07]525                                }
[b95fe40]526                        }
527                }
528                return memberExpr;
529        }
530
531        Expression * FixDtypeStatic::postmutate( MemberExpr * memberExpr ) {
532                Type * aggrType = memberExpr->aggregate->result;
533                if ( isGenericType( aggrType ) ) {
534                        if ( StructInstType * inst = dynamic_cast< StructInstType * >( aggrType ) ) {
535                                return fixMemberExpr( inst, memberExpr );
536                        } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( aggrType ) ) {
537                                return fixMemberExpr( inst, memberExpr );
538                        }
539                }
540                return memberExpr;
541        }
542
[1393df07]543        void FixDtypeStatic::premutate( ApplicationExpr * appExpr ) {
544                GuardValue( isLvalueArg );
545                isLvalueArg = false;
546                DeclarationWithType * function = InitTweak::getFunction( appExpr );
547                if ( function->linkage == LinkageSpec::Intrinsic && CodeGen::isAssignment( function->name ) ) {
548                        // explicitly visit children because only the first argument must be a C lvalue.
549                        visit_children = false;
550                        appExpr->env = maybeMutate( appExpr->env, *visitor );
551                        appExpr->result = maybeMutate( appExpr->result, *visitor );
552                        appExpr->function = maybeMutate( appExpr->function, *visitor );
553                        isLvalueArg = true;
554                        for ( Expression * arg : appExpr->args ) {
555                                arg = maybeMutate( arg, *visitor );
556                                isLvalueArg = false;
557                        }
558                }
559        }
560
561        void FixDtypeStatic::premutate( AddressExpr * ) {
562                // argument of & must be C lvalue
563                GuardValue( isLvalueArg );
564                isLvalueArg = true;
565        }
[ea5daeb]566} // namespace GenPoly
567
568// Local Variables: //
569// tab-width: 4 //
570// mode: c++ //
571// compile-command: "make install" //
572// End: //
Note: See TracBrowser for help on using the repository browser.