IndirectBrExpandPass.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. //===- IndirectBrExpandPass.cpp - Expand indirectbr to switch -------------===//
  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. /// \file
  9. ///
  10. /// Implements an expansion pass to turn `indirectbr` instructions in the IR
  11. /// into `switch` instructions. This works by enumerating the basic blocks in
  12. /// a dense range of integers, replacing each `blockaddr` constant with the
  13. /// corresponding integer constant, and then building a switch that maps from
  14. /// the integers to the actual blocks. All of the indirectbr instructions in the
  15. /// function are redirected to this common switch.
  16. ///
  17. /// While this is generically useful if a target is unable to codegen
  18. /// `indirectbr` natively, it is primarily useful when there is some desire to
  19. /// get the builtin non-jump-table lowering of a switch even when the input
  20. /// source contained an explicit indirect branch construct.
  21. ///
  22. /// Note that it doesn't make any sense to enable this pass unless a target also
  23. /// disables jump-table lowering of switches. Doing that is likely to pessimize
  24. /// the code.
  25. ///
  26. //===----------------------------------------------------------------------===//
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/Sequence.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/Analysis/DomTreeUpdater.h"
  31. #include "llvm/CodeGen/TargetPassConfig.h"
  32. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  33. #include "llvm/IR/BasicBlock.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/IRBuilder.h"
  37. #include "llvm/IR/InstIterator.h"
  38. #include "llvm/IR/Instruction.h"
  39. #include "llvm/IR/Instructions.h"
  40. #include "llvm/InitializePasses.h"
  41. #include "llvm/Pass.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include "llvm/Target/TargetMachine.h"
  46. using namespace llvm;
  47. #define DEBUG_TYPE "indirectbr-expand"
  48. namespace {
  49. class IndirectBrExpandPass : public FunctionPass {
  50. const TargetLowering *TLI = nullptr;
  51. public:
  52. static char ID; // Pass identification, replacement for typeid
  53. IndirectBrExpandPass() : FunctionPass(ID) {
  54. initializeIndirectBrExpandPassPass(*PassRegistry::getPassRegistry());
  55. }
  56. void getAnalysisUsage(AnalysisUsage &AU) const override {
  57. AU.addPreserved<DominatorTreeWrapperPass>();
  58. }
  59. bool runOnFunction(Function &F) override;
  60. };
  61. } // end anonymous namespace
  62. char IndirectBrExpandPass::ID = 0;
  63. INITIALIZE_PASS_BEGIN(IndirectBrExpandPass, DEBUG_TYPE,
  64. "Expand indirectbr instructions", false, false)
  65. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  66. INITIALIZE_PASS_END(IndirectBrExpandPass, DEBUG_TYPE,
  67. "Expand indirectbr instructions", false, false)
  68. FunctionPass *llvm::createIndirectBrExpandPass() {
  69. return new IndirectBrExpandPass();
  70. }
  71. bool IndirectBrExpandPass::runOnFunction(Function &F) {
  72. auto &DL = F.getParent()->getDataLayout();
  73. auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
  74. if (!TPC)
  75. return false;
  76. auto &TM = TPC->getTM<TargetMachine>();
  77. auto &STI = *TM.getSubtargetImpl(F);
  78. if (!STI.enableIndirectBrExpand())
  79. return false;
  80. TLI = STI.getTargetLowering();
  81. Optional<DomTreeUpdater> DTU;
  82. if (auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>())
  83. DTU.emplace(DTWP->getDomTree(), DomTreeUpdater::UpdateStrategy::Lazy);
  84. SmallVector<IndirectBrInst *, 1> IndirectBrs;
  85. // Set of all potential successors for indirectbr instructions.
  86. SmallPtrSet<BasicBlock *, 4> IndirectBrSuccs;
  87. // Build a list of indirectbrs that we want to rewrite.
  88. for (BasicBlock &BB : F)
  89. if (auto *IBr = dyn_cast<IndirectBrInst>(BB.getTerminator())) {
  90. // Handle the degenerate case of no successors by replacing the indirectbr
  91. // with unreachable as there is no successor available.
  92. if (IBr->getNumSuccessors() == 0) {
  93. (void)new UnreachableInst(F.getContext(), IBr);
  94. IBr->eraseFromParent();
  95. continue;
  96. }
  97. IndirectBrs.push_back(IBr);
  98. for (BasicBlock *SuccBB : IBr->successors())
  99. IndirectBrSuccs.insert(SuccBB);
  100. }
  101. if (IndirectBrs.empty())
  102. return false;
  103. // If we need to replace any indirectbrs we need to establish integer
  104. // constants that will correspond to each of the basic blocks in the function
  105. // whose address escapes. We do that here and rewrite all the blockaddress
  106. // constants to just be those integer constants cast to a pointer type.
  107. SmallVector<BasicBlock *, 4> BBs;
  108. for (BasicBlock &BB : F) {
  109. // Skip blocks that aren't successors to an indirectbr we're going to
  110. // rewrite.
  111. if (!IndirectBrSuccs.count(&BB))
  112. continue;
  113. auto IsBlockAddressUse = [&](const Use &U) {
  114. return isa<BlockAddress>(U.getUser());
  115. };
  116. auto BlockAddressUseIt = llvm::find_if(BB.uses(), IsBlockAddressUse);
  117. if (BlockAddressUseIt == BB.use_end())
  118. continue;
  119. assert(std::find_if(std::next(BlockAddressUseIt), BB.use_end(),
  120. IsBlockAddressUse) == BB.use_end() &&
  121. "There should only ever be a single blockaddress use because it is "
  122. "a constant and should be uniqued.");
  123. auto *BA = cast<BlockAddress>(BlockAddressUseIt->getUser());
  124. // Skip if the constant was formed but ended up not being used (due to DCE
  125. // or whatever).
  126. if (!BA->isConstantUsed())
  127. continue;
  128. // Compute the index we want to use for this basic block. We can't use zero
  129. // because null can be compared with block addresses.
  130. int BBIndex = BBs.size() + 1;
  131. BBs.push_back(&BB);
  132. auto *ITy = cast<IntegerType>(DL.getIntPtrType(BA->getType()));
  133. ConstantInt *BBIndexC = ConstantInt::get(ITy, BBIndex);
  134. // Now rewrite the blockaddress to an integer constant based on the index.
  135. // FIXME: This part doesn't properly recognize other uses of blockaddress
  136. // expressions, for instance, where they are used to pass labels to
  137. // asm-goto. This part of the pass needs a rework.
  138. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(BBIndexC, BA->getType()));
  139. }
  140. if (BBs.empty()) {
  141. // There are no blocks whose address is taken, so any indirectbr instruction
  142. // cannot get a valid input and we can replace all of them with unreachable.
  143. SmallVector<DominatorTree::UpdateType, 8> Updates;
  144. if (DTU)
  145. Updates.reserve(IndirectBrSuccs.size());
  146. for (auto *IBr : IndirectBrs) {
  147. if (DTU) {
  148. for (BasicBlock *SuccBB : IBr->successors())
  149. Updates.push_back({DominatorTree::Delete, IBr->getParent(), SuccBB});
  150. }
  151. (void)new UnreachableInst(F.getContext(), IBr);
  152. IBr->eraseFromParent();
  153. }
  154. if (DTU) {
  155. assert(Updates.size() == IndirectBrSuccs.size() &&
  156. "Got unexpected update count.");
  157. DTU->applyUpdates(Updates);
  158. }
  159. return true;
  160. }
  161. BasicBlock *SwitchBB;
  162. Value *SwitchValue;
  163. // Compute a common integer type across all the indirectbr instructions.
  164. IntegerType *CommonITy = nullptr;
  165. for (auto *IBr : IndirectBrs) {
  166. auto *ITy =
  167. cast<IntegerType>(DL.getIntPtrType(IBr->getAddress()->getType()));
  168. if (!CommonITy || ITy->getBitWidth() > CommonITy->getBitWidth())
  169. CommonITy = ITy;
  170. }
  171. auto GetSwitchValue = [DL, CommonITy](IndirectBrInst *IBr) {
  172. return CastInst::CreatePointerCast(
  173. IBr->getAddress(), CommonITy,
  174. Twine(IBr->getAddress()->getName()) + ".switch_cast", IBr);
  175. };
  176. SmallVector<DominatorTree::UpdateType, 8> Updates;
  177. if (IndirectBrs.size() == 1) {
  178. // If we only have one indirectbr, we can just directly replace it within
  179. // its block.
  180. IndirectBrInst *IBr = IndirectBrs[0];
  181. SwitchBB = IBr->getParent();
  182. SwitchValue = GetSwitchValue(IBr);
  183. if (DTU) {
  184. Updates.reserve(IndirectBrSuccs.size());
  185. for (BasicBlock *SuccBB : IBr->successors())
  186. Updates.push_back({DominatorTree::Delete, IBr->getParent(), SuccBB});
  187. assert(Updates.size() == IndirectBrSuccs.size() &&
  188. "Got unexpected update count.");
  189. }
  190. IBr->eraseFromParent();
  191. } else {
  192. // Otherwise we need to create a new block to hold the switch across BBs,
  193. // jump to that block instead of each indirectbr, and phi together the
  194. // values for the switch.
  195. SwitchBB = BasicBlock::Create(F.getContext(), "switch_bb", &F);
  196. auto *SwitchPN = PHINode::Create(CommonITy, IndirectBrs.size(),
  197. "switch_value_phi", SwitchBB);
  198. SwitchValue = SwitchPN;
  199. // Now replace the indirectbr instructions with direct branches to the
  200. // switch block and fill out the PHI operands.
  201. if (DTU)
  202. Updates.reserve(IndirectBrs.size() + 2 * IndirectBrSuccs.size());
  203. for (auto *IBr : IndirectBrs) {
  204. SwitchPN->addIncoming(GetSwitchValue(IBr), IBr->getParent());
  205. BranchInst::Create(SwitchBB, IBr);
  206. if (DTU) {
  207. Updates.push_back({DominatorTree::Insert, IBr->getParent(), SwitchBB});
  208. for (BasicBlock *SuccBB : IBr->successors())
  209. Updates.push_back({DominatorTree::Delete, IBr->getParent(), SuccBB});
  210. }
  211. IBr->eraseFromParent();
  212. }
  213. }
  214. // Now build the switch in the block. The block will have no terminator
  215. // already.
  216. auto *SI = SwitchInst::Create(SwitchValue, BBs[0], BBs.size(), SwitchBB);
  217. // Add a case for each block.
  218. for (int i : llvm::seq<int>(1, BBs.size()))
  219. SI->addCase(ConstantInt::get(CommonITy, i + 1), BBs[i]);
  220. if (DTU) {
  221. // If there were multiple indirectbr's, they may have common successors,
  222. // but in the dominator tree, we only track unique edges.
  223. SmallPtrSet<BasicBlock *, 8> UniqueSuccessors;
  224. Updates.reserve(Updates.size() + BBs.size());
  225. for (BasicBlock *BB : BBs) {
  226. if (UniqueSuccessors.insert(BB).second)
  227. Updates.push_back({DominatorTree::Insert, SwitchBB, BB});
  228. }
  229. DTU->applyUpdates(Updates);
  230. }
  231. return true;
  232. }