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