source: src/GenPoly/Specialize.cc @ cf90b88

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

Convert Specialize to PassVisitor?

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