Path: blob/main/contrib/llvm-project/llvm/lib/Target/ARM/ARMConstantIslandPass.cpp
35294 views
//===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//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//===----------------------------------------------------------------------===//7//8// This file contains a pass that splits the constant pool up into 'islands'9// which are scattered through-out the function. This is required due to the10// limited pc-relative displacements that ARM has.11//12//===----------------------------------------------------------------------===//1314#include "ARM.h"15#include "ARMBaseInstrInfo.h"16#include "ARMBasicBlockInfo.h"17#include "ARMMachineFunctionInfo.h"18#include "ARMSubtarget.h"19#include "MCTargetDesc/ARMBaseInfo.h"20#include "MVETailPredUtils.h"21#include "Thumb2InstrInfo.h"22#include "Utils/ARMBaseInfo.h"23#include "llvm/ADT/DenseMap.h"24#include "llvm/ADT/STLExtras.h"25#include "llvm/ADT/SmallSet.h"26#include "llvm/ADT/SmallVector.h"27#include "llvm/ADT/Statistic.h"28#include "llvm/ADT/StringRef.h"29#include "llvm/CodeGen/LivePhysRegs.h"30#include "llvm/CodeGen/MachineBasicBlock.h"31#include "llvm/CodeGen/MachineConstantPool.h"32#include "llvm/CodeGen/MachineDominators.h"33#include "llvm/CodeGen/MachineFunction.h"34#include "llvm/CodeGen/MachineFunctionPass.h"35#include "llvm/CodeGen/MachineInstr.h"36#include "llvm/CodeGen/MachineJumpTableInfo.h"37#include "llvm/CodeGen/MachineOperand.h"38#include "llvm/CodeGen/MachineRegisterInfo.h"39#include "llvm/Config/llvm-config.h"40#include "llvm/IR/DataLayout.h"41#include "llvm/IR/DebugLoc.h"42#include "llvm/MC/MCInstrDesc.h"43#include "llvm/Pass.h"44#include "llvm/Support/CommandLine.h"45#include "llvm/Support/Compiler.h"46#include "llvm/Support/Debug.h"47#include "llvm/Support/ErrorHandling.h"48#include "llvm/Support/Format.h"49#include "llvm/Support/MathExtras.h"50#include "llvm/Support/raw_ostream.h"51#include <algorithm>52#include <cassert>53#include <cstdint>54#include <iterator>55#include <utility>56#include <vector>5758using namespace llvm;5960#define DEBUG_TYPE "arm-cp-islands"6162#define ARM_CP_ISLANDS_OPT_NAME \63"ARM constant island placement and branch shortening pass"64STATISTIC(NumCPEs, "Number of constpool entries");65STATISTIC(NumSplit, "Number of uncond branches inserted");66STATISTIC(NumCBrFixed, "Number of cond branches fixed");67STATISTIC(NumUBrFixed, "Number of uncond branches fixed");68STATISTIC(NumTBs, "Number of table branches generated");69STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");70STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");71STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");72STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");73STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");74STATISTIC(NumLEInserted, "Number of LE backwards branches inserted");7576static cl::opt<bool>77AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),78cl::desc("Adjust basic block layout to better use TB[BH]"));7980static cl::opt<unsigned>81CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30),82cl::desc("The max number of iteration for converge"));8384static cl::opt<bool> SynthesizeThumb1TBB(85"arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true),86cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "87"equivalent to the TBB/TBH instructions"));8889namespace {9091/// ARMConstantIslands - Due to limited PC-relative displacements, ARM92/// requires constant pool entries to be scattered among the instructions93/// inside a function. To do this, it completely ignores the normal LLVM94/// constant pool; instead, it places constants wherever it feels like with95/// special instructions.96///97/// The terminology used in this pass includes:98/// Islands - Clumps of constants placed in the function.99/// Water - Potential places where an island could be formed.100/// CPE - A constant pool entry that has been placed somewhere, which101/// tracks a list of users.102class ARMConstantIslands : public MachineFunctionPass {103std::unique_ptr<ARMBasicBlockUtils> BBUtils = nullptr;104105/// WaterList - A sorted list of basic blocks where islands could be placed106/// (i.e. blocks that don't fall through to the following block, due107/// to a return, unreachable, or unconditional branch).108std::vector<MachineBasicBlock*> WaterList;109110/// NewWaterList - The subset of WaterList that was created since the111/// previous iteration by inserting unconditional branches.112SmallSet<MachineBasicBlock*, 4> NewWaterList;113114using water_iterator = std::vector<MachineBasicBlock *>::iterator;115116/// CPUser - One user of a constant pool, keeping the machine instruction117/// pointer, the constant pool being referenced, and the max displacement118/// allowed from the instruction to the CP. The HighWaterMark records the119/// highest basic block where a new CPEntry can be placed. To ensure this120/// pass terminates, the CP entries are initially placed at the end of the121/// function and then move monotonically to lower addresses. The122/// exception to this rule is when the current CP entry for a particular123/// CPUser is out of range, but there is another CP entry for the same124/// constant value in range. We want to use the existing in-range CP125/// entry, but if it later moves out of range, the search for new water126/// should resume where it left off. The HighWaterMark is used to record127/// that point.128struct CPUser {129MachineInstr *MI;130MachineInstr *CPEMI;131MachineBasicBlock *HighWaterMark;132unsigned MaxDisp;133bool NegOk;134bool IsSoImm;135bool KnownAlignment = false;136137CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,138bool neg, bool soimm)139: MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm) {140HighWaterMark = CPEMI->getParent();141}142143/// getMaxDisp - Returns the maximum displacement supported by MI.144/// Correct for unknown alignment.145/// Conservatively subtract 2 bytes to handle weird alignment effects.146unsigned getMaxDisp() const {147return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;148}149};150151/// CPUsers - Keep track of all of the machine instructions that use various152/// constant pools and their max displacement.153std::vector<CPUser> CPUsers;154155/// CPEntry - One per constant pool entry, keeping the machine instruction156/// pointer, the constpool index, and the number of CPUser's which157/// reference this entry.158struct CPEntry {159MachineInstr *CPEMI;160unsigned CPI;161unsigned RefCount;162163CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)164: CPEMI(cpemi), CPI(cpi), RefCount(rc) {}165};166167/// CPEntries - Keep track of all of the constant pool entry machine168/// instructions. For each original constpool index (i.e. those that existed169/// upon entry to this pass), it keeps a vector of entries. Original170/// elements are cloned as we go along; the clones are put in the vector of171/// the original element, but have distinct CPIs.172///173/// The first half of CPEntries contains generic constants, the second half174/// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up175/// which vector it will be in here.176std::vector<std::vector<CPEntry>> CPEntries;177178/// Maps a JT index to the offset in CPEntries containing copies of that179/// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.180DenseMap<int, int> JumpTableEntryIndices;181182/// Maps a JT index to the LEA that actually uses the index to calculate its183/// base address.184DenseMap<int, int> JumpTableUserIndices;185186// Maps a MachineBasicBlock to the number of jump tables entries.187DenseMap<const MachineBasicBlock *, int> BlockJumpTableRefCount;188189/// ImmBranch - One per immediate branch, keeping the machine instruction190/// pointer, conditional or unconditional, the max displacement,191/// and (if isCond is true) the corresponding unconditional branch192/// opcode.193struct ImmBranch {194MachineInstr *MI;195unsigned MaxDisp : 31;196bool isCond : 1;197unsigned UncondBr;198199ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)200: MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}201};202203/// ImmBranches - Keep track of all the immediate branch instructions.204std::vector<ImmBranch> ImmBranches;205206/// PushPopMIs - Keep track of all the Thumb push / pop instructions.207SmallVector<MachineInstr*, 4> PushPopMIs;208209/// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.210SmallVector<MachineInstr*, 4> T2JumpTables;211212MachineFunction *MF;213MachineConstantPool *MCP;214const ARMBaseInstrInfo *TII;215const ARMSubtarget *STI;216ARMFunctionInfo *AFI;217MachineDominatorTree *DT = nullptr;218bool isThumb;219bool isThumb1;220bool isThumb2;221bool isPositionIndependentOrROPI;222223public:224static char ID;225226ARMConstantIslands() : MachineFunctionPass(ID) {}227228bool runOnMachineFunction(MachineFunction &MF) override;229230void getAnalysisUsage(AnalysisUsage &AU) const override {231AU.addRequired<MachineDominatorTreeWrapperPass>();232MachineFunctionPass::getAnalysisUsage(AU);233}234235MachineFunctionProperties getRequiredProperties() const override {236return MachineFunctionProperties().set(237MachineFunctionProperties::Property::NoVRegs);238}239240StringRef getPassName() const override {241return ARM_CP_ISLANDS_OPT_NAME;242}243244private:245void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);246void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);247bool BBHasFallthrough(MachineBasicBlock *MBB);248CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);249Align getCPEAlign(const MachineInstr *CPEMI);250void scanFunctionJumpTables();251void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);252MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);253void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);254bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);255unsigned getCombinedIndex(const MachineInstr *CPEMI);256int findInRangeCPEntry(CPUser& U, unsigned UserOffset);257bool findAvailableWater(CPUser&U, unsigned UserOffset,258water_iterator &WaterIter, bool CloserWater);259void createNewWater(unsigned CPUserIndex, unsigned UserOffset,260MachineBasicBlock *&NewMBB);261bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);262void removeDeadCPEMI(MachineInstr *CPEMI);263bool removeUnusedCPEntries();264bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,265MachineInstr *CPEMI, unsigned Disp, bool NegOk,266bool DoDump = false);267bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,268CPUser &U, unsigned &Growth);269bool fixupImmediateBr(ImmBranch &Br);270bool fixupConditionalBr(ImmBranch &Br);271bool fixupUnconditionalBr(ImmBranch &Br);272bool optimizeThumb2Instructions();273bool optimizeThumb2Branches();274bool reorderThumb2JumpTables();275bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,276unsigned &DeadSize, bool &CanDeleteLEA,277bool &BaseRegKill);278bool optimizeThumb2JumpTables();279MachineBasicBlock *adjustJTTargetBlockForward(unsigned JTI,280MachineBasicBlock *BB,281MachineBasicBlock *JTBB);282283unsigned getUserOffset(CPUser&) const;284void dumpBBs();285void verify();286287bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,288unsigned Disp, bool NegativeOK, bool IsSoImm = false);289bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,290const CPUser &U) {291return isOffsetInRange(UserOffset, TrialOffset,292U.getMaxDisp(), U.NegOk, U.IsSoImm);293}294};295296} // end anonymous namespace297298char ARMConstantIslands::ID = 0;299300/// verify - check BBOffsets, BBSizes, alignment of islands301void ARMConstantIslands::verify() {302#ifndef NDEBUG303BBInfoVector &BBInfo = BBUtils->getBBInfo();304assert(is_sorted(*MF, [&BBInfo](const MachineBasicBlock &LHS,305const MachineBasicBlock &RHS) {306return BBInfo[LHS.getNumber()].postOffset() <307BBInfo[RHS.getNumber()].postOffset();308}));309LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");310for (CPUser &U : CPUsers) {311unsigned UserOffset = getUserOffset(U);312// Verify offset using the real max displacement without the safety313// adjustment.314if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,315/* DoDump = */ true)) {316LLVM_DEBUG(dbgs() << "OK\n");317continue;318}319LLVM_DEBUG(dbgs() << "Out of range.\n");320dumpBBs();321LLVM_DEBUG(MF->dump());322llvm_unreachable("Constant pool entry out of range!");323}324#endif325}326327#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)328/// print block size and offset information - debugging329LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {330LLVM_DEBUG({331BBInfoVector &BBInfo = BBUtils->getBBInfo();332for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {333const BasicBlockInfo &BBI = BBInfo[J];334dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)335<< " kb=" << unsigned(BBI.KnownBits)336<< " ua=" << unsigned(BBI.Unalign) << " pa=" << Log2(BBI.PostAlign)337<< format(" size=%#x\n", BBInfo[J].Size);338}339});340}341#endif342343// Align blocks where the previous block does not fall through. This may add344// extra NOP's but they will not be executed. It uses the PrefLoopAlignment as a345// measure of how much to align, and only runs at CodeGenOptLevel::Aggressive.346static bool AlignBlocks(MachineFunction *MF, const ARMSubtarget *STI) {347if (MF->getTarget().getOptLevel() != CodeGenOptLevel::Aggressive ||348MF->getFunction().hasOptSize())349return false;350351auto *TLI = STI->getTargetLowering();352const Align Alignment = TLI->getPrefLoopAlignment();353if (Alignment < 4)354return false;355356bool Changed = false;357bool PrevCanFallthough = true;358for (auto &MBB : *MF) {359if (!PrevCanFallthough) {360Changed = true;361MBB.setAlignment(Alignment);362}363364PrevCanFallthough = MBB.canFallThrough();365366// For LOB's, the ARMLowOverheadLoops pass may remove the unconditional367// branch later in the pipeline.368if (STI->hasLOB()) {369for (const auto &MI : reverse(MBB.terminators())) {370if (MI.getOpcode() == ARM::t2B &&371MI.getOperand(0).getMBB() == MBB.getNextNode())372continue;373if (isLoopStart(MI) || MI.getOpcode() == ARM::t2LoopEnd ||374MI.getOpcode() == ARM::t2LoopEndDec) {375PrevCanFallthough = true;376break;377}378// Any other terminator - nothing to do379break;380}381}382}383384return Changed;385}386387bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {388MF = &mf;389MCP = mf.getConstantPool();390BBUtils = std::make_unique<ARMBasicBlockUtils>(mf);391392LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "393<< MCP->getConstants().size() << " CP entries, aligned to "394<< MCP->getConstantPoolAlign().value() << " bytes *****\n");395396STI = &MF->getSubtarget<ARMSubtarget>();397TII = STI->getInstrInfo();398isPositionIndependentOrROPI =399STI->getTargetLowering()->isPositionIndependent() || STI->isROPI();400AFI = MF->getInfo<ARMFunctionInfo>();401DT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();402403isThumb = AFI->isThumbFunction();404isThumb1 = AFI->isThumb1OnlyFunction();405isThumb2 = AFI->isThumb2Function();406407bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);408// TBB generation code in this constant island pass has not been adapted to409// deal with speculation barriers.410if (STI->hardenSlsRetBr())411GenerateTBB = false;412413// Renumber all of the machine basic blocks in the function, guaranteeing that414// the numbers agree with the position of the block in the function.415MF->RenumberBlocks();416417// Try to reorder and otherwise adjust the block layout to make good use418// of the TB[BH] instructions.419bool MadeChange = false;420if (GenerateTBB && AdjustJumpTableBlocks) {421scanFunctionJumpTables();422MadeChange |= reorderThumb2JumpTables();423// Data is out of date, so clear it. It'll be re-computed later.424T2JumpTables.clear();425// Blocks may have shifted around. Keep the numbering up to date.426MF->RenumberBlocks();427}428429// Align any non-fallthrough blocks430MadeChange |= AlignBlocks(MF, STI);431432// Perform the initial placement of the constant pool entries. To start with,433// we put them all at the end of the function.434std::vector<MachineInstr*> CPEMIs;435if (!MCP->isEmpty())436doInitialConstPlacement(CPEMIs);437438if (MF->getJumpTableInfo())439doInitialJumpTablePlacement(CPEMIs);440441/// The next UID to take is the first unused one.442AFI->initPICLabelUId(CPEMIs.size());443444// Do the initial scan of the function, building up information about the445// sizes of each block, the location of all the water, and finding all of the446// constant pool users.447initializeFunctionInfo(CPEMIs);448CPEMIs.clear();449LLVM_DEBUG(dumpBBs());450451// Functions with jump tables need an alignment of 4 because they use the ADR452// instruction, which aligns the PC to 4 bytes before adding an offset.453if (!T2JumpTables.empty())454MF->ensureAlignment(Align(4));455456/// Remove dead constant pool entries.457MadeChange |= removeUnusedCPEntries();458459// Iteratively place constant pool entries and fix up branches until there460// is no change.461unsigned NoCPIters = 0, NoBRIters = 0;462while (true) {463LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');464bool CPChange = false;465for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)466// For most inputs, it converges in no more than 5 iterations.467// If it doesn't end in 10, the input may have huge BB or many CPEs.468// In this case, we will try different heuristics.469CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2);470if (CPChange && ++NoCPIters > CPMaxIteration)471report_fatal_error("Constant Island pass failed to converge!");472LLVM_DEBUG(dumpBBs());473474// Clear NewWaterList now. If we split a block for branches, it should475// appear as "new water" for the next iteration of constant pool placement.476NewWaterList.clear();477478LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');479bool BRChange = false;480for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)481BRChange |= fixupImmediateBr(ImmBranches[i]);482if (BRChange && ++NoBRIters > 30)483report_fatal_error("Branch Fix Up pass failed to converge!");484LLVM_DEBUG(dumpBBs());485486if (!CPChange && !BRChange)487break;488MadeChange = true;489}490491// Shrink 32-bit Thumb2 load and store instructions.492if (isThumb2 && !STI->prefers32BitThumb())493MadeChange |= optimizeThumb2Instructions();494495// Shrink 32-bit branch instructions.496if (isThumb && STI->hasV8MBaselineOps())497MadeChange |= optimizeThumb2Branches();498499// Optimize jump tables using TBB / TBH.500if (GenerateTBB && !STI->genExecuteOnly())501MadeChange |= optimizeThumb2JumpTables();502503// After a while, this might be made debug-only, but it is not expensive.504verify();505506// Save the mapping between original and cloned constpool entries.507for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {508for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {509const CPEntry & CPE = CPEntries[i][j];510if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI())511AFI->recordCPEClone(i, CPE.CPI);512}513}514515LLVM_DEBUG(dbgs() << '\n'; dumpBBs());516517BBUtils->clear();518WaterList.clear();519CPUsers.clear();520CPEntries.clear();521JumpTableEntryIndices.clear();522JumpTableUserIndices.clear();523BlockJumpTableRefCount.clear();524ImmBranches.clear();525PushPopMIs.clear();526T2JumpTables.clear();527528return MadeChange;529}530531/// Perform the initial placement of the regular constant pool entries.532/// To start with, we put them all at the end of the function.533void534ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {535// Create the basic block to hold the CPE's.536MachineBasicBlock *BB = MF->CreateMachineBasicBlock();537MF->push_back(BB);538539// MachineConstantPool measures alignment in bytes.540const Align MaxAlign = MCP->getConstantPoolAlign();541const unsigned MaxLogAlign = Log2(MaxAlign);542543// Mark the basic block as required by the const-pool.544BB->setAlignment(MaxAlign);545546// The function needs to be as aligned as the basic blocks. The linker may547// move functions around based on their alignment.548// Special case: halfword literals still need word alignment on the function.549Align FuncAlign = MaxAlign;550if (MaxAlign == 2)551FuncAlign = Align(4);552MF->ensureAlignment(FuncAlign);553554// Order the entries in BB by descending alignment. That ensures correct555// alignment of all entries as long as BB is sufficiently aligned. Keep556// track of the insertion point for each alignment. We are going to bucket557// sort the entries as they are created.558SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxLogAlign + 1,559BB->end());560561// Add all of the constants from the constant pool to the end block, use an562// identity mapping of CPI's to CPE's.563const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();564565const DataLayout &TD = MF->getDataLayout();566for (unsigned i = 0, e = CPs.size(); i != e; ++i) {567unsigned Size = CPs[i].getSizeInBytes(TD);568Align Alignment = CPs[i].getAlign();569// Verify that all constant pool entries are a multiple of their alignment.570// If not, we would have to pad them out so that instructions stay aligned.571assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!");572573// Insert CONSTPOOL_ENTRY before entries with a smaller alignment.574unsigned LogAlign = Log2(Alignment);575MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];576MachineInstr *CPEMI =577BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))578.addImm(i).addConstantPoolIndex(i).addImm(Size);579CPEMIs.push_back(CPEMI);580581// Ensure that future entries with higher alignment get inserted before582// CPEMI. This is bucket sort with iterators.583for (unsigned a = LogAlign + 1; a <= MaxLogAlign; ++a)584if (InsPoint[a] == InsAt)585InsPoint[a] = CPEMI;586587// Add a new CPEntry, but no corresponding CPUser yet.588CPEntries.emplace_back(1, CPEntry(CPEMI, i));589++NumCPEs;590LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "591<< Size << ", align = " << Alignment.value() << '\n');592}593LLVM_DEBUG(BB->dump());594}595596/// Do initial placement of the jump tables. Because Thumb2's TBB and TBH597/// instructions can be made more efficient if the jump table immediately598/// follows the instruction, it's best to place them immediately next to their599/// jumps to begin with. In almost all cases they'll never be moved from that600/// position.601void ARMConstantIslands::doInitialJumpTablePlacement(602std::vector<MachineInstr *> &CPEMIs) {603unsigned i = CPEntries.size();604auto MJTI = MF->getJumpTableInfo();605const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();606607// Only inline jump tables are placed in the function.608if (MJTI->getEntryKind() != MachineJumpTableInfo::EK_Inline)609return;610611MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;612for (MachineBasicBlock &MBB : *MF) {613auto MI = MBB.getLastNonDebugInstr();614// Look past potential SpeculationBarriers at end of BB.615while (MI != MBB.end() &&616(isSpeculationBarrierEndBBOpcode(MI->getOpcode()) ||617MI->isDebugInstr()))618--MI;619620if (MI == MBB.end())621continue;622623unsigned JTOpcode;624switch (MI->getOpcode()) {625default:626continue;627case ARM::BR_JTadd:628case ARM::BR_JTr:629case ARM::tBR_JTr:630case ARM::BR_JTm_i12:631case ARM::BR_JTm_rs:632// These instructions are emitted only in ARM or Thumb1 modes which do not633// support PACBTI. Hence we don't add BTI instructions in the destination634// blocks.635assert(!MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement() &&636"Branch protection must not be enabled for Arm or Thumb1 modes");637JTOpcode = ARM::JUMPTABLE_ADDRS;638break;639case ARM::t2BR_JT:640JTOpcode = ARM::JUMPTABLE_INSTS;641break;642case ARM::tTBB_JT:643case ARM::t2TBB_JT:644JTOpcode = ARM::JUMPTABLE_TBB;645break;646case ARM::tTBH_JT:647case ARM::t2TBH_JT:648JTOpcode = ARM::JUMPTABLE_TBH;649break;650}651652unsigned NumOps = MI->getDesc().getNumOperands();653MachineOperand JTOp =654MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1));655unsigned JTI = JTOp.getIndex();656unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t);657MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock();658MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB);659MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(),660DebugLoc(), TII->get(JTOpcode))661.addImm(i++)662.addJumpTableIndex(JTI)663.addImm(Size);664CPEMIs.push_back(CPEMI);665CPEntries.emplace_back(1, CPEntry(CPEMI, JTI));666JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1));667if (!LastCorrectlyNumberedBB)668LastCorrectlyNumberedBB = &MBB;669}670671// If we did anything then we need to renumber the subsequent blocks.672if (LastCorrectlyNumberedBB)673MF->RenumberBlocks(LastCorrectlyNumberedBB);674}675676/// BBHasFallthrough - Return true if the specified basic block can fallthrough677/// into the block immediately after it.678bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {679// Get the next machine basic block in the function.680MachineFunction::iterator MBBI = MBB->getIterator();681// Can't fall off end of function.682if (std::next(MBBI) == MBB->getParent()->end())683return false;684685MachineBasicBlock *NextBB = &*std::next(MBBI);686if (!MBB->isSuccessor(NextBB))687return false;688689// Try to analyze the end of the block. A potential fallthrough may already690// have an unconditional branch for whatever reason.691MachineBasicBlock *TBB, *FBB;692SmallVector<MachineOperand, 4> Cond;693bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);694return TooDifficult || FBB == nullptr;695}696697/// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,698/// look up the corresponding CPEntry.699ARMConstantIslands::CPEntry *700ARMConstantIslands::findConstPoolEntry(unsigned CPI,701const MachineInstr *CPEMI) {702std::vector<CPEntry> &CPEs = CPEntries[CPI];703// Number of entries per constpool index should be small, just do a704// linear search.705for (CPEntry &CPE : CPEs)706if (CPE.CPEMI == CPEMI)707return &CPE;708return nullptr;709}710711/// getCPEAlign - Returns the required alignment of the constant pool entry712/// represented by CPEMI.713Align ARMConstantIslands::getCPEAlign(const MachineInstr *CPEMI) {714switch (CPEMI->getOpcode()) {715case ARM::CONSTPOOL_ENTRY:716break;717case ARM::JUMPTABLE_TBB:718return isThumb1 ? Align(4) : Align(1);719case ARM::JUMPTABLE_TBH:720return isThumb1 ? Align(4) : Align(2);721case ARM::JUMPTABLE_INSTS:722return Align(2);723case ARM::JUMPTABLE_ADDRS:724return Align(4);725default:726llvm_unreachable("unknown constpool entry kind");727}728729unsigned CPI = getCombinedIndex(CPEMI);730assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");731return MCP->getConstants()[CPI].getAlign();732}733734// Exception landing pads, blocks that has their adress taken, and function735// entry blocks will always be (potential) indirect jump targets, regardless of736// whether they are referenced by or not by jump tables.737static bool isAlwaysIndirectTarget(const MachineBasicBlock &MBB) {738return MBB.isEHPad() || MBB.hasAddressTaken() ||739&MBB == &MBB.getParent()->front();740}741742/// scanFunctionJumpTables - Do a scan of the function, building up743/// information about the sizes of each block and the locations of all744/// the jump tables.745void ARMConstantIslands::scanFunctionJumpTables() {746for (MachineBasicBlock &MBB : *MF) {747for (MachineInstr &I : MBB)748if (I.isBranch() &&749(I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))750T2JumpTables.push_back(&I);751}752753if (!MF->getInfo<ARMFunctionInfo>()->branchTargetEnforcement())754return;755756if (const MachineJumpTableInfo *JTI = MF->getJumpTableInfo())757for (const MachineJumpTableEntry &JTE : JTI->getJumpTables())758for (const MachineBasicBlock *MBB : JTE.MBBs) {759if (isAlwaysIndirectTarget(*MBB))760// Set the reference count essentially to infinity, it will never761// reach zero and the BTI Instruction will never be removed.762BlockJumpTableRefCount[MBB] = std::numeric_limits<int>::max();763else764++BlockJumpTableRefCount[MBB];765}766}767768/// initializeFunctionInfo - Do the initial scan of the function, building up769/// information about the sizes of each block, the location of all the water,770/// and finding all of the constant pool users.771void ARMConstantIslands::772initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {773774BBUtils->computeAllBlockSizes();775BBInfoVector &BBInfo = BBUtils->getBBInfo();776// The known bits of the entry block offset are determined by the function777// alignment.778BBInfo.front().KnownBits = Log2(MF->getAlignment());779780// Compute block offsets and known bits.781BBUtils->adjustBBOffsetsAfter(&MF->front());782783// We only care about jump table instructions when jump tables are inline.784MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();785bool InlineJumpTables =786MJTI && MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline;787788// Now go back through the instructions and build up our data structures.789for (MachineBasicBlock &MBB : *MF) {790// If this block doesn't fall through into the next MBB, then this is791// 'water' that a constant pool island could be placed.792if (!BBHasFallthrough(&MBB))793WaterList.push_back(&MBB);794795for (MachineInstr &I : MBB) {796if (I.isDebugInstr())797continue;798799unsigned Opc = I.getOpcode();800if (I.isBranch()) {801bool isCond = false;802unsigned Bits = 0;803unsigned Scale = 1;804int UOpc = Opc;805switch (Opc) {806default:807continue; // Ignore other JT branches808case ARM::t2BR_JT:809case ARM::tBR_JTr:810if (InlineJumpTables)811T2JumpTables.push_back(&I);812continue; // Does not get an entry in ImmBranches813case ARM::Bcc:814isCond = true;815UOpc = ARM::B;816[[fallthrough]];817case ARM::B:818Bits = 24;819Scale = 4;820break;821case ARM::tBcc:822isCond = true;823UOpc = ARM::tB;824Bits = 8;825Scale = 2;826break;827case ARM::tB:828Bits = 11;829Scale = 2;830break;831case ARM::t2Bcc:832isCond = true;833UOpc = ARM::t2B;834Bits = 20;835Scale = 2;836break;837case ARM::t2B:838Bits = 24;839Scale = 2;840break;841}842843// Record this immediate branch.844unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;845ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));846}847848if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)849PushPopMIs.push_back(&I);850851if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||852Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||853Opc == ARM::JUMPTABLE_TBH)854continue;855856// Scan the instructions for constant pool operands.857for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op)858if (I.getOperand(op).isCPI() ||859(I.getOperand(op).isJTI() && InlineJumpTables)) {860// We found one. The addressing mode tells us the max displacement861// from the PC that this instruction permits.862863// Basic size info comes from the TSFlags field.864unsigned Bits = 0;865unsigned Scale = 1;866bool NegOk = false;867bool IsSoImm = false;868869switch (Opc) {870default:871llvm_unreachable("Unknown addressing mode for CP reference!");872873// Taking the address of a CP entry.874case ARM::LEApcrel:875case ARM::LEApcrelJT: {876// This takes a SoImm, which is 8 bit immediate rotated. We'll877// pretend the maximum offset is 255 * 4. Since each instruction878// 4 byte wide, this is always correct. We'll check for other879// displacements that fits in a SoImm as well.880Bits = 8;881NegOk = true;882IsSoImm = true;883unsigned CPI = I.getOperand(op).getIndex();884assert(CPI < CPEMIs.size());885MachineInstr *CPEMI = CPEMIs[CPI];886const Align CPEAlign = getCPEAlign(CPEMI);887const unsigned LogCPEAlign = Log2(CPEAlign);888if (LogCPEAlign >= 2)889Scale = 4;890else891// For constants with less than 4-byte alignment,892// we'll pretend the maximum offset is 255 * 1.893Scale = 1;894}895break;896case ARM::t2LEApcrel:897case ARM::t2LEApcrelJT:898Bits = 12;899NegOk = true;900break;901case ARM::tLEApcrel:902case ARM::tLEApcrelJT:903Bits = 8;904Scale = 4;905break;906907case ARM::LDRBi12:908case ARM::LDRi12:909case ARM::LDRcp:910case ARM::t2LDRpci:911case ARM::t2LDRHpci:912case ARM::t2LDRSHpci:913case ARM::t2LDRBpci:914case ARM::t2LDRSBpci:915Bits = 12; // +-offset_12916NegOk = true;917break;918919case ARM::tLDRpci:920Bits = 8;921Scale = 4; // +(offset_8*4)922break;923924case ARM::VLDRD:925case ARM::VLDRS:926Bits = 8;927Scale = 4; // +-(offset_8*4)928NegOk = true;929break;930case ARM::VLDRH:931Bits = 8;932Scale = 2; // +-(offset_8*2)933NegOk = true;934break;935}936937// Remember that this is a user of a CP entry.938unsigned CPI = I.getOperand(op).getIndex();939if (I.getOperand(op).isJTI()) {940JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size()));941CPI = JumpTableEntryIndices[CPI];942}943944MachineInstr *CPEMI = CPEMIs[CPI];945unsigned MaxOffs = ((1 << Bits)-1) * Scale;946CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));947948// Increment corresponding CPEntry reference count.949CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);950assert(CPE && "Cannot find a corresponding CPEntry!");951CPE->RefCount++;952953// Instructions can only use one CP entry, don't bother scanning the954// rest of the operands.955break;956}957}958}959}960961/// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB962/// ID.963static bool CompareMBBNumbers(const MachineBasicBlock *LHS,964const MachineBasicBlock *RHS) {965return LHS->getNumber() < RHS->getNumber();966}967968/// updateForInsertedWaterBlock - When a block is newly inserted into the969/// machine function, it upsets all of the block numbers. Renumber the blocks970/// and update the arrays that parallel this numbering.971void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {972// Renumber the MBB's to keep them consecutive.973NewBB->getParent()->RenumberBlocks(NewBB);974975// Insert an entry into BBInfo to align it properly with the (newly976// renumbered) block numbers.977BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());978979// Next, update WaterList. Specifically, we need to add NewMBB as having980// available water after it.981water_iterator IP = llvm::lower_bound(WaterList, NewBB, CompareMBBNumbers);982WaterList.insert(IP, NewBB);983}984985/// Split the basic block containing MI into two blocks, which are joined by986/// an unconditional branch. Update data structures and renumber blocks to987/// account for this change and returns the newly created block.988MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {989MachineBasicBlock *OrigBB = MI->getParent();990991// Collect liveness information at MI.992LivePhysRegs LRs(*MF->getSubtarget().getRegisterInfo());993LRs.addLiveOuts(*OrigBB);994auto LivenessEnd = ++MachineBasicBlock::iterator(MI).getReverse();995for (MachineInstr &LiveMI : make_range(OrigBB->rbegin(), LivenessEnd))996LRs.stepBackward(LiveMI);997998// Create a new MBB for the code after the OrigBB.999MachineBasicBlock *NewBB =1000MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());1001MachineFunction::iterator MBBI = ++OrigBB->getIterator();1002MF->insert(MBBI, NewBB);10031004// Splice the instructions starting with MI over to NewBB.1005NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());10061007// Add an unconditional branch from OrigBB to NewBB.1008// Note the new unconditional branch is not being recorded.1009// There doesn't seem to be meaningful DebugInfo available; this doesn't1010// correspond to anything in the source.1011unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;1012if (!isThumb)1013BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);1014else1015BuildMI(OrigBB, DebugLoc(), TII->get(Opc))1016.addMBB(NewBB)1017.add(predOps(ARMCC::AL));1018++NumSplit;10191020// Update the CFG. All succs of OrigBB are now succs of NewBB.1021NewBB->transferSuccessors(OrigBB);10221023// OrigBB branches to NewBB.1024OrigBB->addSuccessor(NewBB);10251026// Update live-in information in the new block.1027MachineRegisterInfo &MRI = MF->getRegInfo();1028for (MCPhysReg L : LRs)1029if (!MRI.isReserved(L))1030NewBB->addLiveIn(L);10311032// Update internal data structures to account for the newly inserted MBB.1033// This is almost the same as updateForInsertedWaterBlock, except that1034// the Water goes after OrigBB, not NewBB.1035MF->RenumberBlocks(NewBB);10361037// Insert an entry into BBInfo to align it properly with the (newly1038// renumbered) block numbers.1039BBUtils->insert(NewBB->getNumber(), BasicBlockInfo());10401041// Next, update WaterList. Specifically, we need to add OrigMBB as having1042// available water after it (but not if it's already there, which happens1043// when splitting before a conditional branch that is followed by an1044// unconditional branch - in that case we want to insert NewBB).1045water_iterator IP = llvm::lower_bound(WaterList, OrigBB, CompareMBBNumbers);1046MachineBasicBlock* WaterBB = *IP;1047if (WaterBB == OrigBB)1048WaterList.insert(std::next(IP), NewBB);1049else1050WaterList.insert(IP, OrigBB);1051NewWaterList.insert(OrigBB);10521053// Figure out how large the OrigBB is. As the first half of the original1054// block, it cannot contain a tablejump. The size includes1055// the new jump we added. (It should be possible to do this without1056// recounting everything, but it's very confusing, and this is rarely1057// executed.)1058BBUtils->computeBlockSize(OrigBB);10591060// Figure out how large the NewMBB is. As the second half of the original1061// block, it may contain a tablejump.1062BBUtils->computeBlockSize(NewBB);10631064// All BBOffsets following these blocks must be modified.1065BBUtils->adjustBBOffsetsAfter(OrigBB);10661067return NewBB;1068}10691070/// getUserOffset - Compute the offset of U.MI as seen by the hardware1071/// displacement computation. Update U.KnownAlignment to match its current1072/// basic block location.1073unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {1074unsigned UserOffset = BBUtils->getOffsetOf(U.MI);10751076SmallVectorImpl<BasicBlockInfo> &BBInfo = BBUtils->getBBInfo();1077const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];1078unsigned KnownBits = BBI.internalKnownBits();10791080// The value read from PC is offset from the actual instruction address.1081UserOffset += (isThumb ? 4 : 8);10821083// Because of inline assembly, we may not know the alignment (mod 4) of U.MI.1084// Make sure U.getMaxDisp() returns a constrained range.1085U.KnownAlignment = (KnownBits >= 2);10861087// On Thumb, offsets==2 mod 4 are rounded down by the hardware for1088// purposes of the displacement computation; compensate for that here.1089// For unknown alignments, getMaxDisp() constrains the range instead.1090if (isThumb && U.KnownAlignment)1091UserOffset &= ~3u;10921093return UserOffset;1094}10951096/// isOffsetInRange - Checks whether UserOffset (the location of a constant pool1097/// reference) is within MaxDisp of TrialOffset (a proposed location of a1098/// constant pool entry).1099/// UserOffset is computed by getUserOffset above to include PC adjustments. If1100/// the mod 4 alignment of UserOffset is not known, the uncertainty must be1101/// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.1102bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,1103unsigned TrialOffset, unsigned MaxDisp,1104bool NegativeOK, bool IsSoImm) {1105if (UserOffset <= TrialOffset) {1106// User before the Trial.1107if (TrialOffset - UserOffset <= MaxDisp)1108return true;1109// FIXME: Make use full range of soimm values.1110} else if (NegativeOK) {1111if (UserOffset - TrialOffset <= MaxDisp)1112return true;1113// FIXME: Make use full range of soimm values.1114}1115return false;1116}11171118/// isWaterInRange - Returns true if a CPE placed after the specified1119/// Water (a basic block) will be in range for the specific MI.1120///1121/// Compute how much the function will grow by inserting a CPE after Water.1122bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,1123MachineBasicBlock* Water, CPUser &U,1124unsigned &Growth) {1125BBInfoVector &BBInfo = BBUtils->getBBInfo();1126const Align CPEAlign = getCPEAlign(U.CPEMI);1127const unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPEAlign);1128unsigned NextBlockOffset;1129Align NextBlockAlignment;1130MachineFunction::const_iterator NextBlock = Water->getIterator();1131if (++NextBlock == MF->end()) {1132NextBlockOffset = BBInfo[Water->getNumber()].postOffset();1133} else {1134NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;1135NextBlockAlignment = NextBlock->getAlignment();1136}1137unsigned Size = U.CPEMI->getOperand(2).getImm();1138unsigned CPEEnd = CPEOffset + Size;11391140// The CPE may be able to hide in the alignment padding before the next1141// block. It may also cause more padding to be required if it is more aligned1142// that the next block.1143if (CPEEnd > NextBlockOffset) {1144Growth = CPEEnd - NextBlockOffset;1145// Compute the padding that would go at the end of the CPE to align the next1146// block.1147Growth += offsetToAlignment(CPEEnd, NextBlockAlignment);11481149// If the CPE is to be inserted before the instruction, that will raise1150// the offset of the instruction. Also account for unknown alignment padding1151// in blocks between CPE and the user.1152if (CPEOffset < UserOffset)1153UserOffset += Growth + UnknownPadding(MF->getAlignment(), Log2(CPEAlign));1154} else1155// CPE fits in existing padding.1156Growth = 0;11571158return isOffsetInRange(UserOffset, CPEOffset, U);1159}11601161/// isCPEntryInRange - Returns true if the distance between specific MI and1162/// specific ConstPool entry instruction can fit in MI's displacement field.1163bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,1164MachineInstr *CPEMI, unsigned MaxDisp,1165bool NegOk, bool DoDump) {1166unsigned CPEOffset = BBUtils->getOffsetOf(CPEMI);11671168if (DoDump) {1169LLVM_DEBUG({1170BBInfoVector &BBInfo = BBUtils->getBBInfo();1171unsigned Block = MI->getParent()->getNumber();1172const BasicBlockInfo &BBI = BBInfo[Block];1173dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()1174<< " max delta=" << MaxDisp1175<< format(" insn address=%#x", UserOffset) << " in "1176<< printMBBReference(*MI->getParent()) << ": "1177<< format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI1178<< format("CPE address=%#x offset=%+d: ", CPEOffset,1179int(CPEOffset - UserOffset));1180});1181}11821183return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);1184}11851186#ifndef NDEBUG1187/// BBIsJumpedOver - Return true of the specified basic block's only predecessor1188/// unconditionally branches to its only successor.1189static bool BBIsJumpedOver(MachineBasicBlock *MBB) {1190if (MBB->pred_size() != 1 || MBB->succ_size() != 1)1191return false;11921193MachineBasicBlock *Succ = *MBB->succ_begin();1194MachineBasicBlock *Pred = *MBB->pred_begin();1195MachineInstr *PredMI = &Pred->back();1196if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB1197|| PredMI->getOpcode() == ARM::t2B)1198return PredMI->getOperand(0).getMBB() == Succ;1199return false;1200}1201#endif // NDEBUG12021203/// decrementCPEReferenceCount - find the constant pool entry with index CPI1204/// and instruction CPEMI, and decrement its refcount. If the refcount1205/// becomes 0 remove the entry and instruction. Returns true if we removed1206/// the entry, false if we didn't.1207bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,1208MachineInstr *CPEMI) {1209// Find the old entry. Eliminate it if it is no longer used.1210CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);1211assert(CPE && "Unexpected!");1212if (--CPE->RefCount == 0) {1213removeDeadCPEMI(CPEMI);1214CPE->CPEMI = nullptr;1215--NumCPEs;1216return true;1217}1218return false;1219}12201221unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {1222if (CPEMI->getOperand(1).isCPI())1223return CPEMI->getOperand(1).getIndex();12241225return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];1226}12271228/// LookForCPEntryInRange - see if the currently referenced CPE is in range;1229/// if not, see if an in-range clone of the CPE is in range, and if so,1230/// change the data structures so the user references the clone. Returns:1231/// 0 = no existing entry found1232/// 1 = entry found, and there were no code insertions or deletions1233/// 2 = entry found, and there were code insertions or deletions1234int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {1235MachineInstr *UserMI = U.MI;1236MachineInstr *CPEMI = U.CPEMI;12371238// Check to see if the CPE is already in-range.1239if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,1240true)) {1241LLVM_DEBUG(dbgs() << "In range\n");1242return 1;1243}12441245// No. Look for previously created clones of the CPE that are in range.1246unsigned CPI = getCombinedIndex(CPEMI);1247std::vector<CPEntry> &CPEs = CPEntries[CPI];1248for (CPEntry &CPE : CPEs) {1249// We already tried this one1250if (CPE.CPEMI == CPEMI)1251continue;1252// Removing CPEs can leave empty entries, skip1253if (CPE.CPEMI == nullptr)1254continue;1255if (isCPEntryInRange(UserMI, UserOffset, CPE.CPEMI, U.getMaxDisp(),1256U.NegOk)) {1257LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI1258<< "\n");1259// Point the CPUser node to the replacement1260U.CPEMI = CPE.CPEMI;1261// Change the CPI in the instruction operand to refer to the clone.1262for (MachineOperand &MO : UserMI->operands())1263if (MO.isCPI()) {1264MO.setIndex(CPE.CPI);1265break;1266}1267// Adjust the refcount of the clone...1268CPE.RefCount++;1269// ...and the original. If we didn't remove the old entry, none of the1270// addresses changed, so we don't need another pass.1271return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;1272}1273}1274return 0;1275}12761277/// getUnconditionalBrDisp - Returns the maximum displacement that can fit in1278/// the specific unconditional branch instruction.1279static inline unsigned getUnconditionalBrDisp(int Opc) {1280switch (Opc) {1281case ARM::tB:1282return ((1<<10)-1)*2;1283case ARM::t2B:1284return ((1<<23)-1)*2;1285default:1286break;1287}12881289return ((1<<23)-1)*4;1290}12911292/// findAvailableWater - Look for an existing entry in the WaterList in which1293/// we can place the CPE referenced from U so it's within range of U's MI.1294/// Returns true if found, false if not. If it returns true, WaterIter1295/// is set to the WaterList entry. For Thumb, prefer water that will not1296/// introduce padding to water that will. To ensure that this pass1297/// terminates, the CPE location for a particular CPUser is only allowed to1298/// move to a lower address, so search backward from the end of the list and1299/// prefer the first water that is in range.1300bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,1301water_iterator &WaterIter,1302bool CloserWater) {1303if (WaterList.empty())1304return false;13051306unsigned BestGrowth = ~0u;1307// The nearest water without splitting the UserBB is right after it.1308// If the distance is still large (we have a big BB), then we need to split it1309// if we don't converge after certain iterations. This helps the following1310// situation to converge:1311// BB0:1312// Big BB1313// BB1:1314// Constant Pool1315// When a CP access is out of range, BB0 may be used as water. However,1316// inserting islands between BB0 and BB1 makes other accesses out of range.1317MachineBasicBlock *UserBB = U.MI->getParent();1318BBInfoVector &BBInfo = BBUtils->getBBInfo();1319const Align CPEAlign = getCPEAlign(U.CPEMI);1320unsigned MinNoSplitDisp = BBInfo[UserBB->getNumber()].postOffset(CPEAlign);1321if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)1322return false;1323for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;1324--IP) {1325MachineBasicBlock* WaterBB = *IP;1326// Check if water is in range and is either at a lower address than the1327// current "high water mark" or a new water block that was created since1328// the previous iteration by inserting an unconditional branch. In the1329// latter case, we want to allow resetting the high water mark back to1330// this new water since we haven't seen it before. Inserting branches1331// should be relatively uncommon and when it does happen, we want to be1332// sure to take advantage of it for all the CPEs near that block, so that1333// we don't insert more branches than necessary.1334// When CloserWater is true, we try to find the lowest address after (or1335// equal to) user MI's BB no matter of padding growth.1336unsigned Growth;1337if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&1338(WaterBB->getNumber() < U.HighWaterMark->getNumber() ||1339NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&1340Growth < BestGrowth) {1341// This is the least amount of required padding seen so far.1342BestGrowth = Growth;1343WaterIter = IP;1344LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)1345<< " Growth=" << Growth << '\n');13461347if (CloserWater && WaterBB == U.MI->getParent())1348return true;1349// Keep looking unless it is perfect and we're not looking for the lowest1350// possible address.1351if (!CloserWater && BestGrowth == 0)1352return true;1353}1354if (IP == B)1355break;1356}1357return BestGrowth != ~0u;1358}13591360/// createNewWater - No existing WaterList entry will work for1361/// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the1362/// block is used if in range, and the conditional branch munged so control1363/// flow is correct. Otherwise the block is split to create a hole with an1364/// unconditional branch around it. In either case NewMBB is set to a1365/// block following which the new island can be inserted (the WaterList1366/// is not adjusted).1367void ARMConstantIslands::createNewWater(unsigned CPUserIndex,1368unsigned UserOffset,1369MachineBasicBlock *&NewMBB) {1370CPUser &U = CPUsers[CPUserIndex];1371MachineInstr *UserMI = U.MI;1372MachineInstr *CPEMI = U.CPEMI;1373const Align CPEAlign = getCPEAlign(CPEMI);1374MachineBasicBlock *UserMBB = UserMI->getParent();1375BBInfoVector &BBInfo = BBUtils->getBBInfo();1376const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];13771378// If the block does not end in an unconditional branch already, and if the1379// end of the block is within range, make new water there. (The addition1380// below is for the unconditional branch we will be adding: 4 bytes on ARM +1381// Thumb2, 2 on Thumb1.1382if (BBHasFallthrough(UserMBB)) {1383// Size of branch to insert.1384unsigned Delta = isThumb1 ? 2 : 4;1385// Compute the offset where the CPE will begin.1386unsigned CPEOffset = UserBBI.postOffset(CPEAlign) + Delta;13871388if (isOffsetInRange(UserOffset, CPEOffset, U)) {1389LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)1390<< format(", expected CPE offset %#x\n", CPEOffset));1391NewMBB = &*++UserMBB->getIterator();1392// Add an unconditional branch from UserMBB to fallthrough block. Record1393// it for branch lengthening; this new branch will not get out of range,1394// but if the preceding conditional branch is out of range, the targets1395// will be exchanged, and the altered branch may be out of range, so the1396// machinery has to know about it.1397int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;1398if (!isThumb)1399BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);1400else1401BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))1402.addMBB(NewMBB)1403.add(predOps(ARMCC::AL));1404unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);1405ImmBranches.push_back(ImmBranch(&UserMBB->back(),1406MaxDisp, false, UncondBr));1407BBUtils->computeBlockSize(UserMBB);1408BBUtils->adjustBBOffsetsAfter(UserMBB);1409return;1410}1411}14121413// What a big block. Find a place within the block to split it. This is a1414// little tricky on Thumb1 since instructions are 2 bytes and constant pool1415// entries are 4 bytes: if instruction I references island CPE, and1416// instruction I+1 references CPE', it will not work well to put CPE as far1417// forward as possible, since then CPE' cannot immediately follow it (that1418// location is 2 bytes farther away from I+1 than CPE was from I) and we'd1419// need to create a new island. So, we make a first guess, then walk through1420// the instructions between the one currently being looked at and the1421// possible insertion point, and make sure any other instructions that1422// reference CPEs will be able to use the same island area; if not, we back1423// up the insertion point.14241425// Try to split the block so it's fully aligned. Compute the latest split1426// point where we can add a 4-byte branch instruction, and then align to1427// Align which is the largest possible alignment in the function.1428const Align Align = MF->getAlignment();1429assert(Align >= CPEAlign && "Over-aligned constant pool entry");1430unsigned KnownBits = UserBBI.internalKnownBits();1431unsigned UPad = UnknownPadding(Align, KnownBits);1432unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;1433LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",1434BaseInsertOffset));14351436// The 4 in the following is for the unconditional branch we'll be inserting1437// (allows for long branch on Thumb1). Alignment of the island is handled1438// inside isOffsetInRange.1439BaseInsertOffset -= 4;14401441LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)1442<< " la=" << Log2(Align) << " kb=" << KnownBits1443<< " up=" << UPad << '\n');14441445// This could point off the end of the block if we've already got constant1446// pool entries following this block; only the last one is in the water list.1447// Back past any possible branches (allow for a conditional and a maximally1448// long unconditional).1449if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {1450// Ensure BaseInsertOffset is larger than the offset of the instruction1451// following UserMI so that the loop which searches for the split point1452// iterates at least once.1453BaseInsertOffset =1454std::max(UserBBI.postOffset() - UPad - 8,1455UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);1456// If the CP is referenced(ie, UserOffset) is in first four instructions1457// after IT, this recalculated BaseInsertOffset could be in the middle of1458// an IT block. If it is, change the BaseInsertOffset to just after the1459// IT block. This still make the CP Entry is in range becuase of the1460// following reasons.1461// 1. The initial BaseseInsertOffset calculated is (UserOffset +1462// U.getMaxDisp() - UPad).1463// 2. An IT block is only at most 4 instructions plus the "it" itself (181464// bytes).1465// 3. All the relevant instructions support much larger Maximum1466// displacement.1467MachineBasicBlock::iterator I = UserMI;1468++I;1469Register PredReg;1470for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);1471I->getOpcode() != ARM::t2IT &&1472getITInstrPredicate(*I, PredReg) != ARMCC::AL;1473Offset += TII->getInstSizeInBytes(*I), I = std::next(I)) {1474BaseInsertOffset =1475std::max(BaseInsertOffset, Offset + TII->getInstSizeInBytes(*I) + 1);1476assert(I != UserMBB->end() && "Fell off end of block");1477}1478LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));1479}1480unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +1481CPEMI->getOperand(2).getImm();1482MachineBasicBlock::iterator MI = UserMI;1483++MI;1484unsigned CPUIndex = CPUserIndex+1;1485unsigned NumCPUsers = CPUsers.size();1486MachineInstr *LastIT = nullptr;1487for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);1488Offset < BaseInsertOffset;1489Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {1490assert(MI != UserMBB->end() && "Fell off end of block");1491if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {1492CPUser &U = CPUsers[CPUIndex];1493if (!isOffsetInRange(Offset, EndInsertOffset, U)) {1494// Shift intertion point by one unit of alignment so it is within reach.1495BaseInsertOffset -= Align.value();1496EndInsertOffset -= Align.value();1497}1498// This is overly conservative, as we don't account for CPEMIs being1499// reused within the block, but it doesn't matter much. Also assume CPEs1500// are added in order with alignment padding. We may eventually be able1501// to pack the aligned CPEs better.1502EndInsertOffset += U.CPEMI->getOperand(2).getImm();1503CPUIndex++;1504}15051506// Remember the last IT instruction.1507if (MI->getOpcode() == ARM::t2IT)1508LastIT = &*MI;1509}15101511--MI;15121513// Avoid splitting an IT block.1514if (LastIT) {1515Register PredReg;1516ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);1517if (CC != ARMCC::AL)1518MI = LastIT;1519}15201521// Avoid splitting a MOVW+MOVT pair with a relocation on Windows.1522// On Windows, this instruction pair is covered by one single1523// IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a1524// constant island is injected inbetween them, the relocation will clobber1525// the instruction and fail to update the MOVT instruction.1526// (These instructions are bundled up until right before the ConstantIslands1527// pass.)1528if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&1529(MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==1530ARMII::MO_HI16) {1531--MI;1532assert(MI->getOpcode() == ARM::t2MOVi16 &&1533(MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==1534ARMII::MO_LO16);1535}15361537// We really must not split an IT block.1538#ifndef NDEBUG1539Register PredReg;1540assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL);1541#endif1542NewMBB = splitBlockBeforeInstr(&*MI);1543}15441545/// handleConstantPoolUser - Analyze the specified user, checking to see if it1546/// is out-of-range. If so, pick up the constant pool value and move it some1547/// place in-range. Return true if we changed any addresses (thus must run1548/// another pass of branch lengthening), false otherwise.1549bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,1550bool CloserWater) {1551CPUser &U = CPUsers[CPUserIndex];1552MachineInstr *UserMI = U.MI;1553MachineInstr *CPEMI = U.CPEMI;1554unsigned CPI = getCombinedIndex(CPEMI);1555unsigned Size = CPEMI->getOperand(2).getImm();1556// Compute this only once, it's expensive.1557unsigned UserOffset = getUserOffset(U);15581559// See if the current entry is within range, or there is a clone of it1560// in range.1561int result = findInRangeCPEntry(U, UserOffset);1562if (result==1) return false;1563else if (result==2) return true;15641565// No existing clone of this CPE is within range.1566// We will be generating a new clone. Get a UID for it.1567unsigned ID = AFI->createPICLabelUId();15681569// Look for water where we can place this CPE.1570MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();1571MachineBasicBlock *NewMBB;1572water_iterator IP;1573if (findAvailableWater(U, UserOffset, IP, CloserWater)) {1574LLVM_DEBUG(dbgs() << "Found water in range\n");1575MachineBasicBlock *WaterBB = *IP;15761577// If the original WaterList entry was "new water" on this iteration,1578// propagate that to the new island. This is just keeping NewWaterList1579// updated to match the WaterList, which will be updated below.1580if (NewWaterList.erase(WaterBB))1581NewWaterList.insert(NewIsland);15821583// The new CPE goes before the following block (NewMBB).1584NewMBB = &*++WaterBB->getIterator();1585} else {1586// No water found.1587LLVM_DEBUG(dbgs() << "No water found\n");1588createNewWater(CPUserIndex, UserOffset, NewMBB);15891590// splitBlockBeforeInstr adds to WaterList, which is important when it is1591// called while handling branches so that the water will be seen on the1592// next iteration for constant pools, but in this context, we don't want1593// it. Check for this so it will be removed from the WaterList.1594// Also remove any entry from NewWaterList.1595MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();1596IP = find(WaterList, WaterBB);1597if (IP != WaterList.end())1598NewWaterList.erase(WaterBB);15991600// We are adding new water. Update NewWaterList.1601NewWaterList.insert(NewIsland);1602}1603// Always align the new block because CP entries can be smaller than 41604// bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may1605// be an already aligned constant pool block.1606const Align Alignment = isThumb ? Align(2) : Align(4);1607if (NewMBB->getAlignment() < Alignment)1608NewMBB->setAlignment(Alignment);16091610// Remove the original WaterList entry; we want subsequent insertions in1611// this vicinity to go after the one we're about to insert. This1612// considerably reduces the number of times we have to move the same CPE1613// more than once and is also important to ensure the algorithm terminates.1614if (IP != WaterList.end())1615WaterList.erase(IP);16161617// Okay, we know we can put an island before NewMBB now, do it!1618MF->insert(NewMBB->getIterator(), NewIsland);16191620// Update internal data structures to account for the newly inserted MBB.1621updateForInsertedWaterBlock(NewIsland);16221623// Now that we have an island to add the CPE to, clone the original CPE and1624// add it to the island.1625U.HighWaterMark = NewIsland;1626U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())1627.addImm(ID)1628.add(CPEMI->getOperand(1))1629.addImm(Size);1630CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));1631++NumCPEs;16321633// Decrement the old entry, and remove it if refcount becomes 0.1634decrementCPEReferenceCount(CPI, CPEMI);16351636// Mark the basic block as aligned as required by the const-pool entry.1637NewIsland->setAlignment(getCPEAlign(U.CPEMI));16381639// Increase the size of the island block to account for the new entry.1640BBUtils->adjustBBSize(NewIsland, Size);1641BBUtils->adjustBBOffsetsAfter(&*--NewIsland->getIterator());16421643// Finally, change the CPI in the instruction operand to be ID.1644for (MachineOperand &MO : UserMI->operands())1645if (MO.isCPI()) {1646MO.setIndex(ID);1647break;1648}16491650LLVM_DEBUG(1651dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI1652<< format(" offset=%#x\n",1653BBUtils->getBBInfo()[NewIsland->getNumber()].Offset));16541655return true;1656}16571658/// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update1659/// sizes and offsets of impacted basic blocks.1660void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {1661MachineBasicBlock *CPEBB = CPEMI->getParent();1662unsigned Size = CPEMI->getOperand(2).getImm();1663CPEMI->eraseFromParent();1664BBInfoVector &BBInfo = BBUtils->getBBInfo();1665BBUtils->adjustBBSize(CPEBB, -Size);1666// All succeeding offsets have the current size value added in, fix this.1667if (CPEBB->empty()) {1668BBInfo[CPEBB->getNumber()].Size = 0;16691670// This block no longer needs to be aligned.1671CPEBB->setAlignment(Align(1));1672} else {1673// Entries are sorted by descending alignment, so realign from the front.1674CPEBB->setAlignment(getCPEAlign(&*CPEBB->begin()));1675}16761677BBUtils->adjustBBOffsetsAfter(CPEBB);1678// An island has only one predecessor BB and one successor BB. Check if1679// this BB's predecessor jumps directly to this BB's successor. This1680// shouldn't happen currently.1681assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");1682// FIXME: remove the empty blocks after all the work is done?1683}16841685/// removeUnusedCPEntries - Remove constant pool entries whose refcounts1686/// are zero.1687bool ARMConstantIslands::removeUnusedCPEntries() {1688unsigned MadeChange = false;1689for (std::vector<CPEntry> &CPEs : CPEntries) {1690for (CPEntry &CPE : CPEs) {1691if (CPE.RefCount == 0 && CPE.CPEMI) {1692removeDeadCPEMI(CPE.CPEMI);1693CPE.CPEMI = nullptr;1694MadeChange = true;1695}1696}1697}1698return MadeChange;1699}170017011702/// fixupImmediateBr - Fix up an immediate branch whose destination is too far1703/// away to fit in its displacement field.1704bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {1705MachineInstr *MI = Br.MI;1706MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();17071708// Check to see if the DestBB is already in-range.1709if (BBUtils->isBBInRange(MI, DestBB, Br.MaxDisp))1710return false;17111712if (!Br.isCond)1713return fixupUnconditionalBr(Br);1714return fixupConditionalBr(Br);1715}17161717/// fixupUnconditionalBr - Fix up an unconditional branch whose destination is1718/// too far away to fit in its displacement field. If the LR register has been1719/// spilled in the epilogue, then we can use BL to implement a far jump.1720/// Otherwise, add an intermediate branch instruction to a branch.1721bool1722ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {1723MachineInstr *MI = Br.MI;1724MachineBasicBlock *MBB = MI->getParent();1725if (!isThumb1)1726llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");17271728if (!AFI->isLRSpilled())1729report_fatal_error("underestimated function size");17301731// Use BL to implement far jump.1732Br.MaxDisp = (1 << 21) * 2;1733MI->setDesc(TII->get(ARM::tBfar));1734BBInfoVector &BBInfo = BBUtils->getBBInfo();1735BBInfo[MBB->getNumber()].Size += 2;1736BBUtils->adjustBBOffsetsAfter(MBB);1737++NumUBrFixed;17381739LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);17401741return true;1742}17431744/// fixupConditionalBr - Fix up a conditional branch whose destination is too1745/// far away to fit in its displacement field. It is converted to an inverse1746/// conditional branch + an unconditional branch to the destination.1747bool1748ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {1749MachineInstr *MI = Br.MI;1750MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();17511752// Add an unconditional branch to the destination and invert the branch1753// condition to jump over it:1754// blt L11755// =>1756// bge L21757// b L11758// L2:1759ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();1760CC = ARMCC::getOppositeCondition(CC);1761Register CCReg = MI->getOperand(2).getReg();17621763// If the branch is at the end of its MBB and that has a fall-through block,1764// direct the updated conditional branch to the fall-through block. Otherwise,1765// split the MBB before the next instruction.1766MachineBasicBlock *MBB = MI->getParent();1767MachineInstr *BMI = &MBB->back();1768bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);17691770++NumCBrFixed;1771if (BMI != MI) {1772if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&1773BMI->getOpcode() == Br.UncondBr) {1774// Last MI in the BB is an unconditional branch. Can we simply invert the1775// condition and swap destinations:1776// beq L11777// b L21778// =>1779// bne L21780// b L11781MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();1782if (BBUtils->isBBInRange(MI, NewDest, Br.MaxDisp)) {1783LLVM_DEBUG(1784dbgs() << " Invert Bcc condition and swap its destination with "1785<< *BMI);1786BMI->getOperand(0).setMBB(DestBB);1787MI->getOperand(0).setMBB(NewDest);1788MI->getOperand(1).setImm(CC);1789return true;1790}1791}1792}17931794if (NeedSplit) {1795splitBlockBeforeInstr(MI);1796// No need for the branch to the next block. We're adding an unconditional1797// branch to the destination.1798int delta = TII->getInstSizeInBytes(MBB->back());1799BBUtils->adjustBBSize(MBB, -delta);1800MBB->back().eraseFromParent();18011802// The conditional successor will be swapped between the BBs after this, so1803// update CFG.1804MBB->addSuccessor(DestBB);1805std::next(MBB->getIterator())->removeSuccessor(DestBB);18061807// BBInfo[SplitBB].Offset is wrong temporarily, fixed below1808}1809MachineBasicBlock *NextBB = &*++MBB->getIterator();18101811LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)1812<< " also invert condition and change dest. to "1813<< printMBBReference(*NextBB) << "\n");18141815// Insert a new conditional branch and a new unconditional branch.1816// Also update the ImmBranch as well as adding a new entry for the new branch.1817BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))1818.addMBB(NextBB).addImm(CC).addReg(CCReg);1819Br.MI = &MBB->back();1820BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));1821if (isThumb)1822BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))1823.addMBB(DestBB)1824.add(predOps(ARMCC::AL));1825else1826BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);1827BBUtils->adjustBBSize(MBB, TII->getInstSizeInBytes(MBB->back()));1828unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);1829ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));18301831// Remove the old conditional branch. It may or may not still be in MBB.1832BBUtils->adjustBBSize(MI->getParent(), -TII->getInstSizeInBytes(*MI));1833MI->eraseFromParent();1834BBUtils->adjustBBOffsetsAfter(MBB);1835return true;1836}18371838bool ARMConstantIslands::optimizeThumb2Instructions() {1839bool MadeChange = false;18401841// Shrink ADR and LDR from constantpool.1842for (CPUser &U : CPUsers) {1843unsigned Opcode = U.MI->getOpcode();1844unsigned NewOpc = 0;1845unsigned Scale = 1;1846unsigned Bits = 0;1847switch (Opcode) {1848default: break;1849case ARM::t2LEApcrel:1850if (isARMLowRegister(U.MI->getOperand(0).getReg())) {1851NewOpc = ARM::tLEApcrel;1852Bits = 8;1853Scale = 4;1854}1855break;1856case ARM::t2LDRpci:1857if (isARMLowRegister(U.MI->getOperand(0).getReg())) {1858NewOpc = ARM::tLDRpci;1859Bits = 8;1860Scale = 4;1861}1862break;1863}18641865if (!NewOpc)1866continue;18671868unsigned UserOffset = getUserOffset(U);1869unsigned MaxOffs = ((1 << Bits) - 1) * Scale;18701871// Be conservative with inline asm.1872if (!U.KnownAlignment)1873MaxOffs -= 2;18741875// FIXME: Check if offset is multiple of scale if scale is not 4.1876if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {1877LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);1878U.MI->setDesc(TII->get(NewOpc));1879MachineBasicBlock *MBB = U.MI->getParent();1880BBUtils->adjustBBSize(MBB, -2);1881BBUtils->adjustBBOffsetsAfter(MBB);1882++NumT2CPShrunk;1883MadeChange = true;1884}1885}18861887return MadeChange;1888}188918901891bool ARMConstantIslands::optimizeThumb2Branches() {18921893auto TryShrinkBranch = [this](ImmBranch &Br) {1894unsigned Opcode = Br.MI->getOpcode();1895unsigned NewOpc = 0;1896unsigned Scale = 1;1897unsigned Bits = 0;1898switch (Opcode) {1899default: break;1900case ARM::t2B:1901NewOpc = ARM::tB;1902Bits = 11;1903Scale = 2;1904break;1905case ARM::t2Bcc:1906NewOpc = ARM::tBcc;1907Bits = 8;1908Scale = 2;1909break;1910}1911if (NewOpc) {1912unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;1913MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();1914if (BBUtils->isBBInRange(Br.MI, DestBB, MaxOffs)) {1915LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);1916Br.MI->setDesc(TII->get(NewOpc));1917MachineBasicBlock *MBB = Br.MI->getParent();1918BBUtils->adjustBBSize(MBB, -2);1919BBUtils->adjustBBOffsetsAfter(MBB);1920++NumT2BrShrunk;1921return true;1922}1923}1924return false;1925};19261927struct ImmCompare {1928MachineInstr* MI = nullptr;1929unsigned NewOpc = 0;1930};19311932auto FindCmpForCBZ = [this](ImmBranch &Br, ImmCompare &ImmCmp,1933MachineBasicBlock *DestBB) {1934ImmCmp.MI = nullptr;1935ImmCmp.NewOpc = 0;19361937// If the conditional branch doesn't kill CPSR, then CPSR can be liveout1938// so this transformation is not safe.1939if (!Br.MI->killsRegister(ARM::CPSR, /*TRI=*/nullptr))1940return false;19411942Register PredReg;1943unsigned NewOpc = 0;1944ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);1945if (Pred == ARMCC::EQ)1946NewOpc = ARM::tCBZ;1947else if (Pred == ARMCC::NE)1948NewOpc = ARM::tCBNZ;1949else1950return false;19511952// Check if the distance is within 126. Subtract starting offset by 21953// because the cmp will be eliminated.1954unsigned BrOffset = BBUtils->getOffsetOf(Br.MI) + 4 - 2;1955BBInfoVector &BBInfo = BBUtils->getBBInfo();1956unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;1957if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)1958return false;19591960// Search backwards to find a tCMPi81961auto *TRI = STI->getRegisterInfo();1962MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);1963if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)1964return false;19651966ImmCmp.MI = CmpMI;1967ImmCmp.NewOpc = NewOpc;1968return true;1969};19701971auto TryConvertToLE = [this](ImmBranch &Br, ImmCompare &Cmp) {1972if (Br.MI->getOpcode() != ARM::t2Bcc || !STI->hasLOB() ||1973STI->hasMinSize())1974return false;19751976MachineBasicBlock *MBB = Br.MI->getParent();1977MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();1978if (BBUtils->getOffsetOf(MBB) < BBUtils->getOffsetOf(DestBB) ||1979!BBUtils->isBBInRange(Br.MI, DestBB, 4094))1980return false;19811982if (!DT->dominates(DestBB, MBB))1983return false;19841985// We queried for the CBN?Z opcode based upon the 'ExitBB', the opposite1986// target of Br. So now we need to reverse the condition.1987Cmp.NewOpc = Cmp.NewOpc == ARM::tCBZ ? ARM::tCBNZ : ARM::tCBZ;19881989MachineInstrBuilder MIB = BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(),1990TII->get(ARM::t2LE));1991// Swapped a t2Bcc for a t2LE, so no need to update the size of the block.1992MIB.add(Br.MI->getOperand(0));1993Br.MI->eraseFromParent();1994Br.MI = MIB;1995++NumLEInserted;1996return true;1997};19981999bool MadeChange = false;20002001// The order in which branches appear in ImmBranches is approximately their2002// order within the function body. By visiting later branches first, we reduce2003// the distance between earlier forward branches and their targets, making it2004// more likely that the cbn?z optimization, which can only apply to forward2005// branches, will succeed.2006for (ImmBranch &Br : reverse(ImmBranches)) {2007MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();2008MachineBasicBlock *MBB = Br.MI->getParent();2009MachineBasicBlock *ExitBB = &MBB->back() == Br.MI ?2010MBB->getFallThrough() :2011MBB->back().getOperand(0).getMBB();20122013ImmCompare Cmp;2014if (FindCmpForCBZ(Br, Cmp, ExitBB) && TryConvertToLE(Br, Cmp)) {2015DestBB = ExitBB;2016MadeChange = true;2017} else {2018FindCmpForCBZ(Br, Cmp, DestBB);2019MadeChange |= TryShrinkBranch(Br);2020}20212022unsigned Opcode = Br.MI->getOpcode();2023if ((Opcode != ARM::tBcc && Opcode != ARM::t2LE) || !Cmp.NewOpc)2024continue;20252026Register Reg = Cmp.MI->getOperand(0).getReg();20272028// Check for Kill flags on Reg. If they are present remove them and set kill2029// on the new CBZ.2030auto *TRI = STI->getRegisterInfo();2031MachineBasicBlock::iterator KillMI = Br.MI;2032bool RegKilled = false;2033do {2034--KillMI;2035if (KillMI->killsRegister(Reg, TRI)) {2036KillMI->clearRegisterKills(Reg, TRI);2037RegKilled = true;2038break;2039}2040} while (KillMI != Cmp.MI);20412042// Create the new CBZ/CBNZ2043LLVM_DEBUG(dbgs() << "Fold: " << *Cmp.MI << " and: " << *Br.MI);2044MachineInstr *NewBR =2045BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(Cmp.NewOpc))2046.addReg(Reg, getKillRegState(RegKilled) |2047getRegState(Cmp.MI->getOperand(0)))2048.addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());20492050Cmp.MI->eraseFromParent();20512052if (Br.MI->getOpcode() == ARM::tBcc) {2053Br.MI->eraseFromParent();2054Br.MI = NewBR;2055BBUtils->adjustBBSize(MBB, -2);2056} else if (MBB->back().getOpcode() != ARM::t2LE) {2057// An LE has been generated, but it's not the terminator - that is an2058// unconditional branch. However, the logic has now been reversed with the2059// CBN?Z being the conditional branch and the LE being the unconditional2060// branch. So this means we can remove the redundant unconditional branch2061// at the end of the block.2062MachineInstr *LastMI = &MBB->back();2063BBUtils->adjustBBSize(MBB, -LastMI->getDesc().getSize());2064LastMI->eraseFromParent();2065}2066BBUtils->adjustBBOffsetsAfter(MBB);2067++NumCBZ;2068MadeChange = true;2069}20702071return MadeChange;2072}20732074static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,2075unsigned BaseReg) {2076if (I.getOpcode() != ARM::t2ADDrs)2077return false;20782079if (I.getOperand(0).getReg() != EntryReg)2080return false;20812082if (I.getOperand(1).getReg() != BaseReg)2083return false;20842085// FIXME: what about CC and IdxReg?2086return true;2087}20882089/// While trying to form a TBB/TBH instruction, we may (if the table2090/// doesn't immediately follow the BR_JT) need access to the start of the2091/// jump-table. We know one instruction that produces such a register; this2092/// function works out whether that definition can be preserved to the BR_JT,2093/// possibly by removing an intervening addition (which is usually needed to2094/// calculate the actual entry to jump to).2095bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,2096MachineInstr *LEAMI,2097unsigned &DeadSize,2098bool &CanDeleteLEA,2099bool &BaseRegKill) {2100if (JumpMI->getParent() != LEAMI->getParent())2101return false;21022103// Now we hope that we have at least these instructions in the basic block:2104// BaseReg = t2LEA ...2105// [...]2106// EntryReg = t2ADDrs BaseReg, ...2107// [...]2108// t2BR_JT EntryReg2109//2110// We have to be very conservative about what we recognise here though. The2111// main perturbing factors to watch out for are:2112// + Spills at any point in the chain: not direct problems but we would2113// expect a blocking Def of the spilled register so in practice what we2114// can do is limited.2115// + EntryReg == BaseReg: this is the one situation we should allow a Def2116// of BaseReg, but only if the t2ADDrs can be removed.2117// + Some instruction other than t2ADDrs computing the entry. Not seen in2118// the wild, but we should be careful.2119Register EntryReg = JumpMI->getOperand(0).getReg();2120Register BaseReg = LEAMI->getOperand(0).getReg();21212122CanDeleteLEA = true;2123BaseRegKill = false;2124MachineInstr *RemovableAdd = nullptr;2125MachineBasicBlock::iterator I(LEAMI);2126for (++I; &*I != JumpMI; ++I) {2127if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {2128RemovableAdd = &*I;2129break;2130}21312132for (const MachineOperand &MO : I->operands()) {2133if (!MO.isReg() || !MO.getReg())2134continue;2135if (MO.isDef() && MO.getReg() == BaseReg)2136return false;2137if (MO.isUse() && MO.getReg() == BaseReg) {2138BaseRegKill = BaseRegKill || MO.isKill();2139CanDeleteLEA = false;2140}2141}2142}21432144if (!RemovableAdd)2145return true;21462147// Check the add really is removable, and that nothing else in the block2148// clobbers BaseReg.2149for (++I; &*I != JumpMI; ++I) {2150for (const MachineOperand &MO : I->operands()) {2151if (!MO.isReg() || !MO.getReg())2152continue;2153if (MO.isDef() && MO.getReg() == BaseReg)2154return false;2155if (MO.isUse() && MO.getReg() == EntryReg)2156RemovableAdd = nullptr;2157}2158}21592160if (RemovableAdd) {2161RemovableAdd->eraseFromParent();2162DeadSize += isThumb2 ? 4 : 2;2163} else if (BaseReg == EntryReg) {2164// The add wasn't removable, but clobbered the base for the TBB. So we can't2165// preserve it.2166return false;2167}21682169// We reached the end of the block without seeing another definition of2170// BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be2171// used in the TBB/TBH if necessary.2172return true;2173}21742175/// Returns whether CPEMI is the first instruction in the block2176/// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,2177/// we can switch the first register to PC and usually remove the address2178/// calculation that preceded it.2179static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {2180MachineFunction::iterator MBB = JTMI->getParent()->getIterator();2181MachineFunction *MF = MBB->getParent();2182++MBB;21832184return MBB != MF->end() && !MBB->empty() && &*MBB->begin() == CPEMI;2185}21862187static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI,2188MachineInstr *JumpMI,2189unsigned &DeadSize) {2190// Remove a dead add between the LEA and JT, which used to compute EntryReg,2191// but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg2192// and is not clobbered / used.2193MachineInstr *RemovableAdd = nullptr;2194Register EntryReg = JumpMI->getOperand(0).getReg();21952196// Find the last ADD to set EntryReg2197MachineBasicBlock::iterator I(LEAMI);2198for (++I; &*I != JumpMI; ++I) {2199if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)2200RemovableAdd = &*I;2201}22022203if (!RemovableAdd)2204return;22052206// Ensure EntryReg is not clobbered or used.2207MachineBasicBlock::iterator J(RemovableAdd);2208for (++J; &*J != JumpMI; ++J) {2209for (const MachineOperand &MO : J->operands()) {2210if (!MO.isReg() || !MO.getReg())2211continue;2212if (MO.isDef() && MO.getReg() == EntryReg)2213return;2214if (MO.isUse() && MO.getReg() == EntryReg)2215return;2216}2217}22182219LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);2220RemovableAdd->eraseFromParent();2221DeadSize += 4;2222}22232224/// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller2225/// jumptables when it's possible.2226bool ARMConstantIslands::optimizeThumb2JumpTables() {2227bool MadeChange = false;22282229// FIXME: After the tables are shrunk, can we get rid some of the2230// constantpool tables?2231MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();2232if (!MJTI) return false;22332234const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();2235for (MachineInstr *MI : T2JumpTables) {2236const MCInstrDesc &MCID = MI->getDesc();2237unsigned NumOps = MCID.getNumOperands();2238unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);2239MachineOperand JTOP = MI->getOperand(JTOpIdx);2240unsigned JTI = JTOP.getIndex();2241assert(JTI < JT.size());22422243bool ByteOk = true;2244bool HalfWordOk = true;2245unsigned JTOffset = BBUtils->getOffsetOf(MI) + 4;2246const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;2247BBInfoVector &BBInfo = BBUtils->getBBInfo();2248for (MachineBasicBlock *MBB : JTBBs) {2249unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;2250// Negative offset is not ok. FIXME: We should change BB layout to make2251// sure all the branches are forward.2252if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)2253ByteOk = false;2254unsigned TBHLimit = ((1<<16)-1)*2;2255if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)2256HalfWordOk = false;2257if (!ByteOk && !HalfWordOk)2258break;2259}22602261if (!ByteOk && !HalfWordOk)2262continue;22632264CPUser &User = CPUsers[JumpTableUserIndices[JTI]];2265MachineBasicBlock *MBB = MI->getParent();2266if (!MI->getOperand(0).isKill()) // FIXME: needed now?2267continue;22682269unsigned DeadSize = 0;2270bool CanDeleteLEA = false;2271bool BaseRegKill = false;22722273unsigned IdxReg = ~0U;2274bool IdxRegKill = true;2275if (isThumb2) {2276IdxReg = MI->getOperand(1).getReg();2277IdxRegKill = MI->getOperand(1).isKill();22782279bool PreservedBaseReg =2280preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);2281if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)2282continue;2283} else {2284// We're in thumb-1 mode, so we must have something like:2285// %idx = tLSLri %idx, 22286// %base = tLEApcrelJT2287// %t = tLDRr %base, %idx2288Register BaseReg = User.MI->getOperand(0).getReg();22892290MachineBasicBlock *UserMBB = User.MI->getParent();2291MachineBasicBlock::iterator Shift = User.MI->getIterator();2292if (Shift == UserMBB->begin())2293continue;22942295Shift = prev_nodbg(Shift, UserMBB->begin());2296if (Shift->getOpcode() != ARM::tLSLri ||2297Shift->getOperand(3).getImm() != 2 ||2298!Shift->getOperand(2).isKill())2299continue;2300IdxReg = Shift->getOperand(2).getReg();2301Register ShiftedIdxReg = Shift->getOperand(0).getReg();23022303// It's important that IdxReg is live until the actual TBB/TBH. Most of2304// the range is checked later, but the LEA might still clobber it and not2305// actually get removed.2306if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))2307continue;23082309MachineInstr *Load = User.MI->getNextNode();2310if (Load->getOpcode() != ARM::tLDRr)2311continue;2312if (Load->getOperand(1).getReg() != BaseReg ||2313Load->getOperand(2).getReg() != ShiftedIdxReg ||2314!Load->getOperand(2).isKill())2315continue;23162317// If we're in PIC mode, there should be another ADD following.2318auto *TRI = STI->getRegisterInfo();23192320// %base cannot be redefined after the load as it will appear before2321// TBB/TBH like:2322// %base =2323// %base =2324// tBB %base, %idx2325if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))2326continue;23272328if (isPositionIndependentOrROPI) {2329MachineInstr *Add = Load->getNextNode();2330if (Add->getOpcode() != ARM::tADDrr ||2331Add->getOperand(2).getReg() != BaseReg ||2332Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||2333!Add->getOperand(3).isKill())2334continue;2335if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())2336continue;2337if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))2338// IdxReg gets redefined in the middle of the sequence.2339continue;2340Add->eraseFromParent();2341DeadSize += 2;2342} else {2343if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())2344continue;2345if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))2346// IdxReg gets redefined in the middle of the sequence.2347continue;2348}23492350// Now safe to delete the load and lsl. The LEA will be removed later.2351CanDeleteLEA = true;2352Shift->eraseFromParent();2353Load->eraseFromParent();2354DeadSize += 4;2355}23562357LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);2358MachineInstr *CPEMI = User.CPEMI;2359unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;2360if (!isThumb2)2361Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;23622363MachineBasicBlock::iterator MI_JT = MI;2364MachineInstr *NewJTMI =2365BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))2366.addReg(User.MI->getOperand(0).getReg(),2367getKillRegState(BaseRegKill))2368.addReg(IdxReg, getKillRegState(IdxRegKill))2369.addJumpTableIndex(JTI, JTOP.getTargetFlags())2370.addImm(CPEMI->getOperand(0).getImm());2371LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);23722373unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;2374CPEMI->setDesc(TII->get(JTOpc));23752376if (jumpTableFollowsTB(MI, User.CPEMI)) {2377NewJTMI->getOperand(0).setReg(ARM::PC);2378NewJTMI->getOperand(0).setIsKill(false);23792380if (CanDeleteLEA) {2381if (isThumb2)2382RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);23832384User.MI->eraseFromParent();2385DeadSize += isThumb2 ? 4 : 2;23862387// The LEA was eliminated, the TBB instruction becomes the only new user2388// of the jump table.2389User.MI = NewJTMI;2390User.MaxDisp = 4;2391User.NegOk = false;2392User.IsSoImm = false;2393User.KnownAlignment = false;2394} else {2395// The LEA couldn't be eliminated, so we must add another CPUser to2396// record the TBB or TBH use.2397int CPEntryIdx = JumpTableEntryIndices[JTI];2398auto &CPEs = CPEntries[CPEntryIdx];2399auto Entry =2400find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });2401++Entry->RefCount;2402CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));2403}2404}24052406unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);2407unsigned OrigSize = TII->getInstSizeInBytes(*MI);2408MI->eraseFromParent();24092410int Delta = OrigSize - NewSize + DeadSize;2411BBInfo[MBB->getNumber()].Size -= Delta;2412BBUtils->adjustBBOffsetsAfter(MBB);24132414++NumTBs;2415MadeChange = true;2416}24172418return MadeChange;2419}24202421/// reorderThumb2JumpTables - Adjust the function's block layout to ensure that2422/// jump tables always branch forwards, since that's what tbb and tbh need.2423bool ARMConstantIslands::reorderThumb2JumpTables() {2424bool MadeChange = false;24252426MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();2427if (!MJTI) return false;24282429const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();2430for (MachineInstr *MI : T2JumpTables) {2431const MCInstrDesc &MCID = MI->getDesc();2432unsigned NumOps = MCID.getNumOperands();2433unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);2434MachineOperand JTOP = MI->getOperand(JTOpIdx);2435unsigned JTI = JTOP.getIndex();2436assert(JTI < JT.size());24372438// We prefer if target blocks for the jump table come after the jump2439// instruction so we can use TB[BH]. Loop through the target blocks2440// and try to adjust them such that that's true.2441int JTNumber = MI->getParent()->getNumber();2442const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;2443for (MachineBasicBlock *MBB : JTBBs) {2444int DTNumber = MBB->getNumber();24452446if (DTNumber < JTNumber) {2447// The destination precedes the switch. Try to move the block forward2448// so we have a positive offset.2449MachineBasicBlock *NewBB =2450adjustJTTargetBlockForward(JTI, MBB, MI->getParent());2451if (NewBB)2452MJTI->ReplaceMBBInJumpTable(JTI, MBB, NewBB);2453MadeChange = true;2454}2455}2456}24572458return MadeChange;2459}24602461MachineBasicBlock *ARMConstantIslands::adjustJTTargetBlockForward(2462unsigned JTI, MachineBasicBlock *BB, MachineBasicBlock *JTBB) {2463// If the destination block is terminated by an unconditional branch,2464// try to move it; otherwise, create a new block following the jump2465// table that branches back to the actual target. This is a very simple2466// heuristic. FIXME: We can definitely improve it.2467MachineBasicBlock *TBB = nullptr, *FBB = nullptr;2468SmallVector<MachineOperand, 4> Cond;2469SmallVector<MachineOperand, 4> CondPrior;2470MachineFunction::iterator BBi = BB->getIterator();2471MachineFunction::iterator OldPrior = std::prev(BBi);2472MachineFunction::iterator OldNext = std::next(BBi);24732474// If the block terminator isn't analyzable, don't try to move the block2475bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);24762477// If the block ends in an unconditional branch, move it. The prior block2478// has to have an analyzable terminator for us to move this one. Be paranoid2479// and make sure we're not trying to move the entry block of the function.2480if (!B && Cond.empty() && BB != &MF->front() &&2481!TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {2482BB->moveAfter(JTBB);2483OldPrior->updateTerminator(BB);2484BB->updateTerminator(OldNext != MF->end() ? &*OldNext : nullptr);2485// Update numbering to account for the block being moved.2486MF->RenumberBlocks();2487++NumJTMoved;2488return nullptr;2489}24902491// Create a new MBB for the code after the jump BB.2492MachineBasicBlock *NewBB =2493MF->CreateMachineBasicBlock(JTBB->getBasicBlock());2494MachineFunction::iterator MBBI = ++JTBB->getIterator();2495MF->insert(MBBI, NewBB);24962497// Copy live-in information to new block.2498for (const MachineBasicBlock::RegisterMaskPair &RegMaskPair : BB->liveins())2499NewBB->addLiveIn(RegMaskPair);25002501// Add an unconditional branch from NewBB to BB.2502// There doesn't seem to be meaningful DebugInfo available; this doesn't2503// correspond directly to anything in the source.2504if (isThumb2)2505BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))2506.addMBB(BB)2507.add(predOps(ARMCC::AL));2508else2509BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))2510.addMBB(BB)2511.add(predOps(ARMCC::AL));25122513// Update internal data structures to account for the newly inserted MBB.2514MF->RenumberBlocks(NewBB);25152516// Update the CFG.2517NewBB->addSuccessor(BB);2518JTBB->replaceSuccessor(BB, NewBB);25192520++NumJTInserted;2521return NewBB;2522}25232524/// createARMConstantIslandPass - returns an instance of the constpool2525/// island pass.2526FunctionPass *llvm::createARMConstantIslandPass() {2527return new ARMConstantIslands();2528}25292530INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,2531false, false)253225332534