SpeculativeExecution.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. //===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass hoists instructions to enable speculative execution on
  11. // targets where branches are expensive. This is aimed at GPUs. It
  12. // currently works on simple if-then and if-then-else
  13. // patterns.
  14. //
  15. // Removing branches is not the only motivation for this
  16. // pass. E.g. consider this code and assume that there is no
  17. // addressing mode for multiplying by sizeof(*a):
  18. //
  19. // if (b > 0)
  20. // c = a[i + 1]
  21. // if (d > 0)
  22. // e = a[i + 2]
  23. //
  24. // turns into
  25. //
  26. // p = &a[i + 1];
  27. // if (b > 0)
  28. // c = *p;
  29. // q = &a[i + 2];
  30. // if (d > 0)
  31. // e = *q;
  32. //
  33. // which could later be optimized to
  34. //
  35. // r = &a[i];
  36. // if (b > 0)
  37. // c = r[1];
  38. // if (d > 0)
  39. // e = r[2];
  40. //
  41. // Later passes sink back much of the speculated code that did not enable
  42. // further optimization.
  43. //
  44. // This pass is more aggressive than the function SpeculativeyExecuteBB in
  45. // SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
  46. // it will speculate at most one instruction. It also will not speculate if
  47. // there is a value defined in the if-block that is only used in the then-block.
  48. // These restrictions make sense since the speculation in SimplifyCFG seems
  49. // aimed at introducing cheap selects, while this pass is intended to do more
  50. // aggressive speculation while counting on later passes to either capitalize on
  51. // that or clean it up.
  52. //
  53. //===----------------------------------------------------------------------===//
  54. #include "llvm/ADT/SmallSet.h"
  55. #include "llvm/Analysis/TargetTransformInfo.h"
  56. #include "llvm/Analysis/ValueTracking.h"
  57. #include "llvm/IR/Instructions.h"
  58. #include "llvm/IR/Module.h"
  59. #include "llvm/IR/Operator.h"
  60. #include "llvm/Support/CommandLine.h"
  61. #include "llvm/Support/Debug.h"
  62. using namespace llvm;
  63. #define DEBUG_TYPE "speculative-execution"
  64. // The risk that speculation will not pay off increases with the
  65. // number of instructions speculated, so we put a limit on that.
  66. static cl::opt<unsigned> SpecExecMaxSpeculationCost(
  67. "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
  68. cl::desc("Speculative execution is not applied to basic blocks where "
  69. "the cost of the instructions to speculatively execute "
  70. "exceeds this limit."));
  71. // Speculating just a few instructions from a larger block tends not
  72. // to be profitable and this limit prevents that. A reason for that is
  73. // that small basic blocks are more likely to be candidates for
  74. // further optimization.
  75. static cl::opt<unsigned> SpecExecMaxNotHoisted(
  76. "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
  77. cl::desc("Speculative execution is not applied to basic blocks where the "
  78. "number of instructions that would not be speculatively executed "
  79. "exceeds this limit."));
  80. namespace {
  81. class SpeculativeExecution : public FunctionPass {
  82. public:
  83. static char ID;
  84. SpeculativeExecution(): FunctionPass(ID) {}
  85. void getAnalysisUsage(AnalysisUsage &AU) const override;
  86. bool runOnFunction(Function &F) override;
  87. private:
  88. bool runOnBasicBlock(BasicBlock &B);
  89. bool considerHoistingFromTo(BasicBlock &FromBlock, BasicBlock &ToBlock);
  90. const TargetTransformInfo *TTI = nullptr;
  91. };
  92. } // namespace
  93. char SpeculativeExecution::ID = 0;
  94. INITIALIZE_PASS_BEGIN(SpeculativeExecution, "speculative-execution",
  95. "Speculatively execute instructions", false, false)
  96. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  97. INITIALIZE_PASS_END(SpeculativeExecution, "speculative-execution",
  98. "Speculatively execute instructions", false, false)
  99. void SpeculativeExecution::getAnalysisUsage(AnalysisUsage &AU) const {
  100. AU.addRequired<TargetTransformInfoWrapperPass>();
  101. }
  102. bool SpeculativeExecution::runOnFunction(Function &F) {
  103. if (skipOptnoneFunction(F))
  104. return false;
  105. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  106. bool Changed = false;
  107. for (auto& B : F) {
  108. Changed |= runOnBasicBlock(B);
  109. }
  110. return Changed;
  111. }
  112. bool SpeculativeExecution::runOnBasicBlock(BasicBlock &B) {
  113. BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
  114. if (BI == nullptr)
  115. return false;
  116. if (BI->getNumSuccessors() != 2)
  117. return false;
  118. BasicBlock &Succ0 = *BI->getSuccessor(0);
  119. BasicBlock &Succ1 = *BI->getSuccessor(1);
  120. if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
  121. return false;
  122. }
  123. // Hoist from if-then (triangle).
  124. if (Succ0.getSinglePredecessor() != nullptr &&
  125. Succ0.getSingleSuccessor() == &Succ1) {
  126. return considerHoistingFromTo(Succ0, B);
  127. }
  128. // Hoist from if-else (triangle).
  129. if (Succ1.getSinglePredecessor() != nullptr &&
  130. Succ1.getSingleSuccessor() == &Succ0) {
  131. return considerHoistingFromTo(Succ1, B);
  132. }
  133. // Hoist from if-then-else (diamond), but only if it is equivalent to
  134. // an if-else or if-then due to one of the branches doing nothing.
  135. if (Succ0.getSinglePredecessor() != nullptr &&
  136. Succ1.getSinglePredecessor() != nullptr &&
  137. Succ1.getSingleSuccessor() != nullptr &&
  138. Succ1.getSingleSuccessor() != &B &&
  139. Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
  140. // If a block has only one instruction, then that is a terminator
  141. // instruction so that the block does nothing. This does happen.
  142. if (Succ1.size() == 1) // equivalent to if-then
  143. return considerHoistingFromTo(Succ0, B);
  144. if (Succ0.size() == 1) // equivalent to if-else
  145. return considerHoistingFromTo(Succ1, B);
  146. }
  147. return false;
  148. }
  149. static unsigned ComputeSpeculationCost(const Instruction *I,
  150. const TargetTransformInfo &TTI) {
  151. switch (Operator::getOpcode(I)) {
  152. case Instruction::GetElementPtr:
  153. case Instruction::Add:
  154. case Instruction::Mul:
  155. case Instruction::And:
  156. case Instruction::Or:
  157. case Instruction::Select:
  158. case Instruction::Shl:
  159. case Instruction::Sub:
  160. case Instruction::LShr:
  161. case Instruction::AShr:
  162. case Instruction::Xor:
  163. case Instruction::ZExt:
  164. case Instruction::SExt:
  165. return TTI.getUserCost(I);
  166. default:
  167. return UINT_MAX; // Disallow anything not whitelisted.
  168. }
  169. }
  170. bool SpeculativeExecution::considerHoistingFromTo(BasicBlock &FromBlock,
  171. BasicBlock &ToBlock) {
  172. SmallSet<const Instruction *, 8> NotHoisted;
  173. const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](User *U) {
  174. for (Value* V : U->operand_values()) {
  175. if (Instruction *I = dyn_cast<Instruction>(V)) {
  176. if (NotHoisted.count(I) > 0)
  177. return false;
  178. }
  179. }
  180. return true;
  181. };
  182. unsigned TotalSpeculationCost = 0;
  183. for (auto& I : FromBlock) {
  184. const unsigned Cost = ComputeSpeculationCost(&I, *TTI);
  185. if (Cost != UINT_MAX && isSafeToSpeculativelyExecute(&I) &&
  186. AllPrecedingUsesFromBlockHoisted(&I)) {
  187. TotalSpeculationCost += Cost;
  188. if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
  189. return false; // too much to hoist
  190. } else {
  191. NotHoisted.insert(&I);
  192. if (NotHoisted.size() > SpecExecMaxNotHoisted)
  193. return false; // too much left behind
  194. }
  195. }
  196. if (TotalSpeculationCost == 0)
  197. return false; // nothing to hoist
  198. for (auto I = FromBlock.begin(); I != FromBlock.end();) {
  199. // We have to increment I before moving Current as moving Current
  200. // changes the list that I is iterating through.
  201. auto Current = I;
  202. ++I;
  203. if (!NotHoisted.count(Current)) {
  204. Current->moveBefore(ToBlock.getTerminator());
  205. }
  206. }
  207. return true;
  208. }
  209. namespace llvm {
  210. FunctionPass *createSpeculativeExecutionPass() {
  211. return new SpeculativeExecution();
  212. }
  213. } // namespace llvm