1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===// 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 file implements inline cost analysis. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/InlineCost.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/AssumptionCache.h" 20 #include "llvm/Analysis/BlockFrequencyInfo.h" 21 #include "llvm/Analysis/CFG.h" 22 #include "llvm/Analysis/CodeMetrics.h" 23 #include "llvm/Analysis/ConstantFolding.h" 24 #include "llvm/Analysis/InstructionSimplify.h" 25 #include "llvm/Analysis/LoopInfo.h" 26 #include "llvm/Analysis/ProfileSummaryInfo.h" 27 #include "llvm/Analysis/TargetTransformInfo.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Config/llvm-config.h" 30 #include "llvm/IR/CallingConv.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Dominators.h" 33 #include "llvm/IR/GetElementPtrTypeIterator.h" 34 #include "llvm/IR/GlobalAlias.h" 35 #include "llvm/IR/InstVisitor.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/IR/Operator.h" 38 #include "llvm/IR/PatternMatch.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/raw_ostream.h" 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "inline-cost" 46 47 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed"); 48 49 static cl::opt<int> InlineThreshold( 50 "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore, 51 cl::desc("Control the amount of inlining to perform (default = 225)")); 52 53 static cl::opt<int> HintThreshold( 54 "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore, 55 cl::desc("Threshold for inlining functions with inline hint")); 56 57 static cl::opt<int> 58 ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden, 59 cl::init(45), cl::ZeroOrMore, 60 cl::desc("Threshold for inlining cold callsites")); 61 62 // We introduce this threshold to help performance of instrumentation based 63 // PGO before we actually hook up inliner with analysis passes such as BPI and 64 // BFI. 65 static cl::opt<int> ColdThreshold( 66 "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore, 67 cl::desc("Threshold for inlining functions with cold attribute")); 68 69 static cl::opt<int> 70 HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000), 71 cl::ZeroOrMore, 72 cl::desc("Threshold for hot callsites ")); 73 74 static cl::opt<int> LocallyHotCallSiteThreshold( 75 "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore, 76 cl::desc("Threshold for locally hot callsites ")); 77 78 static cl::opt<int> ColdCallSiteRelFreq( 79 "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore, 80 cl::desc("Maximum block frequency, expressed as a percentage of caller's " 81 "entry frequency, for a callsite to be cold in the absence of " 82 "profile information.")); 83 84 static cl::opt<int> HotCallSiteRelFreq( 85 "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore, 86 cl::desc("Minimum block frequency, expressed as a multiple of caller's " 87 "entry frequency, for a callsite to be hot in the absence of " 88 "profile information.")); 89 90 static cl::opt<bool> OptComputeFullInlineCost( 91 "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore, 92 cl::desc("Compute the full inline cost of a call site even when the cost " 93 "exceeds the threshold.")); 94 95 namespace { 96 class InlineCostCallAnalyzer; 97 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> { 98 typedef InstVisitor<CallAnalyzer, bool> Base; 99 friend class InstVisitor<CallAnalyzer, bool>; 100 101 protected: 102 virtual ~CallAnalyzer() {} 103 /// The TargetTransformInfo available for this compilation. 104 const TargetTransformInfo &TTI; 105 106 /// Getter for the cache of @llvm.assume intrinsics. 107 std::function<AssumptionCache &(Function &)> &GetAssumptionCache; 108 109 /// Getter for BlockFrequencyInfo 110 Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI; 111 112 /// Profile summary information. 113 ProfileSummaryInfo *PSI; 114 115 /// The called function. 116 Function &F; 117 118 // Cache the DataLayout since we use it a lot. 119 const DataLayout &DL; 120 121 /// The OptimizationRemarkEmitter available for this compilation. 122 OptimizationRemarkEmitter *ORE; 123 124 /// The candidate callsite being analyzed. Please do not use this to do 125 /// analysis in the caller function; we want the inline cost query to be 126 /// easily cacheable. Instead, use the cover function paramHasAttr. 127 CallBase &CandidateCall; 128 129 /// Extension points for handling callsite features. 130 /// Called after a basic block was analyzed. 131 virtual void onBlockAnalyzed(const BasicBlock *BB) {} 132 133 /// Called at the end of the analysis of the callsite. Return the outcome of 134 /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or 135 /// the reason it can't. 136 virtual InlineResult finalizeAnalysis() { return InlineResult::success(); } 137 /// Called when we're about to start processing a basic block, and every time 138 /// we are done processing an instruction. Return true if there is no point in 139 /// continuing the analysis (e.g. we've determined already the call site is 140 /// too expensive to inline) 141 virtual bool shouldStop() { return false; } 142 143 /// Called before the analysis of the callee body starts (with callsite 144 /// contexts propagated). It checks callsite-specific information. Return a 145 /// reason analysis can't continue if that's the case, or 'true' if it may 146 /// continue. 147 virtual InlineResult onAnalysisStart() { return InlineResult::success(); } 148 /// Called if the analysis engine decides SROA cannot be done for the given 149 /// alloca. 150 virtual void onDisableSROA(AllocaInst *Arg) {} 151 152 /// Called the analysis engine determines load elimination won't happen. 153 virtual void onDisableLoadElimination() {} 154 155 /// Called to account for a call. 156 virtual void onCallPenalty() {} 157 158 /// Called to account for the expectation the inlining would result in a load 159 /// elimination. 160 virtual void onLoadEliminationOpportunity() {} 161 162 /// Called to account for the cost of argument setup for the Call in the 163 /// callee's body (not the callsite currently under analysis). 164 virtual void onCallArgumentSetup(const CallBase &Call) {} 165 166 /// Called to account for a load relative intrinsic. 167 virtual void onLoadRelativeIntrinsic() {} 168 169 /// Called to account for a lowered call. 170 virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) { 171 } 172 173 /// Account for a jump table of given size. Return false to stop further 174 /// processing the switch instruction 175 virtual bool onJumpTable(unsigned JumpTableSize) { return true; } 176 177 /// Account for a case cluster of given size. Return false to stop further 178 /// processing of the instruction. 179 virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; } 180 181 /// Called at the end of processing a switch instruction, with the given 182 /// number of case clusters. 183 virtual void onFinalizeSwitch(unsigned JumpTableSize, 184 unsigned NumCaseCluster) {} 185 186 /// Called to account for any other instruction not specifically accounted 187 /// for. 188 virtual void onCommonInstructionSimplification() {} 189 190 /// Start accounting potential benefits due to SROA for the given alloca. 191 virtual void onInitializeSROAArg(AllocaInst *Arg) {} 192 193 /// Account SROA savings for the AllocaInst value. 194 virtual void onAggregateSROAUse(AllocaInst *V) {} 195 196 bool handleSROA(Value *V, bool DoNotDisable) { 197 // Check for SROA candidates in comparisons. 198 if (auto *SROAArg = getSROAArgForValueOrNull(V)) { 199 if (DoNotDisable) { 200 onAggregateSROAUse(SROAArg); 201 return true; 202 } 203 disableSROAForArg(SROAArg); 204 } 205 return false; 206 } 207 208 bool IsCallerRecursive = false; 209 bool IsRecursiveCall = false; 210 bool ExposesReturnsTwice = false; 211 bool HasDynamicAlloca = false; 212 bool ContainsNoDuplicateCall = false; 213 bool HasReturn = false; 214 bool HasIndirectBr = false; 215 bool HasUninlineableIntrinsic = false; 216 bool InitsVargArgs = false; 217 218 /// Number of bytes allocated statically by the callee. 219 uint64_t AllocatedSize = 0; 220 unsigned NumInstructions = 0; 221 unsigned NumVectorInstructions = 0; 222 223 /// While we walk the potentially-inlined instructions, we build up and 224 /// maintain a mapping of simplified values specific to this callsite. The 225 /// idea is to propagate any special information we have about arguments to 226 /// this call through the inlinable section of the function, and account for 227 /// likely simplifications post-inlining. The most important aspect we track 228 /// is CFG altering simplifications -- when we prove a basic block dead, that 229 /// can cause dramatic shifts in the cost of inlining a function. 230 DenseMap<Value *, Constant *> SimplifiedValues; 231 232 /// Keep track of the values which map back (through function arguments) to 233 /// allocas on the caller stack which could be simplified through SROA. 234 DenseMap<Value *, AllocaInst *> SROAArgValues; 235 236 /// Keep track of Allocas for which we believe we may get SROA optimization. 237 /// We don't delete entries in SROAArgValue because we still want 238 /// isAllocaDerivedArg to function correctly. 239 DenseSet<AllocaInst *> EnabledSROAArgValues; 240 241 /// Keep track of values which map to a pointer base and constant offset. 242 DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs; 243 244 /// Keep track of dead blocks due to the constant arguments. 245 SetVector<BasicBlock *> DeadBlocks; 246 247 /// The mapping of the blocks to their known unique successors due to the 248 /// constant arguments. 249 DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors; 250 251 /// Model the elimination of repeated loads that is expected to happen 252 /// whenever we simplify away the stores that would otherwise cause them to be 253 /// loads. 254 bool EnableLoadElimination; 255 SmallPtrSet<Value *, 16> LoadAddrSet; 256 257 AllocaInst *getSROAArgForValueOrNull(Value *V) const { 258 auto It = SROAArgValues.find(V); 259 if (It == SROAArgValues.end() || 260 EnabledSROAArgValues.count(It->second) == 0) 261 return nullptr; 262 return It->second; 263 } 264 265 // Custom simplification helper routines. 266 bool isAllocaDerivedArg(Value *V); 267 void disableSROAForArg(AllocaInst *SROAArg); 268 void disableSROA(Value *V); 269 void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB); 270 void disableLoadElimination(); 271 bool isGEPFree(GetElementPtrInst &GEP); 272 bool canFoldInboundsGEP(GetElementPtrInst &I); 273 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset); 274 bool simplifyCallSite(Function *F, CallBase &Call); 275 template <typename Callable> 276 bool simplifyInstruction(Instruction &I, Callable Evaluate); 277 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V); 278 279 /// Return true if the given argument to the function being considered for 280 /// inlining has the given attribute set either at the call site or the 281 /// function declaration. Primarily used to inspect call site specific 282 /// attributes since these can be more precise than the ones on the callee 283 /// itself. 284 bool paramHasAttr(Argument *A, Attribute::AttrKind Attr); 285 286 /// Return true if the given value is known non null within the callee if 287 /// inlined through this particular callsite. 288 bool isKnownNonNullInCallee(Value *V); 289 290 /// Return true if size growth is allowed when inlining the callee at \p Call. 291 bool allowSizeGrowth(CallBase &Call); 292 293 // Custom analysis routines. 294 InlineResult analyzeBlock(BasicBlock *BB, 295 SmallPtrSetImpl<const Value *> &EphValues); 296 297 // Disable several entry points to the visitor so we don't accidentally use 298 // them by declaring but not defining them here. 299 void visit(Module *); 300 void visit(Module &); 301 void visit(Function *); 302 void visit(Function &); 303 void visit(BasicBlock *); 304 void visit(BasicBlock &); 305 306 // Provide base case for our instruction visit. 307 bool visitInstruction(Instruction &I); 308 309 // Our visit overrides. 310 bool visitAlloca(AllocaInst &I); 311 bool visitPHI(PHINode &I); 312 bool visitGetElementPtr(GetElementPtrInst &I); 313 bool visitBitCast(BitCastInst &I); 314 bool visitPtrToInt(PtrToIntInst &I); 315 bool visitIntToPtr(IntToPtrInst &I); 316 bool visitCastInst(CastInst &I); 317 bool visitUnaryInstruction(UnaryInstruction &I); 318 bool visitCmpInst(CmpInst &I); 319 bool visitSub(BinaryOperator &I); 320 bool visitBinaryOperator(BinaryOperator &I); 321 bool visitFNeg(UnaryOperator &I); 322 bool visitLoad(LoadInst &I); 323 bool visitStore(StoreInst &I); 324 bool visitExtractValue(ExtractValueInst &I); 325 bool visitInsertValue(InsertValueInst &I); 326 bool visitCallBase(CallBase &Call); 327 bool visitReturnInst(ReturnInst &RI); 328 bool visitBranchInst(BranchInst &BI); 329 bool visitSelectInst(SelectInst &SI); 330 bool visitSwitchInst(SwitchInst &SI); 331 bool visitIndirectBrInst(IndirectBrInst &IBI); 332 bool visitResumeInst(ResumeInst &RI); 333 bool visitCleanupReturnInst(CleanupReturnInst &RI); 334 bool visitCatchReturnInst(CatchReturnInst &RI); 335 bool visitUnreachableInst(UnreachableInst &I); 336 337 public: 338 CallAnalyzer(const TargetTransformInfo &TTI, 339 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 340 Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 341 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, 342 Function &Callee, CallBase &Call) 343 : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI), 344 PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE), 345 CandidateCall(Call), EnableLoadElimination(true) {} 346 347 InlineResult analyze(); 348 349 // Keep a bunch of stats about the cost savings found so we can print them 350 // out when debugging. 351 unsigned NumConstantArgs = 0; 352 unsigned NumConstantOffsetPtrArgs = 0; 353 unsigned NumAllocaArgs = 0; 354 unsigned NumConstantPtrCmps = 0; 355 unsigned NumConstantPtrDiffs = 0; 356 unsigned NumInstructionsSimplified = 0; 357 358 void dump(); 359 }; 360 361 /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note 362 /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer 363 class InlineCostCallAnalyzer final : public CallAnalyzer { 364 const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1; 365 const bool ComputeFullInlineCost; 366 int LoadEliminationCost = 0; 367 /// Bonus to be applied when percentage of vector instructions in callee is 368 /// high (see more details in updateThreshold). 369 int VectorBonus = 0; 370 /// Bonus to be applied when the callee has only one reachable basic block. 371 int SingleBBBonus = 0; 372 373 /// Tunable parameters that control the analysis. 374 const InlineParams &Params; 375 376 /// Upper bound for the inlining cost. Bonuses are being applied to account 377 /// for speculative "expected profit" of the inlining decision. 378 int Threshold = 0; 379 380 /// Attempt to evaluate indirect calls to boost its inline cost. 381 const bool BoostIndirectCalls; 382 383 /// Inlining cost measured in abstract units, accounts for all the 384 /// instructions expected to be executed for a given function invocation. 385 /// Instructions that are statically proven to be dead based on call-site 386 /// arguments are not counted here. 387 int Cost = 0; 388 389 bool SingleBB = true; 390 391 unsigned SROACostSavings = 0; 392 unsigned SROACostSavingsLost = 0; 393 394 /// The mapping of caller Alloca values to their accumulated cost savings. If 395 /// we have to disable SROA for one of the allocas, this tells us how much 396 /// cost must be added. 397 DenseMap<AllocaInst *, int> SROAArgCosts; 398 399 /// Return true if \p Call is a cold callsite. 400 bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI); 401 402 /// Update Threshold based on callsite properties such as callee 403 /// attributes and callee hotness for PGO builds. The Callee is explicitly 404 /// passed to support analyzing indirect calls whose target is inferred by 405 /// analysis. 406 void updateThreshold(CallBase &Call, Function &Callee); 407 /// Return a higher threshold if \p Call is a hot callsite. 408 Optional<int> getHotCallSiteThreshold(CallBase &Call, 409 BlockFrequencyInfo *CallerBFI); 410 411 /// Handle a capped 'int' increment for Cost. 412 void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) { 413 assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound"); 414 Cost = (int)std::min(UpperBound, Cost + Inc); 415 } 416 417 void onDisableSROA(AllocaInst *Arg) override { 418 auto CostIt = SROAArgCosts.find(Arg); 419 if (CostIt == SROAArgCosts.end()) 420 return; 421 addCost(CostIt->second); 422 SROACostSavings -= CostIt->second; 423 SROACostSavingsLost += CostIt->second; 424 SROAArgCosts.erase(CostIt); 425 } 426 427 void onDisableLoadElimination() override { 428 addCost(LoadEliminationCost); 429 LoadEliminationCost = 0; 430 } 431 void onCallPenalty() override { addCost(InlineConstants::CallPenalty); } 432 void onCallArgumentSetup(const CallBase &Call) override { 433 // Pay the price of the argument setup. We account for the average 1 434 // instruction per call argument setup here. 435 addCost(Call.arg_size() * InlineConstants::InstrCost); 436 } 437 void onLoadRelativeIntrinsic() override { 438 // This is normally lowered to 4 LLVM instructions. 439 addCost(3 * InlineConstants::InstrCost); 440 } 441 void onLoweredCall(Function *F, CallBase &Call, 442 bool IsIndirectCall) override { 443 // We account for the average 1 instruction per call argument setup here. 444 addCost(Call.arg_size() * InlineConstants::InstrCost); 445 446 // If we have a constant that we are calling as a function, we can peer 447 // through it and see the function target. This happens not infrequently 448 // during devirtualization and so we want to give it a hefty bonus for 449 // inlining, but cap that bonus in the event that inlining wouldn't pan out. 450 // Pretend to inline the function, with a custom threshold. 451 if (IsIndirectCall && BoostIndirectCalls) { 452 auto IndirectCallParams = Params; 453 IndirectCallParams.DefaultThreshold = 454 InlineConstants::IndirectCallThreshold; 455 /// FIXME: if InlineCostCallAnalyzer is derived from, this may need 456 /// to instantiate the derived class. 457 InlineCostCallAnalyzer CA(TTI, GetAssumptionCache, GetBFI, PSI, ORE, *F, 458 Call, IndirectCallParams, false); 459 if (CA.analyze().isSuccess()) { 460 // We were able to inline the indirect call! Subtract the cost from the 461 // threshold to get the bonus we want to apply, but don't go below zero. 462 Cost -= std::max(0, CA.getThreshold() - CA.getCost()); 463 } 464 } else 465 // Otherwise simply add the cost for merely making the call. 466 addCost(InlineConstants::CallPenalty); 467 } 468 469 void onFinalizeSwitch(unsigned JumpTableSize, 470 unsigned NumCaseCluster) override { 471 // If suitable for a jump table, consider the cost for the table size and 472 // branch to destination. 473 // Maximum valid cost increased in this function. 474 if (JumpTableSize) { 475 int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost + 476 4 * InlineConstants::InstrCost; 477 478 addCost(JTCost, (int64_t)CostUpperBound); 479 return; 480 } 481 // Considering forming a binary search, we should find the number of nodes 482 // which is same as the number of comparisons when lowered. For a given 483 // number of clusters, n, we can define a recursive function, f(n), to find 484 // the number of nodes in the tree. The recursion is : 485 // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3, 486 // and f(n) = n, when n <= 3. 487 // This will lead a binary tree where the leaf should be either f(2) or f(3) 488 // when n > 3. So, the number of comparisons from leaves should be n, while 489 // the number of non-leaf should be : 490 // 2^(log2(n) - 1) - 1 491 // = 2^log2(n) * 2^-1 - 1 492 // = n / 2 - 1. 493 // Considering comparisons from leaf and non-leaf nodes, we can estimate the 494 // number of comparisons in a simple closed form : 495 // n + n / 2 - 1 = n * 3 / 2 - 1 496 if (NumCaseCluster <= 3) { 497 // Suppose a comparison includes one compare and one conditional branch. 498 addCost(NumCaseCluster * 2 * InlineConstants::InstrCost); 499 return; 500 } 501 502 int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1; 503 int64_t SwitchCost = 504 ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost; 505 506 addCost(SwitchCost, (int64_t)CostUpperBound); 507 } 508 void onCommonInstructionSimplification() override { 509 addCost(InlineConstants::InstrCost); 510 } 511 512 void onInitializeSROAArg(AllocaInst *Arg) override { 513 assert(Arg != nullptr && 514 "Should not initialize SROA costs for null value."); 515 SROAArgCosts[Arg] = 0; 516 EnabledSROAArgValues.insert(Arg); 517 } 518 519 void onAggregateSROAUse(AllocaInst *SROAArg) override { 520 auto CostIt = SROAArgCosts.find(SROAArg); 521 assert(CostIt != SROAArgCosts.end() && 522 "expected this argument to have a cost"); 523 CostIt->second += InlineConstants::InstrCost; 524 SROACostSavings += InlineConstants::InstrCost; 525 } 526 527 void onBlockAnalyzed(const BasicBlock *BB) override { 528 auto *TI = BB->getTerminator(); 529 // If we had any successors at this point, than post-inlining is likely to 530 // have them as well. Note that we assume any basic blocks which existed 531 // due to branches or switches which folded above will also fold after 532 // inlining. 533 if (SingleBB && TI->getNumSuccessors() > 1) { 534 // Take off the bonus we applied to the threshold. 535 Threshold -= SingleBBBonus; 536 SingleBB = false; 537 } 538 } 539 540 InlineResult finalizeAnalysis() override { 541 // Loops generally act a lot like calls in that they act like barriers to 542 // movement, require a certain amount of setup, etc. So when optimising for 543 // size, we penalise any call sites that perform loops. We do this after all 544 // other costs here, so will likely only be dealing with relatively small 545 // functions (and hence DT and LI will hopefully be cheap). 546 auto *Caller = CandidateCall.getFunction(); 547 if (Caller->hasMinSize()) { 548 DominatorTree DT(F); 549 LoopInfo LI(DT); 550 int NumLoops = 0; 551 for (Loop *L : LI) { 552 // Ignore loops that will not be executed 553 if (DeadBlocks.count(L->getHeader())) 554 continue; 555 NumLoops++; 556 } 557 addCost(NumLoops * InlineConstants::CallPenalty); 558 } 559 560 // We applied the maximum possible vector bonus at the beginning. Now, 561 // subtract the excess bonus, if any, from the Threshold before 562 // comparing against Cost. 563 if (NumVectorInstructions <= NumInstructions / 10) 564 Threshold -= VectorBonus; 565 else if (NumVectorInstructions <= NumInstructions / 2) 566 Threshold -= VectorBonus / 2; 567 568 if (Cost < std::max(1, Threshold)) 569 return InlineResult::success(); 570 return InlineResult::failure("Cost over threshold."); 571 } 572 bool shouldStop() override { 573 // Bail out the moment we cross the threshold. This means we'll under-count 574 // the cost, but only when undercounting doesn't matter. 575 return Cost >= Threshold && !ComputeFullInlineCost; 576 } 577 578 void onLoadEliminationOpportunity() override { 579 LoadEliminationCost += InlineConstants::InstrCost; 580 } 581 582 InlineResult onAnalysisStart() override { 583 // Perform some tweaks to the cost and threshold based on the direct 584 // callsite information. 585 586 // We want to more aggressively inline vector-dense kernels, so up the 587 // threshold, and we'll lower it if the % of vector instructions gets too 588 // low. Note that these bonuses are some what arbitrary and evolved over 589 // time by accident as much as because they are principled bonuses. 590 // 591 // FIXME: It would be nice to remove all such bonuses. At least it would be 592 // nice to base the bonus values on something more scientific. 593 assert(NumInstructions == 0); 594 assert(NumVectorInstructions == 0); 595 596 // Update the threshold based on callsite properties 597 updateThreshold(CandidateCall, F); 598 599 // While Threshold depends on commandline options that can take negative 600 // values, we want to enforce the invariant that the computed threshold and 601 // bonuses are non-negative. 602 assert(Threshold >= 0); 603 assert(SingleBBBonus >= 0); 604 assert(VectorBonus >= 0); 605 606 // Speculatively apply all possible bonuses to Threshold. If cost exceeds 607 // this Threshold any time, and cost cannot decrease, we can stop processing 608 // the rest of the function body. 609 Threshold += (SingleBBBonus + VectorBonus); 610 611 // Give out bonuses for the callsite, as the instructions setting them up 612 // will be gone after inlining. 613 addCost(-getCallsiteCost(this->CandidateCall, DL)); 614 615 // If this function uses the coldcc calling convention, prefer not to inline 616 // it. 617 if (F.getCallingConv() == CallingConv::Cold) 618 Cost += InlineConstants::ColdccPenalty; 619 620 // Check if we're done. This can happen due to bonuses and penalties. 621 if (Cost >= Threshold && !ComputeFullInlineCost) 622 return InlineResult::failure("high cost"); 623 624 return InlineResult::success(); 625 } 626 627 public: 628 InlineCostCallAnalyzer( 629 const TargetTransformInfo &TTI, 630 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 631 Optional<function_ref<BlockFrequencyInfo &(Function &)>> &GetBFI, 632 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee, 633 CallBase &Call, const InlineParams &Params, bool BoostIndirect = true) 634 : CallAnalyzer(TTI, GetAssumptionCache, GetBFI, PSI, ORE, Callee, Call), 635 ComputeFullInlineCost(OptComputeFullInlineCost || 636 Params.ComputeFullInlineCost || ORE), 637 Params(Params), Threshold(Params.DefaultThreshold), 638 BoostIndirectCalls(BoostIndirect) {} 639 void dump(); 640 641 virtual ~InlineCostCallAnalyzer() {} 642 int getThreshold() { return Threshold; } 643 int getCost() { return Cost; } 644 }; 645 } // namespace 646 647 /// Test whether the given value is an Alloca-derived function argument. 648 bool CallAnalyzer::isAllocaDerivedArg(Value *V) { 649 return SROAArgValues.count(V); 650 } 651 652 void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) { 653 onDisableSROA(SROAArg); 654 EnabledSROAArgValues.erase(SROAArg); 655 disableLoadElimination(); 656 } 657 /// If 'V' maps to a SROA candidate, disable SROA for it. 658 void CallAnalyzer::disableSROA(Value *V) { 659 if (auto *SROAArg = getSROAArgForValueOrNull(V)) { 660 disableSROAForArg(SROAArg); 661 } 662 } 663 664 void CallAnalyzer::disableLoadElimination() { 665 if (EnableLoadElimination) { 666 onDisableLoadElimination(); 667 EnableLoadElimination = false; 668 } 669 } 670 671 /// Accumulate a constant GEP offset into an APInt if possible. 672 /// 673 /// Returns false if unable to compute the offset for any reason. Respects any 674 /// simplified values known during the analysis of this callsite. 675 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) { 676 unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType()); 677 assert(IntPtrWidth == Offset.getBitWidth()); 678 679 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); 680 GTI != GTE; ++GTI) { 681 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 682 if (!OpC) 683 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand())) 684 OpC = dyn_cast<ConstantInt>(SimpleOp); 685 if (!OpC) 686 return false; 687 if (OpC->isZero()) 688 continue; 689 690 // Handle a struct index, which adds its field offset to the pointer. 691 if (StructType *STy = GTI.getStructTypeOrNull()) { 692 unsigned ElementIdx = OpC->getZExtValue(); 693 const StructLayout *SL = DL.getStructLayout(STy); 694 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx)); 695 continue; 696 } 697 698 APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType())); 699 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize; 700 } 701 return true; 702 } 703 704 /// Use TTI to check whether a GEP is free. 705 /// 706 /// Respects any simplified values known during the analysis of this callsite. 707 bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) { 708 SmallVector<Value *, 4> Operands; 709 Operands.push_back(GEP.getOperand(0)); 710 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 711 if (Constant *SimpleOp = SimplifiedValues.lookup(*I)) 712 Operands.push_back(SimpleOp); 713 else 714 Operands.push_back(*I); 715 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&GEP, Operands); 716 } 717 718 bool CallAnalyzer::visitAlloca(AllocaInst &I) { 719 // Check whether inlining will turn a dynamic alloca into a static 720 // alloca and handle that case. 721 if (I.isArrayAllocation()) { 722 Constant *Size = SimplifiedValues.lookup(I.getArraySize()); 723 if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) { 724 Type *Ty = I.getAllocatedType(); 725 AllocatedSize = SaturatingMultiplyAdd( 726 AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty).getFixedSize(), 727 AllocatedSize); 728 return Base::visitAlloca(I); 729 } 730 } 731 732 // Accumulate the allocated size. 733 if (I.isStaticAlloca()) { 734 Type *Ty = I.getAllocatedType(); 735 AllocatedSize = 736 SaturatingAdd(DL.getTypeAllocSize(Ty).getFixedSize(), AllocatedSize); 737 } 738 739 // We will happily inline static alloca instructions. 740 if (I.isStaticAlloca()) 741 return Base::visitAlloca(I); 742 743 // FIXME: This is overly conservative. Dynamic allocas are inefficient for 744 // a variety of reasons, and so we would like to not inline them into 745 // functions which don't currently have a dynamic alloca. This simply 746 // disables inlining altogether in the presence of a dynamic alloca. 747 HasDynamicAlloca = true; 748 return false; 749 } 750 751 bool CallAnalyzer::visitPHI(PHINode &I) { 752 // FIXME: We need to propagate SROA *disabling* through phi nodes, even 753 // though we don't want to propagate it's bonuses. The idea is to disable 754 // SROA if it *might* be used in an inappropriate manner. 755 756 // Phi nodes are always zero-cost. 757 // FIXME: Pointer sizes may differ between different address spaces, so do we 758 // need to use correct address space in the call to getPointerSizeInBits here? 759 // Or could we skip the getPointerSizeInBits call completely? As far as I can 760 // see the ZeroOffset is used as a dummy value, so we can probably use any 761 // bit width for the ZeroOffset? 762 APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0)); 763 bool CheckSROA = I.getType()->isPointerTy(); 764 765 // Track the constant or pointer with constant offset we've seen so far. 766 Constant *FirstC = nullptr; 767 std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset}; 768 Value *FirstV = nullptr; 769 770 for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) { 771 BasicBlock *Pred = I.getIncomingBlock(i); 772 // If the incoming block is dead, skip the incoming block. 773 if (DeadBlocks.count(Pred)) 774 continue; 775 // If the parent block of phi is not the known successor of the incoming 776 // block, skip the incoming block. 777 BasicBlock *KnownSuccessor = KnownSuccessors[Pred]; 778 if (KnownSuccessor && KnownSuccessor != I.getParent()) 779 continue; 780 781 Value *V = I.getIncomingValue(i); 782 // If the incoming value is this phi itself, skip the incoming value. 783 if (&I == V) 784 continue; 785 786 Constant *C = dyn_cast<Constant>(V); 787 if (!C) 788 C = SimplifiedValues.lookup(V); 789 790 std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset}; 791 if (!C && CheckSROA) 792 BaseAndOffset = ConstantOffsetPtrs.lookup(V); 793 794 if (!C && !BaseAndOffset.first) 795 // The incoming value is neither a constant nor a pointer with constant 796 // offset, exit early. 797 return true; 798 799 if (FirstC) { 800 if (FirstC == C) 801 // If we've seen a constant incoming value before and it is the same 802 // constant we see this time, continue checking the next incoming value. 803 continue; 804 // Otherwise early exit because we either see a different constant or saw 805 // a constant before but we have a pointer with constant offset this time. 806 return true; 807 } 808 809 if (FirstV) { 810 // The same logic as above, but check pointer with constant offset here. 811 if (FirstBaseAndOffset == BaseAndOffset) 812 continue; 813 return true; 814 } 815 816 if (C) { 817 // This is the 1st time we've seen a constant, record it. 818 FirstC = C; 819 continue; 820 } 821 822 // The remaining case is that this is the 1st time we've seen a pointer with 823 // constant offset, record it. 824 FirstV = V; 825 FirstBaseAndOffset = BaseAndOffset; 826 } 827 828 // Check if we can map phi to a constant. 829 if (FirstC) { 830 SimplifiedValues[&I] = FirstC; 831 return true; 832 } 833 834 // Check if we can map phi to a pointer with constant offset. 835 if (FirstBaseAndOffset.first) { 836 ConstantOffsetPtrs[&I] = FirstBaseAndOffset; 837 838 if (auto *SROAArg = getSROAArgForValueOrNull(FirstV)) 839 SROAArgValues[&I] = SROAArg; 840 } 841 842 return true; 843 } 844 845 /// Check we can fold GEPs of constant-offset call site argument pointers. 846 /// This requires target data and inbounds GEPs. 847 /// 848 /// \return true if the specified GEP can be folded. 849 bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) { 850 // Check if we have a base + offset for the pointer. 851 std::pair<Value *, APInt> BaseAndOffset = 852 ConstantOffsetPtrs.lookup(I.getPointerOperand()); 853 if (!BaseAndOffset.first) 854 return false; 855 856 // Check if the offset of this GEP is constant, and if so accumulate it 857 // into Offset. 858 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) 859 return false; 860 861 // Add the result as a new mapping to Base + Offset. 862 ConstantOffsetPtrs[&I] = BaseAndOffset; 863 864 return true; 865 } 866 867 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) { 868 auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand()); 869 870 // Lambda to check whether a GEP's indices are all constant. 871 auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) { 872 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I) 873 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I)) 874 return false; 875 return true; 876 }; 877 878 if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) { 879 if (SROAArg) 880 SROAArgValues[&I] = SROAArg; 881 882 // Constant GEPs are modeled as free. 883 return true; 884 } 885 886 // Variable GEPs will require math and will disable SROA. 887 if (SROAArg) 888 disableSROAForArg(SROAArg); 889 return isGEPFree(I); 890 } 891 892 /// Simplify \p I if its operands are constants and update SimplifiedValues. 893 /// \p Evaluate is a callable specific to instruction type that evaluates the 894 /// instruction when all the operands are constants. 895 template <typename Callable> 896 bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) { 897 SmallVector<Constant *, 2> COps; 898 for (Value *Op : I.operands()) { 899 Constant *COp = dyn_cast<Constant>(Op); 900 if (!COp) 901 COp = SimplifiedValues.lookup(Op); 902 if (!COp) 903 return false; 904 COps.push_back(COp); 905 } 906 auto *C = Evaluate(COps); 907 if (!C) 908 return false; 909 SimplifiedValues[&I] = C; 910 return true; 911 } 912 913 bool CallAnalyzer::visitBitCast(BitCastInst &I) { 914 // Propagate constants through bitcasts. 915 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 916 return ConstantExpr::getBitCast(COps[0], I.getType()); 917 })) 918 return true; 919 920 // Track base/offsets through casts 921 std::pair<Value *, APInt> BaseAndOffset = 922 ConstantOffsetPtrs.lookup(I.getOperand(0)); 923 // Casts don't change the offset, just wrap it up. 924 if (BaseAndOffset.first) 925 ConstantOffsetPtrs[&I] = BaseAndOffset; 926 927 // Also look for SROA candidates here. 928 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0))) 929 SROAArgValues[&I] = SROAArg; 930 931 // Bitcasts are always zero cost. 932 return true; 933 } 934 935 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { 936 // Propagate constants through ptrtoint. 937 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 938 return ConstantExpr::getPtrToInt(COps[0], I.getType()); 939 })) 940 return true; 941 942 // Track base/offset pairs when converted to a plain integer provided the 943 // integer is large enough to represent the pointer. 944 unsigned IntegerSize = I.getType()->getScalarSizeInBits(); 945 unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace(); 946 if (IntegerSize >= DL.getPointerSizeInBits(AS)) { 947 std::pair<Value *, APInt> BaseAndOffset = 948 ConstantOffsetPtrs.lookup(I.getOperand(0)); 949 if (BaseAndOffset.first) 950 ConstantOffsetPtrs[&I] = BaseAndOffset; 951 } 952 953 // This is really weird. Technically, ptrtoint will disable SROA. However, 954 // unless that ptrtoint is *used* somewhere in the live basic blocks after 955 // inlining, it will be nuked, and SROA should proceed. All of the uses which 956 // would block SROA would also block SROA if applied directly to a pointer, 957 // and so we can just add the integer in here. The only places where SROA is 958 // preserved either cannot fire on an integer, or won't in-and-of themselves 959 // disable SROA (ext) w/o some later use that we would see and disable. 960 if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0))) 961 SROAArgValues[&I] = SROAArg; 962 963 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 964 } 965 966 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { 967 // Propagate constants through ptrtoint. 968 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 969 return ConstantExpr::getIntToPtr(COps[0], I.getType()); 970 })) 971 return true; 972 973 // Track base/offset pairs when round-tripped through a pointer without 974 // modifications provided the integer is not too large. 975 Value *Op = I.getOperand(0); 976 unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); 977 if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) { 978 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); 979 if (BaseAndOffset.first) 980 ConstantOffsetPtrs[&I] = BaseAndOffset; 981 } 982 983 // "Propagate" SROA here in the same manner as we do for ptrtoint above. 984 if (auto *SROAArg = getSROAArgForValueOrNull(Op)) 985 SROAArgValues[&I] = SROAArg; 986 987 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 988 } 989 990 bool CallAnalyzer::visitCastInst(CastInst &I) { 991 // Propagate constants through casts. 992 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 993 return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType()); 994 })) 995 return true; 996 997 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere. 998 disableSROA(I.getOperand(0)); 999 1000 // If this is a floating-point cast, and the target says this operation 1001 // is expensive, this may eventually become a library call. Treat the cost 1002 // as such. 1003 switch (I.getOpcode()) { 1004 case Instruction::FPTrunc: 1005 case Instruction::FPExt: 1006 case Instruction::UIToFP: 1007 case Instruction::SIToFP: 1008 case Instruction::FPToUI: 1009 case Instruction::FPToSI: 1010 if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive) 1011 onCallPenalty(); 1012 break; 1013 default: 1014 break; 1015 } 1016 1017 return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I); 1018 } 1019 1020 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) { 1021 Value *Operand = I.getOperand(0); 1022 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1023 return ConstantFoldInstOperands(&I, COps[0], DL); 1024 })) 1025 return true; 1026 1027 // Disable any SROA on the argument to arbitrary unary instructions. 1028 disableSROA(Operand); 1029 1030 return false; 1031 } 1032 1033 bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) { 1034 return CandidateCall.paramHasAttr(A->getArgNo(), Attr); 1035 } 1036 1037 bool CallAnalyzer::isKnownNonNullInCallee(Value *V) { 1038 // Does the *call site* have the NonNull attribute set on an argument? We 1039 // use the attribute on the call site to memoize any analysis done in the 1040 // caller. This will also trip if the callee function has a non-null 1041 // parameter attribute, but that's a less interesting case because hopefully 1042 // the callee would already have been simplified based on that. 1043 if (Argument *A = dyn_cast<Argument>(V)) 1044 if (paramHasAttr(A, Attribute::NonNull)) 1045 return true; 1046 1047 // Is this an alloca in the caller? This is distinct from the attribute case 1048 // above because attributes aren't updated within the inliner itself and we 1049 // always want to catch the alloca derived case. 1050 if (isAllocaDerivedArg(V)) 1051 // We can actually predict the result of comparisons between an 1052 // alloca-derived value and null. Note that this fires regardless of 1053 // SROA firing. 1054 return true; 1055 1056 return false; 1057 } 1058 1059 bool CallAnalyzer::allowSizeGrowth(CallBase &Call) { 1060 // If the normal destination of the invoke or the parent block of the call 1061 // site is unreachable-terminated, there is little point in inlining this 1062 // unless there is literally zero cost. 1063 // FIXME: Note that it is possible that an unreachable-terminated block has a 1064 // hot entry. For example, in below scenario inlining hot_call_X() may be 1065 // beneficial : 1066 // main() { 1067 // hot_call_1(); 1068 // ... 1069 // hot_call_N() 1070 // exit(0); 1071 // } 1072 // For now, we are not handling this corner case here as it is rare in real 1073 // code. In future, we should elaborate this based on BPI and BFI in more 1074 // general threshold adjusting heuristics in updateThreshold(). 1075 if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) { 1076 if (isa<UnreachableInst>(II->getNormalDest()->getTerminator())) 1077 return false; 1078 } else if (isa<UnreachableInst>(Call.getParent()->getTerminator())) 1079 return false; 1080 1081 return true; 1082 } 1083 1084 bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call, 1085 BlockFrequencyInfo *CallerBFI) { 1086 // If global profile summary is available, then callsite's coldness is 1087 // determined based on that. 1088 if (PSI && PSI->hasProfileSummary()) 1089 return PSI->isColdCallSite(CallSite(&Call), CallerBFI); 1090 1091 // Otherwise we need BFI to be available. 1092 if (!CallerBFI) 1093 return false; 1094 1095 // Determine if the callsite is cold relative to caller's entry. We could 1096 // potentially cache the computation of scaled entry frequency, but the added 1097 // complexity is not worth it unless this scaling shows up high in the 1098 // profiles. 1099 const BranchProbability ColdProb(ColdCallSiteRelFreq, 100); 1100 auto CallSiteBB = Call.getParent(); 1101 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB); 1102 auto CallerEntryFreq = 1103 CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock())); 1104 return CallSiteFreq < CallerEntryFreq * ColdProb; 1105 } 1106 1107 Optional<int> 1108 InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call, 1109 BlockFrequencyInfo *CallerBFI) { 1110 1111 // If global profile summary is available, then callsite's hotness is 1112 // determined based on that. 1113 if (PSI && PSI->hasProfileSummary() && 1114 PSI->isHotCallSite(CallSite(&Call), CallerBFI)) 1115 return Params.HotCallSiteThreshold; 1116 1117 // Otherwise we need BFI to be available and to have a locally hot callsite 1118 // threshold. 1119 if (!CallerBFI || !Params.LocallyHotCallSiteThreshold) 1120 return None; 1121 1122 // Determine if the callsite is hot relative to caller's entry. We could 1123 // potentially cache the computation of scaled entry frequency, but the added 1124 // complexity is not worth it unless this scaling shows up high in the 1125 // profiles. 1126 auto CallSiteBB = Call.getParent(); 1127 auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency(); 1128 auto CallerEntryFreq = CallerBFI->getEntryFreq(); 1129 if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq) 1130 return Params.LocallyHotCallSiteThreshold; 1131 1132 // Otherwise treat it normally. 1133 return None; 1134 } 1135 1136 void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) { 1137 // If no size growth is allowed for this inlining, set Threshold to 0. 1138 if (!allowSizeGrowth(Call)) { 1139 Threshold = 0; 1140 return; 1141 } 1142 1143 Function *Caller = Call.getCaller(); 1144 1145 // return min(A, B) if B is valid. 1146 auto MinIfValid = [](int A, Optional<int> B) { 1147 return B ? std::min(A, B.getValue()) : A; 1148 }; 1149 1150 // return max(A, B) if B is valid. 1151 auto MaxIfValid = [](int A, Optional<int> B) { 1152 return B ? std::max(A, B.getValue()) : A; 1153 }; 1154 1155 // Various bonus percentages. These are multiplied by Threshold to get the 1156 // bonus values. 1157 // SingleBBBonus: This bonus is applied if the callee has a single reachable 1158 // basic block at the given callsite context. This is speculatively applied 1159 // and withdrawn if more than one basic block is seen. 1160 // 1161 // LstCallToStaticBonus: This large bonus is applied to ensure the inlining 1162 // of the last call to a static function as inlining such functions is 1163 // guaranteed to reduce code size. 1164 // 1165 // These bonus percentages may be set to 0 based on properties of the caller 1166 // and the callsite. 1167 int SingleBBBonusPercent = 50; 1168 int VectorBonusPercent = TTI.getInlinerVectorBonusPercent(); 1169 int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus; 1170 1171 // Lambda to set all the above bonus and bonus percentages to 0. 1172 auto DisallowAllBonuses = [&]() { 1173 SingleBBBonusPercent = 0; 1174 VectorBonusPercent = 0; 1175 LastCallToStaticBonus = 0; 1176 }; 1177 1178 // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available 1179 // and reduce the threshold if the caller has the necessary attribute. 1180 if (Caller->hasMinSize()) { 1181 Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold); 1182 // For minsize, we want to disable the single BB bonus and the vector 1183 // bonuses, but not the last-call-to-static bonus. Inlining the last call to 1184 // a static function will, at the minimum, eliminate the parameter setup and 1185 // call/return instructions. 1186 SingleBBBonusPercent = 0; 1187 VectorBonusPercent = 0; 1188 } else if (Caller->hasOptSize()) 1189 Threshold = MinIfValid(Threshold, Params.OptSizeThreshold); 1190 1191 // Adjust the threshold based on inlinehint attribute and profile based 1192 // hotness information if the caller does not have MinSize attribute. 1193 if (!Caller->hasMinSize()) { 1194 if (Callee.hasFnAttribute(Attribute::InlineHint)) 1195 Threshold = MaxIfValid(Threshold, Params.HintThreshold); 1196 1197 // FIXME: After switching to the new passmanager, simplify the logic below 1198 // by checking only the callsite hotness/coldness as we will reliably 1199 // have local profile information. 1200 // 1201 // Callsite hotness and coldness can be determined if sample profile is 1202 // used (which adds hotness metadata to calls) or if caller's 1203 // BlockFrequencyInfo is available. 1204 BlockFrequencyInfo *CallerBFI = GetBFI ? &((*GetBFI)(*Caller)) : nullptr; 1205 auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI); 1206 if (!Caller->hasOptSize() && HotCallSiteThreshold) { 1207 LLVM_DEBUG(dbgs() << "Hot callsite.\n"); 1208 // FIXME: This should update the threshold only if it exceeds the 1209 // current threshold, but AutoFDO + ThinLTO currently relies on this 1210 // behavior to prevent inlining of hot callsites during ThinLTO 1211 // compile phase. 1212 Threshold = HotCallSiteThreshold.getValue(); 1213 } else if (isColdCallSite(Call, CallerBFI)) { 1214 LLVM_DEBUG(dbgs() << "Cold callsite.\n"); 1215 // Do not apply bonuses for a cold callsite including the 1216 // LastCallToStatic bonus. While this bonus might result in code size 1217 // reduction, it can cause the size of a non-cold caller to increase 1218 // preventing it from being inlined. 1219 DisallowAllBonuses(); 1220 Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold); 1221 } else if (PSI) { 1222 // Use callee's global profile information only if we have no way of 1223 // determining this via callsite information. 1224 if (PSI->isFunctionEntryHot(&Callee)) { 1225 LLVM_DEBUG(dbgs() << "Hot callee.\n"); 1226 // If callsite hotness can not be determined, we may still know 1227 // that the callee is hot and treat it as a weaker hint for threshold 1228 // increase. 1229 Threshold = MaxIfValid(Threshold, Params.HintThreshold); 1230 } else if (PSI->isFunctionEntryCold(&Callee)) { 1231 LLVM_DEBUG(dbgs() << "Cold callee.\n"); 1232 // Do not apply bonuses for a cold callee including the 1233 // LastCallToStatic bonus. While this bonus might result in code size 1234 // reduction, it can cause the size of a non-cold caller to increase 1235 // preventing it from being inlined. 1236 DisallowAllBonuses(); 1237 Threshold = MinIfValid(Threshold, Params.ColdThreshold); 1238 } 1239 } 1240 } 1241 1242 // Finally, take the target-specific inlining threshold multiplier into 1243 // account. 1244 Threshold *= TTI.getInliningThresholdMultiplier(); 1245 1246 SingleBBBonus = Threshold * SingleBBBonusPercent / 100; 1247 VectorBonus = Threshold * VectorBonusPercent / 100; 1248 1249 bool OnlyOneCallAndLocalLinkage = 1250 F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction(); 1251 // If there is only one call of the function, and it has internal linkage, 1252 // the cost of inlining it drops dramatically. It may seem odd to update 1253 // Cost in updateThreshold, but the bonus depends on the logic in this method. 1254 if (OnlyOneCallAndLocalLinkage) 1255 Cost -= LastCallToStaticBonus; 1256 } 1257 1258 bool CallAnalyzer::visitCmpInst(CmpInst &I) { 1259 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1260 // First try to handle simplified comparisons. 1261 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1262 return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]); 1263 })) 1264 return true; 1265 1266 if (I.getOpcode() == Instruction::FCmp) 1267 return false; 1268 1269 // Otherwise look for a comparison between constant offset pointers with 1270 // a common base. 1271 Value *LHSBase, *RHSBase; 1272 APInt LHSOffset, RHSOffset; 1273 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 1274 if (LHSBase) { 1275 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 1276 if (RHSBase && LHSBase == RHSBase) { 1277 // We have common bases, fold the icmp to a constant based on the 1278 // offsets. 1279 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 1280 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 1281 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) { 1282 SimplifiedValues[&I] = C; 1283 ++NumConstantPtrCmps; 1284 return true; 1285 } 1286 } 1287 } 1288 1289 // If the comparison is an equality comparison with null, we can simplify it 1290 // if we know the value (argument) can't be null 1291 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) && 1292 isKnownNonNullInCallee(I.getOperand(0))) { 1293 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE; 1294 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType()) 1295 : ConstantInt::getFalse(I.getType()); 1296 return true; 1297 } 1298 return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1))); 1299 } 1300 1301 bool CallAnalyzer::visitSub(BinaryOperator &I) { 1302 // Try to handle a special case: we can fold computing the difference of two 1303 // constant-related pointers. 1304 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1305 Value *LHSBase, *RHSBase; 1306 APInt LHSOffset, RHSOffset; 1307 std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS); 1308 if (LHSBase) { 1309 std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS); 1310 if (RHSBase && LHSBase == RHSBase) { 1311 // We have common bases, fold the subtract to a constant based on the 1312 // offsets. 1313 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset); 1314 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset); 1315 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) { 1316 SimplifiedValues[&I] = C; 1317 ++NumConstantPtrDiffs; 1318 return true; 1319 } 1320 } 1321 } 1322 1323 // Otherwise, fall back to the generic logic for simplifying and handling 1324 // instructions. 1325 return Base::visitSub(I); 1326 } 1327 1328 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) { 1329 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 1330 Constant *CLHS = dyn_cast<Constant>(LHS); 1331 if (!CLHS) 1332 CLHS = SimplifiedValues.lookup(LHS); 1333 Constant *CRHS = dyn_cast<Constant>(RHS); 1334 if (!CRHS) 1335 CRHS = SimplifiedValues.lookup(RHS); 1336 1337 Value *SimpleV = nullptr; 1338 if (auto FI = dyn_cast<FPMathOperator>(&I)) 1339 SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, 1340 FI->getFastMathFlags(), DL); 1341 else 1342 SimpleV = 1343 SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL); 1344 1345 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 1346 SimplifiedValues[&I] = C; 1347 1348 if (SimpleV) 1349 return true; 1350 1351 // Disable any SROA on arguments to arbitrary, unsimplified binary operators. 1352 disableSROA(LHS); 1353 disableSROA(RHS); 1354 1355 // If the instruction is floating point, and the target says this operation 1356 // is expensive, this may eventually become a library call. Treat the cost 1357 // as such. Unless it's fneg which can be implemented with an xor. 1358 using namespace llvm::PatternMatch; 1359 if (I.getType()->isFloatingPointTy() && 1360 TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive && 1361 !match(&I, m_FNeg(m_Value()))) 1362 onCallPenalty(); 1363 1364 return false; 1365 } 1366 1367 bool CallAnalyzer::visitFNeg(UnaryOperator &I) { 1368 Value *Op = I.getOperand(0); 1369 Constant *COp = dyn_cast<Constant>(Op); 1370 if (!COp) 1371 COp = SimplifiedValues.lookup(Op); 1372 1373 Value *SimpleV = SimplifyFNegInst( 1374 COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL); 1375 1376 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 1377 SimplifiedValues[&I] = C; 1378 1379 if (SimpleV) 1380 return true; 1381 1382 // Disable any SROA on arguments to arbitrary, unsimplified fneg. 1383 disableSROA(Op); 1384 1385 return false; 1386 } 1387 1388 bool CallAnalyzer::visitLoad(LoadInst &I) { 1389 if (handleSROA(I.getPointerOperand(), I.isSimple())) 1390 return true; 1391 1392 // If the data is already loaded from this address and hasn't been clobbered 1393 // by any stores or calls, this load is likely to be redundant and can be 1394 // eliminated. 1395 if (EnableLoadElimination && 1396 !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) { 1397 onLoadEliminationOpportunity(); 1398 return true; 1399 } 1400 1401 return false; 1402 } 1403 1404 bool CallAnalyzer::visitStore(StoreInst &I) { 1405 if (handleSROA(I.getPointerOperand(), I.isSimple())) 1406 return true; 1407 1408 // The store can potentially clobber loads and prevent repeated loads from 1409 // being eliminated. 1410 // FIXME: 1411 // 1. We can probably keep an initial set of eliminatable loads substracted 1412 // from the cost even when we finally see a store. We just need to disable 1413 // *further* accumulation of elimination savings. 1414 // 2. We should probably at some point thread MemorySSA for the callee into 1415 // this and then use that to actually compute *really* precise savings. 1416 disableLoadElimination(); 1417 return false; 1418 } 1419 1420 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) { 1421 // Constant folding for extract value is trivial. 1422 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1423 return ConstantExpr::getExtractValue(COps[0], I.getIndices()); 1424 })) 1425 return true; 1426 1427 // SROA can look through these but give them a cost. 1428 return false; 1429 } 1430 1431 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) { 1432 // Constant folding for insert value is trivial. 1433 if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) { 1434 return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0], 1435 /*InsertedValueOperand*/ COps[1], 1436 I.getIndices()); 1437 })) 1438 return true; 1439 1440 // SROA can look through these but give them a cost. 1441 return false; 1442 } 1443 1444 /// Try to simplify a call site. 1445 /// 1446 /// Takes a concrete function and callsite and tries to actually simplify it by 1447 /// analyzing the arguments and call itself with instsimplify. Returns true if 1448 /// it has simplified the callsite to some other entity (a constant), making it 1449 /// free. 1450 bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) { 1451 // FIXME: Using the instsimplify logic directly for this is inefficient 1452 // because we have to continually rebuild the argument list even when no 1453 // simplifications can be performed. Until that is fixed with remapping 1454 // inside of instsimplify, directly constant fold calls here. 1455 if (!canConstantFoldCallTo(&Call, F)) 1456 return false; 1457 1458 // Try to re-map the arguments to constants. 1459 SmallVector<Constant *, 4> ConstantArgs; 1460 ConstantArgs.reserve(Call.arg_size()); 1461 for (Value *I : Call.args()) { 1462 Constant *C = dyn_cast<Constant>(I); 1463 if (!C) 1464 C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I)); 1465 if (!C) 1466 return false; // This argument doesn't map to a constant. 1467 1468 ConstantArgs.push_back(C); 1469 } 1470 if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) { 1471 SimplifiedValues[&Call] = C; 1472 return true; 1473 } 1474 1475 return false; 1476 } 1477 1478 bool CallAnalyzer::visitCallBase(CallBase &Call) { 1479 if (Call.hasFnAttr(Attribute::ReturnsTwice) && 1480 !F.hasFnAttribute(Attribute::ReturnsTwice)) { 1481 // This aborts the entire analysis. 1482 ExposesReturnsTwice = true; 1483 return false; 1484 } 1485 if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate()) 1486 ContainsNoDuplicateCall = true; 1487 1488 Value *Callee = Call.getCalledOperand(); 1489 Function *F = dyn_cast_or_null<Function>(Callee); 1490 bool IsIndirectCall = !F; 1491 if (IsIndirectCall) { 1492 // Check if this happens to be an indirect function call to a known function 1493 // in this inline context. If not, we've done all we can. 1494 F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee)); 1495 if (!F) { 1496 onCallArgumentSetup(Call); 1497 1498 if (!Call.onlyReadsMemory()) 1499 disableLoadElimination(); 1500 return Base::visitCallBase(Call); 1501 } 1502 } 1503 1504 assert(F && "Expected a call to a known function"); 1505 1506 // When we have a concrete function, first try to simplify it directly. 1507 if (simplifyCallSite(F, Call)) 1508 return true; 1509 1510 // Next check if it is an intrinsic we know about. 1511 // FIXME: Lift this into part of the InstVisitor. 1512 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) { 1513 switch (II->getIntrinsicID()) { 1514 default: 1515 if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II)) 1516 disableLoadElimination(); 1517 return Base::visitCallBase(Call); 1518 1519 case Intrinsic::load_relative: 1520 onLoadRelativeIntrinsic(); 1521 return false; 1522 1523 case Intrinsic::memset: 1524 case Intrinsic::memcpy: 1525 case Intrinsic::memmove: 1526 disableLoadElimination(); 1527 // SROA can usually chew through these intrinsics, but they aren't free. 1528 return false; 1529 case Intrinsic::icall_branch_funnel: 1530 case Intrinsic::localescape: 1531 HasUninlineableIntrinsic = true; 1532 return false; 1533 case Intrinsic::vastart: 1534 InitsVargArgs = true; 1535 return false; 1536 } 1537 } 1538 1539 if (F == Call.getFunction()) { 1540 // This flag will fully abort the analysis, so don't bother with anything 1541 // else. 1542 IsRecursiveCall = true; 1543 return false; 1544 } 1545 1546 if (TTI.isLoweredToCall(F)) { 1547 onLoweredCall(F, Call, IsIndirectCall); 1548 } 1549 1550 if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory()))) 1551 disableLoadElimination(); 1552 return Base::visitCallBase(Call); 1553 } 1554 1555 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) { 1556 // At least one return instruction will be free after inlining. 1557 bool Free = !HasReturn; 1558 HasReturn = true; 1559 return Free; 1560 } 1561 1562 bool CallAnalyzer::visitBranchInst(BranchInst &BI) { 1563 // We model unconditional branches as essentially free -- they really 1564 // shouldn't exist at all, but handling them makes the behavior of the 1565 // inliner more regular and predictable. Interestingly, conditional branches 1566 // which will fold away are also free. 1567 return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) || 1568 dyn_cast_or_null<ConstantInt>( 1569 SimplifiedValues.lookup(BI.getCondition())); 1570 } 1571 1572 bool CallAnalyzer::visitSelectInst(SelectInst &SI) { 1573 bool CheckSROA = SI.getType()->isPointerTy(); 1574 Value *TrueVal = SI.getTrueValue(); 1575 Value *FalseVal = SI.getFalseValue(); 1576 1577 Constant *TrueC = dyn_cast<Constant>(TrueVal); 1578 if (!TrueC) 1579 TrueC = SimplifiedValues.lookup(TrueVal); 1580 Constant *FalseC = dyn_cast<Constant>(FalseVal); 1581 if (!FalseC) 1582 FalseC = SimplifiedValues.lookup(FalseVal); 1583 Constant *CondC = 1584 dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition())); 1585 1586 if (!CondC) { 1587 // Select C, X, X => X 1588 if (TrueC == FalseC && TrueC) { 1589 SimplifiedValues[&SI] = TrueC; 1590 return true; 1591 } 1592 1593 if (!CheckSROA) 1594 return Base::visitSelectInst(SI); 1595 1596 std::pair<Value *, APInt> TrueBaseAndOffset = 1597 ConstantOffsetPtrs.lookup(TrueVal); 1598 std::pair<Value *, APInt> FalseBaseAndOffset = 1599 ConstantOffsetPtrs.lookup(FalseVal); 1600 if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) { 1601 ConstantOffsetPtrs[&SI] = TrueBaseAndOffset; 1602 1603 if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal)) 1604 SROAArgValues[&SI] = SROAArg; 1605 return true; 1606 } 1607 1608 return Base::visitSelectInst(SI); 1609 } 1610 1611 // Select condition is a constant. 1612 Value *SelectedV = CondC->isAllOnesValue() 1613 ? TrueVal 1614 : (CondC->isNullValue()) ? FalseVal : nullptr; 1615 if (!SelectedV) { 1616 // Condition is a vector constant that is not all 1s or all 0s. If all 1617 // operands are constants, ConstantExpr::getSelect() can handle the cases 1618 // such as select vectors. 1619 if (TrueC && FalseC) { 1620 if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) { 1621 SimplifiedValues[&SI] = C; 1622 return true; 1623 } 1624 } 1625 return Base::visitSelectInst(SI); 1626 } 1627 1628 // Condition is either all 1s or all 0s. SI can be simplified. 1629 if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) { 1630 SimplifiedValues[&SI] = SelectedC; 1631 return true; 1632 } 1633 1634 if (!CheckSROA) 1635 return true; 1636 1637 std::pair<Value *, APInt> BaseAndOffset = 1638 ConstantOffsetPtrs.lookup(SelectedV); 1639 if (BaseAndOffset.first) { 1640 ConstantOffsetPtrs[&SI] = BaseAndOffset; 1641 1642 if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV)) 1643 SROAArgValues[&SI] = SROAArg; 1644 } 1645 1646 return true; 1647 } 1648 1649 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) { 1650 // We model unconditional switches as free, see the comments on handling 1651 // branches. 1652 if (isa<ConstantInt>(SI.getCondition())) 1653 return true; 1654 if (Value *V = SimplifiedValues.lookup(SI.getCondition())) 1655 if (isa<ConstantInt>(V)) 1656 return true; 1657 1658 // Assume the most general case where the switch is lowered into 1659 // either a jump table, bit test, or a balanced binary tree consisting of 1660 // case clusters without merging adjacent clusters with the same 1661 // destination. We do not consider the switches that are lowered with a mix 1662 // of jump table/bit test/binary search tree. The cost of the switch is 1663 // proportional to the size of the tree or the size of jump table range. 1664 // 1665 // NB: We convert large switches which are just used to initialize large phi 1666 // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent 1667 // inlining those. It will prevent inlining in cases where the optimization 1668 // does not (yet) fire. 1669 1670 unsigned JumpTableSize = 0; 1671 BlockFrequencyInfo *BFI = GetBFI ? &((*GetBFI)(F)) : nullptr; 1672 unsigned NumCaseCluster = 1673 TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI); 1674 1675 onFinalizeSwitch(JumpTableSize, NumCaseCluster); 1676 return false; 1677 } 1678 1679 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) { 1680 // We never want to inline functions that contain an indirectbr. This is 1681 // incorrect because all the blockaddress's (in static global initializers 1682 // for example) would be referring to the original function, and this 1683 // indirect jump would jump from the inlined copy of the function into the 1684 // original function which is extremely undefined behavior. 1685 // FIXME: This logic isn't really right; we can safely inline functions with 1686 // indirectbr's as long as no other function or global references the 1687 // blockaddress of a block within the current function. 1688 HasIndirectBr = true; 1689 return false; 1690 } 1691 1692 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) { 1693 // FIXME: It's not clear that a single instruction is an accurate model for 1694 // the inline cost of a resume instruction. 1695 return false; 1696 } 1697 1698 bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) { 1699 // FIXME: It's not clear that a single instruction is an accurate model for 1700 // the inline cost of a cleanupret instruction. 1701 return false; 1702 } 1703 1704 bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) { 1705 // FIXME: It's not clear that a single instruction is an accurate model for 1706 // the inline cost of a catchret instruction. 1707 return false; 1708 } 1709 1710 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) { 1711 // FIXME: It might be reasonably to discount the cost of instructions leading 1712 // to unreachable as they have the lowest possible impact on both runtime and 1713 // code size. 1714 return true; // No actual code is needed for unreachable. 1715 } 1716 1717 bool CallAnalyzer::visitInstruction(Instruction &I) { 1718 // Some instructions are free. All of the free intrinsics can also be 1719 // handled by SROA, etc. 1720 if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I)) 1721 return true; 1722 1723 // We found something we don't understand or can't handle. Mark any SROA-able 1724 // values in the operand list as no longer viable. 1725 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI) 1726 disableSROA(*OI); 1727 1728 return false; 1729 } 1730 1731 /// Analyze a basic block for its contribution to the inline cost. 1732 /// 1733 /// This method walks the analyzer over every instruction in the given basic 1734 /// block and accounts for their cost during inlining at this callsite. It 1735 /// aborts early if the threshold has been exceeded or an impossible to inline 1736 /// construct has been detected. It returns false if inlining is no longer 1737 /// viable, and true if inlining remains viable. 1738 InlineResult 1739 CallAnalyzer::analyzeBlock(BasicBlock *BB, 1740 SmallPtrSetImpl<const Value *> &EphValues) { 1741 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 1742 // FIXME: Currently, the number of instructions in a function regardless of 1743 // our ability to simplify them during inline to constants or dead code, 1744 // are actually used by the vector bonus heuristic. As long as that's true, 1745 // we have to special case debug intrinsics here to prevent differences in 1746 // inlining due to debug symbols. Eventually, the number of unsimplified 1747 // instructions shouldn't factor into the cost computation, but until then, 1748 // hack around it here. 1749 if (isa<DbgInfoIntrinsic>(I)) 1750 continue; 1751 1752 // Skip ephemeral values. 1753 if (EphValues.count(&*I)) 1754 continue; 1755 1756 ++NumInstructions; 1757 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy()) 1758 ++NumVectorInstructions; 1759 1760 // If the instruction simplified to a constant, there is no cost to this 1761 // instruction. Visit the instructions using our InstVisitor to account for 1762 // all of the per-instruction logic. The visit tree returns true if we 1763 // consumed the instruction in any way, and false if the instruction's base 1764 // cost should count against inlining. 1765 if (Base::visit(&*I)) 1766 ++NumInstructionsSimplified; 1767 else 1768 onCommonInstructionSimplification(); 1769 1770 using namespace ore; 1771 // If the visit this instruction detected an uninlinable pattern, abort. 1772 InlineResult IR = InlineResult::success(); 1773 if (IsRecursiveCall) 1774 IR = InlineResult::failure("recursive"); 1775 else if (ExposesReturnsTwice) 1776 IR = InlineResult::failure("exposes returns twice"); 1777 else if (HasDynamicAlloca) 1778 IR = InlineResult::failure("dynamic alloca"); 1779 else if (HasIndirectBr) 1780 IR = InlineResult::failure("indirect branch"); 1781 else if (HasUninlineableIntrinsic) 1782 IR = InlineResult::failure("uninlinable intrinsic"); 1783 else if (InitsVargArgs) 1784 IR = InlineResult::failure("varargs"); 1785 if (!IR.isSuccess()) { 1786 if (ORE) 1787 ORE->emit([&]() { 1788 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 1789 &CandidateCall) 1790 << NV("Callee", &F) << " has uninlinable pattern (" 1791 << NV("InlineResult", IR.getFailureReason()) 1792 << ") and cost is not fully computed"; 1793 }); 1794 return IR; 1795 } 1796 1797 // If the caller is a recursive function then we don't want to inline 1798 // functions which allocate a lot of stack space because it would increase 1799 // the caller stack usage dramatically. 1800 if (IsCallerRecursive && 1801 AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) { 1802 auto IR = 1803 InlineResult::failure("recursive and allocates too much stack space"); 1804 if (ORE) 1805 ORE->emit([&]() { 1806 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", 1807 &CandidateCall) 1808 << NV("Callee", &F) << " is " 1809 << NV("InlineResult", IR.getFailureReason()) 1810 << ". Cost is not fully computed"; 1811 }); 1812 return IR; 1813 } 1814 1815 if (shouldStop()) 1816 return InlineResult::failure( 1817 "Call site analysis is not favorable to inlining."); 1818 } 1819 1820 return InlineResult::success(); 1821 } 1822 1823 /// Compute the base pointer and cumulative constant offsets for V. 1824 /// 1825 /// This strips all constant offsets off of V, leaving it the base pointer, and 1826 /// accumulates the total constant offset applied in the returned constant. It 1827 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 1828 /// no constant offsets applied. 1829 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) { 1830 if (!V->getType()->isPointerTy()) 1831 return nullptr; 1832 1833 unsigned AS = V->getType()->getPointerAddressSpace(); 1834 unsigned IntPtrWidth = DL.getIndexSizeInBits(AS); 1835 APInt Offset = APInt::getNullValue(IntPtrWidth); 1836 1837 // Even though we don't look through PHI nodes, we could be called on an 1838 // instruction in an unreachable block, which may be on a cycle. 1839 SmallPtrSet<Value *, 4> Visited; 1840 Visited.insert(V); 1841 do { 1842 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 1843 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset)) 1844 return nullptr; 1845 V = GEP->getPointerOperand(); 1846 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 1847 V = cast<Operator>(V)->getOperand(0); 1848 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 1849 if (GA->isInterposable()) 1850 break; 1851 V = GA->getAliasee(); 1852 } else { 1853 break; 1854 } 1855 assert(V->getType()->isPointerTy() && "Unexpected operand type!"); 1856 } while (Visited.insert(V).second); 1857 1858 Type *IdxPtrTy = DL.getIndexType(V->getType()); 1859 return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset)); 1860 } 1861 1862 /// Find dead blocks due to deleted CFG edges during inlining. 1863 /// 1864 /// If we know the successor of the current block, \p CurrBB, has to be \p 1865 /// NextBB, the other successors of \p CurrBB are dead if these successors have 1866 /// no live incoming CFG edges. If one block is found to be dead, we can 1867 /// continue growing the dead block list by checking the successors of the dead 1868 /// blocks to see if all their incoming edges are dead or not. 1869 void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) { 1870 auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) { 1871 // A CFG edge is dead if the predecessor is dead or the predecessor has a 1872 // known successor which is not the one under exam. 1873 return (DeadBlocks.count(Pred) || 1874 (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ)); 1875 }; 1876 1877 auto IsNewlyDead = [&](BasicBlock *BB) { 1878 // If all the edges to a block are dead, the block is also dead. 1879 return (!DeadBlocks.count(BB) && 1880 llvm::all_of(predecessors(BB), 1881 [&](BasicBlock *P) { return IsEdgeDead(P, BB); })); 1882 }; 1883 1884 for (BasicBlock *Succ : successors(CurrBB)) { 1885 if (Succ == NextBB || !IsNewlyDead(Succ)) 1886 continue; 1887 SmallVector<BasicBlock *, 4> NewDead; 1888 NewDead.push_back(Succ); 1889 while (!NewDead.empty()) { 1890 BasicBlock *Dead = NewDead.pop_back_val(); 1891 if (DeadBlocks.insert(Dead)) 1892 // Continue growing the dead block lists. 1893 for (BasicBlock *S : successors(Dead)) 1894 if (IsNewlyDead(S)) 1895 NewDead.push_back(S); 1896 } 1897 } 1898 } 1899 1900 /// Analyze a call site for potential inlining. 1901 /// 1902 /// Returns true if inlining this call is viable, and false if it is not 1903 /// viable. It computes the cost and adjusts the threshold based on numerous 1904 /// factors and heuristics. If this method returns false but the computed cost 1905 /// is below the computed threshold, then inlining was forcibly disabled by 1906 /// some artifact of the routine. 1907 InlineResult CallAnalyzer::analyze() { 1908 ++NumCallsAnalyzed; 1909 1910 auto Result = onAnalysisStart(); 1911 if (!Result.isSuccess()) 1912 return Result; 1913 1914 if (F.empty()) 1915 return InlineResult::success(); 1916 1917 Function *Caller = CandidateCall.getFunction(); 1918 // Check if the caller function is recursive itself. 1919 for (User *U : Caller->users()) { 1920 CallBase *Call = dyn_cast<CallBase>(U); 1921 if (Call && Call->getFunction() == Caller) { 1922 IsCallerRecursive = true; 1923 break; 1924 } 1925 } 1926 1927 // Populate our simplified values by mapping from function arguments to call 1928 // arguments with known important simplifications. 1929 auto CAI = CandidateCall.arg_begin(); 1930 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end(); 1931 FAI != FAE; ++FAI, ++CAI) { 1932 assert(CAI != CandidateCall.arg_end()); 1933 if (Constant *C = dyn_cast<Constant>(CAI)) 1934 SimplifiedValues[&*FAI] = C; 1935 1936 Value *PtrArg = *CAI; 1937 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) { 1938 ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue()); 1939 1940 // We can SROA any pointer arguments derived from alloca instructions. 1941 if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) { 1942 SROAArgValues[&*FAI] = SROAArg; 1943 onInitializeSROAArg(SROAArg); 1944 } 1945 } 1946 } 1947 NumConstantArgs = SimplifiedValues.size(); 1948 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size(); 1949 NumAllocaArgs = SROAArgValues.size(); 1950 1951 // FIXME: If a caller has multiple calls to a callee, we end up recomputing 1952 // the ephemeral values multiple times (and they're completely determined by 1953 // the callee, so this is purely duplicate work). 1954 SmallPtrSet<const Value *, 32> EphValues; 1955 CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues); 1956 1957 // The worklist of live basic blocks in the callee *after* inlining. We avoid 1958 // adding basic blocks of the callee which can be proven to be dead for this 1959 // particular call site in order to get more accurate cost estimates. This 1960 // requires a somewhat heavyweight iteration pattern: we need to walk the 1961 // basic blocks in a breadth-first order as we insert live successors. To 1962 // accomplish this, prioritizing for small iterations because we exit after 1963 // crossing our threshold, we use a small-size optimized SetVector. 1964 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>, 1965 SmallPtrSet<BasicBlock *, 16>> 1966 BBSetVector; 1967 BBSetVector BBWorklist; 1968 BBWorklist.insert(&F.getEntryBlock()); 1969 1970 // Note that we *must not* cache the size, this loop grows the worklist. 1971 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 1972 if (shouldStop()) 1973 break; 1974 1975 BasicBlock *BB = BBWorklist[Idx]; 1976 if (BB->empty()) 1977 continue; 1978 1979 // Disallow inlining a blockaddress with uses other than strictly callbr. 1980 // A blockaddress only has defined behavior for an indirect branch in the 1981 // same function, and we do not currently support inlining indirect 1982 // branches. But, the inliner may not see an indirect branch that ends up 1983 // being dead code at a particular call site. If the blockaddress escapes 1984 // the function, e.g., via a global variable, inlining may lead to an 1985 // invalid cross-function reference. 1986 // FIXME: pr/39560: continue relaxing this overt restriction. 1987 if (BB->hasAddressTaken()) 1988 for (User *U : BlockAddress::get(&*BB)->users()) 1989 if (!isa<CallBrInst>(*U)) 1990 return InlineResult::failure("blockaddress used outside of callbr"); 1991 1992 // Analyze the cost of this block. If we blow through the threshold, this 1993 // returns false, and we can bail on out. 1994 InlineResult IR = analyzeBlock(BB, EphValues); 1995 if (!IR.isSuccess()) 1996 return IR; 1997 1998 Instruction *TI = BB->getTerminator(); 1999 2000 // Add in the live successors by first checking whether we have terminator 2001 // that may be simplified based on the values simplified by this call. 2002 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 2003 if (BI->isConditional()) { 2004 Value *Cond = BI->getCondition(); 2005 if (ConstantInt *SimpleCond = 2006 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 2007 BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0); 2008 BBWorklist.insert(NextBB); 2009 KnownSuccessors[BB] = NextBB; 2010 findDeadBlocks(BB, NextBB); 2011 continue; 2012 } 2013 } 2014 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 2015 Value *Cond = SI->getCondition(); 2016 if (ConstantInt *SimpleCond = 2017 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) { 2018 BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor(); 2019 BBWorklist.insert(NextBB); 2020 KnownSuccessors[BB] = NextBB; 2021 findDeadBlocks(BB, NextBB); 2022 continue; 2023 } 2024 } 2025 2026 // If we're unable to select a particular successor, just count all of 2027 // them. 2028 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; 2029 ++TIdx) 2030 BBWorklist.insert(TI->getSuccessor(TIdx)); 2031 2032 onBlockAnalyzed(BB); 2033 } 2034 2035 bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() && 2036 &F == CandidateCall.getCalledFunction(); 2037 // If this is a noduplicate call, we can still inline as long as 2038 // inlining this would cause the removal of the caller (so the instruction 2039 // is not actually duplicated, just moved). 2040 if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall) 2041 return InlineResult::failure("noduplicate"); 2042 2043 return finalizeAnalysis(); 2044 } 2045 2046 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2047 /// Dump stats about this call's analysis. 2048 LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { 2049 #define DEBUG_PRINT_STAT(x) dbgs() << " " #x ": " << x << "\n" 2050 DEBUG_PRINT_STAT(NumConstantArgs); 2051 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs); 2052 DEBUG_PRINT_STAT(NumAllocaArgs); 2053 DEBUG_PRINT_STAT(NumConstantPtrCmps); 2054 DEBUG_PRINT_STAT(NumConstantPtrDiffs); 2055 DEBUG_PRINT_STAT(NumInstructionsSimplified); 2056 DEBUG_PRINT_STAT(NumInstructions); 2057 DEBUG_PRINT_STAT(SROACostSavings); 2058 DEBUG_PRINT_STAT(SROACostSavingsLost); 2059 DEBUG_PRINT_STAT(LoadEliminationCost); 2060 DEBUG_PRINT_STAT(ContainsNoDuplicateCall); 2061 DEBUG_PRINT_STAT(Cost); 2062 DEBUG_PRINT_STAT(Threshold); 2063 #undef DEBUG_PRINT_STAT 2064 } 2065 #endif 2066 2067 /// Test that there are no attribute conflicts between Caller and Callee 2068 /// that prevent inlining. 2069 static bool functionsHaveCompatibleAttributes(Function *Caller, 2070 Function *Callee, 2071 TargetTransformInfo &TTI) { 2072 return TTI.areInlineCompatible(Caller, Callee) && 2073 AttributeFuncs::areInlineCompatible(*Caller, *Callee); 2074 } 2075 2076 int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) { 2077 int Cost = 0; 2078 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) { 2079 if (Call.isByValArgument(I)) { 2080 // We approximate the number of loads and stores needed by dividing the 2081 // size of the byval type by the target's pointer size. 2082 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType()); 2083 unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType()); 2084 unsigned AS = PTy->getAddressSpace(); 2085 unsigned PointerSize = DL.getPointerSizeInBits(AS); 2086 // Ceiling division. 2087 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize; 2088 2089 // If it generates more than 8 stores it is likely to be expanded as an 2090 // inline memcpy so we take that as an upper bound. Otherwise we assume 2091 // one load and one store per word copied. 2092 // FIXME: The maxStoresPerMemcpy setting from the target should be used 2093 // here instead of a magic number of 8, but it's not available via 2094 // DataLayout. 2095 NumStores = std::min(NumStores, 8U); 2096 2097 Cost += 2 * NumStores * InlineConstants::InstrCost; 2098 } else { 2099 // For non-byval arguments subtract off one instruction per call 2100 // argument. 2101 Cost += InlineConstants::InstrCost; 2102 } 2103 } 2104 // The call instruction also disappears after inlining. 2105 Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty; 2106 return Cost; 2107 } 2108 2109 InlineCost llvm::getInlineCost( 2110 CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, 2111 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 2112 Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 2113 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 2114 return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI, 2115 GetAssumptionCache, GetBFI, PSI, ORE); 2116 } 2117 2118 InlineCost llvm::getInlineCost( 2119 CallBase &Call, Function *Callee, const InlineParams &Params, 2120 TargetTransformInfo &CalleeTTI, 2121 std::function<AssumptionCache &(Function &)> &GetAssumptionCache, 2122 Optional<function_ref<BlockFrequencyInfo &(Function &)>> GetBFI, 2123 ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) { 2124 2125 // Cannot inline indirect calls. 2126 if (!Callee) 2127 return llvm::InlineCost::getNever("indirect call"); 2128 2129 // Never inline calls with byval arguments that does not have the alloca 2130 // address space. Since byval arguments can be replaced with a copy to an 2131 // alloca, the inlined code would need to be adjusted to handle that the 2132 // argument is in the alloca address space (so it is a little bit complicated 2133 // to solve). 2134 unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace(); 2135 for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) 2136 if (Call.isByValArgument(I)) { 2137 PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType()); 2138 if (PTy->getAddressSpace() != AllocaAS) 2139 return llvm::InlineCost::getNever("byval arguments without alloca" 2140 " address space"); 2141 } 2142 2143 // Calls to functions with always-inline attributes should be inlined 2144 // whenever possible. 2145 if (Call.hasFnAttr(Attribute::AlwaysInline)) { 2146 auto IsViable = isInlineViable(*Callee); 2147 if (IsViable.isSuccess()) 2148 return llvm::InlineCost::getAlways("always inline attribute"); 2149 return llvm::InlineCost::getNever(IsViable.getFailureReason()); 2150 } 2151 2152 // Never inline functions with conflicting attributes (unless callee has 2153 // always-inline attribute). 2154 Function *Caller = Call.getCaller(); 2155 if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI)) 2156 return llvm::InlineCost::getNever("conflicting attributes"); 2157 2158 // Don't inline this call if the caller has the optnone attribute. 2159 if (Caller->hasOptNone()) 2160 return llvm::InlineCost::getNever("optnone attribute"); 2161 2162 // Don't inline a function that treats null pointer as valid into a caller 2163 // that does not have this attribute. 2164 if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined()) 2165 return llvm::InlineCost::getNever("nullptr definitions incompatible"); 2166 2167 // Don't inline functions which can be interposed at link-time. 2168 if (Callee->isInterposable()) 2169 return llvm::InlineCost::getNever("interposable"); 2170 2171 // Don't inline functions marked noinline. 2172 if (Callee->hasFnAttribute(Attribute::NoInline)) 2173 return llvm::InlineCost::getNever("noinline function attribute"); 2174 2175 // Don't inline call sites marked noinline. 2176 if (Call.isNoInline()) 2177 return llvm::InlineCost::getNever("noinline call site attribute"); 2178 2179 LLVM_DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() 2180 << "... (caller:" << Caller->getName() << ")\n"); 2181 2182 InlineCostCallAnalyzer CA(CalleeTTI, GetAssumptionCache, GetBFI, PSI, ORE, 2183 *Callee, Call, Params); 2184 InlineResult ShouldInline = CA.analyze(); 2185 2186 LLVM_DEBUG(CA.dump()); 2187 2188 // Check if there was a reason to force inlining or no inlining. 2189 if (!ShouldInline.isSuccess() && CA.getCost() < CA.getThreshold()) 2190 return InlineCost::getNever(ShouldInline.getFailureReason()); 2191 if (ShouldInline.isSuccess() && CA.getCost() >= CA.getThreshold()) 2192 return InlineCost::getAlways("empty function"); 2193 2194 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold()); 2195 } 2196 2197 InlineResult llvm::isInlineViable(Function &F) { 2198 bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice); 2199 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) { 2200 // Disallow inlining of functions which contain indirect branches. 2201 if (isa<IndirectBrInst>(BI->getTerminator())) 2202 return InlineResult::failure("contains indirect branches"); 2203 2204 // Disallow inlining of blockaddresses which are used by non-callbr 2205 // instructions. 2206 if (BI->hasAddressTaken()) 2207 for (User *U : BlockAddress::get(&*BI)->users()) 2208 if (!isa<CallBrInst>(*U)) 2209 return InlineResult::failure("blockaddress used outside of callbr"); 2210 2211 for (auto &II : *BI) { 2212 CallBase *Call = dyn_cast<CallBase>(&II); 2213 if (!Call) 2214 continue; 2215 2216 // Disallow recursive calls. 2217 if (&F == Call->getCalledFunction()) 2218 return InlineResult::failure("recursive call"); 2219 2220 // Disallow calls which expose returns-twice to a function not previously 2221 // attributed as such. 2222 if (!ReturnsTwice && isa<CallInst>(Call) && 2223 cast<CallInst>(Call)->canReturnTwice()) 2224 return InlineResult::failure("exposes returns-twice attribute"); 2225 2226 if (Call->getCalledFunction()) 2227 switch (Call->getCalledFunction()->getIntrinsicID()) { 2228 default: 2229 break; 2230 case llvm::Intrinsic::icall_branch_funnel: 2231 // Disallow inlining of @llvm.icall.branch.funnel because current 2232 // backend can't separate call targets from call arguments. 2233 return InlineResult::failure( 2234 "disallowed inlining of @llvm.icall.branch.funnel"); 2235 case llvm::Intrinsic::localescape: 2236 // Disallow inlining functions that call @llvm.localescape. Doing this 2237 // correctly would require major changes to the inliner. 2238 return InlineResult::failure( 2239 "disallowed inlining of @llvm.localescape"); 2240 case llvm::Intrinsic::vastart: 2241 // Disallow inlining of functions that initialize VarArgs with 2242 // va_start. 2243 return InlineResult::failure( 2244 "contains VarArgs initialized with va_start"); 2245 } 2246 } 2247 } 2248 2249 return InlineResult::success(); 2250 } 2251 2252 // APIs to create InlineParams based on command line flags and/or other 2253 // parameters. 2254 2255 InlineParams llvm::getInlineParams(int Threshold) { 2256 InlineParams Params; 2257 2258 // This field is the threshold to use for a callee by default. This is 2259 // derived from one or more of: 2260 // * optimization or size-optimization levels, 2261 // * a value passed to createFunctionInliningPass function, or 2262 // * the -inline-threshold flag. 2263 // If the -inline-threshold flag is explicitly specified, that is used 2264 // irrespective of anything else. 2265 if (InlineThreshold.getNumOccurrences() > 0) 2266 Params.DefaultThreshold = InlineThreshold; 2267 else 2268 Params.DefaultThreshold = Threshold; 2269 2270 // Set the HintThreshold knob from the -inlinehint-threshold. 2271 Params.HintThreshold = HintThreshold; 2272 2273 // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold. 2274 Params.HotCallSiteThreshold = HotCallSiteThreshold; 2275 2276 // If the -locally-hot-callsite-threshold is explicitly specified, use it to 2277 // populate LocallyHotCallSiteThreshold. Later, we populate 2278 // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if 2279 // we know that optimization level is O3 (in the getInlineParams variant that 2280 // takes the opt and size levels). 2281 // FIXME: Remove this check (and make the assignment unconditional) after 2282 // addressing size regression issues at O2. 2283 if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0) 2284 Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2285 2286 // Set the ColdCallSiteThreshold knob from the 2287 // -inline-cold-callsite-threshold. 2288 Params.ColdCallSiteThreshold = ColdCallSiteThreshold; 2289 2290 // Set the OptMinSizeThreshold and OptSizeThreshold params only if the 2291 // -inlinehint-threshold commandline option is not explicitly given. If that 2292 // option is present, then its value applies even for callees with size and 2293 // minsize attributes. 2294 // If the -inline-threshold is not specified, set the ColdThreshold from the 2295 // -inlinecold-threshold even if it is not explicitly passed. If 2296 // -inline-threshold is specified, then -inlinecold-threshold needs to be 2297 // explicitly specified to set the ColdThreshold knob 2298 if (InlineThreshold.getNumOccurrences() == 0) { 2299 Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold; 2300 Params.OptSizeThreshold = InlineConstants::OptSizeThreshold; 2301 Params.ColdThreshold = ColdThreshold; 2302 } else if (ColdThreshold.getNumOccurrences() > 0) { 2303 Params.ColdThreshold = ColdThreshold; 2304 } 2305 return Params; 2306 } 2307 2308 InlineParams llvm::getInlineParams() { 2309 return getInlineParams(InlineThreshold); 2310 } 2311 2312 // Compute the default threshold for inlining based on the opt level and the 2313 // size opt level. 2314 static int computeThresholdFromOptLevels(unsigned OptLevel, 2315 unsigned SizeOptLevel) { 2316 if (OptLevel > 2) 2317 return InlineConstants::OptAggressiveThreshold; 2318 if (SizeOptLevel == 1) // -Os 2319 return InlineConstants::OptSizeThreshold; 2320 if (SizeOptLevel == 2) // -Oz 2321 return InlineConstants::OptMinSizeThreshold; 2322 return InlineThreshold; 2323 } 2324 2325 InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) { 2326 auto Params = 2327 getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel)); 2328 // At O3, use the value of -locally-hot-callsite-threshold option to populate 2329 // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only 2330 // when it is specified explicitly. 2331 if (OptLevel > 2) 2332 Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold; 2333 return Params; 2334 } 2335