CodeMetrics.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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/Analysis/AssumptionCache.h"
  14. #include "llvm/Analysis/LoopInfo.h"
  15. #include "llvm/Analysis/TargetTransformInfo.h"
  16. #include "llvm/Analysis/ValueTracking.h"
  17. #include "llvm/IR/DataLayout.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #define DEBUG_TYPE "code-metrics"
  22. using namespace llvm;
  23. static void
  24. appendSpeculatableOperands(const Value *V,
  25. SmallPtrSetImpl<const Value *> &Visited,
  26. SmallVectorImpl<const Value *> &Worklist) {
  27. const User *U = dyn_cast<User>(V);
  28. if (!U)
  29. return;
  30. for (const Value *Operand : U->operands())
  31. if (Visited.insert(Operand).second)
  32. if (isSafeToSpeculativelyExecute(Operand))
  33. Worklist.push_back(Operand);
  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(const BasicBlock *BB,
  96. const TargetTransformInfo &TTI,
  97. const SmallPtrSetImpl<const Value*> &EphValues) {
  98. ++NumBlocks;
  99. unsigned 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. // If a function is both internal and has a single use, then it is
  108. // extremely likely to get inlined in the future (it was probably
  109. // exposed by an interleaved devirtualization pass).
  110. if (!Call->isNoInline() && F->hasInternalLinkage() && F->hasOneUse())
  111. ++NumInlineCandidates;
  112. // If this call is to function itself, then the function is recursive.
  113. // Inlining it into other functions is a bad idea, because this is
  114. // basically just a form of loop peeling, and our metrics aren't useful
  115. // for that case.
  116. if (F == BB->getParent())
  117. isRecursive = true;
  118. if (TTI.isLoweredToCall(F))
  119. ++NumCalls;
  120. } else {
  121. // We don't want inline asm to count as a call - that would prevent loop
  122. // unrolling. The argument setup cost is still real, though.
  123. if (!Call->isInlineAsm())
  124. ++NumCalls;
  125. }
  126. }
  127. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
  128. if (!AI->isStaticAlloca())
  129. this->usesDynamicAlloca = true;
  130. }
  131. if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
  132. ++NumVectorInsts;
  133. if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB))
  134. notDuplicatable = true;
  135. if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
  136. if (CI->cannotDuplicate())
  137. notDuplicatable = true;
  138. if (CI->isConvergent())
  139. convergent = true;
  140. }
  141. if (const InvokeInst *InvI = dyn_cast<InvokeInst>(&I))
  142. if (InvI->cannotDuplicate())
  143. notDuplicatable = true;
  144. NumInsts += TTI.getUserCost(&I);
  145. }
  146. if (isa<ReturnInst>(BB->getTerminator()))
  147. ++NumRets;
  148. // We never want to inline functions that contain an indirectbr. This is
  149. // incorrect because all the blockaddress's (in static global initializers
  150. // for example) would be referring to the original function, and this indirect
  151. // jump would jump from the inlined copy of the function into the original
  152. // function which is extremely undefined behavior.
  153. // FIXME: This logic isn't really right; we can safely inline functions
  154. // with indirectbr's as long as no other function or global references the
  155. // blockaddress of a block within the current function. And as a QOI issue,
  156. // if someone is using a blockaddress without an indirectbr, and that
  157. // reference somehow ends up in another function or global, we probably
  158. // don't want to inline this function.
  159. notDuplicatable |= isa<IndirectBrInst>(BB->getTerminator());
  160. // Remember NumInsts for this BB.
  161. NumBBInsts[BB] = NumInsts - NumInstsBeforeThisBB;
  162. }