1 //===- FunctionSpecialization.cpp - Function Specialization ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This specialises functions with constant parameters (e.g. functions, 10 // globals). Constant parameters like function pointers and constant globals 11 // are propagated to the callee by specializing the function. 12 // 13 // Current limitations: 14 // - It does not yet handle integer ranges. 15 // - Only 1 argument per function is specialised, 16 // - The cost-model could be further looked into, 17 // - We are not yet caching analysis results. 18 // 19 // Ideas: 20 // - With a function specialization attribute for arguments, we could have 21 // a direct way to steer function specialization, avoiding the cost-model, 22 // and thus control compile-times / code-size. 23 // 24 // Todos: 25 // - Specializing recursive functions relies on running the transformation a 26 // number of times, which is controlled by option 27 // `func-specialization-max-iters`. Thus, increasing this value and the 28 // number of iterations, will linearly increase the number of times recursive 29 // functions get specialized, see also the discussion in 30 // https://reviews.llvm.org/D106426 for details. Perhaps there is a 31 // compile-time friendlier way to control/limit the number of specialisations 32 // for recursive functions. 33 // - Don't transform the function if there is no function specialization 34 // happens. 35 // 36 //===----------------------------------------------------------------------===// 37 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/Analysis/AssumptionCache.h" 40 #include "llvm/Analysis/CodeMetrics.h" 41 #include "llvm/Analysis/DomTreeUpdater.h" 42 #include "llvm/Analysis/InlineCost.h" 43 #include "llvm/Analysis/LoopInfo.h" 44 #include "llvm/Analysis/TargetLibraryInfo.h" 45 #include "llvm/Analysis/TargetTransformInfo.h" 46 #include "llvm/Transforms/Scalar/SCCP.h" 47 #include "llvm/Transforms/Utils/Cloning.h" 48 #include "llvm/Transforms/Utils/SizeOpts.h" 49 #include <cmath> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "function-specialization" 54 55 STATISTIC(NumFuncSpecialized, "Number of functions specialized"); 56 57 static cl::opt<bool> ForceFunctionSpecialization( 58 "force-function-specialization", cl::init(false), cl::Hidden, 59 cl::desc("Force function specialization for every call site with a " 60 "constant argument")); 61 62 static cl::opt<unsigned> FuncSpecializationMaxIters( 63 "func-specialization-max-iters", cl::Hidden, 64 cl::desc("The maximum number of iterations function specialization is run"), 65 cl::init(1)); 66 67 static cl::opt<unsigned> MaxConstantsThreshold( 68 "func-specialization-max-constants", cl::Hidden, 69 cl::desc("The maximum number of clones allowed for a single function " 70 "specialization"), 71 cl::init(3)); 72 73 static cl::opt<unsigned> SmallFunctionThreshold( 74 "func-specialization-size-threshold", cl::Hidden, 75 cl::desc("Don't specialize functions that have less than this theshold " 76 "number of instructions"), 77 cl::init(100)); 78 79 static cl::opt<unsigned> 80 AvgLoopIterationCount("func-specialization-avg-iters-cost", cl::Hidden, 81 cl::desc("Average loop iteration count cost"), 82 cl::init(10)); 83 84 // TODO: This needs checking to see the impact on compile-times, which is why 85 // this is off by default for now. 86 static cl::opt<bool> EnableSpecializationForLiteralConstant( 87 "function-specialization-for-literal-constant", cl::init(false), cl::Hidden, 88 cl::desc("Enable specialization of functions that take a literal constant " 89 "as an argument.")); 90 91 // Helper to check if \p LV is either a constant or a constant 92 // range with a single element. This should cover exactly the same cases as the 93 // old ValueLatticeElement::isConstant() and is intended to be used in the 94 // transition to ValueLatticeElement. 95 static bool isConstant(const ValueLatticeElement &LV) { 96 return LV.isConstant() || 97 (LV.isConstantRange() && LV.getConstantRange().isSingleElement()); 98 } 99 100 // Helper to check if \p LV is either overdefined or a constant int. 101 static bool isOverdefined(const ValueLatticeElement &LV) { 102 return !LV.isUnknownOrUndef() && !isConstant(LV); 103 } 104 105 static Constant *getPromotableAlloca(AllocaInst *Alloca, CallInst *Call) { 106 Value *StoreValue = nullptr; 107 for (auto *User : Alloca->users()) { 108 // We can't use llvm::isAllocaPromotable() as that would fail because of 109 // the usage in the CallInst, which is what we check here. 110 if (User == Call) 111 continue; 112 if (auto *Bitcast = dyn_cast<BitCastInst>(User)) { 113 if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call) 114 return nullptr; 115 continue; 116 } 117 118 if (auto *Store = dyn_cast<StoreInst>(User)) { 119 // This is a duplicate store, bail out. 120 if (StoreValue || Store->isVolatile()) 121 return nullptr; 122 StoreValue = Store->getValueOperand(); 123 continue; 124 } 125 // Bail if there is any other unknown usage. 126 return nullptr; 127 } 128 return dyn_cast_or_null<Constant>(StoreValue); 129 } 130 131 // A constant stack value is an AllocaInst that has a single constant 132 // value stored to it. Return this constant if such an alloca stack value 133 // is a function argument. 134 static Constant *getConstantStackValue(CallInst *Call, Value *Val, 135 SCCPSolver &Solver) { 136 if (!Val) 137 return nullptr; 138 Val = Val->stripPointerCasts(); 139 if (auto *ConstVal = dyn_cast<ConstantInt>(Val)) 140 return ConstVal; 141 auto *Alloca = dyn_cast<AllocaInst>(Val); 142 if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy()) 143 return nullptr; 144 return getPromotableAlloca(Alloca, Call); 145 } 146 147 // To support specializing recursive functions, it is important to propagate 148 // constant arguments because after a first iteration of specialisation, a 149 // reduced example may look like this: 150 // 151 // define internal void @RecursiveFn(i32* arg1) { 152 // %temp = alloca i32, align 4 153 // store i32 2 i32* %temp, align 4 154 // call void @RecursiveFn.1(i32* nonnull %temp) 155 // ret void 156 // } 157 // 158 // Before a next iteration, we need to propagate the constant like so 159 // which allows further specialization in next iterations. 160 // 161 // @funcspec.arg = internal constant i32 2 162 // 163 // define internal void @someFunc(i32* arg1) { 164 // call void @otherFunc(i32* nonnull @funcspec.arg) 165 // ret void 166 // } 167 // 168 static void constantArgPropagation(SmallVectorImpl<Function *> &WorkList, 169 Module &M, SCCPSolver &Solver) { 170 // Iterate over the argument tracked functions see if there 171 // are any new constant values for the call instruction via 172 // stack variables. 173 for (auto *F : WorkList) { 174 // TODO: Generalize for any read only arguments. 175 if (F->arg_size() != 1) 176 continue; 177 178 auto &Arg = *F->arg_begin(); 179 if (!Arg.onlyReadsMemory() || !Arg.getType()->isPointerTy()) 180 continue; 181 182 for (auto *User : F->users()) { 183 auto *Call = dyn_cast<CallInst>(User); 184 if (!Call) 185 break; 186 auto *ArgOp = Call->getArgOperand(0); 187 auto *ArgOpType = ArgOp->getType(); 188 auto *ConstVal = getConstantStackValue(Call, ArgOp, Solver); 189 if (!ConstVal) 190 break; 191 192 Value *GV = new GlobalVariable(M, ConstVal->getType(), true, 193 GlobalValue::InternalLinkage, ConstVal, 194 "funcspec.arg"); 195 196 if (ArgOpType != ConstVal->getType()) 197 GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOp->getType()); 198 199 Call->setArgOperand(0, GV); 200 201 // Add the changed CallInst to Solver Worklist 202 Solver.visitCall(*Call); 203 } 204 } 205 } 206 207 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics 208 // interfere with the constantArgPropagation optimization. 209 static void removeSSACopy(Function &F) { 210 for (BasicBlock &BB : F) { 211 for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) { 212 Instruction *Inst = &*BI++; 213 auto *II = dyn_cast<IntrinsicInst>(Inst); 214 if (!II) 215 continue; 216 if (II->getIntrinsicID() != Intrinsic::ssa_copy) 217 continue; 218 Inst->replaceAllUsesWith(II->getOperand(0)); 219 Inst->eraseFromParent(); 220 } 221 } 222 } 223 224 static void removeSSACopy(Module &M) { 225 for (Function &F : M) 226 removeSSACopy(F); 227 } 228 229 class FunctionSpecializer { 230 231 /// The IPSCCP Solver. 232 SCCPSolver &Solver; 233 234 /// Analyses used to help determine if a function should be specialized. 235 std::function<AssumptionCache &(Function &)> GetAC; 236 std::function<TargetTransformInfo &(Function &)> GetTTI; 237 std::function<TargetLibraryInfo &(Function &)> GetTLI; 238 239 SmallPtrSet<Function *, 2> SpecializedFuncs; 240 241 public: 242 FunctionSpecializer(SCCPSolver &Solver, 243 std::function<AssumptionCache &(Function &)> GetAC, 244 std::function<TargetTransformInfo &(Function &)> GetTTI, 245 std::function<TargetLibraryInfo &(Function &)> GetTLI) 246 : Solver(Solver), GetAC(GetAC), GetTTI(GetTTI), GetTLI(GetTLI) {} 247 248 /// Attempt to specialize functions in the module to enable constant 249 /// propagation across function boundaries. 250 /// 251 /// \returns true if at least one function is specialized. 252 bool 253 specializeFunctions(SmallVectorImpl<Function *> &FuncDecls, 254 SmallVectorImpl<Function *> &CurrentSpecializations) { 255 256 // Attempt to specialize the argument-tracked functions. 257 bool Changed = false; 258 for (auto *F : FuncDecls) { 259 if (specializeFunction(F, CurrentSpecializations)) { 260 Changed = true; 261 LLVM_DEBUG(dbgs() << "FnSpecialization: Can specialize this func.\n"); 262 } else { 263 LLVM_DEBUG( 264 dbgs() << "FnSpecialization: Cannot specialize this func.\n"); 265 } 266 } 267 268 for (auto *SpecializedFunc : CurrentSpecializations) { 269 SpecializedFuncs.insert(SpecializedFunc); 270 271 // Initialize the state of the newly created functions, marking them 272 // argument-tracked and executable. 273 if (SpecializedFunc->hasExactDefinition() && 274 !SpecializedFunc->hasFnAttribute(Attribute::Naked)) 275 Solver.addTrackedFunction(SpecializedFunc); 276 Solver.addArgumentTrackedFunction(SpecializedFunc); 277 FuncDecls.push_back(SpecializedFunc); 278 Solver.markBlockExecutable(&SpecializedFunc->front()); 279 280 // Replace the function arguments for the specialized functions. 281 for (Argument &Arg : SpecializedFunc->args()) 282 if (!Arg.use_empty() && tryToReplaceWithConstant(&Arg)) 283 LLVM_DEBUG(dbgs() << "FnSpecialization: Replaced constant argument: " 284 << Arg.getName() << "\n"); 285 } 286 287 NumFuncSpecialized += NbFunctionsSpecialized; 288 return Changed; 289 } 290 291 bool tryToReplaceWithConstant(Value *V) { 292 if (!V->getType()->isSingleValueType() || isa<CallBase>(V) || 293 V->user_empty()) 294 return false; 295 296 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V); 297 if (isOverdefined(IV)) 298 return false; 299 auto *Const = 300 isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType()); 301 V->replaceAllUsesWith(Const); 302 303 for (auto *U : Const->users()) 304 if (auto *I = dyn_cast<Instruction>(U)) 305 if (Solver.isBlockExecutable(I->getParent())) 306 Solver.visit(I); 307 308 // Remove the instruction from Block and Solver. 309 if (auto *I = dyn_cast<Instruction>(V)) { 310 if (I->isSafeToRemove()) { 311 I->eraseFromParent(); 312 Solver.removeLatticeValueFor(I); 313 } 314 } 315 return true; 316 } 317 318 private: 319 // The number of functions specialised, used for collecting statistics and 320 // also in the cost model. 321 unsigned NbFunctionsSpecialized = 0; 322 323 /// Clone the function \p F and remove the ssa_copy intrinsics added by 324 /// the SCCPSolver in the cloned version. 325 Function *cloneCandidateFunction(Function *F) { 326 ValueToValueMapTy EmptyMap; 327 Function *Clone = CloneFunction(F, EmptyMap); 328 removeSSACopy(*Clone); 329 return Clone; 330 } 331 332 /// This function decides whether to specialize function \p F based on the 333 /// known constant values its arguments can take on. Specialization is 334 /// performed on the first interesting argument. Specializations based on 335 /// additional arguments will be evaluated on following iterations of the 336 /// main IPSCCP solve loop. \returns true if the function is specialized and 337 /// false otherwise. 338 bool specializeFunction(Function *F, 339 SmallVectorImpl<Function *> &Specializations) { 340 341 // Do not specialize the cloned function again. 342 if (SpecializedFuncs.contains(F)) 343 return false; 344 345 // If we're optimizing the function for size, we shouldn't specialize it. 346 if (F->hasOptSize() || 347 shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass)) 348 return false; 349 350 // Exit if the function is not executable. There's no point in specializing 351 // a dead function. 352 if (!Solver.isBlockExecutable(&F->getEntryBlock())) 353 return false; 354 355 // It wastes time to specialize a function which would get inlined finally. 356 if (F->hasFnAttribute(Attribute::AlwaysInline)) 357 return false; 358 359 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName() 360 << "\n"); 361 362 // Determine if it would be profitable to create a specialization of the 363 // function where the argument takes on the given constant value. If so, 364 // add the constant to Constants. 365 auto FnSpecCost = getSpecializationCost(F); 366 if (!FnSpecCost.isValid()) { 367 LLVM_DEBUG(dbgs() << "FnSpecialization: Invalid specialisation cost.\n"); 368 return false; 369 } 370 371 LLVM_DEBUG(dbgs() << "FnSpecialization: func specialisation cost: "; 372 FnSpecCost.print(dbgs()); dbgs() << "\n"); 373 374 // Determine if we should specialize the function based on the values the 375 // argument can take on. If specialization is not profitable, we continue 376 // on to the next argument. 377 for (Argument &A : F->args()) { 378 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing arg: " << A.getName() 379 << "\n"); 380 // True if this will be a partial specialization. We will need to keep 381 // the original function around in addition to the added specializations. 382 bool IsPartial = true; 383 384 // Determine if this argument is interesting. If we know the argument can 385 // take on any constant values, they are collected in Constants. If the 386 // argument can only ever equal a constant value in Constants, the 387 // function will be completely specialized, and the IsPartial flag will 388 // be set to false by isArgumentInteresting (that function only adds 389 // values to the Constants list that are deemed profitable). 390 SmallVector<Constant *, 4> Constants; 391 if (!isArgumentInteresting(&A, Constants, FnSpecCost, IsPartial)) { 392 LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is not interesting\n"); 393 continue; 394 } 395 396 assert(!Constants.empty() && "No constants on which to specialize"); 397 LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is interesting!\n" 398 << "FnSpecialization: Specializing '" << F->getName() 399 << "' on argument: " << A << "\n" 400 << "FnSpecialization: Constants are:\n\n"; 401 for (unsigned I = 0; I < Constants.size(); ++I) dbgs() 402 << *Constants[I] << "\n"; 403 dbgs() << "FnSpecialization: End of constants\n\n"); 404 405 // Create a version of the function in which the argument is marked 406 // constant with the given value. 407 for (auto *C : Constants) { 408 // Clone the function. We leave the ValueToValueMap empty to allow 409 // IPSCCP to propagate the constant arguments. 410 Function *Clone = cloneCandidateFunction(F); 411 Argument *ClonedArg = Clone->arg_begin() + A.getArgNo(); 412 413 // Rewrite calls to the function so that they call the clone instead. 414 rewriteCallSites(F, Clone, *ClonedArg, C); 415 416 // Initialize the lattice state of the arguments of the function clone, 417 // marking the argument on which we specialized the function constant 418 // with the given value. 419 Solver.markArgInFuncSpecialization(F, ClonedArg, C); 420 421 // Mark all the specialized functions 422 Specializations.push_back(Clone); 423 NbFunctionsSpecialized++; 424 } 425 426 // If the function has been completely specialized, the original function 427 // is no longer needed. Mark it unreachable. 428 if (!IsPartial) 429 Solver.markFunctionUnreachable(F); 430 431 // FIXME: Only one argument per function. 432 return true; 433 } 434 435 return false; 436 } 437 438 /// Compute the cost of specializing function \p F. 439 InstructionCost getSpecializationCost(Function *F) { 440 // Compute the code metrics for the function. 441 SmallPtrSet<const Value *, 32> EphValues; 442 CodeMetrics::collectEphemeralValues(F, &(GetAC)(*F), EphValues); 443 CodeMetrics Metrics; 444 for (BasicBlock &BB : *F) 445 Metrics.analyzeBasicBlock(&BB, (GetTTI)(*F), EphValues); 446 447 // If the code metrics reveal that we shouldn't duplicate the function, we 448 // shouldn't specialize it. Set the specialization cost to Invalid. 449 // Or if the lines of codes implies that this function is easy to get 450 // inlined so that we shouldn't specialize it. 451 if (Metrics.notDuplicatable || 452 (!ForceFunctionSpecialization && 453 Metrics.NumInsts < SmallFunctionThreshold)) { 454 InstructionCost C{}; 455 C.setInvalid(); 456 return C; 457 } 458 459 // Otherwise, set the specialization cost to be the cost of all the 460 // instructions in the function and penalty for specializing more functions. 461 unsigned Penalty = NbFunctionsSpecialized + 1; 462 return Metrics.NumInsts * InlineConstants::InstrCost * Penalty; 463 } 464 465 InstructionCost getUserBonus(User *U, llvm::TargetTransformInfo &TTI, 466 LoopInfo &LI) { 467 auto *I = dyn_cast_or_null<Instruction>(U); 468 // If not an instruction we do not know how to evaluate. 469 // Keep minimum possible cost for now so that it doesnt affect 470 // specialization. 471 if (!I) 472 return std::numeric_limits<unsigned>::min(); 473 474 auto Cost = TTI.getUserCost(U, TargetTransformInfo::TCK_SizeAndLatency); 475 476 // Traverse recursively if there are more uses. 477 // TODO: Any other instructions to be added here? 478 if (I->mayReadFromMemory() || I->isCast()) 479 for (auto *User : I->users()) 480 Cost += getUserBonus(User, TTI, LI); 481 482 // Increase the cost if it is inside the loop. 483 auto LoopDepth = LI.getLoopDepth(I->getParent()); 484 Cost *= std::pow((double)AvgLoopIterationCount, LoopDepth); 485 return Cost; 486 } 487 488 /// Compute a bonus for replacing argument \p A with constant \p C. 489 InstructionCost getSpecializationBonus(Argument *A, Constant *C) { 490 Function *F = A->getParent(); 491 DominatorTree DT(*F); 492 LoopInfo LI(DT); 493 auto &TTI = (GetTTI)(*F); 494 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for: " << *A 495 << "\n"); 496 497 InstructionCost TotalCost = 0; 498 for (auto *U : A->users()) { 499 TotalCost += getUserBonus(U, TTI, LI); 500 LLVM_DEBUG(dbgs() << "FnSpecialization: User cost "; 501 TotalCost.print(dbgs()); dbgs() << " for: " << *U << "\n"); 502 } 503 504 // The below heuristic is only concerned with exposing inlining 505 // opportunities via indirect call promotion. If the argument is not a 506 // function pointer, give up. 507 if (!isa<PointerType>(A->getType()) || 508 !isa<FunctionType>(A->getType()->getPointerElementType())) 509 return TotalCost; 510 511 // Since the argument is a function pointer, its incoming constant values 512 // should be functions or constant expressions. The code below attempts to 513 // look through cast expressions to find the function that will be called. 514 Value *CalledValue = C; 515 while (isa<ConstantExpr>(CalledValue) && 516 cast<ConstantExpr>(CalledValue)->isCast()) 517 CalledValue = cast<User>(CalledValue)->getOperand(0); 518 Function *CalledFunction = dyn_cast<Function>(CalledValue); 519 if (!CalledFunction) 520 return TotalCost; 521 522 // Get TTI for the called function (used for the inline cost). 523 auto &CalleeTTI = (GetTTI)(*CalledFunction); 524 525 // Look at all the call sites whose called value is the argument. 526 // Specializing the function on the argument would allow these indirect 527 // calls to be promoted to direct calls. If the indirect call promotion 528 // would likely enable the called function to be inlined, specializing is a 529 // good idea. 530 int Bonus = 0; 531 for (User *U : A->users()) { 532 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 533 continue; 534 auto *CS = cast<CallBase>(U); 535 if (CS->getCalledOperand() != A) 536 continue; 537 538 // Get the cost of inlining the called function at this call site. Note 539 // that this is only an estimate. The called function may eventually 540 // change in a way that leads to it not being inlined here, even though 541 // inlining looks profitable now. For example, one of its called 542 // functions may be inlined into it, making the called function too large 543 // to be inlined into this call site. 544 // 545 // We apply a boost for performing indirect call promotion by increasing 546 // the default threshold by the threshold for indirect calls. 547 auto Params = getInlineParams(); 548 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold; 549 InlineCost IC = 550 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI); 551 552 // We clamp the bonus for this call to be between zero and the default 553 // threshold. 554 if (IC.isAlways()) 555 Bonus += Params.DefaultThreshold; 556 else if (IC.isVariable() && IC.getCostDelta() > 0) 557 Bonus += IC.getCostDelta(); 558 } 559 560 return TotalCost + Bonus; 561 } 562 563 /// Determine if we should specialize a function based on the incoming values 564 /// of the given argument. 565 /// 566 /// This function implements the goal-directed heuristic. It determines if 567 /// specializing the function based on the incoming values of argument \p A 568 /// would result in any significant optimization opportunities. If 569 /// optimization opportunities exist, the constant values of \p A on which to 570 /// specialize the function are collected in \p Constants. If the values in 571 /// \p Constants represent the complete set of values that \p A can take on, 572 /// the function will be completely specialized, and the \p IsPartial flag is 573 /// set to false. 574 /// 575 /// \returns true if the function should be specialized on the given 576 /// argument. 577 bool isArgumentInteresting(Argument *A, 578 SmallVectorImpl<Constant *> &Constants, 579 const InstructionCost &FnSpecCost, 580 bool &IsPartial) { 581 // For now, don't attempt to specialize functions based on the values of 582 // composite types. 583 if (!A->getType()->isSingleValueType() || A->user_empty()) 584 return false; 585 586 // If the argument isn't overdefined, there's nothing to do. It should 587 // already be constant. 588 if (!Solver.getLatticeValueFor(A).isOverdefined()) { 589 LLVM_DEBUG(dbgs() << "FnSpecialization: nothing to do, arg is already " 590 << "constant?\n"); 591 return false; 592 } 593 594 // Collect the constant values that the argument can take on. If the 595 // argument can't take on any constant values, we aren't going to 596 // specialize the function. While it's possible to specialize the function 597 // based on non-constant arguments, there's likely not much benefit to 598 // constant propagation in doing so. 599 // 600 // TODO 1: currently it won't specialize if there are over the threshold of 601 // calls using the same argument, e.g foo(a) x 4 and foo(b) x 1, but it 602 // might be beneficial to take the occurrences into account in the cost 603 // model, so we would need to find the unique constants. 604 // 605 // TODO 2: this currently does not support constants, i.e. integer ranges. 606 // 607 SmallVector<Constant *, 4> PossibleConstants; 608 bool AllConstant = getPossibleConstants(A, PossibleConstants); 609 if (PossibleConstants.empty()) { 610 LLVM_DEBUG(dbgs() << "FnSpecialization: no possible constants found\n"); 611 return false; 612 } 613 if (PossibleConstants.size() > MaxConstantsThreshold) { 614 LLVM_DEBUG(dbgs() << "FnSpecialization: number of constants found exceed " 615 << "the maximum number of constants threshold.\n"); 616 return false; 617 } 618 619 for (auto *C : PossibleConstants) { 620 LLVM_DEBUG(dbgs() << "FnSpecialization: Constant: " << *C << "\n"); 621 if (ForceFunctionSpecialization) { 622 LLVM_DEBUG(dbgs() << "FnSpecialization: Forced!\n"); 623 Constants.push_back(C); 624 continue; 625 } 626 if (getSpecializationBonus(A, C) > FnSpecCost) { 627 LLVM_DEBUG(dbgs() << "FnSpecialization: profitable!\n"); 628 Constants.push_back(C); 629 } else { 630 LLVM_DEBUG(dbgs() << "FnSpecialization: not profitable\n"); 631 } 632 } 633 634 // None of the constant values the argument can take on were deemed good 635 // candidates on which to specialize the function. 636 if (Constants.empty()) 637 return false; 638 639 // This will be a partial specialization if some of the constants were 640 // rejected due to their profitability. 641 IsPartial = !AllConstant || PossibleConstants.size() != Constants.size(); 642 643 return true; 644 } 645 646 /// Collect in \p Constants all the constant values that argument \p A can 647 /// take on. 648 /// 649 /// \returns true if all of the values the argument can take on are constant 650 /// (e.g., the argument's parent function cannot be called with an 651 /// overdefined value). 652 bool getPossibleConstants(Argument *A, 653 SmallVectorImpl<Constant *> &Constants) { 654 Function *F = A->getParent(); 655 bool AllConstant = true; 656 657 // Iterate over all the call sites of the argument's parent function. 658 for (User *U : F->users()) { 659 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 660 continue; 661 auto &CS = *cast<CallBase>(U); 662 // If the call site has attribute minsize set, that callsite won't be 663 // specialized. 664 if (CS.hasFnAttr(Attribute::MinSize)) { 665 AllConstant = false; 666 continue; 667 } 668 669 // If the parent of the call site will never be executed, we don't need 670 // to worry about the passed value. 671 if (!Solver.isBlockExecutable(CS.getParent())) 672 continue; 673 674 auto *V = CS.getArgOperand(A->getArgNo()); 675 // TrackValueOfGlobalVariable only tracks scalar global variables. 676 if (auto *GV = dyn_cast<GlobalVariable>(V)) 677 if (!GV->getValueType()->isSingleValueType()) 678 return false; 679 680 if (isa<Constant>(V) && (Solver.getLatticeValueFor(V).isConstant() || 681 EnableSpecializationForLiteralConstant)) 682 Constants.push_back(cast<Constant>(V)); 683 else 684 AllConstant = false; 685 } 686 687 // If the argument can only take on constant values, AllConstant will be 688 // true. 689 return AllConstant; 690 } 691 692 /// Rewrite calls to function \p F to call function \p Clone instead. 693 /// 694 /// This function modifies calls to function \p F whose argument at index \p 695 /// ArgNo is equal to constant \p C. The calls are rewritten to call function 696 /// \p Clone instead. 697 /// 698 /// Callsites that have been marked with the MinSize function attribute won't 699 /// be specialized and rewritten. 700 void rewriteCallSites(Function *F, Function *Clone, Argument &Arg, 701 Constant *C) { 702 unsigned ArgNo = Arg.getArgNo(); 703 SmallVector<CallBase *, 4> CallSitesToRewrite; 704 for (auto *U : F->users()) { 705 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 706 continue; 707 auto &CS = *cast<CallBase>(U); 708 if (!CS.getCalledFunction() || CS.getCalledFunction() != F) 709 continue; 710 CallSitesToRewrite.push_back(&CS); 711 } 712 for (auto *CS : CallSitesToRewrite) { 713 if ((CS->getFunction() == Clone && CS->getArgOperand(ArgNo) == &Arg) || 714 CS->getArgOperand(ArgNo) == C) { 715 CS->setCalledFunction(Clone); 716 Solver.markOverdefined(CS); 717 } 718 } 719 } 720 }; 721 722 bool llvm::runFunctionSpecialization( 723 Module &M, const DataLayout &DL, 724 std::function<TargetLibraryInfo &(Function &)> GetTLI, 725 std::function<TargetTransformInfo &(Function &)> GetTTI, 726 std::function<AssumptionCache &(Function &)> GetAC, 727 function_ref<AnalysisResultsForFn(Function &)> GetAnalysis) { 728 SCCPSolver Solver(DL, GetTLI, M.getContext()); 729 FunctionSpecializer FS(Solver, GetAC, GetTTI, GetTLI); 730 bool Changed = false; 731 732 // Loop over all functions, marking arguments to those with their addresses 733 // taken or that are external as overdefined. 734 for (Function &F : M) { 735 if (F.isDeclaration()) 736 continue; 737 if (F.hasFnAttribute(Attribute::NoDuplicate)) 738 continue; 739 740 LLVM_DEBUG(dbgs() << "\nFnSpecialization: Analysing decl: " << F.getName() 741 << "\n"); 742 Solver.addAnalysis(F, GetAnalysis(F)); 743 744 // Determine if we can track the function's arguments. If so, add the 745 // function to the solver's set of argument-tracked functions. 746 if (canTrackArgumentsInterprocedurally(&F)) { 747 LLVM_DEBUG(dbgs() << "FnSpecialization: Can track arguments\n"); 748 Solver.addArgumentTrackedFunction(&F); 749 continue; 750 } else { 751 LLVM_DEBUG(dbgs() << "FnSpecialization: Can't track arguments!\n" 752 << "FnSpecialization: Doesn't have local linkage, or " 753 << "has its address taken\n"); 754 } 755 756 // Assume the function is called. 757 Solver.markBlockExecutable(&F.front()); 758 759 // Assume nothing about the incoming arguments. 760 for (Argument &AI : F.args()) 761 Solver.markOverdefined(&AI); 762 } 763 764 // Determine if we can track any of the module's global variables. If so, add 765 // the global variables we can track to the solver's set of tracked global 766 // variables. 767 for (GlobalVariable &G : M.globals()) { 768 G.removeDeadConstantUsers(); 769 if (canTrackGlobalVariableInterprocedurally(&G)) 770 Solver.trackValueOfGlobalVariable(&G); 771 } 772 773 // Solve for constants. 774 auto RunSCCPSolver = [&](auto &WorkList) { 775 bool ResolvedUndefs = true; 776 777 while (ResolvedUndefs) { 778 LLVM_DEBUG(dbgs() << "FnSpecialization: Running solver\n"); 779 Solver.solve(); 780 LLVM_DEBUG(dbgs() << "FnSpecialization: Resolving undefs\n"); 781 ResolvedUndefs = false; 782 for (Function *F : WorkList) 783 if (Solver.resolvedUndefsIn(*F)) 784 ResolvedUndefs = true; 785 } 786 787 for (auto *F : WorkList) { 788 for (BasicBlock &BB : *F) { 789 if (!Solver.isBlockExecutable(&BB)) 790 continue; 791 // FIXME: The solver may make changes to the function here, so set 792 // Changed, even if later function specialization does not trigger. 793 for (auto &I : make_early_inc_range(BB)) 794 Changed |= FS.tryToReplaceWithConstant(&I); 795 } 796 } 797 }; 798 799 auto &TrackedFuncs = Solver.getArgumentTrackedFunctions(); 800 SmallVector<Function *, 16> FuncDecls(TrackedFuncs.begin(), 801 TrackedFuncs.end()); 802 #ifndef NDEBUG 803 LLVM_DEBUG(dbgs() << "FnSpecialization: Worklist fn decls:\n"); 804 for (auto *F : FuncDecls) 805 LLVM_DEBUG(dbgs() << "FnSpecialization: *) " << F->getName() << "\n"); 806 #endif 807 808 // Initially resolve the constants in all the argument tracked functions. 809 RunSCCPSolver(FuncDecls); 810 811 SmallVector<Function *, 2> CurrentSpecializations; 812 unsigned I = 0; 813 while (FuncSpecializationMaxIters != I++ && 814 FS.specializeFunctions(FuncDecls, CurrentSpecializations)) { 815 816 // Run the solver for the specialized functions. 817 RunSCCPSolver(CurrentSpecializations); 818 819 // Replace some unresolved constant arguments. 820 constantArgPropagation(FuncDecls, M, Solver); 821 822 CurrentSpecializations.clear(); 823 Changed = true; 824 } 825 826 // Clean up the IR by removing ssa_copy intrinsics. 827 removeSSACopy(M); 828 return Changed; 829 } 830