[51587aa] | 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 | // |
---|
[f1e012b] | 7 | // Specialize.cc -- |
---|
[51587aa] | 8 | // |
---|
| 9 | // Author : Richard C. Bilson |
---|
| 10 | // Created On : Mon May 18 07:44:20 2015 |
---|
[dd020c0] | 11 | // Last Modified By : Peter A. Buhr |
---|
[68fe077a] | 12 | // Last Modified On : Thu Mar 16 07:53:59 2017 |
---|
| 13 | // Update Count : 31 |
---|
[51587aa] | 14 | // |
---|
[51b7345] | 15 | |
---|
[08fc48f] | 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 |
---|
[51b7345] | 23 | |
---|
[cf90b88] | 24 | #include "Common/PassVisitor.h" |
---|
[08fc48f] | 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 "ResolvExpr/FindOpenVars.h" // for findOpenVars |
---|
| 31 | #include "ResolvExpr/TypeEnvironment.h" // for OpenVarSet, AssertionSet |
---|
[51b7345] | 32 | #include "Specialize.h" |
---|
[08fc48f] | 33 | #include "SynTree/Attribute.h" // for Attribute |
---|
| 34 | #include "SynTree/Declaration.h" // for FunctionDecl, DeclarationWit... |
---|
| 35 | #include "SynTree/Expression.h" // for ApplicationExpr, Expression |
---|
[ba3706f] | 36 | #include "SynTree/Label.h" // for Label |
---|
[08fc48f] | 37 | #include "SynTree/Mutator.h" // for mutateAll |
---|
| 38 | #include "SynTree/Statement.h" // for CompoundStmt, DeclStmt, Expr... |
---|
| 39 | #include "SynTree/Type.h" // for FunctionType, TupleType, Type |
---|
| 40 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution |
---|
| 41 | #include "SynTree/Visitor.h" // for Visitor |
---|
[51b7345] | 42 | |
---|
| 43 | namespace GenPoly { |
---|
[02fdb8e] | 44 | struct Specialize final : public WithConstTypeSubstitution, public WithStmtsToAdd, public WithVisitorRef<Specialize> { |
---|
[cf90b88] | 45 | Expression * postmutate( ApplicationExpr *applicationExpr ); |
---|
| 46 | Expression * postmutate( CastExpr *castExpr ); |
---|
[01aeade] | 47 | |
---|
| 48 | void handleExplicitParams( ApplicationExpr *appExpr ); |
---|
[f3b0a07] | 49 | Expression * createThunkFunction( FunctionType *funType, Expression *actual, InferredParams *inferParams ); |
---|
[bb666f64] | 50 | Expression * doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ); |
---|
[626dbc10] | 51 | |
---|
| 52 | std::string paramPrefix = "_p"; |
---|
| 53 | }; |
---|
[01aeade] | 54 | |
---|
[698664b3] | 55 | /// Looks up open variables in actual type, returning true if any of them are bound in the environment or formal type. |
---|
[02fdb8e] | 56 | bool needsPolySpecialization( Type *formalType, Type *actualType, const TypeSubstitution *env ) { |
---|
[01aeade] | 57 | if ( env ) { |
---|
| 58 | using namespace ResolvExpr; |
---|
| 59 | OpenVarSet openVars, closedVars; |
---|
| 60 | AssertionSet need, have; |
---|
| 61 | findOpenVars( formalType, openVars, closedVars, need, have, false ); |
---|
| 62 | findOpenVars( actualType, openVars, closedVars, need, have, true ); |
---|
| 63 | for ( OpenVarSet::const_iterator openVar = openVars.begin(); openVar != openVars.end(); ++openVar ) { |
---|
| 64 | Type *boundType = env->lookup( openVar->first ); |
---|
| 65 | if ( ! boundType ) continue; |
---|
| 66 | if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( boundType ) ) { |
---|
[b226721] | 67 | // bound to another type variable |
---|
[01aeade] | 68 | if ( closedVars.find( typeInst->get_name() ) == closedVars.end() ) { |
---|
[b226721] | 69 | // bound to a closed variable => must specialize |
---|
[01aeade] | 70 | return true; |
---|
| 71 | } // if |
---|
| 72 | } else { |
---|
[b226721] | 73 | // variable is bound to a concrete type => must specialize |
---|
[01aeade] | 74 | return true; |
---|
| 75 | } // if |
---|
| 76 | } // for |
---|
[b226721] | 77 | // none of the type variables are bound |
---|
[01aeade] | 78 | return false; |
---|
| 79 | } else { |
---|
[b226721] | 80 | // no env |
---|
[01aeade] | 81 | return false; |
---|
| 82 | } // if |
---|
| 83 | } |
---|
| 84 | |
---|
[dc0557d] | 85 | /// True if both types have the same structure, but not necessarily the same types. |
---|
| 86 | /// That is, either both types are tuple types with the same size (recursively), or |
---|
| 87 | /// both are not tuple types. |
---|
| 88 | bool matchingTupleStructure( Type * t1, Type * t2 ) { |
---|
| 89 | TupleType * tuple1 = dynamic_cast< TupleType * >( t1 ); |
---|
| 90 | TupleType * tuple2 = dynamic_cast< TupleType * >( t2 ); |
---|
| 91 | if ( tuple1 && tuple2 ) { |
---|
| 92 | if ( tuple1->size() != tuple2->size() ) return false; |
---|
| 93 | for ( auto types : group_iterate( tuple1->get_types(), tuple2->get_types() ) ) { |
---|
| 94 | if ( ! matchingTupleStructure( std::get<0>( types ), std::get<1>( types ) ) ) return false; |
---|
| 95 | } |
---|
| 96 | return true; |
---|
| 97 | } else if ( ! tuple1 && ! tuple2 ) return true; |
---|
| 98 | return false; |
---|
| 99 | } |
---|
| 100 | |
---|
[ae4038d] | 101 | // walk into tuple type and find the number of components |
---|
| 102 | size_t singleParameterSize( Type * type ) { |
---|
| 103 | if ( TupleType * tt = dynamic_cast< TupleType * >( type ) ) { |
---|
| 104 | size_t sz = 0; |
---|
| 105 | for ( Type * t : *tt ) { |
---|
| 106 | sz += singleParameterSize( t ); |
---|
| 107 | } |
---|
| 108 | return sz; |
---|
| 109 | } else { |
---|
| 110 | return 1; |
---|
| 111 | } |
---|
| 112 | } |
---|
| 113 | |
---|
| 114 | // find the total number of components in a parameter list |
---|
| 115 | size_t functionParameterSize( FunctionType * ftype ) { |
---|
| 116 | size_t sz = 0; |
---|
| 117 | for ( DeclarationWithType * p : ftype->get_parameters() ) { |
---|
| 118 | sz += singleParameterSize( p->get_type() ); |
---|
| 119 | } |
---|
| 120 | return sz; |
---|
| 121 | } |
---|
| 122 | |
---|
[d7dc824] | 123 | bool needsTupleSpecialization( Type *formalType, Type *actualType ) { |
---|
[dc0557d] | 124 | // Needs tuple specialization if the structure of the formal type and actual type do not match. |
---|
| 125 | // This is the case if the formal type has ttype polymorphism, or if the structure of tuple types |
---|
| 126 | // between the function do not match exactly. |
---|
| 127 | if ( FunctionType * fftype = getFunctionType( formalType ) ) { |
---|
| 128 | if ( fftype->isTtype() ) return true; |
---|
[969ee0df] | 129 | // conversion of 0 (null) to function type does not require tuple specialization |
---|
| 130 | if ( dynamic_cast< ZeroType * >( actualType ) ) return false; |
---|
[1744e6d] | 131 | FunctionType * aftype = getFunctionType( actualType->stripReferences() ); |
---|
| 132 | assertf( aftype, "formal type is a function type, but actual type is not: %s", toString( actualType ).c_str() ); |
---|
[ae4038d] | 133 | // Can't tuple specialize if parameter sizes deeply-differ. |
---|
| 134 | if ( functionParameterSize( fftype ) != functionParameterSize( aftype ) ) return false; |
---|
| 135 | // tuple-parameter sizes are the same, but actual parameter sizes differ - must tuple specialize |
---|
[bb666f64] | 136 | if ( fftype->parameters.size() != aftype->parameters.size() ) return true; |
---|
[ae4038d] | 137 | // total parameter size can be the same, while individual parameters can have different structure |
---|
[bb666f64] | 138 | for ( auto params : group_iterate( fftype->parameters, aftype->parameters ) ) { |
---|
[dc0557d] | 139 | DeclarationWithType * formal = std::get<0>(params); |
---|
| 140 | DeclarationWithType * actual = std::get<1>(params); |
---|
| 141 | if ( ! matchingTupleStructure( formal->get_type(), actual->get_type() ) ) return true; |
---|
| 142 | } |
---|
[f3b0a07] | 143 | } |
---|
| 144 | return false; |
---|
| 145 | } |
---|
[698664b3] | 146 | |
---|
[02fdb8e] | 147 | bool needsSpecialization( Type *formalType, Type *actualType, const TypeSubstitution *env ) { |
---|
[d7dc824] | 148 | return needsPolySpecialization( formalType, actualType, env ) || needsTupleSpecialization( formalType, actualType ); |
---|
[698664b3] | 149 | } |
---|
[f1e012b] | 150 | |
---|
[f3b0a07] | 151 | Expression * Specialize::doSpecialization( Type *formalType, Expression *actual, InferredParams *inferParams ) { |
---|
[d29fa5f] | 152 | assertf( actual->result, "attempting to specialize an untyped expression" ); |
---|
[906e24d] | 153 | if ( needsSpecialization( formalType, actual->get_result(), env ) ) { |
---|
[6c3a988f] | 154 | if ( FunctionType *funType = getFunctionType( formalType ) ) { |
---|
[bb666f64] | 155 | if ( ApplicationExpr * appExpr = dynamic_cast<ApplicationExpr*>( actual ) ) { |
---|
[698664b3] | 156 | return createThunkFunction( funType, appExpr->get_function(), inferParams ); |
---|
[bb666f64] | 157 | } else if ( VariableExpr * varExpr = dynamic_cast<VariableExpr*>( actual ) ) { |
---|
[698664b3] | 158 | return createThunkFunction( funType, varExpr, inferParams ); |
---|
[01aeade] | 159 | } else { |
---|
[698664b3] | 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 | } |
---|
[01aeade] | 163 | } else { |
---|
| 164 | return actual; |
---|
| 165 | } // if |
---|
| 166 | } else { |
---|
| 167 | return actual; |
---|
| 168 | } // if |
---|
| 169 | } |
---|
| 170 | |
---|
[dc0557d] | 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 ) ) { |
---|
[64eae56] | 176 | std::list< Expression * > exprs; |
---|
[dc0557d] | 177 | for ( Type * t : *tuple ) { |
---|
| 178 | structureArg( t, begin, end, back_inserter( exprs ) ); |
---|
[64eae56] | 179 | } |
---|
| 180 | *out++ = new TupleExpr( exprs ); |
---|
| 181 | } else { |
---|
[dc0557d] | 182 | assertf( begin != end, "reached the end of the arguments while structuring" ); |
---|
| 183 | *out++ = *begin++; |
---|
[64eae56] | 184 | } |
---|
| 185 | } |
---|
| 186 | |
---|
[dc0557d] | 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 ); |
---|
[f3b0a07] | 194 | } |
---|
[dc0557d] | 195 | delete expr; |
---|
| 196 | } else { |
---|
| 197 | // non-tuple type - output a clone of the expression |
---|
| 198 | *out++ = expr; |
---|
[626dbc10] | 199 | } |
---|
| 200 | } |
---|
| 201 | |
---|
[f3b0a07] | 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" ); |
---|
[626dbc10] | 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 |
---|
[6c3a988f] | 210 | env->applyFree( newType ); |
---|
[626dbc10] | 211 | } // if |
---|
| 212 | // create new thunk with same signature as formal type (C linkage, empty body) |
---|
[ba3706f] | 213 | FunctionDecl *thunkFunc = new FunctionDecl( thunkNamer.newName(), Type::StorageClasses(), LinkageSpec::C, newType, new CompoundStmt() ); |
---|
[626dbc10] | 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 | |
---|
[6c3a988f] | 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 |
---|
[4c8621ac] | 229 | std::list< DeclarationWithType * >::iterator actualBegin = actualType->get_parameters().begin(); |
---|
| 230 | std::list< DeclarationWithType * >::iterator actualEnd = actualType->get_parameters().end(); |
---|
[626dbc10] | 231 | |
---|
[dc0557d] | 232 | std::list< Expression * > args; |
---|
[626dbc10] | 233 | for ( DeclarationWithType* param : thunkFunc->get_functionType()->get_parameters() ) { |
---|
[dc0557d] | 234 | // name each thunk parameter and explode it - these are then threaded back into the actual function call. |
---|
[626dbc10] | 235 | param->set_name( paramNamer.newName() ); |
---|
[dc0557d] | 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 | } |
---|
[4c8621ac] | 244 | |
---|
[2ec65ad] | 245 | appExpr->env = TypeSubstitution::newFromExpr( appExpr, env ); |
---|
[626dbc10] | 246 | if ( inferParams ) { |
---|
[0b00df0] | 247 | appExpr->inferParams = *inferParams; |
---|
[626dbc10] | 248 | } // if |
---|
| 249 | |
---|
| 250 | // handle any specializations that may still be present |
---|
| 251 | std::string oldParamPrefix = paramPrefix; |
---|
| 252 | paramPrefix += "p"; |
---|
[cf90b88] | 253 | // save stmtsToAddBefore in oldStmts |
---|
[626dbc10] | 254 | std::list< Statement* > oldStmts; |
---|
[cf90b88] | 255 | oldStmts.splice( oldStmts.end(), stmtsToAddBefore ); |
---|
| 256 | appExpr->acceptMutator( *visitor ); |
---|
[626dbc10] | 257 | paramPrefix = oldParamPrefix; |
---|
| 258 | // write any statements added for recursive specializations into the thunk body |
---|
[cf90b88] | 259 | thunkFunc->statements->kids.splice( thunkFunc->statements->kids.end(), stmtsToAddBefore ); |
---|
| 260 | // restore oldStmts into stmtsToAddBefore |
---|
| 261 | stmtsToAddBefore.splice( stmtsToAddBefore.end(), oldStmts ); |
---|
[626dbc10] | 262 | |
---|
| 263 | // add return (or valueless expression) to the thunk |
---|
| 264 | Statement *appStmt; |
---|
[cf90b88] | 265 | if ( funType->returnVals.empty() ) { |
---|
[ba3706f] | 266 | appStmt = new ExprStmt( appExpr ); |
---|
[626dbc10] | 267 | } else { |
---|
[ba3706f] | 268 | appStmt = new ReturnStmt( appExpr ); |
---|
[626dbc10] | 269 | } // if |
---|
[cf90b88] | 270 | thunkFunc->statements->kids.push_back( appStmt ); |
---|
[626dbc10] | 271 | |
---|
| 272 | // add thunk definition to queue of statements to add |
---|
[ba3706f] | 273 | stmtsToAddBefore.push_back( new DeclStmt( thunkFunc ) ); |
---|
[626dbc10] | 274 | // return address of thunk function as replacement expression |
---|
| 275 | return new AddressExpr( new VariableExpr( thunkFunc ) ); |
---|
| 276 | } |
---|
| 277 | |
---|
[01aeade] | 278 | void Specialize::handleExplicitParams( ApplicationExpr *appExpr ) { |
---|
| 279 | // create thunks for the explicit parameters |
---|
[cf90b88] | 280 | assert( appExpr->function->result ); |
---|
| 281 | FunctionType *function = getFunctionType( appExpr->function->result ); |
---|
[698664b3] | 282 | assert( function ); |
---|
[01aeade] | 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 ) { |
---|
[0b00df0] | 286 | *actual = doSpecialization( (*formal)->get_type(), *actual, &appExpr->inferParams ); |
---|
[01aeade] | 287 | } |
---|
| 288 | } |
---|
| 289 | |
---|
[cf90b88] | 290 | Expression * Specialize::postmutate( ApplicationExpr *appExpr ) { |
---|
[aedfd91] | 291 | if ( ! InitTweak::isIntrinsicCallExpr( appExpr ) ) { |
---|
| 292 | // create thunks for the inferred parameters |
---|
| 293 | // don't need to do this for intrinsic calls, because they aren't actually passed |
---|
[f3b0a07] | 294 | // need to handle explicit params before inferred params so that explicit params do not recieve a changed set of inferParams (and change them again) |
---|
| 295 | // alternatively, if order starts to matter then copy appExpr's inferParams and pass them to handleExplicitParams. |
---|
| 296 | handleExplicitParams( appExpr ); |
---|
[0b00df0] | 297 | for ( InferredParams::iterator inferParam = appExpr->inferParams.begin(); inferParam != appExpr->inferParams.end(); ++inferParam ) { |
---|
| 298 | inferParam->second.expr = doSpecialization( inferParam->second.formalType, inferParam->second.expr, &inferParam->second.expr->inferParams ); |
---|
[aedfd91] | 299 | } |
---|
| 300 | } |
---|
[01aeade] | 301 | return appExpr; |
---|
| 302 | } |
---|
| 303 | |
---|
[cf90b88] | 304 | Expression * Specialize::postmutate( CastExpr *castExpr ) { |
---|
| 305 | if ( castExpr->result->isVoid() ) { |
---|
[803deb1] | 306 | // can't specialize if we don't have a return value |
---|
| 307 | return castExpr; |
---|
| 308 | } |
---|
[bb666f64] | 309 | Expression *specialized = doSpecialization( castExpr->result, castExpr->arg, &castExpr->inferParams ); |
---|
[cf90b88] | 310 | if ( specialized != castExpr->arg ) { |
---|
[698664b3] | 311 | // assume here that the specialization incorporates the cast |
---|
| 312 | return specialized; |
---|
| 313 | } else { |
---|
| 314 | return castExpr; |
---|
| 315 | } |
---|
[01aeade] | 316 | } |
---|
| 317 | |
---|
[626dbc10] | 318 | void convertSpecializations( std::list< Declaration* >& translationUnit ) { |
---|
[cf90b88] | 319 | PassVisitor<Specialize> spec; |
---|
[626dbc10] | 320 | mutateAll( translationUnit, spec ); |
---|
| 321 | } |
---|
[51b7345] | 322 | } // namespace GenPoly |
---|
[01aeade] | 323 | |
---|
[51587aa] | 324 | // Local Variables: // |
---|
| 325 | // tab-width: 4 // |
---|
| 326 | // mode: c++ // |
---|
| 327 | // compile-command: "make install" // |
---|
| 328 | // End: // |
---|