source: src/GenPoly/Specialize.cc@ be9288a

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 be9288a was 08fc48f, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Big header cleaning pass - commit 1

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