source: src/GenPoly/InstantiateGeneric.cc @ 84993ff2

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 84993ff2 was 9ff56e7, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Removed several new warnings

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