source: src/GenPoly/InstantiateGeneric.cc @ 69d8a9a

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

Fix scoping bug with generic type instantiations (thanks Rob!)

  • Property mode set to 100644
File size: 17.1 KB
Line 
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>
18#include <utility>
19#include <vector>
20#include <unordered_map>
21
22#include "InstantiateGeneric.h"
23
24#include "DeclMutator.h"
25#include "GenPoly.h"
26#include "ScopedSet.h"
27#include "PolyMutator.h"
28
29#include "ResolvExpr/typeops.h"
30
31#include "SynTree/Declaration.h"
32#include "SynTree/Expression.h"
33#include "SynTree/Type.h"
34
35#include "Common/ScopedMap.h"
36#include "Common/UniqueName.h"
37#include "Common/utility.h"
38
39namespace GenPoly {
40
41        /// Abstracts type equality for a list of parameter types
42        struct TypeList {
43                TypeList() : params() {}
44                TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
45                TypeList( std::list< Type* > &&_params ) : params( _params ) {}
46
47                TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
48                TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
49
50                /// Extracts types from a list of TypeExpr*
51                TypeList( const std::list< TypeExpr* >& _params ) : params() {
52                        for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
53                                params.push_back( (*param)->get_type()->clone() );
54                        }
55                }
56
57                TypeList& operator= ( const TypeList &that ) {
58                        deleteAll( params );
59
60                        params.clear();
61                        cloneAll( that.params, params );
62
63                        return *this;
64                }
65
66                TypeList& operator= ( TypeList &&that ) {
67                        deleteAll( params );
68
69                        params = std::move( that.params );
70
71                        return *this;
72                }
73
74                ~TypeList() { deleteAll( params ); }
75
76                bool operator== ( const TypeList& that ) const {
77                        if ( params.size() != that.params.size() ) return false;
78
79                        SymTab::Indexer dummy;
80                        for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
81                                if ( ! ResolvExpr::typesCompatible( *it, *jt, dummy ) ) return false;
82                        }
83                        return true;
84                }
85
86                std::list< Type* > params;  ///< Instantiation parameters
87        };
88
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 ) {
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                        }
130                }
131        };
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        }
154
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:
159                using GenPoly::PolyMutator::mutate;
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
172        /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
173        class GenericInstantiator final : public DeclMutator {
174                /// Map of (generic type, parameter list) pairs to concrete type instantiations
175                InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
176                /// Set of types which are dtype-only generic (and therefore have static layout)
177                ScopedSet< AggregateDecl* > dtypeStatics;
178                /// Namer for concrete types
179                UniqueName typeNamer;
180                /// Reference to mapping of environments
181                const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap;
182        public:
183                GenericInstantiator( const std::unordered_map< ReferenceToType *, TypeSubstitution * > & envMap ) : DeclMutator(), instantiations(), dtypeStatics(), typeNamer("_conc_"), envMap( envMap ) {}
184
185                using DeclMutator::mutate;
186                virtual Type* mutate( StructInstType *inst ) override;
187                virtual Type* mutate( UnionInstType *inst ) override;
188
189                virtual void doBeginScope() override;
190                virtual void doEndScope() override;
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 ); }
200
201                void replaceParametersWithConcrete( std::list< Expression* >& params );
202                Type *replaceWithConcrete( Type *type, bool doClone );
203
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 );
206        };
207
208        void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
209                EnvFinder finder;
210                mutateAll( translationUnit, finder );
211                GenericInstantiator instantiator( finder.envMap );
212                instantiator.mutateDeclarationList( translationUnit );
213        }
214
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
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");
226
227                        if ( (*baseParam)->isComplete() ) {
228                                // substitute parameter for complete (otype or sized dtype) type; makes the struct concrete or dynamic depending on the parameter
229                                out.push_back( paramType->clone() );
230                                gt |= isPolyType( paramType->get_type() ) ? genericType::dynamic : genericType::concrete;
231                        } else switch ( (*baseParam)->get_kind() ) {
232                                case TypeDecl::Dtype:
233                                        // can pretend that any incomplete dtype is `void`
234                                        out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
235                                        break;
236                                case TypeDecl::Ftype:
237                                        // can pretend that any ftype is `void (*)(void)`
238                                        out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
239                                        break;
240                                case TypeDecl::Ttype:
241                                        assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
242                                        break;
243                                case TypeDecl::Any:
244                                        assertf( false, "otype parameters handled by baseParam->isComplete()." );
245                                        break;
246                        }
247                }
248
249                assert( baseParam == baseParams.end() && param == params.end() && "Type parameters should match type variables" );
250                return gt;
251        }
252
253        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
254        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
255                                                        std::list< Declaration* >& out ) {
256                // substitute types into new members
257                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
258                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
259                        Declaration *newMember = (*member)->clone();
260                        subs.apply(newMember);
261                        out.push_back( newMember );
262                }
263        }
264
265        /// Substitutes types of members according to baseParams => typeSubs, working in-place
266        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
267                // substitute types into new members
268                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
269                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
270                        subs.apply(*member);
271                }
272        }
273
274        /// Strips the instances's type parameters
275        void stripInstParams( ReferenceToType *inst ) {
276                deleteAll( inst->get_parameters() );
277                inst->get_parameters().clear();
278        }
279
280        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
281                substituteMembers( base->get_members(), baseParams, typeSubs );
282
283                deleteAll( baseParams );
284                baseParams.clear();
285
286                dtypeStatics.insert( base );
287        }
288
289        /// xxx - more or less copied from box -- these should be merged with those somehow...
290        void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
291                for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
292                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
293                        assertf(paramType, "Aggregate parameters should be type expressions");
294                        paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
295                }
296        }
297
298        Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
299                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
300                        if ( envMap.count( typeInst ) ) {
301                                TypeSubstitution * env = envMap.at( typeInst );
302                                Type *concrete = env->lookup( typeInst->get_name() );
303                                if ( concrete ) {
304                                        return concrete->clone();
305                                }
306                                else return typeInst->clone();
307                        }
308                } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
309                        if ( doClone ) {
310                                structType = structType->clone();
311                        }
312                        replaceParametersWithConcrete( structType->get_parameters() );
313                        return structType;
314                } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
315                        if ( doClone ) {
316                                unionType = unionType->clone();
317                        }
318                        replaceParametersWithConcrete( unionType->get_parameters() );
319                        return unionType;
320                }
321                return type;
322        }
323
324
325        Type* GenericInstantiator::mutate( StructInstType *inst ) {
326                // mutate subtypes
327                Type *mutated = Mutator::mutate( inst );
328                inst = dynamic_cast< StructInstType* >( mutated );
329                if ( ! inst ) return mutated;
330
331                // exit early if no need for further mutation
332                if ( inst->get_parameters().empty() ) return inst;
333
334                // 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).
335                replaceWithConcrete( inst, false );
336
337                // check for an already-instantiatiated dtype-static type
338                if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
339                        stripInstParams( inst );
340                        return inst;
341                }
342
343                // check if type can be concretely instantiated; put substitutions into typeSubs
344                assertf( inst->get_baseParameters(), "Base struct has parameters" );
345                std::list< TypeExpr* > typeSubs;
346                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
347                switch ( gt ) {
348                case genericType::dtypeStatic:
349                        stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
350                        stripInstParams( inst );
351                        break;
352
353                case genericType::concrete: {
354                        // make concrete instantiation of generic type
355                        StructDecl *concDecl = lookup( inst, typeSubs );
356                        if ( ! concDecl ) {
357                                // set concDecl to new type, insert type declaration into statements to add
358                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
359                                concDecl->set_body( inst->get_baseStruct()->has_body() );
360                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs,        concDecl->get_members() );
361                                DeclMutator::addDeclaration( concDecl );
362                                insert( inst, typeSubs, concDecl );
363                        }
364                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
365                        newInst->set_baseStruct( concDecl );
366
367                        delete inst;
368                        inst = newInst;
369                        break;
370                }
371
372                case genericType::dynamic:
373                        // do nothing
374                        break;
375                }
376
377                deleteAll( typeSubs );
378                return inst;
379        }
380
381        Type* GenericInstantiator::mutate( UnionInstType *inst ) {
382                // mutate subtypes
383                Type *mutated = Mutator::mutate( inst );
384                inst = dynamic_cast< UnionInstType* >( mutated );
385                if ( ! inst ) return mutated;
386
387                // exit early if no need for further mutation
388                if ( inst->get_parameters().empty() ) return inst;
389
390                // check for an already-instantiatiated dtype-static type
391                if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
392                        stripInstParams( inst );
393                        return inst;
394                }
395
396                // check if type can be concretely instantiated; put substitutions into typeSubs
397                assert( inst->get_baseParameters() && "Base union has parameters" );
398                std::list< TypeExpr* > typeSubs;
399                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
400                switch ( gt ) {
401                case genericType::dtypeStatic:
402                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
403                        stripInstParams( inst );
404                        break;
405
406                case genericType::concrete:
407                {
408                        // make concrete instantiation of generic type
409                        UnionDecl *concDecl = lookup( inst, typeSubs );
410                        if ( ! concDecl ) {
411                                // set concDecl to new type, insert type declaration into statements to add
412                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
413                                concDecl->set_body( inst->get_baseUnion()->has_body() );
414                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
415                                DeclMutator::addDeclaration( concDecl );
416                                insert( inst, typeSubs, concDecl );
417                        }
418                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
419                        newInst->set_baseUnion( concDecl );
420
421                        delete inst;
422                        inst = newInst;
423                        break;
424                }
425                case genericType::dynamic:
426                        // do nothing
427                        break;
428                }
429
430                deleteAll( typeSubs );
431                return inst;
432        }
433
434        void GenericInstantiator::doBeginScope() {
435                DeclMutator::doBeginScope();
436                instantiations.beginScope();
437                dtypeStatics.beginScope();
438        }
439
440        void GenericInstantiator::doEndScope() {
441                DeclMutator::doEndScope();
442                instantiations.endScope();
443                dtypeStatics.endScope();
444        }
445
446} // namespace GenPoly
447
448// Local Variables: //
449// tab-width: 4 //
450// mode: c++ //
451// compile-command: "make install" //
452// End: //
Note: See TracBrowser for help on using the repository browser.