source: src/GenPoly/InstantiateGeneric.cc @ 3bb195cb

ADTaaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 3bb195cb was 3bb195cb, checked in by Aaron Moss <a3moss@…>, 7 years ago

Dtypes now erased on dtype-only generic types, tests pass, build produces many warnings

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