SpeculativeExecution.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. //===- SpeculativeExecution.cpp ---------------------------------*- C++ -*-===//
  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 pass hoists instructions to enable speculative execution on
  10. // targets where branches are expensive. This is aimed at GPUs. It
  11. // currently works on simple if-then and if-then-else
  12. // patterns.
  13. //
  14. // Removing branches is not the only motivation for this
  15. // pass. E.g. consider this code and assume that there is no
  16. // addressing mode for multiplying by sizeof(*a):
  17. //
  18. // if (b > 0)
  19. // c = a[i + 1]
  20. // if (d > 0)
  21. // e = a[i + 2]
  22. //
  23. // turns into
  24. //
  25. // p = &a[i + 1];
  26. // if (b > 0)
  27. // c = *p;
  28. // q = &a[i + 2];
  29. // if (d > 0)
  30. // e = *q;
  31. //
  32. // which could later be optimized to
  33. //
  34. // r = &a[i];
  35. // if (b > 0)
  36. // c = r[1];
  37. // if (d > 0)
  38. // e = r[2];
  39. //
  40. // Later passes sink back much of the speculated code that did not enable
  41. // further optimization.
  42. //
  43. // This pass is more aggressive than the function SpeculativeyExecuteBB in
  44. // SimplifyCFG. SimplifyCFG will not speculate if no selects are introduced and
  45. // it will speculate at most one instruction. It also will not speculate if
  46. // there is a value defined in the if-block that is only used in the then-block.
  47. // These restrictions make sense since the speculation in SimplifyCFG seems
  48. // aimed at introducing cheap selects, while this pass is intended to do more
  49. // aggressive speculation while counting on later passes to either capitalize on
  50. // that or clean it up.
  51. //
  52. // If the pass was created by calling
  53. // createSpeculativeExecutionIfHasBranchDivergencePass or the
  54. // -spec-exec-only-if-divergent-target option is present, this pass only has an
  55. // effect on targets where TargetTransformInfo::hasBranchDivergence() is true;
  56. // on other targets, it is a nop.
  57. //
  58. // This lets you include this pass unconditionally in the IR pass pipeline, but
  59. // only enable it for relevant targets.
  60. //
  61. //===----------------------------------------------------------------------===//
  62. #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
  63. #include "llvm/ADT/SmallPtrSet.h"
  64. #include "llvm/Analysis/GlobalsModRef.h"
  65. #include "llvm/Analysis/TargetTransformInfo.h"
  66. #include "llvm/Analysis/ValueTracking.h"
  67. #include "llvm/IR/Instructions.h"
  68. #include "llvm/IR/IntrinsicInst.h"
  69. #include "llvm/IR/Operator.h"
  70. #include "llvm/InitializePasses.h"
  71. #include "llvm/Support/CommandLine.h"
  72. #include "llvm/Support/Debug.h"
  73. using namespace llvm;
  74. #define DEBUG_TYPE "speculative-execution"
  75. // The risk that speculation will not pay off increases with the
  76. // number of instructions speculated, so we put a limit on that.
  77. static cl::opt<unsigned> SpecExecMaxSpeculationCost(
  78. "spec-exec-max-speculation-cost", cl::init(7), cl::Hidden,
  79. cl::desc("Speculative execution is not applied to basic blocks where "
  80. "the cost of the instructions to speculatively execute "
  81. "exceeds this limit."));
  82. // Speculating just a few instructions from a larger block tends not
  83. // to be profitable and this limit prevents that. A reason for that is
  84. // that small basic blocks are more likely to be candidates for
  85. // further optimization.
  86. static cl::opt<unsigned> SpecExecMaxNotHoisted(
  87. "spec-exec-max-not-hoisted", cl::init(5), cl::Hidden,
  88. cl::desc("Speculative execution is not applied to basic blocks where the "
  89. "number of instructions that would not be speculatively executed "
  90. "exceeds this limit."));
  91. static cl::opt<bool> SpecExecOnlyIfDivergentTarget(
  92. "spec-exec-only-if-divergent-target", cl::init(false), cl::Hidden,
  93. cl::desc("Speculative execution is applied only to targets with divergent "
  94. "branches, even if the pass was configured to apply only to all "
  95. "targets."));
  96. namespace {
  97. class SpeculativeExecutionLegacyPass : public FunctionPass {
  98. public:
  99. static char ID;
  100. explicit SpeculativeExecutionLegacyPass(bool OnlyIfDivergentTarget = false)
  101. : FunctionPass(ID), OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
  102. SpecExecOnlyIfDivergentTarget),
  103. Impl(OnlyIfDivergentTarget) {}
  104. void getAnalysisUsage(AnalysisUsage &AU) const override;
  105. bool runOnFunction(Function &F) override;
  106. StringRef getPassName() const override {
  107. if (OnlyIfDivergentTarget)
  108. return "Speculatively execute instructions if target has divergent "
  109. "branches";
  110. return "Speculatively execute instructions";
  111. }
  112. private:
  113. // Variable preserved purely for correct name printing.
  114. const bool OnlyIfDivergentTarget;
  115. SpeculativeExecutionPass Impl;
  116. };
  117. } // namespace
  118. char SpeculativeExecutionLegacyPass::ID = 0;
  119. INITIALIZE_PASS_BEGIN(SpeculativeExecutionLegacyPass, "speculative-execution",
  120. "Speculatively execute instructions", false, false)
  121. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  122. INITIALIZE_PASS_END(SpeculativeExecutionLegacyPass, "speculative-execution",
  123. "Speculatively execute instructions", false, false)
  124. void SpeculativeExecutionLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
  125. AU.addRequired<TargetTransformInfoWrapperPass>();
  126. AU.addPreserved<GlobalsAAWrapperPass>();
  127. AU.setPreservesCFG();
  128. }
  129. bool SpeculativeExecutionLegacyPass::runOnFunction(Function &F) {
  130. if (skipFunction(F))
  131. return false;
  132. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  133. return Impl.runImpl(F, TTI);
  134. }
  135. namespace llvm {
  136. bool SpeculativeExecutionPass::runImpl(Function &F, TargetTransformInfo *TTI) {
  137. if (OnlyIfDivergentTarget && !TTI->hasBranchDivergence()) {
  138. LLVM_DEBUG(dbgs() << "Not running SpeculativeExecution because "
  139. "TTI->hasBranchDivergence() is false.\n");
  140. return false;
  141. }
  142. this->TTI = TTI;
  143. bool Changed = false;
  144. for (auto& B : F) {
  145. Changed |= runOnBasicBlock(B);
  146. }
  147. return Changed;
  148. }
  149. bool SpeculativeExecutionPass::runOnBasicBlock(BasicBlock &B) {
  150. BranchInst *BI = dyn_cast<BranchInst>(B.getTerminator());
  151. if (BI == nullptr)
  152. return false;
  153. if (BI->getNumSuccessors() != 2)
  154. return false;
  155. BasicBlock &Succ0 = *BI->getSuccessor(0);
  156. BasicBlock &Succ1 = *BI->getSuccessor(1);
  157. if (&B == &Succ0 || &B == &Succ1 || &Succ0 == &Succ1) {
  158. return false;
  159. }
  160. // Hoist from if-then (triangle).
  161. if (Succ0.getSinglePredecessor() != nullptr &&
  162. Succ0.getSingleSuccessor() == &Succ1) {
  163. return considerHoistingFromTo(Succ0, B);
  164. }
  165. // Hoist from if-else (triangle).
  166. if (Succ1.getSinglePredecessor() != nullptr &&
  167. Succ1.getSingleSuccessor() == &Succ0) {
  168. return considerHoistingFromTo(Succ1, B);
  169. }
  170. // Hoist from if-then-else (diamond), but only if it is equivalent to
  171. // an if-else or if-then due to one of the branches doing nothing.
  172. if (Succ0.getSinglePredecessor() != nullptr &&
  173. Succ1.getSinglePredecessor() != nullptr &&
  174. Succ1.getSingleSuccessor() != nullptr &&
  175. Succ1.getSingleSuccessor() != &B &&
  176. Succ1.getSingleSuccessor() == Succ0.getSingleSuccessor()) {
  177. // If a block has only one instruction, then that is a terminator
  178. // instruction so that the block does nothing. This does happen.
  179. if (Succ1.size() == 1) // equivalent to if-then
  180. return considerHoistingFromTo(Succ0, B);
  181. if (Succ0.size() == 1) // equivalent to if-else
  182. return considerHoistingFromTo(Succ1, B);
  183. }
  184. return false;
  185. }
  186. static InstructionCost ComputeSpeculationCost(const Instruction *I,
  187. const TargetTransformInfo &TTI) {
  188. switch (Operator::getOpcode(I)) {
  189. case Instruction::GetElementPtr:
  190. case Instruction::Add:
  191. case Instruction::Mul:
  192. case Instruction::And:
  193. case Instruction::Or:
  194. case Instruction::Select:
  195. case Instruction::Shl:
  196. case Instruction::Sub:
  197. case Instruction::LShr:
  198. case Instruction::AShr:
  199. case Instruction::Xor:
  200. case Instruction::ZExt:
  201. case Instruction::SExt:
  202. case Instruction::Call:
  203. case Instruction::BitCast:
  204. case Instruction::PtrToInt:
  205. case Instruction::IntToPtr:
  206. case Instruction::AddrSpaceCast:
  207. case Instruction::FPToUI:
  208. case Instruction::FPToSI:
  209. case Instruction::UIToFP:
  210. case Instruction::SIToFP:
  211. case Instruction::FPExt:
  212. case Instruction::FPTrunc:
  213. case Instruction::FAdd:
  214. case Instruction::FSub:
  215. case Instruction::FMul:
  216. case Instruction::FDiv:
  217. case Instruction::FRem:
  218. case Instruction::FNeg:
  219. case Instruction::ICmp:
  220. case Instruction::FCmp:
  221. case Instruction::Trunc:
  222. case Instruction::Freeze:
  223. case Instruction::ExtractElement:
  224. case Instruction::InsertElement:
  225. case Instruction::ShuffleVector:
  226. case Instruction::ExtractValue:
  227. case Instruction::InsertValue:
  228. return TTI.getInstructionCost(I, TargetTransformInfo::TCK_SizeAndLatency);
  229. default:
  230. return InstructionCost::getInvalid(); // Disallow anything not explicitly
  231. // listed.
  232. }
  233. }
  234. bool SpeculativeExecutionPass::considerHoistingFromTo(
  235. BasicBlock &FromBlock, BasicBlock &ToBlock) {
  236. SmallPtrSet<const Instruction *, 8> NotHoisted;
  237. const auto AllPrecedingUsesFromBlockHoisted = [&NotHoisted](const User *U) {
  238. // Debug variable has special operand to check it's not hoisted.
  239. if (const auto *DVI = dyn_cast<DbgVariableIntrinsic>(U)) {
  240. return all_of(DVI->location_ops(), [&NotHoisted](Value *V) {
  241. if (const auto *I = dyn_cast_or_null<Instruction>(V)) {
  242. if (!NotHoisted.contains(I))
  243. return true;
  244. }
  245. return false;
  246. });
  247. }
  248. // Usially debug label intrinsic corresponds to label in LLVM IR. In these
  249. // cases we should not move it here.
  250. // TODO: Possible special processing needed to detect it is related to a
  251. // hoisted instruction.
  252. if (isa<DbgLabelInst>(U))
  253. return false;
  254. for (const Value *V : U->operand_values()) {
  255. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  256. if (NotHoisted.contains(I))
  257. return false;
  258. }
  259. }
  260. return true;
  261. };
  262. InstructionCost TotalSpeculationCost = 0;
  263. unsigned NotHoistedInstCount = 0;
  264. for (const auto &I : FromBlock) {
  265. const InstructionCost Cost = ComputeSpeculationCost(&I, *TTI);
  266. if (Cost.isValid() && isSafeToSpeculativelyExecute(&I) &&
  267. AllPrecedingUsesFromBlockHoisted(&I)) {
  268. TotalSpeculationCost += Cost;
  269. if (TotalSpeculationCost > SpecExecMaxSpeculationCost)
  270. return false; // too much to hoist
  271. } else {
  272. // Debug info intrinsics should not be counted for threshold.
  273. if (!isa<DbgInfoIntrinsic>(I))
  274. NotHoistedInstCount++;
  275. if (NotHoistedInstCount > SpecExecMaxNotHoisted)
  276. return false; // too much left behind
  277. NotHoisted.insert(&I);
  278. }
  279. }
  280. for (auto I = FromBlock.begin(); I != FromBlock.end();) {
  281. // We have to increment I before moving Current as moving Current
  282. // changes the list that I is iterating through.
  283. auto Current = I;
  284. ++I;
  285. if (!NotHoisted.count(&*Current)) {
  286. Current->moveBefore(ToBlock.getTerminator());
  287. }
  288. }
  289. return true;
  290. }
  291. FunctionPass *createSpeculativeExecutionPass() {
  292. return new SpeculativeExecutionLegacyPass();
  293. }
  294. FunctionPass *createSpeculativeExecutionIfHasBranchDivergencePass() {
  295. return new SpeculativeExecutionLegacyPass(/* OnlyIfDivergentTarget = */ true);
  296. }
  297. SpeculativeExecutionPass::SpeculativeExecutionPass(bool OnlyIfDivergentTarget)
  298. : OnlyIfDivergentTarget(OnlyIfDivergentTarget ||
  299. SpecExecOnlyIfDivergentTarget) {}
  300. PreservedAnalyses SpeculativeExecutionPass::run(Function &F,
  301. FunctionAnalysisManager &AM) {
  302. auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
  303. bool Changed = runImpl(F, TTI);
  304. if (!Changed)
  305. return PreservedAnalyses::all();
  306. PreservedAnalyses PA;
  307. PA.preserveSet<CFGAnalyses>();
  308. return PA;
  309. }
  310. } // namespace llvm