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