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 | |
---|
36 | namespace 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 ) { |
---|
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 | // conversion of 0 (null) to function type does not require tuple specialization |
---|
102 | if ( dynamic_cast< ZeroType * >( actualType ) ) return false; |
---|
103 | FunctionType * aftype = getFunctionType( actualType->stripReferences() ); |
---|
104 | assertf( aftype, "formal type is a function type, but actual type is not: %s", toString( actualType ).c_str() ); |
---|
105 | if ( fftype->get_parameters().size() != aftype->get_parameters().size() ) return true; |
---|
106 | for ( auto params : group_iterate( fftype->get_parameters(), aftype->get_parameters() ) ) { |
---|
107 | DeclarationWithType * formal = std::get<0>(params); |
---|
108 | DeclarationWithType * actual = std::get<1>(params); |
---|
109 | if ( ! matchingTupleStructure( formal->get_type(), actual->get_type() ) ) return true; |
---|
110 | } |
---|
111 | } |
---|
112 | return false; |
---|
113 | } |
---|
114 | |
---|
115 | bool needsSpecialization( Type *formalType, Type *actualType, TypeSubstitution *env ) { |
---|
116 | return needsPolySpecialization( formalType, actualType, env ) || needsTupleSpecialization( formalType, actualType ); |
---|
117 | } |
---|
118 | |
---|
119 | Expression * Specialize::doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ) { |
---|
120 | assertf( actual->has_result(), "attempting to specialize an untyped expression" ); |
---|
121 | if ( needsSpecialization( formalType, actual->get_result(), env ) ) { |
---|
122 | if ( FunctionType *funType = getFunctionType( formalType ) ) { |
---|
123 | ApplicationExpr *appExpr; |
---|
124 | VariableExpr *varExpr; |
---|
125 | if ( ( appExpr = dynamic_cast<ApplicationExpr*>( actual ) ) ) { |
---|
126 | return createThunkFunction( funType, appExpr->get_function(), inferParams ); |
---|
127 | } else if ( ( varExpr = dynamic_cast<VariableExpr*>( actual ) ) ) { |
---|
128 | return createThunkFunction( funType, varExpr, inferParams ); |
---|
129 | } else { |
---|
130 | // This likely won't work, as anything that could build an ApplicationExpr probably hit one of the previous two branches |
---|
131 | return createThunkFunction( funType, actual, inferParams ); |
---|
132 | } |
---|
133 | } else { |
---|
134 | return actual; |
---|
135 | } // if |
---|
136 | } else { |
---|
137 | return actual; |
---|
138 | } // if |
---|
139 | } |
---|
140 | |
---|
141 | /// restructures the arguments to match the structure of the formal parameters of the actual function. |
---|
142 | /// [begin, end) are the exploded arguments. |
---|
143 | template< typename Iterator, typename OutIterator > |
---|
144 | void structureArg( Type * type, Iterator & begin, Iterator end, OutIterator out ) { |
---|
145 | if ( TupleType * tuple = dynamic_cast< TupleType * >( type ) ) { |
---|
146 | std::list< Expression * > exprs; |
---|
147 | for ( Type * t : *tuple ) { |
---|
148 | structureArg( t, begin, end, back_inserter( exprs ) ); |
---|
149 | } |
---|
150 | *out++ = new TupleExpr( exprs ); |
---|
151 | } else { |
---|
152 | assertf( begin != end, "reached the end of the arguments while structuring" ); |
---|
153 | *out++ = *begin++; |
---|
154 | } |
---|
155 | } |
---|
156 | |
---|
157 | /// explode assuming simple cases: either type is pure tuple (but not tuple expr) or type is non-tuple. |
---|
158 | template< typename OutputIterator > |
---|
159 | void explodeSimple( Expression * expr, OutputIterator out ) { |
---|
160 | if ( TupleType * tupleType = dynamic_cast< TupleType * > ( expr->get_result() ) ) { |
---|
161 | // tuple type, recursively index into its components |
---|
162 | for ( unsigned int i = 0; i < tupleType->size(); i++ ) { |
---|
163 | explodeSimple( new TupleIndexExpr( expr->clone(), i ), out ); |
---|
164 | } |
---|
165 | delete expr; |
---|
166 | } else { |
---|
167 | // non-tuple type - output a clone of the expression |
---|
168 | *out++ = expr; |
---|
169 | } |
---|
170 | } |
---|
171 | |
---|
172 | struct EnvTrimmer : public Visitor { |
---|
173 | TypeSubstitution * env, * newEnv; |
---|
174 | EnvTrimmer( TypeSubstitution * env, TypeSubstitution * newEnv ) : env( env ), newEnv( newEnv ){} |
---|
175 | virtual void visit( TypeDecl * tyDecl ) { |
---|
176 | // transfer known bindings for seen type variables |
---|
177 | if ( Type * t = env->lookup( tyDecl->get_name() ) ) { |
---|
178 | newEnv->add( tyDecl->get_name(), t ); |
---|
179 | } |
---|
180 | } |
---|
181 | }; |
---|
182 | |
---|
183 | /// reduce environment to just the parts that are referenced in a given expression |
---|
184 | TypeSubstitution * trimEnv( ApplicationExpr * expr, TypeSubstitution * env ) { |
---|
185 | if ( env ) { |
---|
186 | TypeSubstitution * newEnv = new TypeSubstitution(); |
---|
187 | EnvTrimmer trimmer( env, newEnv ); |
---|
188 | expr->accept( trimmer ); |
---|
189 | return newEnv; |
---|
190 | } |
---|
191 | return nullptr; |
---|
192 | } |
---|
193 | |
---|
194 | /// Generates a thunk that calls `actual` with type `funType` and returns its address |
---|
195 | Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) { |
---|
196 | static UniqueName thunkNamer( "_thunk" ); |
---|
197 | |
---|
198 | FunctionType *newType = funType->clone(); |
---|
199 | if ( env ) { |
---|
200 | // it is important to replace only occurrences of type variables that occur free in the |
---|
201 | // thunk's type |
---|
202 | env->applyFree( newType ); |
---|
203 | } // if |
---|
204 | // create new thunk with same signature as formal type (C linkage, empty body) |
---|
205 | FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt( noLabels ) ); |
---|
206 | thunkFunc->fixUniqueId(); |
---|
207 | |
---|
208 | // thunks may be generated and not used - silence warning with attribute |
---|
209 | thunkFunc->get_attributes().push_back( new Attribute( "unused" ) ); |
---|
210 | |
---|
211 | // thread thunk parameters into call to actual function, naming thunk parameters as we go |
---|
212 | UniqueName paramNamer( paramPrefix ); |
---|
213 | ApplicationExpr *appExpr = new ApplicationExpr( actual ); |
---|
214 | |
---|
215 | FunctionType * actualType = getFunctionType( actual->get_result() )->clone(); |
---|
216 | if ( env ) { |
---|
217 | // need to apply the environment to the actual function's type, since it may itself be polymorphic |
---|
218 | env->apply( actualType ); |
---|
219 | } |
---|
220 | std::unique_ptr< FunctionType > actualTypeManager( actualType ); // for RAII |
---|
221 | std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin(); |
---|
222 | std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end(); |
---|
223 | |
---|
224 | std::list< Expression * > args; |
---|
225 | for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) { |
---|
226 | // name each thunk parameter and explode it - these are then threaded back into the actual function call. |
---|
227 | param->set_name( paramNamer.newName() ); |
---|
228 | explodeSimple( new VariableExpr( param ), back_inserter( args ) ); |
---|
229 | } |
---|
230 | |
---|
231 | // walk parameters to the actual function alongside the exploded thunk parameters and restructure the arguments to match the actual parameters. |
---|
232 | std::list< Expression * >::iterator argBegin = args.begin(), argEnd = args.end(); |
---|
233 | for ( ; actualBegin != actualEnd; ++actualBegin ) { |
---|
234 | structureArg( (*actualBegin)->get_type(), argBegin, argEnd, back_inserter( appExpr->get_args() ) ); |
---|
235 | } |
---|
236 | |
---|
237 | appExpr->set_env( trimEnv( appExpr, env ) ); |
---|
238 | if ( inferParams ) { |
---|
239 | appExpr->get_inferParams() = *inferParams; |
---|
240 | } // if |
---|
241 | |
---|
242 | // handle any specializations that may still be present |
---|
243 | std::string oldParamPrefix = paramPrefix; |
---|
244 | paramPrefix += "p"; |
---|
245 | // save stmtsToAdd in oldStmts |
---|
246 | std::list< Statement* > oldStmts; |
---|
247 | oldStmts.splice( oldStmts.end(), stmtsToAdd ); |
---|
248 | mutate( appExpr ); |
---|
249 | paramPrefix = oldParamPrefix; |
---|
250 | // write any statements added for recursive specializations into the thunk body |
---|
251 | thunkFunc->get_statements()->get_kids().splice( thunkFunc->get_statements()->get_kids().end(), stmtsToAdd ); |
---|
252 | // restore oldStmts into stmtsToAdd |
---|
253 | stmtsToAdd.splice( stmtsToAdd.end(), oldStmts ); |
---|
254 | |
---|
255 | // add return (or valueless expression) to the thunk |
---|
256 | Statement *appStmt; |
---|
257 | if ( funType->get_returnVals().empty() ) { |
---|
258 | appStmt = new ExprStmt( noLabels, appExpr ); |
---|
259 | } else { |
---|
260 | appStmt = new ReturnStmt( noLabels, appExpr ); |
---|
261 | } // if |
---|
262 | thunkFunc->get_statements()->get_kids().push_back( appStmt ); |
---|
263 | |
---|
264 | // add thunk definition to queue of statements to add |
---|
265 | stmtsToAdd.push_back( new DeclStmt( noLabels, thunkFunc ) ); |
---|
266 | // return address of thunk function as replacement expression |
---|
267 | return new AddressExpr( new VariableExpr( thunkFunc ) ); |
---|
268 | } |
---|
269 | |
---|
270 | void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) { |
---|
271 | // create thunks for the explicit parameters |
---|
272 | assert( appExpr->get_function()->has_result() ); |
---|
273 | FunctionType *function = getFunctionType( appExpr->get_function()->get_result() ); |
---|
274 | assert( function ); |
---|
275 | std::list< DeclarationWithType* >::iterator formal; |
---|
276 | std::list< Expression* >::iterator actual; |
---|
277 | for ( formal = function->get_parameters().begin(), actual = appExpr->get_args().begin(); formal != function->get_parameters().end() && actual != appExpr->get_args().end(); ++formal, ++actual ) { |
---|
278 | *actual = doSpecialization( (*formal )->get_type(), *actual, &appExpr->get_inferParams() ); |
---|
279 | } |
---|
280 | } |
---|
281 | |
---|
282 | Expression * Specialize::mutate( ApplicationExpr *appExpr ) { |
---|
283 | appExpr->get_function()->acceptMutator( *this ); |
---|
284 | mutateAll( appExpr->get_args(), *this ); |
---|
285 | |
---|
286 | if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) { |
---|
287 | // create thunks for the inferred parameters |
---|
288 | // don't need to do this for intrinsic calls, because they aren't actually passed |
---|
289 | // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again) |
---|
290 | // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams. |
---|
291 | handleExplicitParams( appExpr ); |
---|
292 | for ( InferredParams::iterator inferParam = appExpr->get_inferParams().begin(); inferParam != appExpr->get_inferParams().end(); ++inferParam ) { |
---|
293 | inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, inferParam->second.inferParams.get() ); |
---|
294 | } |
---|
295 | } |
---|
296 | return appExpr; |
---|
297 | } |
---|
298 | |
---|
299 | Expression * Specialize::mutate( AddressExpr *addrExpr ) { |
---|
300 | addrExpr->get_arg()->acceptMutator( *this ); |
---|
301 | assert( addrExpr->has_result() ); |
---|
302 | addrExpr->set_arg( doSpecialization( addrExpr->get_result(), addrExpr->get_arg() ) ); |
---|
303 | return addrExpr; |
---|
304 | } |
---|
305 | |
---|
306 | Expression * Specialize::mutate( CastExpr *castExpr ) { |
---|
307 | castExpr->get_arg()->acceptMutator( *this ); |
---|
308 | if ( castExpr->get_result()->isVoid() ) { |
---|
309 | // can't specialize if we don't have a return value |
---|
310 | return castExpr; |
---|
311 | } |
---|
312 | Expression *specialized = doSpecialization( castExpr->get_result(), castExpr->get_arg() ); |
---|
313 | if ( specialized != castExpr->get_arg() ) { |
---|
314 | // assume here that the specialization incorporates the cast |
---|
315 | return specialized; |
---|
316 | } else { |
---|
317 | return castExpr; |
---|
318 | } |
---|
319 | } |
---|
320 | |
---|
321 | // Removing these for now. Richard put these in for some reason, but it's not clear why. |
---|
322 | // In particular, copy constructors produce a comma expression, and with this code the parts |
---|
323 | // of that comma expression are not specialized, which causes problems. |
---|
324 | |
---|
325 | // Expression * Specialize::mutate( LogicalExpr *logicalExpr ) { |
---|
326 | // return logicalExpr; |
---|
327 | // } |
---|
328 | |
---|
329 | // Expression * Specialize::mutate( ConditionalExpr *condExpr ) { |
---|
330 | // return condExpr; |
---|
331 | // } |
---|
332 | |
---|
333 | // Expression * Specialize::mutate( CommaExpr *commaExpr ) { |
---|
334 | // return commaExpr; |
---|
335 | // } |
---|
336 | |
---|
337 | void convertSpecializations( std::list< Declaration* >& translationUnit ) { |
---|
338 | Specialize spec; |
---|
339 | mutateAll( translationUnit, spec ); |
---|
340 | } |
---|
341 | } // namespace GenPoly |
---|
342 | |
---|
343 | // Local Variables: // |
---|
344 | // tab-width: 4 // |
---|
345 | // mode: c++ // |
---|
346 | // compile-command: "make install" // |
---|
347 | // End: // |
---|