source: src/GenPoly/InstantiateGeneric.cc @ 0e7ea335

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 0e7ea335 was 87c3bef, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fix bug with generated structs for pointer-to-polymorphic types

  • Property mode set to 100644
File size: 17.6 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>
18#include <utility>
19#include <vector>
[b940dc71]20#include <unordered_map>
[ea5daeb]21
22#include "InstantiateGeneric.h"
23
24#include "DeclMutator.h"
25#include "GenPoly.h"
[3bb195cb]26#include "ScopedSet.h"
[b940dc71]27#include "PolyMutator.h"
[ea5daeb]28
29#include "ResolvExpr/typeops.h"
30
31#include "SynTree/Declaration.h"
32#include "SynTree/Expression.h"
33#include "SynTree/Type.h"
34
[e491159]35#include "Common/ScopedMap.h"
[ea5daeb]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        };
[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
229                                int pointerLevels = 0;
230                                if ( hasPolyBase( paramType->get_type(), &pointerLevels ) && pointerLevels > 0 ) {
231                                        // Make a void* with equivalent nesting
232                                        Type* voidPtr = new VoidType( Type::Qualifiers() );
233                                        while ( pointerLevels > 0 ) {
234                                                // Just about data layout, so qualifiers *shouldn't* matter
235                                                voidPtr = new PointerType( Type::Qualifiers(), voidPtr );
236                                                --pointerLevels;
237                                        }
238                                        out.push_back( new TypeExpr( voidPtr ) );
239                                } else {
240                                        // Just clone parameter type
241                                        out.push_back( paramType->clone() );
242                                }
243                                // make the struct concrete or dynamic depending on the parameter
[ea5daeb]244                                gt |= isPolyType( paramType->get_type() ) ? genericType::dynamic : genericType::concrete;
[0bfaf80]245                        } else switch ( (*baseParam)->get_kind() ) {
246                                case TypeDecl::Dtype:
247                                        // can pretend that any incomplete dtype is `void`
248                                        out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
249                                        break;
250                                case TypeDecl::Ftype:
251                                        // can pretend that any ftype is `void (*)(void)`
252                                        out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
253                                        break;
254                                case TypeDecl::Ttype:
255                                        assertf( false, "Ttype parameters are not currently allowed as parameters to generic types." );
256                                        break;
257                                case TypeDecl::Any:
258                                        assertf( false, "otype parameters handled by baseParam->isComplete()." );
259                                        break;
[ea5daeb]260                        }
261                }
262
263                assert( baseParam == baseParams.end() && param == params.end() && "Type parameters should match type variables" );
264                return gt;
265        }
266
267        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
268        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
269                                                        std::list< Declaration* >& out ) {
270                // substitute types into new members
271                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
272                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
273                        Declaration *newMember = (*member)->clone();
274                        subs.apply(newMember);
275                        out.push_back( newMember );
276                }
277        }
278
[3bb195cb]279        /// Substitutes types of members according to baseParams => typeSubs, working in-place
280        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
281                // substitute types into new members
282                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
283                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
284                        subs.apply(*member);
285                }
286        }
287
[f18a711]288        /// Strips the instances's type parameters
289        void stripInstParams( ReferenceToType *inst ) {
[3bb195cb]290                deleteAll( inst->get_parameters() );
291                inst->get_parameters().clear();
292        }
[e491159]293
[3bb195cb]294        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
295                substituteMembers( base->get_members(), baseParams, typeSubs );
296
297                deleteAll( baseParams );
298                baseParams.clear();
[e491159]299
[3bb195cb]300                dtypeStatics.insert( base );
301        }
302
[b940dc71]303        /// xxx - more or less copied from box -- these should be merged with those somehow...
304        void GenericInstantiator::replaceParametersWithConcrete( std::list< Expression* >& params ) {
305                for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
306                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
307                        assertf(paramType, "Aggregate parameters should be type expressions");
308                        paramType->set_type( replaceWithConcrete( paramType->get_type(), false ) );
309                }
310        }
311
312        Type *GenericInstantiator::replaceWithConcrete( Type *type, bool doClone ) {
313                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
314                        if ( envMap.count( typeInst ) ) {
315                                TypeSubstitution * env = envMap.at( typeInst );
316                                Type *concrete = env->lookup( typeInst->get_name() );
317                                if ( concrete ) {
318                                        return concrete->clone();
319                                }
320                                else return typeInst->clone();
321                        }
322                } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
323                        if ( doClone ) {
324                                structType = structType->clone();
325                        }
326                        replaceParametersWithConcrete( structType->get_parameters() );
327                        return structType;
328                } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
329                        if ( doClone ) {
330                                unionType = unionType->clone();
331                        }
332                        replaceParametersWithConcrete( unionType->get_parameters() );
333                        return unionType;
334                }
335                return type;
336        }
337
338
[ea5daeb]339        Type* GenericInstantiator::mutate( StructInstType *inst ) {
340                // mutate subtypes
341                Type *mutated = Mutator::mutate( inst );
342                inst = dynamic_cast< StructInstType* >( mutated );
343                if ( ! inst ) return mutated;
344
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() );
[ea5daeb]374                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs,        concDecl->get_members() );
375                                DeclMutator::addDeclaration( concDecl );
376                                insert( inst, typeSubs, concDecl );
377                        }
378                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
379                        newInst->set_baseStruct( concDecl );
380
381                        delete inst;
382                        inst = newInst;
383                        break;
384                }
385
386                case genericType::dynamic:
387                        // do nothing
388                        break;
389                }
390
391                deleteAll( typeSubs );
392                return inst;
393        }
394
395        Type* GenericInstantiator::mutate( UnionInstType *inst ) {
396                // mutate subtypes
397                Type *mutated = Mutator::mutate( inst );
398                inst = dynamic_cast< UnionInstType* >( mutated );
399                if ( ! inst ) return mutated;
400
401                // exit early if no need for further mutation
402                if ( inst->get_parameters().empty() ) return inst;
[3bb195cb]403
404                // check for an already-instantiatiated dtype-static type
[f18a711]405                if ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
406                        stripInstParams( inst );
407                        return inst;
408                }
[ea5daeb]409
410                // check if type can be concretely instantiated; put substitutions into typeSubs
[3bb195cb]411                assert( inst->get_baseParameters() && "Base union has parameters" );
[ea5daeb]412                std::list< TypeExpr* > typeSubs;
413                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
414                switch ( gt ) {
[3bb195cb]415                case genericType::dtypeStatic:
416                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
[f18a711]417                        stripInstParams( inst );
[3bb195cb]418                        break;
[e491159]419
[ea5daeb]420                case genericType::concrete:
421                {
422                        // make concrete instantiation of generic type
423                        UnionDecl *concDecl = lookup( inst, typeSubs );
424                        if ( ! concDecl ) {
425                                // set concDecl to new type, insert type declaration into statements to add
426                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
[2c57025]427                                concDecl->set_body( inst->get_baseUnion()->has_body() );
[ea5daeb]428                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
429                                DeclMutator::addDeclaration( concDecl );
430                                insert( inst, typeSubs, concDecl );
431                        }
432                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
433                        newInst->set_baseUnion( concDecl );
434
435                        delete inst;
436                        inst = newInst;
437                        break;
438                }
439                case genericType::dynamic:
440                        // do nothing
441                        break;
442                }
443
444                deleteAll( typeSubs );
445                return inst;
446        }
447
448        void GenericInstantiator::doBeginScope() {
449                DeclMutator::doBeginScope();
450                instantiations.beginScope();
[3bb195cb]451                dtypeStatics.beginScope();
[ea5daeb]452        }
453
454        void GenericInstantiator::doEndScope() {
455                DeclMutator::doEndScope();
456                instantiations.endScope();
[3bb195cb]457                dtypeStatics.endScope();
[ea5daeb]458        }
459
460} // namespace GenPoly
461
462// Local Variables: //
463// tab-width: 4 //
464// mode: c++ //
465// compile-command: "make install" //
466// End: //
Note: See TracBrowser for help on using the repository browser.