BranchRelaxation.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. //===- BranchRelaxation.cpp -----------------------------------------------===//
  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. #include "llvm/ADT/SmallVector.h"
  9. #include "llvm/ADT/Statistic.h"
  10. #include "llvm/CodeGen/LivePhysRegs.h"
  11. #include "llvm/CodeGen/MachineBasicBlock.h"
  12. #include "llvm/CodeGen/MachineFunction.h"
  13. #include "llvm/CodeGen/MachineFunctionPass.h"
  14. #include "llvm/CodeGen/MachineInstr.h"
  15. #include "llvm/CodeGen/RegisterScavenging.h"
  16. #include "llvm/CodeGen/TargetInstrInfo.h"
  17. #include "llvm/CodeGen/TargetRegisterInfo.h"
  18. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  19. #include "llvm/Config/llvm-config.h"
  20. #include "llvm/IR/DebugLoc.h"
  21. #include "llvm/InitializePasses.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/Support/Compiler.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/Format.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cassert>
  29. #include <cstdint>
  30. #include <iterator>
  31. #include <memory>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "branch-relaxation"
  34. STATISTIC(NumSplit, "Number of basic blocks split");
  35. STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
  36. STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
  37. #define BRANCH_RELAX_NAME "Branch relaxation pass"
  38. namespace {
  39. class BranchRelaxation : public MachineFunctionPass {
  40. /// BasicBlockInfo - Information about the offset and size of a single
  41. /// basic block.
  42. struct BasicBlockInfo {
  43. /// Offset - Distance from the beginning of the function to the beginning
  44. /// of this basic block.
  45. ///
  46. /// The offset is always aligned as required by the basic block.
  47. unsigned Offset = 0;
  48. /// Size - Size of the basic block in bytes. If the block contains
  49. /// inline assembly, this is a worst case estimate.
  50. ///
  51. /// The size does not include any alignment padding whether from the
  52. /// beginning of the block, or from an aligned jump table at the end.
  53. unsigned Size = 0;
  54. BasicBlockInfo() = default;
  55. /// Compute the offset immediately following this block. \p MBB is the next
  56. /// block.
  57. unsigned postOffset(const MachineBasicBlock &MBB) const {
  58. const unsigned PO = Offset + Size;
  59. const Align Alignment = MBB.getAlignment();
  60. const Align ParentAlign = MBB.getParent()->getAlignment();
  61. if (Alignment <= ParentAlign)
  62. return alignTo(PO, Alignment);
  63. // The alignment of this MBB is larger than the function's alignment, so we
  64. // can't tell whether or not it will insert nops. Assume that it will.
  65. return alignTo(PO, Alignment) + Alignment.value() - ParentAlign.value();
  66. }
  67. };
  68. SmallVector<BasicBlockInfo, 16> BlockInfo;
  69. std::unique_ptr<RegScavenger> RS;
  70. LivePhysRegs LiveRegs;
  71. MachineFunction *MF;
  72. const TargetRegisterInfo *TRI;
  73. const TargetInstrInfo *TII;
  74. bool relaxBranchInstructions();
  75. void scanFunction();
  76. MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB);
  77. MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB,
  78. const BasicBlock *BB);
  79. MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
  80. MachineBasicBlock *DestBB);
  81. void adjustBlockOffsets(MachineBasicBlock &Start);
  82. bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
  83. bool fixupConditionalBranch(MachineInstr &MI);
  84. bool fixupUnconditionalBranch(MachineInstr &MI);
  85. uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
  86. unsigned getInstrOffset(const MachineInstr &MI) const;
  87. void dumpBBs();
  88. void verify();
  89. public:
  90. static char ID;
  91. BranchRelaxation() : MachineFunctionPass(ID) {}
  92. bool runOnMachineFunction(MachineFunction &MF) override;
  93. StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
  94. };
  95. } // end anonymous namespace
  96. char BranchRelaxation::ID = 0;
  97. char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
  98. INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
  99. /// verify - check BBOffsets, BBSizes, alignment of islands
  100. void BranchRelaxation::verify() {
  101. #ifndef NDEBUG
  102. unsigned PrevNum = MF->begin()->getNumber();
  103. for (MachineBasicBlock &MBB : *MF) {
  104. const unsigned Num = MBB.getNumber();
  105. assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
  106. assert(BlockInfo[Num].Size == computeBlockSize(MBB));
  107. PrevNum = Num;
  108. }
  109. #endif
  110. }
  111. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  112. /// print block size and offset information - debugging
  113. LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
  114. for (auto &MBB : *MF) {
  115. const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
  116. dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
  117. << format("size=%#x\n", BBI.Size);
  118. }
  119. }
  120. #endif
  121. /// scanFunction - Do the initial scan of the function, building up
  122. /// information about each block.
  123. void BranchRelaxation::scanFunction() {
  124. BlockInfo.clear();
  125. BlockInfo.resize(MF->getNumBlockIDs());
  126. // First thing, compute the size of all basic blocks, and see if the function
  127. // has any inline assembly in it. If so, we have to be conservative about
  128. // alignment assumptions, as we don't know for sure the size of any
  129. // instructions in the inline assembly.
  130. for (MachineBasicBlock &MBB : *MF)
  131. BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
  132. // Compute block offsets and known bits.
  133. adjustBlockOffsets(*MF->begin());
  134. }
  135. /// computeBlockSize - Compute the size for MBB.
  136. uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
  137. uint64_t Size = 0;
  138. for (const MachineInstr &MI : MBB)
  139. Size += TII->getInstSizeInBytes(MI);
  140. return Size;
  141. }
  142. /// getInstrOffset - Return the current offset of the specified machine
  143. /// instruction from the start of the function. This offset changes as stuff is
  144. /// moved around inside the function.
  145. unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
  146. const MachineBasicBlock *MBB = MI.getParent();
  147. // The offset is composed of two things: the sum of the sizes of all MBB's
  148. // before this instruction's block, and the offset from the start of the block
  149. // it is in.
  150. unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
  151. // Sum instructions before MI in MBB.
  152. for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
  153. assert(I != MBB->end() && "Didn't find MI in its own basic block?");
  154. Offset += TII->getInstSizeInBytes(*I);
  155. }
  156. return Offset;
  157. }
  158. void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
  159. unsigned PrevNum = Start.getNumber();
  160. for (auto &MBB :
  161. make_range(std::next(MachineFunction::iterator(Start)), MF->end())) {
  162. unsigned Num = MBB.getNumber();
  163. // Get the offset and known bits at the end of the layout predecessor.
  164. // Include the alignment of the current block.
  165. BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
  166. PrevNum = Num;
  167. }
  168. }
  169. /// Insert a new empty MachineBasicBlock and insert it after \p OrigMBB
  170. MachineBasicBlock *
  171. BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {
  172. return createNewBlockAfter(OrigBB, OrigBB.getBasicBlock());
  173. }
  174. /// Insert a new empty MachineBasicBlock with \p BB as its BasicBlock
  175. /// and insert it after \p OrigMBB
  176. MachineBasicBlock *
  177. BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,
  178. const BasicBlock *BB) {
  179. // Create a new MBB for the code after the OrigBB.
  180. MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);
  181. MF->insert(++OrigMBB.getIterator(), NewBB);
  182. // Insert an entry into BlockInfo to align it properly with the block numbers.
  183. BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
  184. return NewBB;
  185. }
  186. /// Split the basic block containing MI into two blocks, which are joined by
  187. /// an unconditional branch. Update data structures and renumber blocks to
  188. /// account for this change and returns the newly created block.
  189. MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
  190. MachineBasicBlock *DestBB) {
  191. MachineBasicBlock *OrigBB = MI.getParent();
  192. // Create a new MBB for the code after the OrigBB.
  193. MachineBasicBlock *NewBB =
  194. MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
  195. MF->insert(++OrigBB->getIterator(), NewBB);
  196. // Splice the instructions starting with MI over to NewBB.
  197. NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
  198. // Add an unconditional branch from OrigBB to NewBB.
  199. // Note the new unconditional branch is not being recorded.
  200. // There doesn't seem to be meaningful DebugInfo available; this doesn't
  201. // correspond to anything in the source.
  202. TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
  203. // Insert an entry into BlockInfo to align it properly with the block numbers.
  204. BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
  205. NewBB->transferSuccessors(OrigBB);
  206. OrigBB->addSuccessor(NewBB);
  207. OrigBB->addSuccessor(DestBB);
  208. // Cleanup potential unconditional branch to successor block.
  209. // Note that updateTerminator may change the size of the blocks.
  210. OrigBB->updateTerminator(NewBB);
  211. // Figure out how large the OrigBB is. As the first half of the original
  212. // block, it cannot contain a tablejump. The size includes
  213. // the new jump we added. (It should be possible to do this without
  214. // recounting everything, but it's very confusing, and this is rarely
  215. // executed.)
  216. BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
  217. // Figure out how large the NewMBB is. As the second half of the original
  218. // block, it may contain a tablejump.
  219. BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
  220. // All BBOffsets following these blocks must be modified.
  221. adjustBlockOffsets(*OrigBB);
  222. // Need to fix live-in lists if we track liveness.
  223. if (TRI->trackLivenessAfterRegAlloc(*MF))
  224. computeAndAddLiveIns(LiveRegs, *NewBB);
  225. ++NumSplit;
  226. return NewBB;
  227. }
  228. /// isBlockInRange - Returns true if the distance between specific MI and
  229. /// specific BB can fit in MI's displacement field.
  230. bool BranchRelaxation::isBlockInRange(
  231. const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
  232. int64_t BrOffset = getInstrOffset(MI);
  233. int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
  234. if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
  235. return true;
  236. LLVM_DEBUG(dbgs() << "Out of range branch to destination "
  237. << printMBBReference(DestBB) << " from "
  238. << printMBBReference(*MI.getParent()) << " to "
  239. << DestOffset << " offset " << DestOffset - BrOffset << '\t'
  240. << MI);
  241. return false;
  242. }
  243. /// fixupConditionalBranch - Fix up a conditional branch whose destination is
  244. /// too far away to fit in its displacement field. It is converted to an inverse
  245. /// conditional branch + an unconditional branch to the destination.
  246. bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
  247. DebugLoc DL = MI.getDebugLoc();
  248. MachineBasicBlock *MBB = MI.getParent();
  249. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  250. MachineBasicBlock *NewBB = nullptr;
  251. SmallVector<MachineOperand, 4> Cond;
  252. auto insertUncondBranch = [&](MachineBasicBlock *MBB,
  253. MachineBasicBlock *DestBB) {
  254. unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
  255. int NewBrSize = 0;
  256. TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
  257. BBSize += NewBrSize;
  258. };
  259. auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
  260. MachineBasicBlock *FBB,
  261. SmallVectorImpl<MachineOperand>& Cond) {
  262. unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
  263. int NewBrSize = 0;
  264. TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
  265. BBSize += NewBrSize;
  266. };
  267. auto removeBranch = [&](MachineBasicBlock *MBB) {
  268. unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
  269. int RemovedSize = 0;
  270. TII->removeBranch(*MBB, &RemovedSize);
  271. BBSize -= RemovedSize;
  272. };
  273. auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
  274. MachineBasicBlock *NewBB) {
  275. // Keep the block offsets up to date.
  276. adjustBlockOffsets(*MBB);
  277. // Need to fix live-in lists if we track liveness.
  278. if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
  279. computeAndAddLiveIns(LiveRegs, *NewBB);
  280. };
  281. bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
  282. assert(!Fail && "branches to be relaxed must be analyzable");
  283. (void)Fail;
  284. // Add an unconditional branch to the destination and invert the branch
  285. // condition to jump over it:
  286. // tbz L1
  287. // =>
  288. // tbnz L2
  289. // b L1
  290. // L2:
  291. bool ReversedCond = !TII->reverseBranchCondition(Cond);
  292. if (ReversedCond) {
  293. if (FBB && isBlockInRange(MI, *FBB)) {
  294. // Last MI in the BB is an unconditional branch. We can simply invert the
  295. // condition and swap destinations:
  296. // beq L1
  297. // b L2
  298. // =>
  299. // bne L2
  300. // b L1
  301. LLVM_DEBUG(dbgs() << " Invert condition and swap "
  302. "its destination with "
  303. << MBB->back());
  304. removeBranch(MBB);
  305. insertBranch(MBB, FBB, TBB, Cond);
  306. finalizeBlockChanges(MBB, nullptr);
  307. return true;
  308. }
  309. if (FBB) {
  310. // We need to split the basic block here to obtain two long-range
  311. // unconditional branches.
  312. NewBB = createNewBlockAfter(*MBB);
  313. insertUncondBranch(NewBB, FBB);
  314. // Update the succesor lists according to the transformation to follow.
  315. // Do it here since if there's no split, no update is needed.
  316. MBB->replaceSuccessor(FBB, NewBB);
  317. NewBB->addSuccessor(FBB);
  318. }
  319. // We now have an appropriate fall-through block in place (either naturally or
  320. // just created), so we can use the inverted the condition.
  321. MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
  322. LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
  323. << ", invert condition and change dest. to "
  324. << printMBBReference(NextBB) << '\n');
  325. removeBranch(MBB);
  326. // Insert a new conditional branch and a new unconditional branch.
  327. insertBranch(MBB, &NextBB, TBB, Cond);
  328. finalizeBlockChanges(MBB, NewBB);
  329. return true;
  330. }
  331. // Branch cond can't be inverted.
  332. // In this case we always add a block after the MBB.
  333. LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
  334. << " Insert a new BB after " << MBB->back());
  335. if (!FBB)
  336. FBB = &(*std::next(MachineFunction::iterator(MBB)));
  337. // This is the block with cond. branch and the distance to TBB is too long.
  338. // beq L1
  339. // L2:
  340. // We do the following transformation:
  341. // beq NewBB
  342. // b L2
  343. // NewBB:
  344. // b L1
  345. // L2:
  346. NewBB = createNewBlockAfter(*MBB);
  347. insertUncondBranch(NewBB, TBB);
  348. LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
  349. << printMBBReference(*NewBB)
  350. << " Keep the exiting condition.\n"
  351. << " Insert B to " << printMBBReference(*FBB) << ".\n"
  352. << " In the new BB: Insert B to "
  353. << printMBBReference(*TBB) << ".\n");
  354. // Update the successor lists according to the transformation to follow.
  355. MBB->replaceSuccessor(TBB, NewBB);
  356. NewBB->addSuccessor(TBB);
  357. // Replace branch in the current (MBB) block.
  358. removeBranch(MBB);
  359. insertBranch(MBB, NewBB, FBB, Cond);
  360. finalizeBlockChanges(MBB, NewBB);
  361. return true;
  362. }
  363. bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
  364. MachineBasicBlock *MBB = MI.getParent();
  365. SmallVector<MachineOperand, 4> Cond;
  366. unsigned OldBrSize = TII->getInstSizeInBytes(MI);
  367. MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
  368. int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
  369. int64_t SrcOffset = getInstrOffset(MI);
  370. assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
  371. BlockInfo[MBB->getNumber()].Size -= OldBrSize;
  372. MachineBasicBlock *BranchBB = MBB;
  373. // If this was an expanded conditional branch, there is already a single
  374. // unconditional branch in a block.
  375. if (!MBB->empty()) {
  376. BranchBB = createNewBlockAfter(*MBB);
  377. // Add live outs.
  378. for (const MachineBasicBlock *Succ : MBB->successors()) {
  379. for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
  380. BranchBB->addLiveIn(LiveIn);
  381. }
  382. BranchBB->sortUniqueLiveIns();
  383. BranchBB->addSuccessor(DestBB);
  384. MBB->replaceSuccessor(DestBB, BranchBB);
  385. }
  386. DebugLoc DL = MI.getDebugLoc();
  387. MI.eraseFromParent();
  388. // Create the optional restore block and, initially, place it at the end of
  389. // function. That block will be placed later if it's used; otherwise, it will
  390. // be erased.
  391. MachineBasicBlock *RestoreBB = createNewBlockAfter(MF->back(),
  392. DestBB->getBasicBlock());
  393. TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB, DL,
  394. DestOffset - SrcOffset, RS.get());
  395. BlockInfo[BranchBB->getNumber()].Size = computeBlockSize(*BranchBB);
  396. adjustBlockOffsets(*MBB);
  397. // If RestoreBB is required, try to place just before DestBB.
  398. if (!RestoreBB->empty()) {
  399. // TODO: For multiple far branches to the same destination, there are
  400. // chances that some restore blocks could be shared if they clobber the
  401. // same registers and share the same restore sequence. So far, those
  402. // restore blocks are just duplicated for each far branch.
  403. assert(!DestBB->isEntryBlock());
  404. MachineBasicBlock *PrevBB = &*std::prev(DestBB->getIterator());
  405. // Fall through only if PrevBB has no unconditional branch as one of its
  406. // terminators.
  407. if (auto *FT = PrevBB->getLogicalFallThrough()) {
  408. assert(FT == DestBB);
  409. TII->insertUnconditionalBranch(*PrevBB, FT, DebugLoc());
  410. BlockInfo[PrevBB->getNumber()].Size = computeBlockSize(*PrevBB);
  411. }
  412. // Now, RestoreBB could be placed directly before DestBB.
  413. MF->splice(DestBB->getIterator(), RestoreBB->getIterator());
  414. // Update successors and predecessors.
  415. RestoreBB->addSuccessor(DestBB);
  416. BranchBB->replaceSuccessor(DestBB, RestoreBB);
  417. if (TRI->trackLivenessAfterRegAlloc(*MF))
  418. computeAndAddLiveIns(LiveRegs, *RestoreBB);
  419. // Compute the restore block size.
  420. BlockInfo[RestoreBB->getNumber()].Size = computeBlockSize(*RestoreBB);
  421. // Update the offset starting from the previous block.
  422. adjustBlockOffsets(*PrevBB);
  423. } else {
  424. // Remove restore block if it's not required.
  425. MF->erase(RestoreBB);
  426. }
  427. return true;
  428. }
  429. bool BranchRelaxation::relaxBranchInstructions() {
  430. bool Changed = false;
  431. // Relaxing branches involves creating new basic blocks, so re-eval
  432. // end() for termination.
  433. for (MachineBasicBlock &MBB : *MF) {
  434. // Empty block?
  435. MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
  436. if (Last == MBB.end())
  437. continue;
  438. // Expand the unconditional branch first if necessary. If there is a
  439. // conditional branch, this will end up changing the branch destination of
  440. // it to be over the newly inserted indirect branch block, which may avoid
  441. // the need to try expanding the conditional branch first, saving an extra
  442. // jump.
  443. if (Last->isUnconditionalBranch()) {
  444. // Unconditional branch destination might be unanalyzable, assume these
  445. // are OK.
  446. if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
  447. if (!isBlockInRange(*Last, *DestBB)) {
  448. fixupUnconditionalBranch(*Last);
  449. ++NumUnconditionalRelaxed;
  450. Changed = true;
  451. }
  452. }
  453. }
  454. // Loop over the conditional branches.
  455. MachineBasicBlock::iterator Next;
  456. for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
  457. J != MBB.end(); J = Next) {
  458. Next = std::next(J);
  459. MachineInstr &MI = *J;
  460. if (!MI.isConditionalBranch())
  461. continue;
  462. if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
  463. // FAULTING_OP's destination is not encoded in the instruction stream
  464. // and thus never needs relaxed.
  465. continue;
  466. MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
  467. if (!isBlockInRange(MI, *DestBB)) {
  468. if (Next != MBB.end() && Next->isConditionalBranch()) {
  469. // If there are multiple conditional branches, this isn't an
  470. // analyzable block. Split later terminators into a new block so
  471. // each one will be analyzable.
  472. splitBlockBeforeInstr(*Next, DestBB);
  473. } else {
  474. fixupConditionalBranch(MI);
  475. ++NumConditionalRelaxed;
  476. }
  477. Changed = true;
  478. // This may have modified all of the terminators, so start over.
  479. Next = MBB.getFirstTerminator();
  480. }
  481. }
  482. }
  483. return Changed;
  484. }
  485. bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
  486. MF = &mf;
  487. LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
  488. const TargetSubtargetInfo &ST = MF->getSubtarget();
  489. TII = ST.getInstrInfo();
  490. TRI = ST.getRegisterInfo();
  491. if (TRI->trackLivenessAfterRegAlloc(*MF))
  492. RS.reset(new RegScavenger());
  493. // Renumber all of the machine basic blocks in the function, guaranteeing that
  494. // the numbers agree with the position of the block in the function.
  495. MF->RenumberBlocks();
  496. // Do the initial scan of the function, building up information about the
  497. // sizes of each block.
  498. scanFunction();
  499. LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
  500. bool MadeChange = false;
  501. while (relaxBranchInstructions())
  502. MadeChange = true;
  503. // After a while, this might be made debug-only, but it is not expensive.
  504. verify();
  505. LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
  506. BlockInfo.clear();
  507. return MadeChange;
  508. }