source: src/GenPoly/InstantiateGeneric.cc @ 5a3ac84

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 5a3ac84 was 5a3ac84, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fixed Box(T*) generic instantiation bug

  • Property mode set to 100644
File size: 17.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
16#include <cassert>
17#include <list>
[5a3ac84]18#include <unordered_map>
[ea5daeb]19#include <utility>
20#include <vector>
21
22#include "InstantiateGeneric.h"
23
24#include "DeclMutator.h"
25#include "GenPoly.h"
[3bb195cb]26#include "ScopedSet.h"
[5a3ac84]27#include "ScrubTyVars.h"
[b940dc71]28#include "PolyMutator.h"
[ea5daeb]29
30#include "ResolvExpr/typeops.h"
31
32#include "SynTree/Declaration.h"
33#include "SynTree/Expression.h"
34#include "SynTree/Type.h"
35
[e491159]36#include "Common/ScopedMap.h"
[ea5daeb]37#include "Common/UniqueName.h"
38#include "Common/utility.h"
39
40namespace GenPoly {
41
42        /// Abstracts type equality for a list of parameter types
43        struct TypeList {
44                TypeList() : params() {}
45                TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
46                TypeList( std::list< Type* > &&_params ) : params( _params ) {}
47
48                TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
49                TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
50
51                /// Extracts types from a list of TypeExpr*
52                TypeList( const std::list< TypeExpr* >& _params ) : params() {
53                        for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
54                                params.push_back( (*param)->get_type()->clone() );
55                        }
56                }
57
58                TypeList& operator= ( const TypeList &that ) {
59                        deleteAll( params );
60
61                        params.clear();
62                        cloneAll( that.params, params );
63
64                        return *this;
65                }
66
67                TypeList& operator= ( TypeList &&that ) {
68                        deleteAll( params );
69
70                        params = std::move( that.params );
71
72                        return *this;
73                }
74
75                ~TypeList() { deleteAll( params ); }
76
77                bool operator== ( const TypeList& that ) const {
78                        if ( params.size() != that.params.size() ) return false;
79
80                        for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
[5a3ac84]81                                if ( ! typesPolyCompatible( *it, *jt ) ) return false;
[ea5daeb]82                        }
83                        return true;
84                }
85
86                std::list< Type* > params;  ///< Instantiation parameters
87        };
[e491159]88
[ea5daeb]89        /// Maps a key and a TypeList to the some value, accounting for scope
90        template< typename Key, typename Value >
91        class InstantiationMap {
92                /// Wraps value for a specific (Key, TypeList) combination
93                typedef std::pair< TypeList, Value* > Instantiation;
94                /// List of TypeLists paired with their appropriate values
95                typedef std::vector< Instantiation > ValueList;
96                /// Underlying map type; maps keys to a linear list of corresponding TypeLists and values
97                typedef ScopedMap< Key*, ValueList > InnerMap;
98
99                InnerMap instantiations;  ///< instantiations
100
101        public:
102                /// Starts a new scope
103                void beginScope() { instantiations.beginScope(); }
104
105                /// Ends a scope
106                void endScope() { instantiations.endScope(); }
107
108                /// Gets the value for the (key, typeList) pair, returns NULL on none such.
109                Value *lookup( Key *key, const std::list< TypeExpr* >& params ) const {
110                        TypeList typeList( params );
111
112                        // scan scopes for matches to the key
113                        for ( typename InnerMap::const_iterator insts = instantiations.find( key ); insts != instantiations.end(); insts = instantiations.findNext( insts, key ) ) {
114                                for ( typename ValueList::const_reverse_iterator inst = insts->second.rbegin(); inst != insts->second.rend(); ++inst ) {
115                                        if ( inst->first == typeList ) return inst->second;
116                                }
117                        }
118                        // no matching instantiations found
119                        return 0;
120                }
121
122                /// Adds a value for a (key, typeList) pair to the current scope
123                void insert( Key *key, const std::list< TypeExpr* > &params, Value *value ) {
[e58dfb9]124                        auto it = instantiations.findAt( instantiations.currentScope(), key );
125                        if ( it == instantiations.end() ) {
126                                instantiations.insert( key, ValueList{ Instantiation{ TypeList( params ), value } } );
127                        } else {
128                                it->second.push_back( Instantiation{ TypeList( params ), value } );
129                        }
[ea5daeb]130                }
131        };
[3bb195cb]132
133        /// Possible options for a given specialization of a generic type
134        enum class genericType {
135                dtypeStatic,  ///< Concrete instantiation based solely on {d,f}type-to-void conversions
136                concrete,     ///< Concrete instantiation requiring at least one parameter type
137                dynamic       ///< No concrete instantiation
138        };
139
140        genericType& operator |= ( genericType& gt, const genericType& ht ) {
141                switch ( gt ) {
142                case genericType::dtypeStatic:
143                        gt = ht;
144                        break;
145                case genericType::concrete:
146                        if ( ht == genericType::dynamic ) { gt = genericType::dynamic; }
147                        break;
148                case genericType::dynamic:
149                        // nothing possible
150                        break;
151                }
152                return gt;
153        }
[e491159]154
[b940dc71]155        // collect the environments of each TypeInstType so that type variables can be replaced
156        // xxx - possibly temporary solution. Access to type environments is required in GenericInstantiator, but it needs to be a DeclMutator which does not provide easy access to the type environments.
157        class EnvFinder final : public GenPoly::PolyMutator {
158        public:
[075734f]159                using GenPoly::PolyMutator::mutate;
[b940dc71]160                virtual Type * mutate( TypeInstType * inst ) override {
161                        if ( env ) envMap[inst] = env;
162                        return inst;
163                }
164
165                // don't want to associate an environment with TypeInstTypes that occur in function types - this may actually only apply to function types belonging to DeclarationWithTypes (or even just FunctionDecl)?
166                virtual Type * mutate( FunctionType * ftype ) override {
167                        return ftype;
168                }
169                std::unordered_map< ReferenceToType *, TypeSubstitution * > envMap;
170        };
171
[ea5daeb]172        /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
[62e5546]173        class GenericInstantiator final : public DeclMutator {
[ea5daeb]174                /// Map of (generic type, parameter list) pairs to concrete type instantiations
175                InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
[3bb195cb]176                /// Set of types which are dtype-only generic (and therefore have static layout)
177                ScopedSet< AggregateDecl* > dtypeStatics;
[ea5daeb]178                /// Namer for concrete types
179                UniqueName typeNamer;
[b940dc71]180                /// Reference to mapping of environments
181                const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap;
[ea5daeb]182        public:
[b940dc71]183                GenericInstantiator( const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap ) : DeclMutator(), instantiations(), dtypeStatics(), typeNamer("_conc_"), envMap( envMap ) {}
[ea5daeb]184
[62e5546]185                using DeclMutator::mutate;
186                virtual Type* mutate( StructInstType *inst ) override;
187                virtual Type* mutate( UnionInstType *inst ) override;
[ea5daeb]188
[62e5546]189                virtual void doBeginScope() override;
190                virtual void doEndScope() override;
[ea5daeb]191        private:
192                /// Wrap instantiation lookup for structs
193                StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
194                /// Wrap instantiation lookup for unions
195                UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
196                /// Wrap instantiation insertion for structs
197                void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
198                /// Wrap instantiation insertion for unions
199                void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
[3bb195cb]200
[b940dc71]201                void replaceParametersWithConcrete( std::list< Expression* >& params );
202                Type *replaceWithConcrete( Type *type, bool doClone );
203
[3bb195cb]204                /// Strips a dtype-static aggregate decl of its type parameters, marks it as stripped
205                void stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs );
[ea5daeb]206        };
207
208        void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
[b940dc71]209                EnvFinder finder;
210                mutateAll( translationUnit, finder );
211                GenericInstantiator instantiator( finder.envMap );
[ea5daeb]212                instantiator.mutateDeclarationList( translationUnit );
213        }
214
[3bb195cb]215        /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
216        /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
[ea5daeb]217        genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
218                genericType gt = genericType::dtypeStatic;
219
220                // substitute concrete types for given parameters, and incomplete types for placeholders
221                std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
222                std::list< Expression* >::const_iterator param = params.begin();
223                for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
224                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
225                        assert(paramType && "Aggregate parameters should be type expressions");
[e491159]226
[0bfaf80]227                        if ( (*baseParam)->isComplete() ) {
[87c3bef]228                                // substitute parameter for complete (otype or sized dtype) type
[5a3ac84]229                                if ( isPolyType( paramType->get_type() ) ) {
230                                        // substitute polymorphic parameter type in to generic type
[87c3bef]231                                        out.push_back( paramType->clone() );
[5a3ac84]232                                        gt = genericType::dynamic;
233                                } else {
234                                        // normalize possibly dtype-static parameter type
235                                        out.push_back( new TypeExpr{ 
236                                                ScrubTyVars::scrubAll( paramType->get_type()->clone() ) } );
237                                        gt |= genericType::concrete;
[87c3bef]238                                }
[0bfaf80]239                        } else switch ( (*baseParam)->get_kind() ) {
240                                case TypeDecl::Dtype:
241                                        // can pretend that any incomplete dtype is `void`
242                                        out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
243                                        break;
244                                case TypeDecl::Ftype:
245                                        // can pretend that any ftype is `void (*)(void)`
246                                        out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
247                                        break;
248                                case TypeDecl::Ttype:
249                                        assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
250                                        break;
251                                case TypeDecl::Any:
252                                        assertf( false, "otype parameters handled by baseParam->isComplete()." );
253                                        break;
[ea5daeb]254                        }
255                }
256
257                assert( baseParam == baseParams.end() && param == params.end() && "Type parameters should match type variables" );
258                return gt;
259        }
260
261        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
262        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
263                                                        std::list< Declaration* >& out ) {
264                // substitute types into new members
265                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
266                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
267                        Declaration *newMember = (*member)->clone();
268                        subs.apply(newMember);
269                        out.push_back( newMember );
270                }
271        }
272
[3bb195cb]273        /// Substitutes types of members according to baseParams => typeSubs, working in-place
274        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
275                // substitute types into new members
276                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
277                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
278                        subs.apply(*member);
279                }
280        }
281
[f18a711]282        /// Strips the instances's type parameters
283        void stripInstParams( ReferenceToType *inst ) {
[3bb195cb]284                deleteAll( inst->get_parameters() );
285                inst->get_parameters().clear();
286        }
[e491159]287
[3bb195cb]288        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
289                substituteMembers( base->get_members(), baseParams, typeSubs );
290
291                deleteAll( baseParams );
292                baseParams.clear();
[e491159]293
[3bb195cb]294                dtypeStatics.insert( base );
295        }
296
[b940dc71]297        /// xxx - more or less copied from box -- these should be merged with those somehow...
298        void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
299                for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
300                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
301                        assertf(paramType, "Aggregate parameters should be type expressions");
302                        paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
303                }
304        }
305
306        Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
307                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
308                        if ( envMap.count( typeInst ) ) {
309                                TypeSubstitution * env = envMap.at( typeInst );
310                                Type *concrete = env->lookup( typeInst->get_name() );
311                                if ( concrete ) {
312                                        return concrete->clone();
313                                }
314                                else return typeInst->clone();
315                        }
316                } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
317                        if ( doClone ) {
318                                structType = structType->clone();
319                        }
320                        replaceParametersWithConcrete( structType->get_parameters() );
321                        return structType;
322                } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
323                        if ( doClone ) {
324                                unionType = unionType->clone();
325                        }
326                        replaceParametersWithConcrete( unionType->get_parameters() );
327                        return unionType;
328                }
329                return type;
330        }
331
332
[ea5daeb]333        Type* GenericInstantiator::mutate( StructInstType *inst ) {
334                // mutate subtypes
335                Type *mutated = Mutator::mutate( inst );
336                inst = dynamic_cast< StructInstType* >( mutated );
337                if ( ! inst ) return mutated;
338
339                // exit early if no need for further mutation
340                if ( inst->get_parameters().empty() ) return inst;
341
[b940dc71]342                // 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).
343                replaceWithConcrete( inst, false );
344
[3bb195cb]345                // check for an already-instantiatiated dtype-static type
[f18a711]346                if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
347                        stripInstParams( inst );
348                        return inst;
349                }
[e491159]350
[ea5daeb]351                // check if type can be concretely instantiated; put substitutions into typeSubs
[b940dc71]352                assertf( inst->get_baseParameters(), "Base struct has parameters" );
[ea5daeb]353                std::list< TypeExpr* > typeSubs;
354                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
355                switch ( gt ) {
[3bb195cb]356                case genericType::dtypeStatic:
357                        stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
[f18a711]358                        stripInstParams( inst );
[3bb195cb]359                        break;
[e491159]360
[3bb195cb]361                case genericType::concrete: {
[ea5daeb]362                        // make concrete instantiation of generic type
363                        StructDecl *concDecl = lookup( inst, typeSubs );
364                        if ( ! concDecl ) {
365                                // set concDecl to new type, insert type declaration into statements to add
366                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]367                                concDecl->set_body( inst->get_baseStruct()->has_body() );
[5a3ac84]368                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
[ea5daeb]369                                DeclMutator::addDeclaration( concDecl );
370                                insert( inst, typeSubs, concDecl );
371                        }
372                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
373                        newInst->set_baseStruct( concDecl );
374
375                        delete inst;
376                        inst = newInst;
377                        break;
378                }
379
380                case genericType::dynamic:
381                        // do nothing
382                        break;
383                }
384
385                deleteAll( typeSubs );
386                return inst;
387        }
388
389        Type* GenericInstantiator::mutate( UnionInstType *inst ) {
390                // mutate subtypes
391                Type *mutated = Mutator::mutate( inst );
392                inst = dynamic_cast< UnionInstType* >( mutated );
393                if ( ! inst ) return mutated;
394
395                // exit early if no need for further mutation
396                if ( inst->get_parameters().empty() ) return inst;
[3bb195cb]397
398                // check for an already-instantiatiated dtype-static type
[f18a711]399                if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
400                        stripInstParams( inst );
401                        return inst;
402                }
[ea5daeb]403
404                // check if type can be concretely instantiated; put substitutions into typeSubs
[3bb195cb]405                assert( inst->get_baseParameters() && "Base union has parameters" );
[ea5daeb]406                std::list< TypeExpr* > typeSubs;
407                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
408                switch ( gt ) {
[3bb195cb]409                case genericType::dtypeStatic:
410                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
[f18a711]411                        stripInstParams( inst );
[3bb195cb]412                        break;
[e491159]413
[ea5daeb]414                case genericType::concrete:
415                {
416                        // make concrete instantiation of generic type
417                        UnionDecl *concDecl = lookup( inst, typeSubs );
418                        if ( ! concDecl ) {
419                                // set concDecl to new type, insert type declaration into statements to add
420                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]421                                concDecl->set_body( inst->get_baseUnion()->has_body() );
[ea5daeb]422                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
423                                DeclMutator::addDeclaration( concDecl );
424                                insert( inst, typeSubs, concDecl );
425                        }
426                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
427                        newInst->set_baseUnion( concDecl );
428
429                        delete inst;
430                        inst = newInst;
431                        break;
432                }
433                case genericType::dynamic:
434                        // do nothing
435                        break;
436                }
437
438                deleteAll( typeSubs );
439                return inst;
440        }
441
442        void GenericInstantiator::doBeginScope() {
443                DeclMutator::doBeginScope();
444                instantiations.beginScope();
[3bb195cb]445                dtypeStatics.beginScope();
[ea5daeb]446        }
447
448        void GenericInstantiator::doEndScope() {
449                DeclMutator::doEndScope();
450                instantiations.endScope();
[3bb195cb]451                dtypeStatics.endScope();
[ea5daeb]452        }
453
454} // namespace GenPoly
455
456// Local Variables: //
457// tab-width: 4 //
458// mode: c++ //
459// compile-command: "make install" //
460// End: //
Note: See TracBrowser for help on using the repository browser.