source: src/GenPoly/InstantiateGeneric.cc @ 2c57025

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 2c57025 was 2c57025, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

add support for built-in sized trait which decouples size/alignment information from otype parameters, add test for sized trait

  • Property mode set to 100644
File size: 13.7 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 "ScopedSet.h"
26
27#include "ResolvExpr/typeops.h"
28
29#include "SynTree/Declaration.h"
30#include "SynTree/Expression.h"
31#include "SynTree/Type.h"
32
33#include "Common/ScopedMap.h"
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 final : 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                using DeclMutator::mutate;
161                virtual Type* mutate( StructInstType *inst ) override;
162                virtual Type* mutate( UnionInstType *inst ) override;
163
164                virtual void doBeginScope() override;
165                virtual void doEndScope() override;
166        private:
167                /// Wrap instantiation lookup for structs
168                StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
169                /// Wrap instantiation lookup for unions
170                UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
171                /// Wrap instantiation insertion for structs
172                void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
173                /// Wrap instantiation insertion for unions
174                void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
175
176                /// Strips a dtype-static aggregate decl of its type parameters, marks it as stripped
177                void stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs );
178        };
179
180        void instantiateGeneric( std::list< Declaration* > &translationUnit ) {
181                GenericInstantiator instantiator;
182                instantiator.mutateDeclarationList( translationUnit );
183        }
184
185        /// Makes substitutions of params into baseParams; returns dtypeStatic if there is a concrete instantiation based only on {d,f}type-to-void conversions,
186        /// concrete if there is a concrete instantiation requiring at least one parameter type, and dynamic if there is no concrete instantiation
187        genericType makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
188                genericType gt = genericType::dtypeStatic;
189
190                // substitute concrete types for given parameters, and incomplete types for placeholders
191                std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
192                std::list< Expression* >::const_iterator param = params.begin();
193                for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
194                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
195                        assert(paramType && "Aggregate parameters should be type expressions");
196
197                        switch ( (*baseParam)->get_kind() ) {
198                        case TypeDecl::Any: {
199                                // substitute parameter for otype; makes the type concrete or dynamic depending on the parameter
200                                out.push_back( paramType->clone() );
201                                gt |= isPolyType( paramType->get_type() ) ? genericType::dynamic : genericType::concrete;
202                                break;
203                        }
204                        case TypeDecl::Dtype:
205                                // can pretend that any dtype is `void`
206                                out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
207                                break;
208                        case TypeDecl::Ftype:
209                                // can pretend that any ftype is `void (*)(void)`
210                                out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
211                                break;
212                        }
213                }
214
215                assert( baseParam == baseParams.end() && param == params.end() && "Type parameters should match type variables" );
216                return gt;
217        }
218
219        /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
220        void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
221                                                        std::list< Declaration* >& out ) {
222                // substitute types into new members
223                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
224                for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
225                        Declaration *newMember = (*member)->clone();
226                        subs.apply(newMember);
227                        out.push_back( newMember );
228                }
229        }
230
231        /// Substitutes types of members according to baseParams => typeSubs, working in-place
232        void substituteMembers( std::list< Declaration* >& members, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
233                // substitute types into new members
234                TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
235                for ( std::list< Declaration* >::iterator member = members.begin(); member != members.end(); ++member ) {
236                        subs.apply(*member);
237                }
238        }
239
240        /// Strips the instances's type parameters
241        void stripInstParams( ReferenceToType *inst ) {
242                deleteAll( inst->get_parameters() );
243                inst->get_parameters().clear();
244        }
245
246        void GenericInstantiator::stripDtypeParams( AggregateDecl *base, std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs ) {
247                substituteMembers( base->get_members(), baseParams, typeSubs );
248
249                deleteAll( baseParams );
250                baseParams.clear();
251
252                dtypeStatics.insert( base );
253        }
254
255        Type* GenericInstantiator::mutate( StructInstType *inst ) {
256                // mutate subtypes
257                Type *mutated = Mutator::mutate( inst );
258                inst = dynamic_cast< StructInstType* >( mutated );
259                if ( ! inst ) return mutated;
260
261                // exit early if no need for further mutation
262                if ( inst->get_parameters().empty() ) return inst;
263
264                // check for an already-instantiatiated dtype-static type
265                if ( dtypeStatics.find( inst->get_baseStruct() ) != dtypeStatics.end() ) {
266                        stripInstParams( inst );
267                        return inst;
268                }
269
270                // check if type can be concretely instantiated; put substitutions into typeSubs
271                assert( inst->get_baseParameters() && "Base struct has parameters" );
272                std::list< TypeExpr* > typeSubs;
273                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
274                switch ( gt ) {
275                case genericType::dtypeStatic:
276                        stripDtypeParams( inst->get_baseStruct(), *inst->get_baseParameters(), typeSubs );
277                        stripInstParams( inst );
278                        break;
279
280                case genericType::concrete: {
281                        // make concrete instantiation of generic type
282                        StructDecl *concDecl = lookup( inst, typeSubs );
283                        if ( ! concDecl ) {
284                                // set concDecl to new type, insert type declaration into statements to add
285                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
286                                concDecl->set_body( inst->get_baseStruct()->has_body() );
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 ( dtypeStatics.find( inst->get_baseUnion() ) != dtypeStatics.end() ) {
319                        stripInstParams( inst );
320                        return inst;
321                }
322
323                // check if type can be concretely instantiated; put substitutions into typeSubs
324                assert( inst->get_baseParameters() && "Base union has parameters" );
325                std::list< TypeExpr* > typeSubs;
326                genericType gt = makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs );
327                switch ( gt ) {
328                case genericType::dtypeStatic:
329                        stripDtypeParams( inst->get_baseUnion(), *inst->get_baseParameters(), typeSubs );
330                        stripInstParams( inst );
331                        break;
332
333                case genericType::concrete:
334                {
335                        // make concrete instantiation of generic type
336                        UnionDecl *concDecl = lookup( inst, typeSubs );
337                        if ( ! concDecl ) {
338                                // set concDecl to new type, insert type declaration into statements to add
339                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
340                                concDecl->set_body( inst->get_baseUnion()->has_body() );
341                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
342                                DeclMutator::addDeclaration( concDecl );
343                                insert( inst, typeSubs, concDecl );
344                        }
345                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
346                        newInst->set_baseUnion( concDecl );
347
348                        delete inst;
349                        inst = newInst;
350                        break;
351                }
352                case genericType::dynamic:
353                        // do nothing
354                        break;
355                }
356
357                deleteAll( typeSubs );
358                return inst;
359        }
360
361        void GenericInstantiator::doBeginScope() {
362                DeclMutator::doBeginScope();
363                instantiations.beginScope();
364                dtypeStatics.beginScope();
365        }
366
367        void GenericInstantiator::doEndScope() {
368                DeclMutator::doEndScope();
369                instantiations.endScope();
370                dtypeStatics.endScope();
371        }
372
373} // namespace GenPoly
374
375// Local Variables: //
376// tab-width: 4 //
377// mode: c++ //
378// compile-command: "make install" //
379// End: //
Note: See TracBrowser for help on using the repository browser.