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