BranchRelaxation.cpp 21 KB

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