CodeMetrics.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. //===- CodeMetrics.cpp - Code cost measurements ---------------------------===//
  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 code cost measurement utilities.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Analysis/CodeMetrics.h"
  13. #include "llvm/ADT/SmallPtrSet.h"
  14. #include "llvm/Analysis/AssumptionCache.h"
  15. #include "llvm/Analysis/LoopInfo.h"
  16. #include "llvm/Analysis/TargetTransformInfo.h"
  17. #include "llvm/IR/Function.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/InstructionCost.h"
  20. #define DEBUG_TYPE "code-metrics"
  21. using namespace llvm;
  22. static void
  23. appendSpeculatableOperands(const Value *V,
  24. SmallPtrSetImpl<const Value *> &Visited,
  25. SmallVectorImpl<const Value *> &Worklist) {
  26. const User *U = dyn_cast<User>(V);
  27. if (!U)
  28. return;
  29. for (const Value *Operand : U->operands())
  30. if (Visited.insert(Operand).second)
  31. if (const auto *I = dyn_cast<Instruction>(Operand))
  32. if (!I->mayHaveSideEffects() && !I->isTerminator())
  33. Worklist.push_back(I);
  34. }
  35. static void completeEphemeralValues(SmallPtrSetImpl<const Value *> &Visited,
  36. SmallVectorImpl<const Value *> &Worklist,
  37. SmallPtrSetImpl<const Value *> &EphValues) {
  38. // Note: We don't speculate PHIs here, so we'll miss instruction chains kept
  39. // alive only by ephemeral values.
  40. // Walk the worklist using an index but without caching the size so we can
  41. // append more entries as we process the worklist. This forms a queue without
  42. // quadratic behavior by just leaving processed nodes at the head of the
  43. // worklist forever.
  44. for (int i = 0; i < (int)Worklist.size(); ++i) {
  45. const Value *V = Worklist[i];
  46. assert(Visited.count(V) &&
  47. "Failed to add a worklist entry to our visited set!");
  48. // If all uses of this value are ephemeral, then so is this value.
  49. if (!all_of(V->users(), [&](const User *U) { return EphValues.count(U); }))
  50. continue;
  51. EphValues.insert(V);
  52. LLVM_DEBUG(dbgs() << "Ephemeral Value: " << *V << "\n");
  53. // Append any more operands to consider.
  54. appendSpeculatableOperands(V, Visited, Worklist);
  55. }
  56. }
  57. // Find all ephemeral values.
  58. void CodeMetrics::collectEphemeralValues(
  59. const Loop *L, AssumptionCache *AC,
  60. SmallPtrSetImpl<const Value *> &EphValues) {
  61. SmallPtrSet<const Value *, 32> Visited;
  62. SmallVector<const Value *, 16> Worklist;
  63. for (auto &AssumeVH : AC->assumptions()) {
  64. if (!AssumeVH)
  65. continue;
  66. Instruction *I = cast<Instruction>(AssumeVH);
  67. // Filter out call sites outside of the loop so we don't do a function's
  68. // worth of work for each of its loops (and, in the common case, ephemeral
  69. // values in the loop are likely due to @llvm.assume calls in the loop).
  70. if (!L->contains(I->getParent()))
  71. continue;
  72. if (EphValues.insert(I).second)
  73. appendSpeculatableOperands(I, Visited, Worklist);
  74. }
  75. completeEphemeralValues(Visited, Worklist, EphValues);
  76. }
  77. void CodeMetrics::collectEphemeralValues(
  78. const Function *F, AssumptionCache *AC,
  79. SmallPtrSetImpl<const Value *> &EphValues) {
  80. SmallPtrSet<const Value *, 32> Visited;
  81. SmallVector<const Value *, 16> Worklist;
  82. for (auto &AssumeVH : AC->assumptions()) {
  83. if (!AssumeVH)
  84. continue;
  85. Instruction *I = cast<Instruction>(AssumeVH);
  86. assert(I->getParent()->getParent() == F &&
  87. "Found assumption for the wrong function!");
  88. if (EphValues.insert(I).second)
  89. appendSpeculatableOperands(I, Visited, Worklist);
  90. }
  91. completeEphemeralValues(Visited, Worklist, EphValues);
  92. }
  93. /// Fill in the current structure with information gleaned from the specified
  94. /// block.
  95. void CodeMetrics::analyzeBasicBlock(
  96. const BasicBlock *BB, const TargetTransformInfo &TTI,
  97. const SmallPtrSetImpl<const Value *> &EphValues, bool PrepareForLTO) {
  98. ++NumBlocks;
  99. InstructionCost NumInstsBeforeThisBB = NumInsts;
  100. for (const Instruction &I : *BB) {
  101. // Skip ephemeral values.
  102. if (EphValues.count(&I))
  103. continue;
  104. // Special handling for calls.
  105. if (const auto *Call = dyn_cast<CallBase>(&I)) {
  106. if (const Function *F = Call->getCalledFunction()) {
  107. bool IsLoweredToCall = TTI.isLoweredToCall(F);
  108. // If a function is both internal and has a single use, then it is
  109. // extremely likely to get inlined in the future (it was probably
  110. // exposed by an interleaved devirtualization pass).
  111. // When preparing for LTO, liberally consider calls as inline
  112. // candidates.
  113. if (!Call->isNoInline() && IsLoweredToCall &&
  114. ((F->hasInternalLinkage() && F->hasOneLiveUse()) ||
  115. PrepareForLTO)) {
  116. ++NumInlineCandidates;
  117. }
  118. // If this call is to function itself, then the function is recursive.
  119. // Inlining it into other functions is a bad idea, because this is
  120. // basically just a form of loop peeling, and our metrics aren't useful
  121. // for that case.
  122. if (F == BB->getParent())
  123. isRecursive = true;
  124. if (IsLoweredToCall)
  125. ++NumCalls;
  126. } else {
  127. // We don't want inline asm to count as a call - that would prevent loop
  128. // unrolling. The argument setup cost is still real, though.
  129. if (!Call->isInlineAsm())
  130. ++NumCalls;
  131. }
  132. }
  133. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  134. if (!AI->isStaticAlloca())
  135. this->usesDynamicAlloca = true;
  136. }
  137. if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
  138. ++NumVectorInsts;
  139. if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
  140. notDuplicatable = true;
  141. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  142. if (CI->cannotDuplicate())
  143. notDuplicatable = true;
  144. if (CI->isConvergent())
  145. convergent = true;
  146. }
  147. if (const InvokeInst *InvI = dyn_cast<InvokeInst>(&I))
  148. if (InvI->cannotDuplicate())
  149. notDuplicatable = true;
  150. NumInsts += TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
  151. }
  152. if (isa<ReturnInst>(BB->getTerminator()))
  153. ++NumRets;
  154. // We never want to inline functions that contain an indirectbr. This is
  155. // incorrect because all the blockaddress's (in static global initializers
  156. // for example) would be referring to the original function, and this indirect
  157. // jump would jump from the inlined copy of the function into the original
  158. // function which is extremely undefined behavior.
  159. // FIXME: This logic isn't really right; we can safely inline functions
  160. // with indirectbr's as long as no other function or global references the
  161. // blockaddress of a block within the current function. And as a QOI issue,
  162. // if someone is using a blockaddress without an indirectbr, and that
  163. // reference somehow ends up in another function or global, we probably
  164. // don't want to inline this function.
  165. notDuplicatable |= isa<IndirectBrInst>(BB->getTerminator());
  166. // Remember NumInsts for this BB.
  167. InstructionCost NumInstsThisBB = NumInsts - NumInstsBeforeThisBB;
  168. NumBBInsts[BB] = NumInstsThisBB;
  169. }