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