source: src/GenPoly/Specialize.cc @ 1a59641

new-env
Last change on this file since 1a59641 was 8d7bef2, checked in by Aaron Moss <a3moss@…>, 6 years ago

First compiling build of CFA-CC with GC

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