source: src/GenPoly/Specialize.cc @ af397ef8

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

trim type environment for specialized expressions

  • Property mode set to 100644
File size: 14.0 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 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// Specialize.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Mar 16 07:53:59 2017
13// Update Count     : 31
14//
15
16#include <cassert>
17
18#include "Specialize.h"
19#include "GenPoly.h"
20#include "PolyMutator.h"
21
22#include "Parser/ParseNode.h"
23
24#include "SynTree/Expression.h"
25#include "SynTree/Statement.h"
26#include "SynTree/Type.h"
27#include "SynTree/Attribute.h"
28#include "SynTree/TypeSubstitution.h"
29#include "SynTree/Mutator.h"
30#include "ResolvExpr/FindOpenVars.h"
31#include "Common/UniqueName.h"
32#include "Common/utility.h"
33#include "InitTweak/InitTweak.h"
34#include "Tuples/Tuples.h"
35
36namespace GenPoly {
37        class Specialize final : public PolyMutator {
38          public:
39                using PolyMutator::mutate;
40                virtual Expression * mutate( ApplicationExpr *applicationExpr ) override;
41                virtual Expression * mutate( AddressExpr *castExpr ) override;
42                virtual Expression * mutate( CastExpr *castExpr ) override;
43                // virtual Expression * mutate( LogicalExpr *logicalExpr );
44                // virtual Expression * mutate( ConditionalExpr *conditionalExpr );
45                // virtual Expression * mutate( CommaExpr *commaExpr );
46
47                void handleExplicitParams( ApplicationExpr *appExpr );
48                Expression * createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams );
49                Expression * doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams = nullptr );
50
51                std::string paramPrefix = "_p";
52        };
53
54        /// Looks up open variables in actual type, returning true if any of them are bound in the environment or formal type.
55        bool needsPolySpecialization( Type *formalType, Type *actualType, TypeSubstitution *env ) {
56                if ( env ) {
57                        using namespace ResolvExpr;
58                        OpenVarSet openVars, closedVars;
59                        AssertionSet need, have;
60                        findOpenVars( formalType, openVars, closedVars, need, have, false );
61                        findOpenVars( actualType, openVars, closedVars, need, have, true );
62                        for ( OpenVarSet::const_iterator openVar = openVars.begin(); openVar != openVars.end(); ++openVar ) {
63                                Type *boundType = env->lookup( openVar->first );
64                                if ( ! boundType ) continue;
65                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( boundType ) ) {
66                                        if ( closedVars.find( typeInst->get_name() ) == closedVars.end() ) {
67                                                return true;
68                                        } // if
69                                } else {
70                                        return true;
71                                } // if
72                        } // for
73                        return false;
74                } else {
75                        return false;
76                } // if
77        }
78
79        /// True if both types have the same structure, but not necessarily the same types.
80        /// That is, either both types are tuple types with the same size (recursively), or
81        /// both are not tuple types.
82        bool matchingTupleStructure( Type * t1, Type * t2 ) {
83                TupleType * tuple1 = dynamic_cast< TupleType * >( t1 );
84                TupleType * tuple2 = dynamic_cast< TupleType * >( t2 );
85                if ( tuple1 && tuple2 ) {
86                        if ( tuple1->size() != tuple2->size() ) return false;
87                        for ( auto types : group_iterate( tuple1->get_types(), tuple2->get_types() ) ) {
88                                if ( ! matchingTupleStructure( std::get<0>( types ), std::get<1>( types ) ) ) return false;
89                        }
90                        return true;
91                } else if ( ! tuple1 && ! tuple2 ) return true;
92                return false;
93        }
94
95        bool needsTupleSpecialization( Type *formalType, Type *actualType, TypeSubstitution *env ) {
96                // Needs tuple specialization if the structure of the formal type and actual type do not match.
97                // This is the case if the formal type has ttype polymorphism, or if the structure  of tuple types
98                // between the function do not match exactly.
99                if ( FunctionType * fftype = getFunctionType( formalType ) ) {
100                        if ( fftype->isTtype() ) return true;
101                        FunctionType * aftype = getFunctionType( actualType );
102                        assertf( aftype, "formal type is a function type, but actual type is not." );
103                        if ( fftype->get_parameters().size() != aftype->get_parameters().size() ) return true;
104                        for ( auto params : group_iterate( fftype->get_parameters(), aftype->get_parameters() ) ) {
105                                DeclarationWithType * formal = std::get<0>(params);
106                                DeclarationWithType * actual = std::get<1>(params);
107                                if ( ! matchingTupleStructure( formal->get_type(), actual->get_type() ) ) return true;
108                        }
109                }
110                return false;
111        }
112
113        bool needsSpecialization( Type *formalType, Type *actualType, TypeSubstitution *env ) {
114                return needsPolySpecialization( formalType, actualType, env ) || needsTupleSpecialization( formalType, actualType, env );
115        }
116
117        Expression * Specialize::doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ) {
118                assertf( actual->has_result(), "attempting to specialize an untyped expression" );
119                if ( needsSpecialization( formalType, actual->get_result(), env ) ) {
120                        if ( FunctionType *funType = getFunctionType( formalType ) ) {
121                                ApplicationExpr *appExpr;
122                                VariableExpr *varExpr;
123                                if ( ( appExpr = dynamic_cast<ApplicationExpr*>( actual ) ) ) {
124                                        return createThunkFunction( funType, appExpr->get_function(), inferParams );
125                                } else if ( ( varExpr = dynamic_cast<VariableExpr*>( actual ) ) ) {
126                                        return createThunkFunction( funType, varExpr, inferParams );
127                                } else {
128                                        // This likely won't work, as anything that could build an ApplicationExpr probably hit one of the previous two branches
129                                        return createThunkFunction( funType, actual, inferParams );
130                                }
131                        } else {
132                                return actual;
133                        } // if
134                } else {
135                        return actual;
136                } // if
137        }
138
139        /// restructures the arguments to match the structure of the formal parameters of the actual function.
140        /// [begin, end) are the exploded arguments.
141        template< typename Iterator, typename OutIterator >
142        void structureArg( Type * type, Iterator & begin, Iterator end, OutIterator out ) {
143                if ( TupleType * tuple = dynamic_cast< TupleType * >( type ) ) {
144                        std::list< Expression * > exprs;
145                        for ( Type * t : *tuple ) {
146                                structureArg( t, begin, end, back_inserter( exprs ) );
147                        }
148                        *out++ = new TupleExpr( exprs );
149                } else {
150                        assertf( begin != end, "reached the end of the arguments while structuring" );
151                        *out++ = *begin++;
152                }
153        }
154
155        /// explode assuming simple cases: either type is pure tuple (but not tuple expr) or type is non-tuple.
156        template< typename OutputIterator >
157        void explodeSimple( Expression * expr, OutputIterator out ) {
158                if ( TupleType * tupleType = dynamic_cast< TupleType * > ( expr->get_result() ) ) {
159                        // tuple type, recursively index into its components
160                        for ( unsigned int i = 0; i < tupleType->size(); i++ ) {
161                                explodeSimple( new TupleIndexExpr( expr->clone(), i ), out );
162                        }
163                        delete expr;
164                } else {
165                        // non-tuple type - output a clone of the expression
166                        *out++ = expr;
167                }
168        }
169
170        struct EnvTrimmer : public Visitor {
171                TypeSubstitution * env, * newEnv;
172                EnvTrimmer( TypeSubstitution * env, TypeSubstitution * newEnv ) : env( env ), newEnv( newEnv ){}
173                virtual void visit( TypeDecl * tyDecl ) {
174                        // transfer known bindings for seen type variables
175                        if ( Type * t = env->lookup( tyDecl->get_name() ) ) {
176                                newEnv->add( tyDecl->get_name(), t );
177                        }
178                }
179        };
180
181        /// reduce environment to just the parts that are referenced in a given expression
182        TypeSubstitution * trimEnv( ApplicationExpr * expr, TypeSubstitution * env ) {
183                if ( env ) {
184                        TypeSubstitution * newEnv = new TypeSubstitution();
185                        EnvTrimmer trimmer( env, newEnv );
186                        expr->accept( trimmer );
187                        return newEnv;
188                }
189                return nullptr;
190        }
191
192        /// Generates a thunk that calls `actual` with type `funType` and returns its address
193        Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) {
194                static UniqueName thunkNamer( "_thunk" );
195
196                FunctionType *newType = funType->clone();
197                if ( env ) {
198                        // it is important to replace only occurrences of type variables that occur free in the
199                        // thunk's type
200                        env->applyFree( newType );
201                } // if
202                // create new thunk with same signature as formal type (C linkage, empty body)
203                FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt( noLabels ) );
204                thunkFunc->fixUniqueId();
205
206                // thunks may be generated and not used - silence warning with attribute
207                thunkFunc->get_attributes().push_back( new Attribute( "unused" ) );
208
209                // thread thunk parameters into call to actual function, naming thunk parameters as we go
210                UniqueName paramNamer( paramPrefix );
211                ApplicationExpr *appExpr = new ApplicationExpr( actual );
212
213                FunctionType * actualType = getFunctionType( actual->get_result() )->clone();
214                if ( env ) {
215                        // need to apply the environment to the actual function's type, since it may itself be polymorphic
216                        env->apply( actualType );
217                }
218                std::unique_ptr< FunctionType > actualTypeManager( actualType ); // for RAII
219                std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin();
220                std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end();
221
222                std::list< Expression * > args;
223                for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) {
224                        // name each thunk parameter and explode it - these are then threaded back into the actual function call.
225                        param->set_name( paramNamer.newName() );
226                        explodeSimple( new VariableExpr( param ), back_inserter( args ) );
227                }
228
229                // walk parameters to the actual function alongside the exploded thunk parameters and restructure the arguments to match the actual parameters.
230                std::list< Expression * >::iterator argBegin = args.begin(), argEnd = args.end();
231                for ( ; actualBegin != actualEnd; ++actualBegin ) {
232                        structureArg( (*actualBegin)->get_type(), argBegin, argEnd, back_inserter( appExpr->get_args() ) );
233                }
234
235                appExpr->set_env( trimEnv( appExpr, env ) );
236                if ( inferParams ) {
237                        appExpr->get_inferParams() = *inferParams;
238                } // if
239
240                // handle any specializations that may still be present
241                std::string oldParamPrefix = paramPrefix;
242                paramPrefix += "p";
243                // save stmtsToAdd in oldStmts
244                std::list< Statement* > oldStmts;
245                oldStmts.splice( oldStmts.end(), stmtsToAdd );
246                mutate( appExpr );
247                paramPrefix = oldParamPrefix;
248                // write any statements added for recursive specializations into the thunk body
249                thunkFunc->get_statements()->get_kids().splice( thunkFunc->get_statements()->get_kids().end(), stmtsToAdd );
250                // restore oldStmts into stmtsToAdd
251                stmtsToAdd.splice( stmtsToAdd.end(), oldStmts );
252
253                // add return (or valueless expression) to the thunk
254                Statement *appStmt;
255                if ( funType->get_returnVals().empty() ) {
256                        appStmt = new ExprStmt( noLabels, appExpr );
257                } else {
258                        appStmt = new ReturnStmt( noLabels, appExpr );
259                } // if
260                thunkFunc->get_statements()->get_kids().push_back( appStmt );
261
262                // add thunk definition to queue of statements to add
263                stmtsToAdd.push_back( new DeclStmt( noLabels, thunkFunc ) );
264                // return address of thunk function as replacement expression
265                return new AddressExpr( new VariableExpr( thunkFunc ) );
266        }
267
268        void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) {
269                // create thunks for the explicit parameters
270                assert( appExpr->get_function()->has_result() );
271                FunctionType *function = getFunctionType( appExpr->get_function()->get_result() );
272                assert( function );
273                std::list< DeclarationWithType* >::iterator formal;
274                std::list< Expression* >::iterator actual;
275                for ( formal = function->get_parameters().begin(), actual = appExpr->get_args().begin(); formal != function->get_parameters().end() && actual != appExpr->get_args().end(); ++formal, ++actual ) {
276                        *actual = doSpecialization( (*formal )->get_type(), *actual, &appExpr->get_inferParams() );
277                }
278        }
279
280        Expression * Specialize::mutate( ApplicationExpr *appExpr ) {
281                appExpr->get_function()->acceptMutator( *this );
282                mutateAll( appExpr->get_args(), *this );
283
284                if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) {
285                        // create thunks for the inferred parameters
286                        // don't need to do this for intrinsic calls, because they aren't actually passed
287                        // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again)
288                        // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams.
289                        handleExplicitParams( appExpr );
290                        for ( InferredParams::iterator inferParam = appExpr->get_inferParams().begin(); inferParam != appExpr->get_inferParams().end(); ++inferParam ) {
291                                inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, inferParam->second.inferParams.get() );
292                        }
293                }
294                return appExpr;
295        }
296
297        Expression * Specialize::mutate( AddressExpr *addrExpr ) {
298                addrExpr->get_arg()->acceptMutator( *this );
299                assert( addrExpr->has_result() );
300                addrExpr->set_arg( doSpecialization( addrExpr->get_result(), addrExpr->get_arg() ) );
301                return addrExpr;
302        }
303
304        Expression * Specialize::mutate( CastExpr *castExpr ) {
305                castExpr->get_arg()->acceptMutator( *this );
306                if ( castExpr->get_result()->isVoid() ) {
307                        // can't specialize if we don't have a return value
308                        return castExpr;
309                }
310                Expression *specialized = doSpecialization( castExpr->get_result(), castExpr->get_arg() );
311                if ( specialized != castExpr->get_arg() ) {
312                        // assume here that the specialization incorporates the cast
313                        return specialized;
314                } else {
315                        return castExpr;
316                }
317        }
318
319        // Removing these for now. Richard put these in for some reason, but it's not clear why.
320        // In particular, copy constructors produce a comma expression, and with this code the parts
321        // of that comma expression are not specialized, which causes problems.
322
323        // Expression * Specialize::mutate( LogicalExpr *logicalExpr ) {
324        //      return logicalExpr;
325        // }
326
327        // Expression * Specialize::mutate( ConditionalExpr *condExpr ) {
328        //      return condExpr;
329        // }
330
331        // Expression * Specialize::mutate( CommaExpr *commaExpr ) {
332        //      return commaExpr;
333        // }
334
335        void convertSpecializations( std::list< Declaration* >& translationUnit ) {
336                Specialize spec;
337                mutateAll( translationUnit, spec );
338        }
339} // namespace GenPoly
340
341// Local Variables: //
342// tab-width: 4 //
343// mode: c++ //
344// compile-command: "make install" //
345// End: //
Note: See TracBrowser for help on using the repository browser.