Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/BranchRelaxation.cpp
35233 views
//===- BranchRelaxation.cpp -----------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#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 "llvm/Target/TargetMachine.h"29#include <cassert>30#include <cstdint>31#include <iterator>32#include <memory>3334using namespace llvm;3536#define DEBUG_TYPE "branch-relaxation"3738STATISTIC(NumSplit, "Number of basic blocks split");39STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");40STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");4142#define BRANCH_RELAX_NAME "Branch relaxation pass"4344namespace {4546class BranchRelaxation : public MachineFunctionPass {47/// BasicBlockInfo - Information about the offset and size of a single48/// basic block.49struct BasicBlockInfo {50/// Offset - Distance from the beginning of the function to the beginning51/// of this basic block.52///53/// The offset is always aligned as required by the basic block.54unsigned Offset = 0;5556/// Size - Size of the basic block in bytes. If the block contains57/// inline assembly, this is a worst case estimate.58///59/// The size does not include any alignment padding whether from the60/// beginning of the block, or from an aligned jump table at the end.61unsigned Size = 0;6263BasicBlockInfo() = default;6465/// Compute the offset immediately following this block. \p MBB is the next66/// block.67unsigned postOffset(const MachineBasicBlock &MBB) const {68const unsigned PO = Offset + Size;69const Align Alignment = MBB.getAlignment();70const Align ParentAlign = MBB.getParent()->getAlignment();71if (Alignment <= ParentAlign)72return alignTo(PO, Alignment);7374// The alignment of this MBB is larger than the function's alignment, so we75// can't tell whether or not it will insert nops. Assume that it will.76return alignTo(PO, Alignment) + Alignment.value() - ParentAlign.value();77}78};7980SmallVector<BasicBlockInfo, 16> BlockInfo;8182// The basic block after which trampolines are inserted. This is the last83// basic block that isn't in the cold section.84MachineBasicBlock *TrampolineInsertionPoint = nullptr;85SmallDenseSet<std::pair<MachineBasicBlock *, MachineBasicBlock *>>86RelaxedUnconditionals;87std::unique_ptr<RegScavenger> RS;88LivePhysRegs LiveRegs;8990MachineFunction *MF = nullptr;91const TargetRegisterInfo *TRI = nullptr;92const TargetInstrInfo *TII = nullptr;93const TargetMachine *TM = nullptr;9495bool relaxBranchInstructions();96void scanFunction();9798MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB);99MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &OrigMBB,100const BasicBlock *BB);101102MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,103MachineBasicBlock *DestBB);104void adjustBlockOffsets(MachineBasicBlock &Start);105bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;106107bool fixupConditionalBranch(MachineInstr &MI);108bool fixupUnconditionalBranch(MachineInstr &MI);109uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;110unsigned getInstrOffset(const MachineInstr &MI) const;111void dumpBBs();112void verify();113114public:115static char ID;116117BranchRelaxation() : MachineFunctionPass(ID) {}118119bool runOnMachineFunction(MachineFunction &MF) override;120121StringRef getPassName() const override { return BRANCH_RELAX_NAME; }122};123124} // end anonymous namespace125126char BranchRelaxation::ID = 0;127128char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;129130INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)131132/// verify - check BBOffsets, BBSizes, alignment of islands133void BranchRelaxation::verify() {134#ifndef NDEBUG135unsigned PrevNum = MF->begin()->getNumber();136for (MachineBasicBlock &MBB : *MF) {137const unsigned Num = MBB.getNumber();138assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);139assert(BlockInfo[Num].Size == computeBlockSize(MBB));140PrevNum = Num;141}142143for (MachineBasicBlock &MBB : *MF) {144for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();145J != MBB.end(); J = std::next(J)) {146MachineInstr &MI = *J;147if (!MI.isConditionalBranch() && !MI.isUnconditionalBranch())148continue;149if (MI.getOpcode() == TargetOpcode::FAULTING_OP)150continue;151MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);152assert(isBlockInRange(MI, *DestBB) ||153RelaxedUnconditionals.contains({&MBB, DestBB}));154}155}156#endif157}158159#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)160/// print block size and offset information - debugging161LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {162for (auto &MBB : *MF) {163const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];164dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)165<< format("size=%#x\n", BBI.Size);166}167}168#endif169170/// scanFunction - Do the initial scan of the function, building up171/// information about each block.172void BranchRelaxation::scanFunction() {173BlockInfo.clear();174BlockInfo.resize(MF->getNumBlockIDs());175176TrampolineInsertionPoint = nullptr;177RelaxedUnconditionals.clear();178179// First thing, compute the size of all basic blocks, and see if the function180// has any inline assembly in it. If so, we have to be conservative about181// alignment assumptions, as we don't know for sure the size of any182// instructions in the inline assembly. At the same time, place the183// trampoline insertion point at the end of the hot portion of the function.184for (MachineBasicBlock &MBB : *MF) {185BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);186187if (MBB.getSectionID() != MBBSectionID::ColdSectionID)188TrampolineInsertionPoint = &MBB;189}190191// Compute block offsets and known bits.192adjustBlockOffsets(*MF->begin());193194if (TrampolineInsertionPoint == nullptr) {195LLVM_DEBUG(dbgs() << " No suitable trampoline insertion point found in "196<< MF->getName() << ".\n");197}198}199200/// computeBlockSize - Compute the size for MBB.201uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {202uint64_t Size = 0;203for (const MachineInstr &MI : MBB)204Size += TII->getInstSizeInBytes(MI);205return Size;206}207208/// getInstrOffset - Return the current offset of the specified machine209/// instruction from the start of the function. This offset changes as stuff is210/// moved around inside the function.211unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {212const MachineBasicBlock *MBB = MI.getParent();213214// The offset is composed of two things: the sum of the sizes of all MBB's215// before this instruction's block, and the offset from the start of the block216// it is in.217unsigned Offset = BlockInfo[MBB->getNumber()].Offset;218219// Sum instructions before MI in MBB.220for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {221assert(I != MBB->end() && "Didn't find MI in its own basic block?");222Offset += TII->getInstSizeInBytes(*I);223}224225return Offset;226}227228void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {229unsigned PrevNum = Start.getNumber();230for (auto &MBB :231make_range(std::next(MachineFunction::iterator(Start)), MF->end())) {232unsigned Num = MBB.getNumber();233// Get the offset and known bits at the end of the layout predecessor.234// Include the alignment of the current block.235BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);236237PrevNum = Num;238}239}240241/// Insert a new empty MachineBasicBlock and insert it after \p OrigMBB242MachineBasicBlock *243BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigBB) {244return createNewBlockAfter(OrigBB, OrigBB.getBasicBlock());245}246247/// Insert a new empty MachineBasicBlock with \p BB as its BasicBlock248/// and insert it after \p OrigMBB249MachineBasicBlock *250BranchRelaxation::createNewBlockAfter(MachineBasicBlock &OrigMBB,251const BasicBlock *BB) {252// Create a new MBB for the code after the OrigBB.253MachineBasicBlock *NewBB = MF->CreateMachineBasicBlock(BB);254MF->insert(++OrigMBB.getIterator(), NewBB);255256// Place the new block in the same section as OrigBB257NewBB->setSectionID(OrigMBB.getSectionID());258NewBB->setIsEndSection(OrigMBB.isEndSection());259OrigMBB.setIsEndSection(false);260261// Insert an entry into BlockInfo to align it properly with the block numbers.262BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());263264return NewBB;265}266267/// Split the basic block containing MI into two blocks, which are joined by268/// an unconditional branch. Update data structures and renumber blocks to269/// account for this change and returns the newly created block.270MachineBasicBlock *271BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,272MachineBasicBlock *DestBB) {273MachineBasicBlock *OrigBB = MI.getParent();274275// Create a new MBB for the code after the OrigBB.276MachineBasicBlock *NewBB =277MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());278MF->insert(++OrigBB->getIterator(), NewBB);279280// Place the new block in the same section as OrigBB.281NewBB->setSectionID(OrigBB->getSectionID());282NewBB->setIsEndSection(OrigBB->isEndSection());283OrigBB->setIsEndSection(false);284285// Splice the instructions starting with MI over to NewBB.286NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());287288// Add an unconditional branch from OrigBB to NewBB.289// Note the new unconditional branch is not being recorded.290// There doesn't seem to be meaningful DebugInfo available; this doesn't291// correspond to anything in the source.292TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());293294// Insert an entry into BlockInfo to align it properly with the block numbers.295BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());296297NewBB->transferSuccessors(OrigBB);298OrigBB->addSuccessor(NewBB);299OrigBB->addSuccessor(DestBB);300301// Cleanup potential unconditional branch to successor block.302// Note that updateTerminator may change the size of the blocks.303OrigBB->updateTerminator(NewBB);304305// Figure out how large the OrigBB is. As the first half of the original306// block, it cannot contain a tablejump. The size includes307// the new jump we added. (It should be possible to do this without308// recounting everything, but it's very confusing, and this is rarely309// executed.)310BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);311312// Figure out how large the NewMBB is. As the second half of the original313// block, it may contain a tablejump.314BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);315316// All BBOffsets following these blocks must be modified.317adjustBlockOffsets(*OrigBB);318319// Need to fix live-in lists if we track liveness.320if (TRI->trackLivenessAfterRegAlloc(*MF))321computeAndAddLiveIns(LiveRegs, *NewBB);322323++NumSplit;324325return NewBB;326}327328/// isBlockInRange - Returns true if the distance between specific MI and329/// specific BB can fit in MI's displacement field.330bool BranchRelaxation::isBlockInRange(331const MachineInstr &MI, const MachineBasicBlock &DestBB) const {332int64_t BrOffset = getInstrOffset(MI);333int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;334335const MachineBasicBlock *SrcBB = MI.getParent();336337if (TII->isBranchOffsetInRange(MI.getOpcode(),338SrcBB->getSectionID() != DestBB.getSectionID()339? TM->getMaxCodeSize()340: DestOffset - BrOffset))341return true;342343LLVM_DEBUG(dbgs() << "Out of range branch to destination "344<< printMBBReference(DestBB) << " from "345<< printMBBReference(*MI.getParent()) << " to "346<< DestOffset << " offset " << DestOffset - BrOffset << '\t'347<< MI);348349return false;350}351352/// fixupConditionalBranch - Fix up a conditional branch whose destination is353/// too far away to fit in its displacement field. It is converted to an inverse354/// conditional branch + an unconditional branch to the destination.355bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {356DebugLoc DL = MI.getDebugLoc();357MachineBasicBlock *MBB = MI.getParent();358MachineBasicBlock *TBB = nullptr, *FBB = nullptr;359MachineBasicBlock *NewBB = nullptr;360SmallVector<MachineOperand, 4> Cond;361362auto insertUncondBranch = [&](MachineBasicBlock *MBB,363MachineBasicBlock *DestBB) {364unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;365int NewBrSize = 0;366TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);367BBSize += NewBrSize;368};369auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,370MachineBasicBlock *FBB,371SmallVectorImpl<MachineOperand>& Cond) {372unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;373int NewBrSize = 0;374TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);375BBSize += NewBrSize;376};377auto removeBranch = [&](MachineBasicBlock *MBB) {378unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;379int RemovedSize = 0;380TII->removeBranch(*MBB, &RemovedSize);381BBSize -= RemovedSize;382};383384auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,385MachineBasicBlock *NewBB) {386// Keep the block offsets up to date.387adjustBlockOffsets(*MBB);388389// Need to fix live-in lists if we track liveness.390if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))391computeAndAddLiveIns(LiveRegs, *NewBB);392};393394bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);395assert(!Fail && "branches to be relaxed must be analyzable");396(void)Fail;397398// Since cross-section conditional branches to the cold section are rarely399// taken, try to avoid inverting the condition. Instead, add a "trampoline400// branch", which unconditionally branches to the branch destination. Place401// the trampoline branch at the end of the function and retarget the402// conditional branch to the trampoline.403// tbz L1404// =>405// tbz L1Trampoline406// ...407// L1Trampoline: b L1408if (MBB->getSectionID() != TBB->getSectionID() &&409TBB->getSectionID() == MBBSectionID::ColdSectionID &&410TrampolineInsertionPoint != nullptr) {411// If the insertion point is out of range, we can't put a trampoline there.412NewBB =413createNewBlockAfter(*TrampolineInsertionPoint, MBB->getBasicBlock());414415if (isBlockInRange(MI, *NewBB)) {416LLVM_DEBUG(dbgs() << " Retarget destination to trampoline at "417<< NewBB->back());418419insertUncondBranch(NewBB, TBB);420421// Update the successor lists to include the trampoline.422MBB->replaceSuccessor(TBB, NewBB);423NewBB->addSuccessor(TBB);424425// Replace branch in the current (MBB) block.426removeBranch(MBB);427insertBranch(MBB, NewBB, FBB, Cond);428429TrampolineInsertionPoint = NewBB;430finalizeBlockChanges(MBB, NewBB);431return true;432}433434LLVM_DEBUG(435dbgs() << " Trampoline insertion point out of range for Bcc from "436<< printMBBReference(*MBB) << " to " << printMBBReference(*TBB)437<< ".\n");438TrampolineInsertionPoint->setIsEndSection(NewBB->isEndSection());439MF->erase(NewBB);440}441442// Add an unconditional branch to the destination and invert the branch443// condition to jump over it:444// tbz L1445// =>446// tbnz L2447// b L1448// L2:449450bool ReversedCond = !TII->reverseBranchCondition(Cond);451if (ReversedCond) {452if (FBB && isBlockInRange(MI, *FBB)) {453// Last MI in the BB is an unconditional branch. We can simply invert the454// condition and swap destinations:455// beq L1456// b L2457// =>458// bne L2459// b L1460LLVM_DEBUG(dbgs() << " Invert condition and swap "461"its destination with "462<< MBB->back());463464removeBranch(MBB);465insertBranch(MBB, FBB, TBB, Cond);466finalizeBlockChanges(MBB, nullptr);467return true;468}469if (FBB) {470// We need to split the basic block here to obtain two long-range471// unconditional branches.472NewBB = createNewBlockAfter(*MBB);473474insertUncondBranch(NewBB, FBB);475// Update the succesor lists according to the transformation to follow.476// Do it here since if there's no split, no update is needed.477MBB->replaceSuccessor(FBB, NewBB);478NewBB->addSuccessor(FBB);479}480481// We now have an appropriate fall-through block in place (either naturally or482// just created), so we can use the inverted the condition.483MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));484485LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)486<< ", invert condition and change dest. to "487<< printMBBReference(NextBB) << '\n');488489removeBranch(MBB);490// Insert a new conditional branch and a new unconditional branch.491insertBranch(MBB, &NextBB, TBB, Cond);492493finalizeBlockChanges(MBB, NewBB);494return true;495}496// Branch cond can't be inverted.497// In this case we always add a block after the MBB.498LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "499<< " Insert a new BB after " << MBB->back());500501if (!FBB)502FBB = &(*std::next(MachineFunction::iterator(MBB)));503504// This is the block with cond. branch and the distance to TBB is too long.505// beq L1506// L2:507508// We do the following transformation:509// beq NewBB510// b L2511// NewBB:512// b L1513// L2:514515NewBB = createNewBlockAfter(*MBB);516insertUncondBranch(NewBB, TBB);517518LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "519<< printMBBReference(*NewBB)520<< " Keep the exiting condition.\n"521<< " Insert B to " << printMBBReference(*FBB) << ".\n"522<< " In the new BB: Insert B to "523<< printMBBReference(*TBB) << ".\n");524525// Update the successor lists according to the transformation to follow.526MBB->replaceSuccessor(TBB, NewBB);527NewBB->addSuccessor(TBB);528529// Replace branch in the current (MBB) block.530removeBranch(MBB);531insertBranch(MBB, NewBB, FBB, Cond);532533finalizeBlockChanges(MBB, NewBB);534return true;535}536537bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {538MachineBasicBlock *MBB = MI.getParent();539SmallVector<MachineOperand, 4> Cond;540unsigned OldBrSize = TII->getInstSizeInBytes(MI);541MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);542543int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;544int64_t SrcOffset = getInstrOffset(MI);545546assert(!TII->isBranchOffsetInRange(547MI.getOpcode(), MBB->getSectionID() != DestBB->getSectionID()548? TM->getMaxCodeSize()549: DestOffset - SrcOffset));550551BlockInfo[MBB->getNumber()].Size -= OldBrSize;552553MachineBasicBlock *BranchBB = MBB;554555// If this was an expanded conditional branch, there is already a single556// unconditional branch in a block.557if (!MBB->empty()) {558BranchBB = createNewBlockAfter(*MBB);559560// Add live outs.561for (const MachineBasicBlock *Succ : MBB->successors()) {562for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())563BranchBB->addLiveIn(LiveIn);564}565566BranchBB->sortUniqueLiveIns();567BranchBB->addSuccessor(DestBB);568MBB->replaceSuccessor(DestBB, BranchBB);569if (TrampolineInsertionPoint == MBB)570TrampolineInsertionPoint = BranchBB;571}572573DebugLoc DL = MI.getDebugLoc();574MI.eraseFromParent();575576// Create the optional restore block and, initially, place it at the end of577// function. That block will be placed later if it's used; otherwise, it will578// be erased.579MachineBasicBlock *RestoreBB = createNewBlockAfter(MF->back(),580DestBB->getBasicBlock());581std::prev(RestoreBB->getIterator())582->setIsEndSection(RestoreBB->isEndSection());583RestoreBB->setIsEndSection(false);584585TII->insertIndirectBranch(*BranchBB, *DestBB, *RestoreBB, DL,586BranchBB->getSectionID() != DestBB->getSectionID()587? TM->getMaxCodeSize()588: DestOffset - SrcOffset,589RS.get());590591BlockInfo[BranchBB->getNumber()].Size = computeBlockSize(*BranchBB);592adjustBlockOffsets(*MBB);593594// If RestoreBB is required, place it appropriately.595if (!RestoreBB->empty()) {596// If the jump is Cold -> Hot, don't place the restore block (which is597// cold) in the middle of the function. Place it at the end.598if (MBB->getSectionID() == MBBSectionID::ColdSectionID &&599DestBB->getSectionID() != MBBSectionID::ColdSectionID) {600MachineBasicBlock *NewBB = createNewBlockAfter(*TrampolineInsertionPoint);601TII->insertUnconditionalBranch(*NewBB, DestBB, DebugLoc());602BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);603604// New trampolines should be inserted after NewBB.605TrampolineInsertionPoint = NewBB;606607// Retarget the unconditional branch to the trampoline block.608BranchBB->replaceSuccessor(DestBB, NewBB);609NewBB->addSuccessor(DestBB);610611DestBB = NewBB;612}613614// In all other cases, try to place just before DestBB.615616// TODO: For multiple far branches to the same destination, there are617// chances that some restore blocks could be shared if they clobber the618// same registers and share the same restore sequence. So far, those619// restore blocks are just duplicated for each far branch.620assert(!DestBB->isEntryBlock());621MachineBasicBlock *PrevBB = &*std::prev(DestBB->getIterator());622// Fall through only if PrevBB has no unconditional branch as one of its623// terminators.624if (auto *FT = PrevBB->getLogicalFallThrough()) {625assert(FT == DestBB);626TII->insertUnconditionalBranch(*PrevBB, FT, DebugLoc());627BlockInfo[PrevBB->getNumber()].Size = computeBlockSize(*PrevBB);628}629// Now, RestoreBB could be placed directly before DestBB.630MF->splice(DestBB->getIterator(), RestoreBB->getIterator());631// Update successors and predecessors.632RestoreBB->addSuccessor(DestBB);633BranchBB->replaceSuccessor(DestBB, RestoreBB);634if (TRI->trackLivenessAfterRegAlloc(*MF))635computeAndAddLiveIns(LiveRegs, *RestoreBB);636// Compute the restore block size.637BlockInfo[RestoreBB->getNumber()].Size = computeBlockSize(*RestoreBB);638// Update the offset starting from the previous block.639adjustBlockOffsets(*PrevBB);640641// Fix up section information for RestoreBB and DestBB642RestoreBB->setSectionID(DestBB->getSectionID());643RestoreBB->setIsBeginSection(DestBB->isBeginSection());644DestBB->setIsBeginSection(false);645RelaxedUnconditionals.insert({BranchBB, RestoreBB});646} else {647// Remove restore block if it's not required.648MF->erase(RestoreBB);649RelaxedUnconditionals.insert({BranchBB, DestBB});650}651652return true;653}654655bool BranchRelaxation::relaxBranchInstructions() {656bool Changed = false;657658// Relaxing branches involves creating new basic blocks, so re-eval659// end() for termination.660for (MachineBasicBlock &MBB : *MF) {661// Empty block?662MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();663if (Last == MBB.end())664continue;665666// Expand the unconditional branch first if necessary. If there is a667// conditional branch, this will end up changing the branch destination of668// it to be over the newly inserted indirect branch block, which may avoid669// the need to try expanding the conditional branch first, saving an extra670// jump.671if (Last->isUnconditionalBranch()) {672// Unconditional branch destination might be unanalyzable, assume these673// are OK.674if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {675if (!isBlockInRange(*Last, *DestBB) && !TII->isTailCall(*Last) &&676!RelaxedUnconditionals.contains({&MBB, DestBB})) {677fixupUnconditionalBranch(*Last);678++NumUnconditionalRelaxed;679Changed = true;680}681}682}683684// Loop over the conditional branches.685MachineBasicBlock::iterator Next;686for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();687J != MBB.end(); J = Next) {688Next = std::next(J);689MachineInstr &MI = *J;690691if (!MI.isConditionalBranch())692continue;693694if (MI.getOpcode() == TargetOpcode::FAULTING_OP)695// FAULTING_OP's destination is not encoded in the instruction stream696// and thus never needs relaxed.697continue;698699MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);700if (!isBlockInRange(MI, *DestBB)) {701if (Next != MBB.end() && Next->isConditionalBranch()) {702// If there are multiple conditional branches, this isn't an703// analyzable block. Split later terminators into a new block so704// each one will be analyzable.705706splitBlockBeforeInstr(*Next, DestBB);707} else {708fixupConditionalBranch(MI);709++NumConditionalRelaxed;710}711712Changed = true;713714// This may have modified all of the terminators, so start over.715Next = MBB.getFirstTerminator();716}717}718}719720return Changed;721}722723bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {724MF = &mf;725726LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");727728const TargetSubtargetInfo &ST = MF->getSubtarget();729TII = ST.getInstrInfo();730TM = &MF->getTarget();731732TRI = ST.getRegisterInfo();733if (TRI->trackLivenessAfterRegAlloc(*MF))734RS.reset(new RegScavenger());735736// Renumber all of the machine basic blocks in the function, guaranteeing that737// the numbers agree with the position of the block in the function.738MF->RenumberBlocks();739740// Do the initial scan of the function, building up information about the741// sizes of each block.742scanFunction();743744LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););745746bool MadeChange = false;747while (relaxBranchInstructions())748MadeChange = true;749750// After a while, this might be made debug-only, but it is not expensive.751verify();752753LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());754755BlockInfo.clear();756RelaxedUnconditionals.clear();757758return MadeChange;759}760761762