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 #include "llvm/Transforms/IPO/FunctionSpecialization.h" 10 #include "llvm/ADT/Statistic.h" 11 #include "llvm/Analysis/CodeMetrics.h" 12 #include "llvm/Analysis/ConstantFolding.h" 13 #include "llvm/Analysis/InlineCost.h" 14 #include "llvm/Analysis/InstructionSimplify.h" 15 #include "llvm/Analysis/TargetTransformInfo.h" 16 #include "llvm/Analysis/ValueLattice.h" 17 #include "llvm/Analysis/ValueLatticeUtils.h" 18 #include "llvm/Analysis/ValueTracking.h" 19 #include "llvm/IR/IntrinsicInst.h" 20 #include "llvm/Transforms/Scalar/SCCP.h" 21 #include "llvm/Transforms/Utils/Cloning.h" 22 #include "llvm/Transforms/Utils/SCCPSolver.h" 23 #include "llvm/Transforms/Utils/SizeOpts.h" 24 #include <cmath> 25 26 using namespace llvm; 27 28 #define DEBUG_TYPE "function-specialization" 29 30 STATISTIC(NumSpecsCreated, "Number of specializations created"); 31 32 static cl::opt<bool> ForceSpecialization( 33 "force-specialization", cl::init(false), cl::Hidden, cl::desc( 34 "Force function specialization for every call site with a constant " 35 "argument")); 36 37 static cl::opt<unsigned> MaxClones( 38 "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc( 39 "The maximum number of clones allowed for a single function " 40 "specialization")); 41 42 static cl::opt<unsigned> 43 MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100), 44 cl::Hidden, 45 cl::desc("The maximum number of iterations allowed " 46 "when searching for transitive " 47 "phis")); 48 49 static cl::opt<unsigned> MaxIncomingPhiValues( 50 "funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden, 51 cl::desc("The maximum number of incoming values a PHI node can have to be " 52 "considered during the specialization bonus estimation")); 53 54 static cl::opt<unsigned> MaxBlockPredecessors( 55 "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc( 56 "The maximum number of predecessors a basic block can have to be " 57 "considered during the estimation of dead code")); 58 59 static cl::opt<unsigned> MinFunctionSize( 60 "funcspec-min-function-size", cl::init(500), cl::Hidden, 61 cl::desc("Don't specialize functions that have less than this number of " 62 "instructions")); 63 64 static cl::opt<unsigned> MaxCodeSizeGrowth( 65 "funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc( 66 "Maximum codesize growth allowed per function")); 67 68 static cl::opt<unsigned> MinCodeSizeSavings( 69 "funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc( 70 "Reject specializations whose codesize savings are less than this" 71 "much percent of the original function size")); 72 73 static cl::opt<unsigned> MinLatencySavings( 74 "funcspec-min-latency-savings", cl::init(40), cl::Hidden, 75 cl::desc("Reject specializations whose latency savings are less than this" 76 "much percent of the original function size")); 77 78 static cl::opt<unsigned> MinInliningBonus( 79 "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc( 80 "Reject specializations whose inlining bonus is less than this" 81 "much percent of the original function size")); 82 83 static cl::opt<bool> SpecializeOnAddress( 84 "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc( 85 "Enable function specialization on the address of global values")); 86 87 static cl::opt<bool> SpecializeLiteralConstant( 88 "funcspec-for-literal-constant", cl::init(true), cl::Hidden, 89 cl::desc( 90 "Enable specialization of functions that take a literal constant as an " 91 "argument")); 92 93 bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB, BasicBlock *Succ, 94 DenseSet<BasicBlock *> &DeadBlocks) { 95 unsigned I = 0; 96 return all_of(predecessors(Succ), 97 [&I, BB, Succ, &DeadBlocks] (BasicBlock *Pred) { 98 return I++ < MaxBlockPredecessors && 99 (Pred == BB || Pred == Succ || DeadBlocks.contains(Pred)); 100 }); 101 } 102 103 // Estimates the codesize savings due to dead code after constant propagation. 104 // \p WorkList represents the basic blocks of a specialization which will 105 // eventually become dead once we replace instructions that are known to be 106 // constants. The successors of such blocks are added to the list as long as 107 // the \p Solver found they were executable prior to specialization, and only 108 // if all their predecessors are dead. 109 Cost InstCostVisitor::estimateBasicBlocks( 110 SmallVectorImpl<BasicBlock *> &WorkList) { 111 Cost CodeSize = 0; 112 // Accumulate the codesize savings of each basic block. 113 while (!WorkList.empty()) { 114 BasicBlock *BB = WorkList.pop_back_val(); 115 116 // These blocks are considered dead as far as the InstCostVisitor 117 // is concerned. They haven't been proven dead yet by the Solver, 118 // but may become if we propagate the specialization arguments. 119 if (!DeadBlocks.insert(BB).second) 120 continue; 121 122 for (Instruction &I : *BB) { 123 // Disregard SSA copies. 124 if (auto *II = dyn_cast<IntrinsicInst>(&I)) 125 if (II->getIntrinsicID() == Intrinsic::ssa_copy) 126 continue; 127 // If it's a known constant we have already accounted for it. 128 if (KnownConstants.contains(&I)) 129 continue; 130 131 Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize); 132 133 LLVM_DEBUG(dbgs() << "FnSpecialization: CodeSize " << C 134 << " for user " << I << "\n"); 135 CodeSize += C; 136 } 137 138 // Keep adding dead successors to the list as long as they are 139 // executable and only reachable from dead blocks. 140 for (BasicBlock *SuccBB : successors(BB)) 141 if (isBlockExecutable(SuccBB) && 142 canEliminateSuccessor(BB, SuccBB, DeadBlocks)) 143 WorkList.push_back(SuccBB); 144 } 145 return CodeSize; 146 } 147 148 static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) { 149 if (auto *C = dyn_cast<Constant>(V)) 150 return C; 151 return KnownConstants.lookup(V); 152 } 153 154 Cost InstCostVisitor::getCodeSizeSavingsFromPendingPHIs() { 155 Cost CodeSize; 156 while (!PendingPHIs.empty()) { 157 Instruction *Phi = PendingPHIs.pop_back_val(); 158 // The pending PHIs could have been proven dead by now. 159 if (isBlockExecutable(Phi->getParent())) 160 CodeSize += getCodeSizeSavingsForUser(Phi); 161 } 162 return CodeSize; 163 } 164 165 /// Compute the codesize savings for replacing argument \p A with constant \p C. 166 Cost InstCostVisitor::getCodeSizeSavingsForArg(Argument *A, Constant *C) { 167 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: " 168 << C->getNameOrAsOperand() << "\n"); 169 Cost CodeSize; 170 for (auto *U : A->users()) 171 if (auto *UI = dyn_cast<Instruction>(U)) 172 if (isBlockExecutable(UI->getParent())) 173 CodeSize += getCodeSizeSavingsForUser(UI, A, C); 174 175 LLVM_DEBUG(dbgs() << "FnSpecialization: Accumulated bonus {CodeSize = " 176 << CodeSize << "} for argument " << *A << "\n"); 177 return CodeSize; 178 } 179 180 /// Compute the latency savings from replacing all arguments with constants for 181 /// a specialization candidate. As this function computes the latency savings 182 /// for all Instructions in KnownConstants at once, it should be called only 183 /// after every instruction has been visited, i.e. after: 184 /// 185 /// * getCodeSizeSavingsForArg has been run for every constant argument of a 186 /// specialization candidate 187 /// 188 /// * getCodeSizeSavingsFromPendingPHIs has been run 189 /// 190 /// to ensure that the latency savings are calculated for all Instructions we 191 /// have visited and found to be constant. 192 Cost InstCostVisitor::getLatencySavingsForKnownConstants() { 193 auto &BFI = GetBFI(*F); 194 Cost TotalLatency = 0; 195 196 for (auto Pair : KnownConstants) { 197 Instruction *I = dyn_cast<Instruction>(Pair.first); 198 if (!I) 199 continue; 200 201 uint64_t Weight = BFI.getBlockFreq(I->getParent()).getFrequency() / 202 BFI.getEntryFreq().getFrequency(); 203 204 Cost Latency = 205 Weight * TTI.getInstructionCost(I, TargetTransformInfo::TCK_Latency); 206 207 LLVM_DEBUG(dbgs() << "FnSpecialization: {Latency = " << Latency 208 << "} for instruction " << *I << "\n"); 209 210 TotalLatency += Latency; 211 } 212 213 return TotalLatency; 214 } 215 216 Cost InstCostVisitor::getCodeSizeSavingsForUser(Instruction *User, Value *Use, 217 Constant *C) { 218 // We have already propagated a constant for this user. 219 if (KnownConstants.contains(User)) 220 return 0; 221 222 // Cache the iterator before visiting. 223 LastVisited = Use ? KnownConstants.insert({Use, C}).first 224 : KnownConstants.end(); 225 226 Cost CodeSize = 0; 227 if (auto *I = dyn_cast<SwitchInst>(User)) { 228 CodeSize = estimateSwitchInst(*I); 229 } else if (auto *I = dyn_cast<BranchInst>(User)) { 230 CodeSize = estimateBranchInst(*I); 231 } else { 232 C = visit(*User); 233 if (!C) 234 return 0; 235 } 236 237 // Even though it doesn't make sense to bind switch and branch instructions 238 // with a constant, unlike any other instruction type, it prevents estimating 239 // their bonus multiple times. 240 KnownConstants.insert({User, C}); 241 242 CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize); 243 244 LLVM_DEBUG(dbgs() << "FnSpecialization: {CodeSize = " << CodeSize 245 << "} for user " << *User << "\n"); 246 247 for (auto *U : User->users()) 248 if (auto *UI = dyn_cast<Instruction>(U)) 249 if (UI != User && isBlockExecutable(UI->getParent())) 250 CodeSize += getCodeSizeSavingsForUser(UI, User, C); 251 252 return CodeSize; 253 } 254 255 Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) { 256 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 257 258 if (I.getCondition() != LastVisited->first) 259 return 0; 260 261 auto *C = dyn_cast<ConstantInt>(LastVisited->second); 262 if (!C) 263 return 0; 264 265 BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor(); 266 // Initialize the worklist with the dead basic blocks. These are the 267 // destination labels which are different from the one corresponding 268 // to \p C. They should be executable and have a unique predecessor. 269 SmallVector<BasicBlock *> WorkList; 270 for (const auto &Case : I.cases()) { 271 BasicBlock *BB = Case.getCaseSuccessor(); 272 if (BB != Succ && isBlockExecutable(BB) && 273 canEliminateSuccessor(I.getParent(), BB, DeadBlocks)) 274 WorkList.push_back(BB); 275 } 276 277 return estimateBasicBlocks(WorkList); 278 } 279 280 Cost InstCostVisitor::estimateBranchInst(BranchInst &I) { 281 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 282 283 if (I.getCondition() != LastVisited->first) 284 return 0; 285 286 BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue()); 287 // Initialize the worklist with the dead successor as long as 288 // it is executable and has a unique predecessor. 289 SmallVector<BasicBlock *> WorkList; 290 if (isBlockExecutable(Succ) && 291 canEliminateSuccessor(I.getParent(), Succ, DeadBlocks)) 292 WorkList.push_back(Succ); 293 294 return estimateBasicBlocks(WorkList); 295 } 296 297 bool InstCostVisitor::discoverTransitivelyIncomingValues( 298 Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) { 299 300 SmallVector<PHINode *, 64> WorkList; 301 WorkList.push_back(Root); 302 unsigned Iter = 0; 303 304 while (!WorkList.empty()) { 305 PHINode *PN = WorkList.pop_back_val(); 306 307 if (++Iter > MaxDiscoveryIterations || 308 PN->getNumIncomingValues() > MaxIncomingPhiValues) 309 return false; 310 311 if (!TransitivePHIs.insert(PN).second) 312 continue; 313 314 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { 315 Value *V = PN->getIncomingValue(I); 316 317 // Disregard self-references and dead incoming values. 318 if (auto *Inst = dyn_cast<Instruction>(V)) 319 if (Inst == PN || DeadBlocks.contains(PN->getIncomingBlock(I))) 320 continue; 321 322 if (Constant *C = findConstantFor(V, KnownConstants)) { 323 // Not all incoming values are the same constant. Bail immediately. 324 if (C != Const) 325 return false; 326 continue; 327 } 328 329 if (auto *Phi = dyn_cast<PHINode>(V)) { 330 WorkList.push_back(Phi); 331 continue; 332 } 333 334 // We can't reason about anything else. 335 return false; 336 } 337 } 338 return true; 339 } 340 341 Constant *InstCostVisitor::visitPHINode(PHINode &I) { 342 if (I.getNumIncomingValues() > MaxIncomingPhiValues) 343 return nullptr; 344 345 bool Inserted = VisitedPHIs.insert(&I).second; 346 Constant *Const = nullptr; 347 bool HaveSeenIncomingPHI = false; 348 349 for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) { 350 Value *V = I.getIncomingValue(Idx); 351 352 // Disregard self-references and dead incoming values. 353 if (auto *Inst = dyn_cast<Instruction>(V)) 354 if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx))) 355 continue; 356 357 if (Constant *C = findConstantFor(V, KnownConstants)) { 358 if (!Const) 359 Const = C; 360 // Not all incoming values are the same constant. Bail immediately. 361 if (C != Const) 362 return nullptr; 363 continue; 364 } 365 366 if (Inserted) { 367 // First time we are seeing this phi. We will retry later, after 368 // all the constant arguments have been propagated. Bail for now. 369 PendingPHIs.push_back(&I); 370 return nullptr; 371 } 372 373 if (isa<PHINode>(V)) { 374 // Perhaps it is a Transitive Phi. We will confirm later. 375 HaveSeenIncomingPHI = true; 376 continue; 377 } 378 379 // We can't reason about anything else. 380 return nullptr; 381 } 382 383 if (!Const) 384 return nullptr; 385 386 if (!HaveSeenIncomingPHI) 387 return Const; 388 389 DenseSet<PHINode *> TransitivePHIs; 390 if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs)) 391 return nullptr; 392 393 return Const; 394 } 395 396 Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) { 397 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 398 399 if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second)) 400 return LastVisited->second; 401 return nullptr; 402 } 403 404 Constant *InstCostVisitor::visitCallBase(CallBase &I) { 405 Function *F = I.getCalledFunction(); 406 if (!F || !canConstantFoldCallTo(&I, F)) 407 return nullptr; 408 409 SmallVector<Constant *, 8> Operands; 410 Operands.reserve(I.getNumOperands()); 411 412 for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) { 413 Value *V = I.getOperand(Idx); 414 Constant *C = findConstantFor(V, KnownConstants); 415 if (!C) 416 return nullptr; 417 Operands.push_back(C); 418 } 419 420 auto Ops = ArrayRef(Operands.begin(), Operands.end()); 421 return ConstantFoldCall(&I, F, Ops); 422 } 423 424 Constant *InstCostVisitor::visitLoadInst(LoadInst &I) { 425 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 426 427 if (isa<ConstantPointerNull>(LastVisited->second)) 428 return nullptr; 429 return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL); 430 } 431 432 Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) { 433 SmallVector<Constant *, 8> Operands; 434 Operands.reserve(I.getNumOperands()); 435 436 for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) { 437 Value *V = I.getOperand(Idx); 438 Constant *C = findConstantFor(V, KnownConstants); 439 if (!C) 440 return nullptr; 441 Operands.push_back(C); 442 } 443 444 auto Ops = ArrayRef(Operands.begin(), Operands.end()); 445 return ConstantFoldInstOperands(&I, Ops, DL); 446 } 447 448 Constant *InstCostVisitor::visitSelectInst(SelectInst &I) { 449 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 450 451 if (I.getCondition() == LastVisited->first) { 452 Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue() 453 : I.getTrueValue(); 454 return findConstantFor(V, KnownConstants); 455 } 456 if (Constant *Condition = findConstantFor(I.getCondition(), KnownConstants)) 457 if ((I.getTrueValue() == LastVisited->first && Condition->isOneValue()) || 458 (I.getFalseValue() == LastVisited->first && Condition->isZeroValue())) 459 return LastVisited->second; 460 return nullptr; 461 } 462 463 Constant *InstCostVisitor::visitCastInst(CastInst &I) { 464 return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second, 465 I.getType(), DL); 466 } 467 468 Constant *InstCostVisitor::visitCmpInst(CmpInst &I) { 469 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 470 471 bool Swap = I.getOperand(1) == LastVisited->first; 472 Value *V = Swap ? I.getOperand(0) : I.getOperand(1); 473 Constant *Other = findConstantFor(V, KnownConstants); 474 if (!Other) 475 return nullptr; 476 477 Constant *Const = LastVisited->second; 478 return Swap ? 479 ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL) 480 : ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL); 481 } 482 483 Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) { 484 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 485 486 return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL); 487 } 488 489 Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) { 490 assert(LastVisited != KnownConstants.end() && "Invalid iterator!"); 491 492 bool Swap = I.getOperand(1) == LastVisited->first; 493 Value *V = Swap ? I.getOperand(0) : I.getOperand(1); 494 Constant *Other = findConstantFor(V, KnownConstants); 495 if (!Other) 496 return nullptr; 497 498 Constant *Const = LastVisited->second; 499 return dyn_cast_or_null<Constant>(Swap ? 500 simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL)) 501 : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL))); 502 } 503 504 Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca, 505 CallInst *Call) { 506 Value *StoreValue = nullptr; 507 for (auto *User : Alloca->users()) { 508 // We can't use llvm::isAllocaPromotable() as that would fail because of 509 // the usage in the CallInst, which is what we check here. 510 if (User == Call) 511 continue; 512 513 if (auto *Store = dyn_cast<StoreInst>(User)) { 514 // This is a duplicate store, bail out. 515 if (StoreValue || Store->isVolatile()) 516 return nullptr; 517 StoreValue = Store->getValueOperand(); 518 continue; 519 } 520 // Bail if there is any other unknown usage. 521 return nullptr; 522 } 523 524 if (!StoreValue) 525 return nullptr; 526 527 return getCandidateConstant(StoreValue); 528 } 529 530 // A constant stack value is an AllocaInst that has a single constant 531 // value stored to it. Return this constant if such an alloca stack value 532 // is a function argument. 533 Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call, 534 Value *Val) { 535 if (!Val) 536 return nullptr; 537 Val = Val->stripPointerCasts(); 538 if (auto *ConstVal = dyn_cast<ConstantInt>(Val)) 539 return ConstVal; 540 auto *Alloca = dyn_cast<AllocaInst>(Val); 541 if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy()) 542 return nullptr; 543 return getPromotableAlloca(Alloca, Call); 544 } 545 546 // To support specializing recursive functions, it is important to propagate 547 // constant arguments because after a first iteration of specialisation, a 548 // reduced example may look like this: 549 // 550 // define internal void @RecursiveFn(i32* arg1) { 551 // %temp = alloca i32, align 4 552 // store i32 2 i32* %temp, align 4 553 // call void @RecursiveFn.1(i32* nonnull %temp) 554 // ret void 555 // } 556 // 557 // Before a next iteration, we need to propagate the constant like so 558 // which allows further specialization in next iterations. 559 // 560 // @funcspec.arg = internal constant i32 2 561 // 562 // define internal void @someFunc(i32* arg1) { 563 // call void @otherFunc(i32* nonnull @funcspec.arg) 564 // ret void 565 // } 566 // 567 // See if there are any new constant values for the callers of \p F via 568 // stack variables and promote them to global variables. 569 void FunctionSpecializer::promoteConstantStackValues(Function *F) { 570 for (User *U : F->users()) { 571 572 auto *Call = dyn_cast<CallInst>(U); 573 if (!Call) 574 continue; 575 576 if (!Solver.isBlockExecutable(Call->getParent())) 577 continue; 578 579 for (const Use &U : Call->args()) { 580 unsigned Idx = Call->getArgOperandNo(&U); 581 Value *ArgOp = Call->getArgOperand(Idx); 582 Type *ArgOpType = ArgOp->getType(); 583 584 if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy()) 585 continue; 586 587 auto *ConstVal = getConstantStackValue(Call, ArgOp); 588 if (!ConstVal) 589 continue; 590 591 Value *GV = new GlobalVariable(M, ConstVal->getType(), true, 592 GlobalValue::InternalLinkage, ConstVal, 593 "specialized.arg." + Twine(++NGlobals)); 594 Call->setArgOperand(Idx, GV); 595 } 596 } 597 } 598 599 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics 600 // interfere with the promoteConstantStackValues() optimization. 601 static void removeSSACopy(Function &F) { 602 for (BasicBlock &BB : F) { 603 for (Instruction &Inst : llvm::make_early_inc_range(BB)) { 604 auto *II = dyn_cast<IntrinsicInst>(&Inst); 605 if (!II) 606 continue; 607 if (II->getIntrinsicID() != Intrinsic::ssa_copy) 608 continue; 609 Inst.replaceAllUsesWith(II->getOperand(0)); 610 Inst.eraseFromParent(); 611 } 612 } 613 } 614 615 /// Remove any ssa_copy intrinsics that may have been introduced. 616 void FunctionSpecializer::cleanUpSSA() { 617 for (Function *F : Specializations) 618 removeSSACopy(*F); 619 } 620 621 622 template <> struct llvm::DenseMapInfo<SpecSig> { 623 static inline SpecSig getEmptyKey() { return {~0U, {}}; } 624 625 static inline SpecSig getTombstoneKey() { return {~1U, {}}; } 626 627 static unsigned getHashValue(const SpecSig &S) { 628 return static_cast<unsigned>(hash_value(S)); 629 } 630 631 static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) { 632 return LHS == RHS; 633 } 634 }; 635 636 FunctionSpecializer::~FunctionSpecializer() { 637 LLVM_DEBUG( 638 if (NumSpecsCreated > 0) 639 dbgs() << "FnSpecialization: Created " << NumSpecsCreated 640 << " specializations in module " << M.getName() << "\n"); 641 // Eliminate dead code. 642 removeDeadFunctions(); 643 cleanUpSSA(); 644 } 645 646 /// Attempt to specialize functions in the module to enable constant 647 /// propagation across function boundaries. 648 /// 649 /// \returns true if at least one function is specialized. 650 bool FunctionSpecializer::run() { 651 // Find possible specializations for each function. 652 SpecMap SM; 653 SmallVector<Spec, 32> AllSpecs; 654 unsigned NumCandidates = 0; 655 for (Function &F : M) { 656 if (!isCandidateFunction(&F)) 657 continue; 658 659 auto [It, Inserted] = FunctionMetrics.try_emplace(&F); 660 CodeMetrics &Metrics = It->second; 661 //Analyze the function. 662 if (Inserted) { 663 SmallPtrSet<const Value *, 32> EphValues; 664 CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues); 665 for (BasicBlock &BB : F) 666 Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues); 667 } 668 669 // When specializing literal constants is enabled, always require functions 670 // to be larger than MinFunctionSize, to prevent excessive specialization. 671 const bool RequireMinSize = 672 !ForceSpecialization && 673 (SpecializeLiteralConstant || !F.hasFnAttribute(Attribute::NoInline)); 674 675 // If the code metrics reveal that we shouldn't duplicate the function, 676 // or if the code size implies that this function is easy to get inlined, 677 // then we shouldn't specialize it. 678 if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() || 679 (RequireMinSize && Metrics.NumInsts < MinFunctionSize)) 680 continue; 681 682 // When specialization on literal constants is disabled, only consider 683 // recursive functions when running multiple times to save wasted analysis, 684 // as we will not be able to specialize on any newly found literal constant 685 // return values. 686 if (!SpecializeLiteralConstant && !Inserted && !Metrics.isRecursive) 687 continue; 688 689 int64_t Sz = *Metrics.NumInsts.getValue(); 690 assert(Sz > 0 && "CodeSize should be positive"); 691 // It is safe to down cast from int64_t, NumInsts is always positive. 692 unsigned FuncSize = static_cast<unsigned>(Sz); 693 694 LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for " 695 << F.getName() << " is " << FuncSize << "\n"); 696 697 if (Inserted && Metrics.isRecursive) 698 promoteConstantStackValues(&F); 699 700 if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) { 701 LLVM_DEBUG( 702 dbgs() << "FnSpecialization: No possible specializations found for " 703 << F.getName() << "\n"); 704 continue; 705 } 706 707 ++NumCandidates; 708 } 709 710 if (!NumCandidates) { 711 LLVM_DEBUG( 712 dbgs() 713 << "FnSpecialization: No possible specializations found in module\n"); 714 return false; 715 } 716 717 // Choose the most profitable specialisations, which fit in the module 718 // specialization budget, which is derived from maximum number of 719 // specializations per specialization candidate function. 720 auto CompareScore = [&AllSpecs](unsigned I, unsigned J) { 721 if (AllSpecs[I].Score != AllSpecs[J].Score) 722 return AllSpecs[I].Score > AllSpecs[J].Score; 723 return I > J; 724 }; 725 const unsigned NSpecs = 726 std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size())); 727 SmallVector<unsigned> BestSpecs(NSpecs + 1); 728 std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0); 729 if (AllSpecs.size() > NSpecs) { 730 LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed " 731 << "the maximum number of clones threshold.\n" 732 << "FnSpecialization: Specializing the " 733 << NSpecs 734 << " most profitable candidates.\n"); 735 std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore); 736 for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) { 737 BestSpecs[NSpecs] = I; 738 std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore); 739 std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore); 740 } 741 } 742 743 LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n"; 744 for (unsigned I = 0; I < NSpecs; ++I) { 745 const Spec &S = AllSpecs[BestSpecs[I]]; 746 dbgs() << "FnSpecialization: Function " << S.F->getName() 747 << " , score " << S.Score << "\n"; 748 for (const ArgInfo &Arg : S.Sig.Args) 749 dbgs() << "FnSpecialization: FormalArg = " 750 << Arg.Formal->getNameOrAsOperand() 751 << ", ActualArg = " << Arg.Actual->getNameOrAsOperand() 752 << "\n"; 753 }); 754 755 // Create the chosen specializations. 756 SmallPtrSet<Function *, 8> OriginalFuncs; 757 SmallVector<Function *> Clones; 758 for (unsigned I = 0; I < NSpecs; ++I) { 759 Spec &S = AllSpecs[BestSpecs[I]]; 760 S.Clone = createSpecialization(S.F, S.Sig); 761 762 // Update the known call sites to call the clone. 763 for (CallBase *Call : S.CallSites) { 764 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call 765 << " to call " << S.Clone->getName() << "\n"); 766 Call->setCalledFunction(S.Clone); 767 } 768 769 Clones.push_back(S.Clone); 770 OriginalFuncs.insert(S.F); 771 } 772 773 Solver.solveWhileResolvedUndefsIn(Clones); 774 775 // Update the rest of the call sites - these are the recursive calls, calls 776 // to discarded specialisations and calls that may match a specialisation 777 // after the solver runs. 778 for (Function *F : OriginalFuncs) { 779 auto [Begin, End] = SM[F]; 780 updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End); 781 } 782 783 for (Function *F : Clones) { 784 if (F->getReturnType()->isVoidTy()) 785 continue; 786 if (F->getReturnType()->isStructTy()) { 787 auto *STy = cast<StructType>(F->getReturnType()); 788 if (!Solver.isStructLatticeConstant(F, STy)) 789 continue; 790 } else { 791 auto It = Solver.getTrackedRetVals().find(F); 792 assert(It != Solver.getTrackedRetVals().end() && 793 "Return value ought to be tracked"); 794 if (SCCPSolver::isOverdefined(It->second)) 795 continue; 796 } 797 for (User *U : F->users()) { 798 if (auto *CS = dyn_cast<CallBase>(U)) { 799 //The user instruction does not call our function. 800 if (CS->getCalledFunction() != F) 801 continue; 802 Solver.resetLatticeValueFor(CS); 803 } 804 } 805 } 806 807 // Rerun the solver to notify the users of the modified callsites. 808 Solver.solveWhileResolvedUndefs(); 809 810 for (Function *F : OriginalFuncs) 811 if (FunctionMetrics[F].isRecursive) 812 promoteConstantStackValues(F); 813 814 return true; 815 } 816 817 void FunctionSpecializer::removeDeadFunctions() { 818 for (Function *F : FullySpecialized) { 819 LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function " 820 << F->getName() << "\n"); 821 if (FAM) 822 FAM->clear(*F, F->getName()); 823 F->eraseFromParent(); 824 } 825 FullySpecialized.clear(); 826 } 827 828 /// Clone the function \p F and remove the ssa_copy intrinsics added by 829 /// the SCCPSolver in the cloned version. 830 static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) { 831 ValueToValueMapTy Mappings; 832 Function *Clone = CloneFunction(F, Mappings); 833 Clone->setName(F->getName() + ".specialized." + Twine(NSpecs)); 834 removeSSACopy(*Clone); 835 return Clone; 836 } 837 838 /// Get the unsigned Value of given Cost object. Assumes the Cost is always 839 /// non-negative, which is true for both TCK_CodeSize and TCK_Latency, and 840 /// always Valid. 841 static unsigned getCostValue(const Cost &C) { 842 int64_t Value = *C.getValue(); 843 844 assert(Value >= 0 && "CodeSize and Latency cannot be negative"); 845 // It is safe to down cast since we know the arguments cannot be negative and 846 // Cost is of type int64_t. 847 return static_cast<unsigned>(Value); 848 } 849 850 bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize, 851 SmallVectorImpl<Spec> &AllSpecs, 852 SpecMap &SM) { 853 // A mapping from a specialisation signature to the index of the respective 854 // entry in the all specialisation array. Used to ensure uniqueness of 855 // specialisations. 856 DenseMap<SpecSig, unsigned> UniqueSpecs; 857 858 // Get a list of interesting arguments. 859 SmallVector<Argument *> Args; 860 for (Argument &Arg : F->args()) 861 if (isArgumentInteresting(&Arg)) 862 Args.push_back(&Arg); 863 864 if (Args.empty()) 865 return false; 866 867 for (User *U : F->users()) { 868 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 869 continue; 870 auto &CS = *cast<CallBase>(U); 871 872 // The user instruction does not call our function. 873 if (CS.getCalledFunction() != F) 874 continue; 875 876 // If the call site has attribute minsize set, that callsite won't be 877 // specialized. 878 if (CS.hasFnAttr(Attribute::MinSize)) 879 continue; 880 881 // If the parent of the call site will never be executed, we don't need 882 // to worry about the passed value. 883 if (!Solver.isBlockExecutable(CS.getParent())) 884 continue; 885 886 // Examine arguments and create a specialisation candidate from the 887 // constant operands of this call site. 888 SpecSig S; 889 for (Argument *A : Args) { 890 Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo())); 891 if (!C) 892 continue; 893 LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument " 894 << A->getName() << " : " << C->getNameOrAsOperand() 895 << "\n"); 896 S.Args.push_back({A, C}); 897 } 898 899 if (S.Args.empty()) 900 continue; 901 902 // Check if we have encountered the same specialisation already. 903 if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) { 904 // Existing specialisation. Add the call to the list to rewrite, unless 905 // it's a recursive call. A specialisation, generated because of a 906 // recursive call may end up as not the best specialisation for all 907 // the cloned instances of this call, which result from specialising 908 // functions. Hence we don't rewrite the call directly, but match it with 909 // the best specialisation once all specialisations are known. 910 if (CS.getFunction() == F) 911 continue; 912 const unsigned Index = It->second; 913 AllSpecs[Index].CallSites.push_back(&CS); 914 } else { 915 // Calculate the specialisation gain. 916 Cost CodeSize; 917 unsigned Score = 0; 918 InstCostVisitor Visitor = getInstCostVisitorFor(F); 919 for (ArgInfo &A : S.Args) { 920 CodeSize += Visitor.getCodeSizeSavingsForArg(A.Formal, A.Actual); 921 Score += getInliningBonus(A.Formal, A.Actual); 922 } 923 CodeSize += Visitor.getCodeSizeSavingsFromPendingPHIs(); 924 925 auto IsProfitable = [&]() -> bool { 926 // No check required. 927 if (ForceSpecialization) 928 return true; 929 930 unsigned CodeSizeSavings = getCostValue(CodeSize); 931 // TODO: We should only accumulate codesize increase of specializations 932 // that are actually created. 933 FunctionGrowth[F] += FuncSize - CodeSizeSavings; 934 935 LLVM_DEBUG( 936 dbgs() << "FnSpecialization: Specialization bonus {Inlining = " 937 << Score << " (" << (Score * 100 / FuncSize) << "%)}\n"); 938 939 // Minimum inlining bonus. 940 if (Score > MinInliningBonus * FuncSize / 100) 941 return true; 942 943 LLVM_DEBUG( 944 dbgs() << "FnSpecialization: Specialization bonus {CodeSize = " 945 << CodeSizeSavings << " (" 946 << (CodeSizeSavings * 100 / FuncSize) << "%)}\n"); 947 948 // Minimum codesize savings. 949 if (CodeSizeSavings < MinCodeSizeSavings * FuncSize / 100) 950 return false; 951 952 // Lazily compute the Latency, to avoid unnecessarily computing BFI. 953 unsigned LatencySavings = 954 getCostValue(Visitor.getLatencySavingsForKnownConstants()); 955 956 LLVM_DEBUG( 957 dbgs() << "FnSpecialization: Specialization bonus {Latency = " 958 << LatencySavings << " (" 959 << (LatencySavings * 100 / FuncSize) << "%)}\n"); 960 961 // Minimum latency savings. 962 if (LatencySavings < MinLatencySavings * FuncSize / 100) 963 return false; 964 // Maximum codesize growth. 965 if (FunctionGrowth[F] / FuncSize > MaxCodeSizeGrowth) 966 return false; 967 968 Score += std::max(CodeSizeSavings, LatencySavings); 969 return true; 970 }; 971 972 // Discard unprofitable specialisations. 973 if (!IsProfitable()) 974 continue; 975 976 // Create a new specialisation entry. 977 auto &Spec = AllSpecs.emplace_back(F, S, Score); 978 if (CS.getFunction() != F) 979 Spec.CallSites.push_back(&CS); 980 const unsigned Index = AllSpecs.size() - 1; 981 UniqueSpecs[S] = Index; 982 if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted) 983 It->second.second = Index + 1; 984 } 985 } 986 987 return !UniqueSpecs.empty(); 988 } 989 990 bool FunctionSpecializer::isCandidateFunction(Function *F) { 991 if (F->isDeclaration() || F->arg_empty()) 992 return false; 993 994 if (F->hasFnAttribute(Attribute::NoDuplicate)) 995 return false; 996 997 // Do not specialize the cloned function again. 998 if (Specializations.contains(F)) 999 return false; 1000 1001 // If we're optimizing the function for size, we shouldn't specialize it. 1002 if (shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass)) 1003 return false; 1004 1005 // Exit if the function is not executable. There's no point in specializing 1006 // a dead function. 1007 if (!Solver.isBlockExecutable(&F->getEntryBlock())) 1008 return false; 1009 1010 // It wastes time to specialize a function which would get inlined finally. 1011 if (F->hasFnAttribute(Attribute::AlwaysInline)) 1012 return false; 1013 1014 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName() 1015 << "\n"); 1016 return true; 1017 } 1018 1019 Function *FunctionSpecializer::createSpecialization(Function *F, 1020 const SpecSig &S) { 1021 Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1); 1022 1023 // The original function does not neccessarily have internal linkage, but the 1024 // clone must. 1025 Clone->setLinkage(GlobalValue::InternalLinkage); 1026 1027 // Initialize the lattice state of the arguments of the function clone, 1028 // marking the argument on which we specialized the function constant 1029 // with the given value. 1030 Solver.setLatticeValueForSpecializationArguments(Clone, S.Args); 1031 Solver.markBlockExecutable(&Clone->front()); 1032 Solver.addArgumentTrackedFunction(Clone); 1033 Solver.addTrackedFunction(Clone); 1034 1035 // Mark all the specialized functions 1036 Specializations.insert(Clone); 1037 ++NumSpecsCreated; 1038 1039 return Clone; 1040 } 1041 1042 /// Compute the inlining bonus for replacing argument \p A with constant \p C. 1043 /// The below heuristic is only concerned with exposing inlining 1044 /// opportunities via indirect call promotion. If the argument is not a 1045 /// (potentially casted) function pointer, give up. 1046 unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) { 1047 Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts()); 1048 if (!CalledFunction) 1049 return 0; 1050 1051 // Get TTI for the called function (used for the inline cost). 1052 auto &CalleeTTI = (GetTTI)(*CalledFunction); 1053 1054 // Look at all the call sites whose called value is the argument. 1055 // Specializing the function on the argument would allow these indirect 1056 // calls to be promoted to direct calls. If the indirect call promotion 1057 // would likely enable the called function to be inlined, specializing is a 1058 // good idea. 1059 int InliningBonus = 0; 1060 for (User *U : A->users()) { 1061 if (!isa<CallInst>(U) && !isa<InvokeInst>(U)) 1062 continue; 1063 auto *CS = cast<CallBase>(U); 1064 if (CS->getCalledOperand() != A) 1065 continue; 1066 if (CS->getFunctionType() != CalledFunction->getFunctionType()) 1067 continue; 1068 1069 // Get the cost of inlining the called function at this call site. Note 1070 // that this is only an estimate. The called function may eventually 1071 // change in a way that leads to it not being inlined here, even though 1072 // inlining looks profitable now. For example, one of its called 1073 // functions may be inlined into it, making the called function too large 1074 // to be inlined into this call site. 1075 // 1076 // We apply a boost for performing indirect call promotion by increasing 1077 // the default threshold by the threshold for indirect calls. 1078 auto Params = getInlineParams(); 1079 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold; 1080 InlineCost IC = 1081 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI); 1082 1083 // We clamp the bonus for this call to be between zero and the default 1084 // threshold. 1085 if (IC.isAlways()) 1086 InliningBonus += Params.DefaultThreshold; 1087 else if (IC.isVariable() && IC.getCostDelta() > 0) 1088 InliningBonus += IC.getCostDelta(); 1089 1090 LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << InliningBonus 1091 << " for user " << *U << "\n"); 1092 } 1093 1094 return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0; 1095 } 1096 1097 /// Determine if it is possible to specialise the function for constant values 1098 /// of the formal parameter \p A. 1099 bool FunctionSpecializer::isArgumentInteresting(Argument *A) { 1100 // No point in specialization if the argument is unused. 1101 if (A->user_empty()) 1102 return false; 1103 1104 Type *Ty = A->getType(); 1105 if (!Ty->isPointerTy() && (!SpecializeLiteralConstant || 1106 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy()))) 1107 return false; 1108 1109 // SCCP solver does not record an argument that will be constructed on 1110 // stack. 1111 if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory()) 1112 return false; 1113 1114 // For non-argument-tracked functions every argument is overdefined. 1115 if (!Solver.isArgumentTrackedFunction(A->getParent())) 1116 return true; 1117 1118 // Check the lattice value and decide if we should attemt to specialize, 1119 // based on this argument. No point in specialization, if the lattice value 1120 // is already a constant. 1121 bool IsOverdefined = Ty->isStructTy() 1122 ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined) 1123 : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A)); 1124 1125 LLVM_DEBUG( 1126 if (IsOverdefined) 1127 dbgs() << "FnSpecialization: Found interesting parameter " 1128 << A->getNameOrAsOperand() << "\n"; 1129 else 1130 dbgs() << "FnSpecialization: Nothing to do, parameter " 1131 << A->getNameOrAsOperand() << " is already constant\n"; 1132 ); 1133 return IsOverdefined; 1134 } 1135 1136 /// Check if the value \p V (an actual argument) is a constant or can only 1137 /// have a constant value. Return that constant. 1138 Constant *FunctionSpecializer::getCandidateConstant(Value *V) { 1139 if (isa<PoisonValue>(V)) 1140 return nullptr; 1141 1142 // Select for possible specialisation values that are constants or 1143 // are deduced to be constants or constant ranges with a single element. 1144 Constant *C = dyn_cast<Constant>(V); 1145 if (!C) 1146 C = Solver.getConstantOrNull(V); 1147 1148 // Don't specialize on (anything derived from) the address of a non-constant 1149 // global variable, unless explicitly enabled. 1150 if (C && C->getType()->isPointerTy() && !C->isNullValue()) 1151 if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C)); 1152 GV && !(GV->isConstant() || SpecializeOnAddress)) 1153 return nullptr; 1154 1155 return C; 1156 } 1157 1158 void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin, 1159 const Spec *End) { 1160 // Collect the call sites that need updating. 1161 SmallVector<CallBase *> ToUpdate; 1162 for (User *U : F->users()) 1163 if (auto *CS = dyn_cast<CallBase>(U); 1164 CS && CS->getCalledFunction() == F && 1165 Solver.isBlockExecutable(CS->getParent())) 1166 ToUpdate.push_back(CS); 1167 1168 unsigned NCallsLeft = ToUpdate.size(); 1169 for (CallBase *CS : ToUpdate) { 1170 bool ShouldDecrementCount = CS->getFunction() == F; 1171 1172 // Find the best matching specialisation. 1173 const Spec *BestSpec = nullptr; 1174 for (const Spec &S : make_range(Begin, End)) { 1175 if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score)) 1176 continue; 1177 1178 if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) { 1179 unsigned ArgNo = Arg.Formal->getArgNo(); 1180 return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual; 1181 })) 1182 continue; 1183 1184 BestSpec = &S; 1185 } 1186 1187 if (BestSpec) { 1188 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS 1189 << " to call " << BestSpec->Clone->getName() << "\n"); 1190 CS->setCalledFunction(BestSpec->Clone); 1191 ShouldDecrementCount = true; 1192 } 1193 1194 if (ShouldDecrementCount) 1195 --NCallsLeft; 1196 } 1197 1198 // If the function has been completely specialized, the original function 1199 // is no longer needed. Mark it unreachable. 1200 if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) { 1201 Solver.markFunctionUnreachable(F); 1202 FullySpecialized.insert(F); 1203 } 1204 } 1205