source: src/GenPoly/Specialize.cc@ 395fc37

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 395fc37 was 1fbab5a, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Merge branch 'master' of plg.uwaterloo.ca:/u/cforall/software/cfa/cfa-cc

  • Property mode set to 100644
File size: 13.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>
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 /// Generates a thunk that calls `actual` with type `funType` and returns its address
171 Expression * Specialize::createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ) {
172 static UniqueName thunkNamer( "_thunk" );
173
174 FunctionType *newType = funType->clone();
175 if ( env ) {
176 // it is important to replace only occurrences of type variables that occur free in the
177 // thunk's type
178 env->applyFree( newType );
179 } // if
180 // create new thunk with same signature as formal type (C linkage, empty body)
181 FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt( noLabels ) );
182 thunkFunc->fixUniqueId();
183
184 // thunks may be generated and not used - silence warning with attribute
185 thunkFunc->get_attributes().push_back( new Attribute( "unused" ) );
186
187 // thread thunk parameters into call to actual function, naming thunk parameters as we go
188 UniqueName paramNamer( paramPrefix );
189 ApplicationExpr *appExpr = new ApplicationExpr( actual );
190
191 FunctionType * actualType = getFunctionType( actual->get_result() )->clone();
192 if ( env ) {
193 // need to apply the environment to the actual function's type, since it may itself be polymorphic
194 env->apply( actualType );
195 }
196 std::unique_ptr< FunctionType > actualTypeManager( actualType ); // for RAII
197 std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin();
198 std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end();
199
200 std::list< Expression * > args;
201 for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) {
202 // name each thunk parameter and explode it - these are then threaded back into the actual function call.
203 param->set_name( paramNamer.newName() );
204 explodeSimple( new VariableExpr( param ), back_inserter( args ) );
205 }
206
207 // walk parameters to the actual function alongside the exploded thunk parameters and restructure the arguments to match the actual parameters.
208 std::list< Expression * >::iterator argBegin = args.begin(), argEnd = args.end();
209 for ( ; actualBegin != actualEnd; ++actualBegin ) {
210 structureArg( (*actualBegin)->get_type(), argBegin, argEnd, back_inserter( appExpr->get_args() ) );
211 }
212
213 appExpr->set_env( maybeClone( env ) );
214 if ( inferParams ) {
215 appExpr->get_inferParams() = *inferParams;
216 } // if
217
218 // handle any specializations that may still be present
219 std::string oldParamPrefix = paramPrefix;
220 paramPrefix += "p";
221 // save stmtsToAdd in oldStmts
222 std::list< Statement* > oldStmts;
223 oldStmts.splice( oldStmts.end(), stmtsToAdd );
224 mutate( appExpr );
225 paramPrefix = oldParamPrefix;
226 // write any statements added for recursive specializations into the thunk body
227 thunkFunc->get_statements()->get_kids().splice( thunkFunc->get_statements()->get_kids().end(), stmtsToAdd );
228 // restore oldStmts into stmtsToAdd
229 stmtsToAdd.splice( stmtsToAdd.end(), oldStmts );
230
231 // add return (or valueless expression) to the thunk
232 Statement *appStmt;
233 if ( funType->get_returnVals().empty() ) {
234 appStmt = new ExprStmt( noLabels, appExpr );
235 } else {
236 appStmt = new ReturnStmt( noLabels, appExpr );
237 } // if
238 thunkFunc->get_statements()->get_kids().push_back( appStmt );
239
240 // add thunk definition to queue of statements to add
241 stmtsToAdd.push_back( new DeclStmt( noLabels, thunkFunc ) );
242 // return address of thunk function as replacement expression
243 return new AddressExpr( new VariableExpr( thunkFunc ) );
244 }
245
246 void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) {
247 // create thunks for the explicit parameters
248 assert( appExpr->get_function()->has_result() );
249 FunctionType *function = getFunctionType( appExpr->get_function()->get_result() );
250 assert( function );
251 std::list< DeclarationWithType* >::iterator formal;
252 std::list< Expression* >::iterator actual;
253 for ( formal = function->get_parameters().begin(), actual = appExpr->get_args().begin(); formal != function->get_parameters().end() && actual != appExpr->get_args().end(); ++formal, ++actual ) {
254 *actual = doSpecialization( (*formal )->get_type(), *actual, &appExpr->get_inferParams() );
255 }
256 }
257
258 Expression * Specialize::mutate( ApplicationExpr *appExpr ) {
259 appExpr->get_function()->acceptMutator( *this );
260 mutateAll( appExpr->get_args(), *this );
261
262 if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) {
263 // create thunks for the inferred parameters
264 // don't need to do this for intrinsic calls, because they aren't actually passed
265 // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again)
266 // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams.
267 handleExplicitParams( appExpr );
268 for ( InferredParams::iterator inferParam = appExpr->get_inferParams().begin(); inferParam != appExpr->get_inferParams().end(); ++inferParam ) {
269 inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, inferParam->second.inferParams.get() );
270 }
271 }
272 return appExpr;
273 }
274
275 Expression * Specialize::mutate( AddressExpr *addrExpr ) {
276 addrExpr->get_arg()->acceptMutator( *this );
277 assert( addrExpr->has_result() );
278 addrExpr->set_arg( doSpecialization( addrExpr->get_result(), addrExpr->get_arg() ) );
279 return addrExpr;
280 }
281
282 Expression * Specialize::mutate( CastExpr *castExpr ) {
283 castExpr->get_arg()->acceptMutator( *this );
284 if ( castExpr->get_result()->isVoid() ) {
285 // can't specialize if we don't have a return value
286 return castExpr;
287 }
288 Expression *specialized = doSpecialization( castExpr->get_result(), castExpr->get_arg() );
289 if ( specialized != castExpr->get_arg() ) {
290 // assume here that the specialization incorporates the cast
291 return specialized;
292 } else {
293 return castExpr;
294 }
295 }
296
297 // Removing these for now. Richard put these in for some reason, but it's not clear why.
298 // In particular, copy constructors produce a comma expression, and with this code the parts
299 // of that comma expression are not specialized, which causes problems.
300
301 // Expression * Specialize::mutate( LogicalExpr *logicalExpr ) {
302 // return logicalExpr;
303 // }
304
305 // Expression * Specialize::mutate( ConditionalExpr *condExpr ) {
306 // return condExpr;
307 // }
308
309 // Expression * Specialize::mutate( CommaExpr *commaExpr ) {
310 // return commaExpr;
311 // }
312
313 void convertSpecializations( std::list< Declaration* >& translationUnit ) {
314 Specialize spec;
315 mutateAll( translationUnit, spec );
316 }
317} // namespace GenPoly
318
319// Local Variables: //
320// tab-width: 4 //
321// mode: c++ //
322// compile-command: "make install" //
323// End: //
Note: See TracBrowser for help on using the repository browser.