1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a pass that splits the constant pool up into 'islands'
11 // which are scattered through-out the function. This is required due to the
12 // limited pc-relative displacements that ARM has.
14 //===----------------------------------------------------------------------===//
17 #include "ARMMachineFunctionInfo.h"
18 #include "MCTargetDesc/ARMAddressingModes.h"
19 #include "Thumb2InstrInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
38 #define DEBUG_TYPE "arm-cp-islands"
40 STATISTIC(NumCPEs, "Number of constpool entries");
41 STATISTIC(NumSplit, "Number of uncond branches inserted");
42 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
43 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
44 STATISTIC(NumTBs, "Number of table branches generated");
45 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
46 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
47 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
48 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
49 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
53 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
54 cl::desc("Adjust basic block layout to better use TB[BH]"));
56 /// UnknownPadding - Return the worst case padding that could result from
57 /// unknown offset bits. This does not include alignment padding caused by
58 /// known offset bits.
60 /// @param LogAlign log2(alignment)
61 /// @param KnownBits Number of known low offset bits.
62 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
63 if (KnownBits < LogAlign)
64 return (1u << LogAlign) - (1u << KnownBits);
69 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
70 /// requires constant pool entries to be scattered among the instructions
71 /// inside a function. To do this, it completely ignores the normal LLVM
72 /// constant pool; instead, it places constants wherever it feels like with
73 /// special instructions.
75 /// The terminology used in this pass includes:
76 /// Islands - Clumps of constants placed in the function.
77 /// Water - Potential places where an island could be formed.
78 /// CPE - A constant pool entry that has been placed somewhere, which
79 /// tracks a list of users.
80 class ARMConstantIslands : public MachineFunctionPass {
81 /// BasicBlockInfo - Information about the offset and size of a single
83 struct BasicBlockInfo {
84 /// Offset - Distance from the beginning of the function to the beginning
85 /// of this basic block.
87 /// Offsets are computed assuming worst case padding before an aligned
88 /// block. This means that subtracting basic block offsets always gives a
89 /// conservative estimate of the real distance which may be smaller.
91 /// Because worst case padding is used, the computed offset of an aligned
92 /// block may not actually be aligned.
95 /// Size - Size of the basic block in bytes. If the block contains
96 /// inline assembly, this is a worst case estimate.
98 /// The size does not include any alignment padding whether from the
99 /// beginning of the block, or from an aligned jump table at the end.
102 /// KnownBits - The number of low bits in Offset that are known to be
103 /// exact. The remaining bits of Offset are an upper bound.
106 /// Unalign - When non-zero, the block contains instructions (inline asm)
107 /// of unknown size. The real size may be smaller than Size bytes by a
108 /// multiple of 1 << Unalign.
111 /// PostAlign - When non-zero, the block terminator contains a .align
112 /// directive, so the end of the block is aligned to 1 << PostAlign
116 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
119 /// Compute the number of known offset bits internally to this block.
120 /// This number should be used to predict worst case padding when
121 /// splitting the block.
122 unsigned internalKnownBits() const {
123 unsigned Bits = Unalign ? Unalign : KnownBits;
124 // If the block size isn't a multiple of the known bits, assume the
125 // worst case padding.
126 if (Size & ((1u << Bits) - 1))
127 Bits = countTrailingZeros(Size);
131 /// Compute the offset immediately following this block. If LogAlign is
132 /// specified, return the offset the successor block will get if it has
134 unsigned postOffset(unsigned LogAlign = 0) const {
135 unsigned PO = Offset + Size;
136 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
139 // Add alignment padding from the terminator.
140 return PO + UnknownPadding(LA, internalKnownBits());
143 /// Compute the number of known low bits of postOffset. If this block
144 /// contains inline asm, the number of known bits drops to the
145 /// instruction alignment. An aligned terminator may increase the number
147 /// If LogAlign is given, also consider the alignment of the next block.
148 unsigned postKnownBits(unsigned LogAlign = 0) const {
149 return std::max(std::max(unsigned(PostAlign), LogAlign),
150 internalKnownBits());
154 std::vector<BasicBlockInfo> BBInfo;
156 /// WaterList - A sorted list of basic blocks where islands could be placed
157 /// (i.e. blocks that don't fall through to the following block, due
158 /// to a return, unreachable, or unconditional branch).
159 std::vector<MachineBasicBlock*> WaterList;
161 /// NewWaterList - The subset of WaterList that was created since the
162 /// previous iteration by inserting unconditional branches.
163 SmallSet<MachineBasicBlock*, 4> NewWaterList;
165 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
167 /// CPUser - One user of a constant pool, keeping the machine instruction
168 /// pointer, the constant pool being referenced, and the max displacement
169 /// allowed from the instruction to the CP. The HighWaterMark records the
170 /// highest basic block where a new CPEntry can be placed. To ensure this
171 /// pass terminates, the CP entries are initially placed at the end of the
172 /// function and then move monotonically to lower addresses. The
173 /// exception to this rule is when the current CP entry for a particular
174 /// CPUser is out of range, but there is another CP entry for the same
175 /// constant value in range. We want to use the existing in-range CP
176 /// entry, but if it later moves out of range, the search for new water
177 /// should resume where it left off. The HighWaterMark is used to record
182 MachineBasicBlock *HighWaterMark;
189 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
190 bool neg, bool soimm)
191 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
192 KnownAlignment(false) {
193 HighWaterMark = CPEMI->getParent();
195 /// getMaxDisp - Returns the maximum displacement supported by MI.
196 /// Correct for unknown alignment.
197 /// Conservatively subtract 2 bytes to handle weird alignment effects.
198 unsigned getMaxDisp() const {
199 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2;
203 /// CPUsers - Keep track of all of the machine instructions that use various
204 /// constant pools and their max displacement.
205 std::vector<CPUser> CPUsers;
207 /// CPEntry - One per constant pool entry, keeping the machine instruction
208 /// pointer, the constpool index, and the number of CPUser's which
209 /// reference this entry.
214 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
215 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
218 /// CPEntries - Keep track of all of the constant pool entry machine
219 /// instructions. For each original constpool index (i.e. those that
220 /// existed upon entry to this pass), it keeps a vector of entries.
221 /// Original elements are cloned as we go along; the clones are
222 /// put in the vector of the original element, but have distinct CPIs.
223 std::vector<std::vector<CPEntry> > CPEntries;
225 /// ImmBranch - One per immediate branch, keeping the machine instruction
226 /// pointer, conditional or unconditional, the max displacement,
227 /// and (if isCond is true) the corresponding unconditional branch
231 unsigned MaxDisp : 31;
234 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
235 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
238 /// ImmBranches - Keep track of all the immediate branch instructions.
240 std::vector<ImmBranch> ImmBranches;
242 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
244 SmallVector<MachineInstr*, 4> PushPopMIs;
246 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
247 SmallVector<MachineInstr*, 4> T2JumpTables;
249 /// HasFarJump - True if any far jump instruction has been emitted during
250 /// the branch fix up pass.
254 MachineConstantPool *MCP;
255 const ARMBaseInstrInfo *TII;
256 const ARMSubtarget *STI;
257 ARMFunctionInfo *AFI;
263 ARMConstantIslands() : MachineFunctionPass(ID) {}
265 bool runOnMachineFunction(MachineFunction &MF) override;
267 const char *getPassName() const override {
268 return "ARM constant island placement and branch shortening pass";
272 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
273 bool BBHasFallthrough(MachineBasicBlock *MBB);
274 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
275 unsigned getCPELogAlign(const MachineInstr *CPEMI);
276 void scanFunctionJumpTables();
277 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
278 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
279 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
280 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
281 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
282 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
283 bool findAvailableWater(CPUser&U, unsigned UserOffset,
284 water_iterator &WaterIter);
285 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
286 MachineBasicBlock *&NewMBB);
287 bool handleConstantPoolUser(unsigned CPUserIndex);
288 void removeDeadCPEMI(MachineInstr *CPEMI);
289 bool removeUnusedCPEntries();
290 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
291 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
292 bool DoDump = false);
293 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
294 CPUser &U, unsigned &Growth);
295 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
296 bool fixupImmediateBr(ImmBranch &Br);
297 bool fixupConditionalBr(ImmBranch &Br);
298 bool fixupUnconditionalBr(ImmBranch &Br);
299 bool undoLRSpillRestore();
300 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
301 bool optimizeThumb2Instructions();
302 bool optimizeThumb2Branches();
303 bool reorderThumb2JumpTables();
304 bool optimizeThumb2JumpTables();
305 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
306 MachineBasicBlock *JTBB);
308 void computeBlockSize(MachineBasicBlock *MBB);
309 unsigned getOffsetOf(MachineInstr *MI) const;
310 unsigned getUserOffset(CPUser&) const;
314 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
315 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
316 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
318 return isOffsetInRange(UserOffset, TrialOffset,
319 U.getMaxDisp(), U.NegOk, U.IsSoImm);
322 char ARMConstantIslands::ID = 0;
325 /// verify - check BBOffsets, BBSizes, alignment of islands
326 void ARMConstantIslands::verify() {
328 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
330 MachineBasicBlock *MBB = MBBI;
331 unsigned MBBId = MBB->getNumber();
332 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
334 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
335 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
336 CPUser &U = CPUsers[i];
337 unsigned UserOffset = getUserOffset(U);
338 // Verify offset using the real max displacement without the safety
340 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
341 /* DoDump = */ true)) {
342 DEBUG(dbgs() << "OK\n");
345 DEBUG(dbgs() << "Out of range.\n");
348 llvm_unreachable("Constant pool entry out of range!");
353 /// print block size and offset information - debugging
354 void ARMConstantIslands::dumpBBs() {
356 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
357 const BasicBlockInfo &BBI = BBInfo[J];
358 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
359 << " kb=" << unsigned(BBI.KnownBits)
360 << " ua=" << unsigned(BBI.Unalign)
361 << " pa=" << unsigned(BBI.PostAlign)
362 << format(" size=%#x\n", BBInfo[J].Size);
367 /// createARMConstantIslandPass - returns an instance of the constpool
369 FunctionPass *llvm::createARMConstantIslandPass() {
370 return new ARMConstantIslands();
373 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
375 MCP = mf.getConstantPool();
377 DEBUG(dbgs() << "***** ARMConstantIslands: "
378 << MCP->getConstants().size() << " CP entries, aligned to "
379 << MCP->getConstantPoolAlignment() << " bytes *****\n");
381 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget());
382 TII = STI->getInstrInfo();
383 AFI = MF->getInfo<ARMFunctionInfo>();
385 isThumb = AFI->isThumbFunction();
386 isThumb1 = AFI->isThumb1OnlyFunction();
387 isThumb2 = AFI->isThumb2Function();
391 // This pass invalidates liveness information when it splits basic blocks.
392 MF->getRegInfo().invalidateLiveness();
394 // Renumber all of the machine basic blocks in the function, guaranteeing that
395 // the numbers agree with the position of the block in the function.
396 MF->RenumberBlocks();
398 // Try to reorder and otherwise adjust the block layout to make good use
399 // of the TB[BH] instructions.
400 bool MadeChange = false;
401 if (isThumb2 && AdjustJumpTableBlocks) {
402 scanFunctionJumpTables();
403 MadeChange |= reorderThumb2JumpTables();
404 // Data is out of date, so clear it. It'll be re-computed later.
405 T2JumpTables.clear();
406 // Blocks may have shifted around. Keep the numbering up to date.
407 MF->RenumberBlocks();
410 // Perform the initial placement of the constant pool entries. To start with,
411 // we put them all at the end of the function.
412 std::vector<MachineInstr*> CPEMIs;
414 doInitialPlacement(CPEMIs);
416 /// The next UID to take is the first unused one.
417 AFI->initPICLabelUId(CPEMIs.size());
419 // Do the initial scan of the function, building up information about the
420 // sizes of each block, the location of all the water, and finding all of the
421 // constant pool users.
422 initializeFunctionInfo(CPEMIs);
427 /// Remove dead constant pool entries.
428 MadeChange |= removeUnusedCPEntries();
430 // Iteratively place constant pool entries and fix up branches until there
432 unsigned NoCPIters = 0, NoBRIters = 0;
434 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
435 bool CPChange = false;
436 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
437 CPChange |= handleConstantPoolUser(i);
438 if (CPChange && ++NoCPIters > 30)
439 report_fatal_error("Constant Island pass failed to converge!");
442 // Clear NewWaterList now. If we split a block for branches, it should
443 // appear as "new water" for the next iteration of constant pool placement.
444 NewWaterList.clear();
446 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
447 bool BRChange = false;
448 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
449 BRChange |= fixupImmediateBr(ImmBranches[i]);
450 if (BRChange && ++NoBRIters > 30)
451 report_fatal_error("Branch Fix Up pass failed to converge!");
454 if (!CPChange && !BRChange)
459 // Shrink 32-bit Thumb2 branch, load, and store instructions.
460 if (isThumb2 && !STI->prefers32BitThumb())
461 MadeChange |= optimizeThumb2Instructions();
463 // After a while, this might be made debug-only, but it is not expensive.
466 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
467 // undo the spill / restore of LR if possible.
468 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
469 MadeChange |= undoLRSpillRestore();
471 // Save the mapping between original and cloned constpool entries.
472 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
473 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
474 const CPEntry & CPE = CPEntries[i][j];
475 AFI->recordCPEClone(i, CPE.CPI);
479 DEBUG(dbgs() << '\n'; dumpBBs());
487 T2JumpTables.clear();
492 /// doInitialPlacement - Perform the initial placement of the constant pool
493 /// entries. To start with, we put them all at the end of the function.
495 ARMConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
496 // Create the basic block to hold the CPE's.
497 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
500 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
501 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
503 // Mark the basic block as required by the const-pool.
504 BB->setAlignment(MaxAlign);
506 // The function needs to be as aligned as the basic blocks. The linker may
507 // move functions around based on their alignment.
508 MF->ensureAlignment(BB->getAlignment());
510 // Order the entries in BB by descending alignment. That ensures correct
511 // alignment of all entries as long as BB is sufficiently aligned. Keep
512 // track of the insertion point for each alignment. We are going to bucket
513 // sort the entries as they are created.
514 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
516 // Add all of the constants from the constant pool to the end block, use an
517 // identity mapping of CPI's to CPE's.
518 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
520 const DataLayout &TD = *MF->getTarget().getDataLayout();
521 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
522 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
523 assert(Size >= 4 && "Too small constant pool entry");
524 unsigned Align = CPs[i].getAlignment();
525 assert(isPowerOf2_32(Align) && "Invalid alignment");
526 // Verify that all constant pool entries are a multiple of their alignment.
527 // If not, we would have to pad them out so that instructions stay aligned.
528 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
530 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
531 unsigned LogAlign = Log2_32(Align);
532 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
533 MachineInstr *CPEMI =
534 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
535 .addImm(i).addConstantPoolIndex(i).addImm(Size);
536 CPEMIs.push_back(CPEMI);
538 // Ensure that future entries with higher alignment get inserted before
539 // CPEMI. This is bucket sort with iterators.
540 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
541 if (InsPoint[a] == InsAt)
544 // Add a new CPEntry, but no corresponding CPUser yet.
545 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
547 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
548 << Size << ", align = " << Align <<'\n');
553 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
554 /// into the block immediately after it.
555 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) {
556 // Get the next machine basic block in the function.
557 MachineFunction::iterator MBBI = MBB;
558 // Can't fall off end of function.
559 if (std::next(MBBI) == MBB->getParent()->end())
562 MachineBasicBlock *NextBB = std::next(MBBI);
563 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end())
566 // Try to analyze the end of the block. A potential fallthrough may already
567 // have an unconditional branch for whatever reason.
568 MachineBasicBlock *TBB, *FBB;
569 SmallVector<MachineOperand, 4> Cond;
570 bool TooDifficult = TII->AnalyzeBranch(*MBB, TBB, FBB, Cond);
571 return TooDifficult || FBB == nullptr;
574 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
575 /// look up the corresponding CPEntry.
576 ARMConstantIslands::CPEntry
577 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
578 const MachineInstr *CPEMI) {
579 std::vector<CPEntry> &CPEs = CPEntries[CPI];
580 // Number of entries per constpool index should be small, just do a
582 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
583 if (CPEs[i].CPEMI == CPEMI)
589 /// getCPELogAlign - Returns the required alignment of the constant pool entry
590 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
591 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
592 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
594 unsigned CPI = CPEMI->getOperand(1).getIndex();
595 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
596 unsigned Align = MCP->getConstants()[CPI].getAlignment();
597 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
598 return Log2_32(Align);
601 /// scanFunctionJumpTables - Do a scan of the function, building up
602 /// information about the sizes of each block and the locations of all
604 void ARMConstantIslands::scanFunctionJumpTables() {
605 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
607 MachineBasicBlock &MBB = *MBBI;
609 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
611 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
612 T2JumpTables.push_back(I);
616 /// initializeFunctionInfo - Do the initial scan of the function, building up
617 /// information about the sizes of each block, the location of all the water,
618 /// and finding all of the constant pool users.
619 void ARMConstantIslands::
620 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
622 BBInfo.resize(MF->getNumBlockIDs());
624 // First thing, compute the size of all basic blocks, and see if the function
625 // has any inline assembly in it. If so, we have to be conservative about
626 // alignment assumptions, as we don't know for sure the size of any
627 // instructions in the inline assembly.
628 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
631 // The known bits of the entry block offset are determined by the function
633 BBInfo.front().KnownBits = MF->getAlignment();
635 // Compute block offsets and known bits.
636 adjustBBOffsetsAfter(MF->begin());
638 // Now go back through the instructions and build up our data structures.
639 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
641 MachineBasicBlock &MBB = *MBBI;
643 // If this block doesn't fall through into the next MBB, then this is
644 // 'water' that a constant pool island could be placed.
645 if (!BBHasFallthrough(&MBB))
646 WaterList.push_back(&MBB);
648 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
650 if (I->isDebugValue())
653 int Opc = I->getOpcode();
661 continue; // Ignore other JT branches
663 T2JumpTables.push_back(I);
664 continue; // Does not get an entry in ImmBranches
695 // Record this immediate branch.
696 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
697 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
700 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
701 PushPopMIs.push_back(I);
703 if (Opc == ARM::CONSTPOOL_ENTRY)
706 // Scan the instructions for constant pool operands.
707 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
708 if (I->getOperand(op).isCPI()) {
709 // We found one. The addressing mode tells us the max displacement
710 // from the PC that this instruction permits.
712 // Basic size info comes from the TSFlags field.
716 bool IsSoImm = false;
720 llvm_unreachable("Unknown addressing mode for CP reference!");
722 // Taking the address of a CP entry.
724 // This takes a SoImm, which is 8 bit immediate rotated. We'll
725 // pretend the maximum offset is 255 * 4. Since each instruction
726 // 4 byte wide, this is always correct. We'll check for other
727 // displacements that fits in a SoImm as well.
733 case ARM::t2LEApcrel:
746 Bits = 12; // +-offset_12
752 Scale = 4; // +(offset_8*4)
758 Scale = 4; // +-(offset_8*4)
763 // Remember that this is a user of a CP entry.
764 unsigned CPI = I->getOperand(op).getIndex();
765 MachineInstr *CPEMI = CPEMIs[CPI];
766 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
767 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
769 // Increment corresponding CPEntry reference count.
770 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
771 assert(CPE && "Cannot find a corresponding CPEntry!");
774 // Instructions can only use one CP entry, don't bother scanning the
775 // rest of the operands.
782 /// computeBlockSize - Compute the size and some alignment information for MBB.
783 /// This function updates BBInfo directly.
784 void ARMConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
785 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
790 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
792 BBI.Size += TII->GetInstSizeInBytes(I);
793 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
794 // The actual size may be smaller, but still a multiple of the instr size.
795 if (I->isInlineAsm())
796 BBI.Unalign = isThumb ? 1 : 2;
797 // Also consider instructions that may be shrunk later.
798 else if (isThumb && mayOptimizeThumb2Instruction(I))
802 // tBR_JTr contains a .align 2 directive.
803 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
805 MBB->getParent()->ensureAlignment(2);
809 /// getOffsetOf - Return the current offset of the specified machine instruction
810 /// from the start of the function. This offset changes as stuff is moved
811 /// around inside the function.
812 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
813 MachineBasicBlock *MBB = MI->getParent();
815 // The offset is composed of two things: the sum of the sizes of all MBB's
816 // before this instruction's block, and the offset from the start of the block
818 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
820 // Sum instructions before MI in MBB.
821 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
822 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
823 Offset += TII->GetInstSizeInBytes(I);
828 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
830 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
831 const MachineBasicBlock *RHS) {
832 return LHS->getNumber() < RHS->getNumber();
835 /// updateForInsertedWaterBlock - When a block is newly inserted into the
836 /// machine function, it upsets all of the block numbers. Renumber the blocks
837 /// and update the arrays that parallel this numbering.
838 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
839 // Renumber the MBB's to keep them consecutive.
840 NewBB->getParent()->RenumberBlocks(NewBB);
842 // Insert an entry into BBInfo to align it properly with the (newly
843 // renumbered) block numbers.
844 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
846 // Next, update WaterList. Specifically, we need to add NewMBB as having
847 // available water after it.
849 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
851 WaterList.insert(IP, NewBB);
855 /// Split the basic block containing MI into two blocks, which are joined by
856 /// an unconditional branch. Update data structures and renumber blocks to
857 /// account for this change and returns the newly created block.
858 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
859 MachineBasicBlock *OrigBB = MI->getParent();
861 // Create a new MBB for the code after the OrigBB.
862 MachineBasicBlock *NewBB =
863 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
864 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
865 MF->insert(MBBI, NewBB);
867 // Splice the instructions starting with MI over to NewBB.
868 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
870 // Add an unconditional branch from OrigBB to NewBB.
871 // Note the new unconditional branch is not being recorded.
872 // There doesn't seem to be meaningful DebugInfo available; this doesn't
873 // correspond to anything in the source.
874 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
876 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
878 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
879 .addImm(ARMCC::AL).addReg(0);
882 // Update the CFG. All succs of OrigBB are now succs of NewBB.
883 NewBB->transferSuccessors(OrigBB);
885 // OrigBB branches to NewBB.
886 OrigBB->addSuccessor(NewBB);
888 // Update internal data structures to account for the newly inserted MBB.
889 // This is almost the same as updateForInsertedWaterBlock, except that
890 // the Water goes after OrigBB, not NewBB.
891 MF->RenumberBlocks(NewBB);
893 // Insert an entry into BBInfo to align it properly with the (newly
894 // renumbered) block numbers.
895 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
897 // Next, update WaterList. Specifically, we need to add OrigMBB as having
898 // available water after it (but not if it's already there, which happens
899 // when splitting before a conditional branch that is followed by an
900 // unconditional branch - in that case we want to insert NewBB).
902 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
904 MachineBasicBlock* WaterBB = *IP;
905 if (WaterBB == OrigBB)
906 WaterList.insert(std::next(IP), NewBB);
908 WaterList.insert(IP, OrigBB);
909 NewWaterList.insert(OrigBB);
911 // Figure out how large the OrigBB is. As the first half of the original
912 // block, it cannot contain a tablejump. The size includes
913 // the new jump we added. (It should be possible to do this without
914 // recounting everything, but it's very confusing, and this is rarely
916 computeBlockSize(OrigBB);
918 // Figure out how large the NewMBB is. As the second half of the original
919 // block, it may contain a tablejump.
920 computeBlockSize(NewBB);
922 // All BBOffsets following these blocks must be modified.
923 adjustBBOffsetsAfter(OrigBB);
928 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
929 /// displacement computation. Update U.KnownAlignment to match its current
930 /// basic block location.
931 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
932 unsigned UserOffset = getOffsetOf(U.MI);
933 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
934 unsigned KnownBits = BBI.internalKnownBits();
936 // The value read from PC is offset from the actual instruction address.
937 UserOffset += (isThumb ? 4 : 8);
939 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
940 // Make sure U.getMaxDisp() returns a constrained range.
941 U.KnownAlignment = (KnownBits >= 2);
943 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
944 // purposes of the displacement computation; compensate for that here.
945 // For unknown alignments, getMaxDisp() constrains the range instead.
946 if (isThumb && U.KnownAlignment)
952 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
953 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
954 /// constant pool entry).
955 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
956 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
957 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
958 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
959 unsigned TrialOffset, unsigned MaxDisp,
960 bool NegativeOK, bool IsSoImm) {
961 if (UserOffset <= TrialOffset) {
962 // User before the Trial.
963 if (TrialOffset - UserOffset <= MaxDisp)
965 // FIXME: Make use full range of soimm values.
966 } else if (NegativeOK) {
967 if (UserOffset - TrialOffset <= MaxDisp)
969 // FIXME: Make use full range of soimm values.
974 /// isWaterInRange - Returns true if a CPE placed after the specified
975 /// Water (a basic block) will be in range for the specific MI.
977 /// Compute how much the function will grow by inserting a CPE after Water.
978 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
979 MachineBasicBlock* Water, CPUser &U,
981 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
982 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
983 unsigned NextBlockOffset, NextBlockAlignment;
984 MachineFunction::const_iterator NextBlock = Water;
985 if (++NextBlock == MF->end()) {
986 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
987 NextBlockAlignment = 0;
989 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
990 NextBlockAlignment = NextBlock->getAlignment();
992 unsigned Size = U.CPEMI->getOperand(2).getImm();
993 unsigned CPEEnd = CPEOffset + Size;
995 // The CPE may be able to hide in the alignment padding before the next
996 // block. It may also cause more padding to be required if it is more aligned
997 // that the next block.
998 if (CPEEnd > NextBlockOffset) {
999 Growth = CPEEnd - NextBlockOffset;
1000 // Compute the padding that would go at the end of the CPE to align the next
1002 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1004 // If the CPE is to be inserted before the instruction, that will raise
1005 // the offset of the instruction. Also account for unknown alignment padding
1006 // in blocks between CPE and the user.
1007 if (CPEOffset < UserOffset)
1008 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1010 // CPE fits in existing padding.
1013 return isOffsetInRange(UserOffset, CPEOffset, U);
1016 /// isCPEntryInRange - Returns true if the distance between specific MI and
1017 /// specific ConstPool entry instruction can fit in MI's displacement field.
1018 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1019 MachineInstr *CPEMI, unsigned MaxDisp,
1020 bool NegOk, bool DoDump) {
1021 unsigned CPEOffset = getOffsetOf(CPEMI);
1025 unsigned Block = MI->getParent()->getNumber();
1026 const BasicBlockInfo &BBI = BBInfo[Block];
1027 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1028 << " max delta=" << MaxDisp
1029 << format(" insn address=%#x", UserOffset)
1030 << " in BB#" << Block << ": "
1031 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1032 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1033 int(CPEOffset-UserOffset));
1037 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1041 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1042 /// unconditionally branches to its only successor.
1043 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1044 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1047 MachineBasicBlock *Succ = *MBB->succ_begin();
1048 MachineBasicBlock *Pred = *MBB->pred_begin();
1049 MachineInstr *PredMI = &Pred->back();
1050 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1051 || PredMI->getOpcode() == ARM::t2B)
1052 return PredMI->getOperand(0).getMBB() == Succ;
1057 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1058 unsigned BBNum = BB->getNumber();
1059 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1060 // Get the offset and known bits at the end of the layout predecessor.
1061 // Include the alignment of the current block.
1062 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1063 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1064 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1066 // This is where block i begins. Stop if the offset is already correct,
1067 // and we have updated 2 blocks. This is the maximum number of blocks
1068 // changed before calling this function.
1069 if (i > BBNum + 2 &&
1070 BBInfo[i].Offset == Offset &&
1071 BBInfo[i].KnownBits == KnownBits)
1074 BBInfo[i].Offset = Offset;
1075 BBInfo[i].KnownBits = KnownBits;
1079 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1080 /// and instruction CPEMI, and decrement its refcount. If the refcount
1081 /// becomes 0 remove the entry and instruction. Returns true if we removed
1082 /// the entry, false if we didn't.
1084 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1085 MachineInstr *CPEMI) {
1086 // Find the old entry. Eliminate it if it is no longer used.
1087 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1088 assert(CPE && "Unexpected!");
1089 if (--CPE->RefCount == 0) {
1090 removeDeadCPEMI(CPEMI);
1091 CPE->CPEMI = nullptr;
1098 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1099 /// if not, see if an in-range clone of the CPE is in range, and if so,
1100 /// change the data structures so the user references the clone. Returns:
1101 /// 0 = no existing entry found
1102 /// 1 = entry found, and there were no code insertions or deletions
1103 /// 2 = entry found, and there were code insertions or deletions
1104 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1106 MachineInstr *UserMI = U.MI;
1107 MachineInstr *CPEMI = U.CPEMI;
1109 // Check to see if the CPE is already in-range.
1110 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1112 DEBUG(dbgs() << "In range\n");
1116 // No. Look for previously created clones of the CPE that are in range.
1117 unsigned CPI = CPEMI->getOperand(1).getIndex();
1118 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1119 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1120 // We already tried this one
1121 if (CPEs[i].CPEMI == CPEMI)
1123 // Removing CPEs can leave empty entries, skip
1124 if (CPEs[i].CPEMI == nullptr)
1126 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1128 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1129 << CPEs[i].CPI << "\n");
1130 // Point the CPUser node to the replacement
1131 U.CPEMI = CPEs[i].CPEMI;
1132 // Change the CPI in the instruction operand to refer to the clone.
1133 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1134 if (UserMI->getOperand(j).isCPI()) {
1135 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1138 // Adjust the refcount of the clone...
1140 // ...and the original. If we didn't remove the old entry, none of the
1141 // addresses changed, so we don't need another pass.
1142 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1148 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1149 /// the specific unconditional branch instruction.
1150 static inline unsigned getUnconditionalBrDisp(int Opc) {
1153 return ((1<<10)-1)*2;
1155 return ((1<<23)-1)*2;
1160 return ((1<<23)-1)*4;
1163 /// findAvailableWater - Look for an existing entry in the WaterList in which
1164 /// we can place the CPE referenced from U so it's within range of U's MI.
1165 /// Returns true if found, false if not. If it returns true, WaterIter
1166 /// is set to the WaterList entry. For Thumb, prefer water that will not
1167 /// introduce padding to water that will. To ensure that this pass
1168 /// terminates, the CPE location for a particular CPUser is only allowed to
1169 /// move to a lower address, so search backward from the end of the list and
1170 /// prefer the first water that is in range.
1171 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1172 water_iterator &WaterIter) {
1173 if (WaterList.empty())
1176 unsigned BestGrowth = ~0u;
1177 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1179 MachineBasicBlock* WaterBB = *IP;
1180 // Check if water is in range and is either at a lower address than the
1181 // current "high water mark" or a new water block that was created since
1182 // the previous iteration by inserting an unconditional branch. In the
1183 // latter case, we want to allow resetting the high water mark back to
1184 // this new water since we haven't seen it before. Inserting branches
1185 // should be relatively uncommon and when it does happen, we want to be
1186 // sure to take advantage of it for all the CPEs near that block, so that
1187 // we don't insert more branches than necessary.
1189 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1190 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1191 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1192 Growth < BestGrowth) {
1193 // This is the least amount of required padding seen so far.
1194 BestGrowth = Growth;
1196 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1197 << " Growth=" << Growth << '\n');
1199 // Keep looking unless it is perfect.
1200 if (BestGrowth == 0)
1206 return BestGrowth != ~0u;
1209 /// createNewWater - No existing WaterList entry will work for
1210 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1211 /// block is used if in range, and the conditional branch munged so control
1212 /// flow is correct. Otherwise the block is split to create a hole with an
1213 /// unconditional branch around it. In either case NewMBB is set to a
1214 /// block following which the new island can be inserted (the WaterList
1215 /// is not adjusted).
1216 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1217 unsigned UserOffset,
1218 MachineBasicBlock *&NewMBB) {
1219 CPUser &U = CPUsers[CPUserIndex];
1220 MachineInstr *UserMI = U.MI;
1221 MachineInstr *CPEMI = U.CPEMI;
1222 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1223 MachineBasicBlock *UserMBB = UserMI->getParent();
1224 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1226 // If the block does not end in an unconditional branch already, and if the
1227 // end of the block is within range, make new water there. (The addition
1228 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1229 // Thumb2, 2 on Thumb1.
1230 if (BBHasFallthrough(UserMBB)) {
1231 // Size of branch to insert.
1232 unsigned Delta = isThumb1 ? 2 : 4;
1233 // Compute the offset where the CPE will begin.
1234 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1236 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1237 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1238 << format(", expected CPE offset %#x\n", CPEOffset));
1239 NewMBB = std::next(MachineFunction::iterator(UserMBB));
1240 // Add an unconditional branch from UserMBB to fallthrough block. Record
1241 // it for branch lengthening; this new branch will not get out of range,
1242 // but if the preceding conditional branch is out of range, the targets
1243 // will be exchanged, and the altered branch may be out of range, so the
1244 // machinery has to know about it.
1245 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1247 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1249 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1250 .addImm(ARMCC::AL).addReg(0);
1251 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1252 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1253 MaxDisp, false, UncondBr));
1254 computeBlockSize(UserMBB);
1255 adjustBBOffsetsAfter(UserMBB);
1260 // What a big block. Find a place within the block to split it. This is a
1261 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1262 // entries are 4 bytes: if instruction I references island CPE, and
1263 // instruction I+1 references CPE', it will not work well to put CPE as far
1264 // forward as possible, since then CPE' cannot immediately follow it (that
1265 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1266 // need to create a new island. So, we make a first guess, then walk through
1267 // the instructions between the one currently being looked at and the
1268 // possible insertion point, and make sure any other instructions that
1269 // reference CPEs will be able to use the same island area; if not, we back
1270 // up the insertion point.
1272 // Try to split the block so it's fully aligned. Compute the latest split
1273 // point where we can add a 4-byte branch instruction, and then align to
1274 // LogAlign which is the largest possible alignment in the function.
1275 unsigned LogAlign = MF->getAlignment();
1276 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1277 unsigned KnownBits = UserBBI.internalKnownBits();
1278 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1279 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1280 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1283 // The 4 in the following is for the unconditional branch we'll be inserting
1284 // (allows for long branch on Thumb1). Alignment of the island is handled
1285 // inside isOffsetInRange.
1286 BaseInsertOffset -= 4;
1288 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1289 << " la=" << LogAlign
1290 << " kb=" << KnownBits
1291 << " up=" << UPad << '\n');
1293 // This could point off the end of the block if we've already got constant
1294 // pool entries following this block; only the last one is in the water list.
1295 // Back past any possible branches (allow for a conditional and a maximally
1296 // long unconditional).
1297 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1298 // Ensure BaseInsertOffset is larger than the offset of the instruction
1299 // following UserMI so that the loop which searches for the split point
1300 // iterates at least once.
1302 std::max(UserBBI.postOffset() - UPad - 8,
1303 UserOffset + TII->GetInstSizeInBytes(UserMI) + 1);
1304 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1306 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1307 CPEMI->getOperand(2).getImm();
1308 MachineBasicBlock::iterator MI = UserMI;
1310 unsigned CPUIndex = CPUserIndex+1;
1311 unsigned NumCPUsers = CPUsers.size();
1312 MachineInstr *LastIT = nullptr;
1313 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1314 Offset < BaseInsertOffset;
1315 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
1316 assert(MI != UserMBB->end() && "Fell off end of block");
1317 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1318 CPUser &U = CPUsers[CPUIndex];
1319 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1320 // Shift intertion point by one unit of alignment so it is within reach.
1321 BaseInsertOffset -= 1u << LogAlign;
1322 EndInsertOffset -= 1u << LogAlign;
1324 // This is overly conservative, as we don't account for CPEMIs being
1325 // reused within the block, but it doesn't matter much. Also assume CPEs
1326 // are added in order with alignment padding. We may eventually be able
1327 // to pack the aligned CPEs better.
1328 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1332 // Remember the last IT instruction.
1333 if (MI->getOpcode() == ARM::t2IT)
1339 // Avoid splitting an IT block.
1341 unsigned PredReg = 0;
1342 ARMCC::CondCodes CC = getITInstrPredicate(MI, PredReg);
1343 if (CC != ARMCC::AL)
1347 // We really must not split an IT block.
1348 DEBUG(unsigned PredReg;
1349 assert(!isThumb || getITInstrPredicate(MI, PredReg) == ARMCC::AL));
1351 NewMBB = splitBlockBeforeInstr(MI);
1354 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1355 /// is out-of-range. If so, pick up the constant pool value and move it some
1356 /// place in-range. Return true if we changed any addresses (thus must run
1357 /// another pass of branch lengthening), false otherwise.
1358 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1359 CPUser &U = CPUsers[CPUserIndex];
1360 MachineInstr *UserMI = U.MI;
1361 MachineInstr *CPEMI = U.CPEMI;
1362 unsigned CPI = CPEMI->getOperand(1).getIndex();
1363 unsigned Size = CPEMI->getOperand(2).getImm();
1364 // Compute this only once, it's expensive.
1365 unsigned UserOffset = getUserOffset(U);
1367 // See if the current entry is within range, or there is a clone of it
1369 int result = findInRangeCPEntry(U, UserOffset);
1370 if (result==1) return false;
1371 else if (result==2) return true;
1373 // No existing clone of this CPE is within range.
1374 // We will be generating a new clone. Get a UID for it.
1375 unsigned ID = AFI->createPICLabelUId();
1377 // Look for water where we can place this CPE.
1378 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1379 MachineBasicBlock *NewMBB;
1381 if (findAvailableWater(U, UserOffset, IP)) {
1382 DEBUG(dbgs() << "Found water in range\n");
1383 MachineBasicBlock *WaterBB = *IP;
1385 // If the original WaterList entry was "new water" on this iteration,
1386 // propagate that to the new island. This is just keeping NewWaterList
1387 // updated to match the WaterList, which will be updated below.
1388 if (NewWaterList.erase(WaterBB))
1389 NewWaterList.insert(NewIsland);
1391 // The new CPE goes before the following block (NewMBB).
1392 NewMBB = std::next(MachineFunction::iterator(WaterBB));
1396 DEBUG(dbgs() << "No water found\n");
1397 createNewWater(CPUserIndex, UserOffset, NewMBB);
1399 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1400 // called while handling branches so that the water will be seen on the
1401 // next iteration for constant pools, but in this context, we don't want
1402 // it. Check for this so it will be removed from the WaterList.
1403 // Also remove any entry from NewWaterList.
1404 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
1405 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1406 if (IP != WaterList.end())
1407 NewWaterList.erase(WaterBB);
1409 // We are adding new water. Update NewWaterList.
1410 NewWaterList.insert(NewIsland);
1413 // Remove the original WaterList entry; we want subsequent insertions in
1414 // this vicinity to go after the one we're about to insert. This
1415 // considerably reduces the number of times we have to move the same CPE
1416 // more than once and is also important to ensure the algorithm terminates.
1417 if (IP != WaterList.end())
1418 WaterList.erase(IP);
1420 // Okay, we know we can put an island before NewMBB now, do it!
1421 MF->insert(NewMBB, NewIsland);
1423 // Update internal data structures to account for the newly inserted MBB.
1424 updateForInsertedWaterBlock(NewIsland);
1426 // Decrement the old entry, and remove it if refcount becomes 0.
1427 decrementCPEReferenceCount(CPI, CPEMI);
1429 // Now that we have an island to add the CPE to, clone the original CPE and
1430 // add it to the island.
1431 U.HighWaterMark = NewIsland;
1432 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1433 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1434 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1437 // Mark the basic block as aligned as required by the const-pool entry.
1438 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1440 // Increase the size of the island block to account for the new entry.
1441 BBInfo[NewIsland->getNumber()].Size += Size;
1442 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
1444 // Finally, change the CPI in the instruction operand to be ID.
1445 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1446 if (UserMI->getOperand(i).isCPI()) {
1447 UserMI->getOperand(i).setIndex(ID);
1451 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1452 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1457 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1458 /// sizes and offsets of impacted basic blocks.
1459 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1460 MachineBasicBlock *CPEBB = CPEMI->getParent();
1461 unsigned Size = CPEMI->getOperand(2).getImm();
1462 CPEMI->eraseFromParent();
1463 BBInfo[CPEBB->getNumber()].Size -= Size;
1464 // All succeeding offsets have the current size value added in, fix this.
1465 if (CPEBB->empty()) {
1466 BBInfo[CPEBB->getNumber()].Size = 0;
1468 // This block no longer needs to be aligned.
1469 CPEBB->setAlignment(0);
1471 // Entries are sorted by descending alignment, so realign from the front.
1472 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1474 adjustBBOffsetsAfter(CPEBB);
1475 // An island has only one predecessor BB and one successor BB. Check if
1476 // this BB's predecessor jumps directly to this BB's successor. This
1477 // shouldn't happen currently.
1478 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1479 // FIXME: remove the empty blocks after all the work is done?
1482 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1484 bool ARMConstantIslands::removeUnusedCPEntries() {
1485 unsigned MadeChange = false;
1486 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1487 std::vector<CPEntry> &CPEs = CPEntries[i];
1488 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1489 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1490 removeDeadCPEMI(CPEs[j].CPEMI);
1491 CPEs[j].CPEMI = nullptr;
1499 /// isBBInRange - Returns true if the distance between specific MI and
1500 /// specific BB can fit in MI's displacement field.
1501 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1503 unsigned PCAdj = isThumb ? 4 : 8;
1504 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1505 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1507 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1508 << " from BB#" << MI->getParent()->getNumber()
1509 << " max delta=" << MaxDisp
1510 << " from " << getOffsetOf(MI) << " to " << DestOffset
1511 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1513 if (BrOffset <= DestOffset) {
1514 // Branch before the Dest.
1515 if (DestOffset-BrOffset <= MaxDisp)
1518 if (BrOffset-DestOffset <= MaxDisp)
1524 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1525 /// away to fit in its displacement field.
1526 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1527 MachineInstr *MI = Br.MI;
1528 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1530 // Check to see if the DestBB is already in-range.
1531 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1535 return fixupUnconditionalBr(Br);
1536 return fixupConditionalBr(Br);
1539 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1540 /// too far away to fit in its displacement field. If the LR register has been
1541 /// spilled in the epilogue, then we can use BL to implement a far jump.
1542 /// Otherwise, add an intermediate branch instruction to a branch.
1544 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1545 MachineInstr *MI = Br.MI;
1546 MachineBasicBlock *MBB = MI->getParent();
1548 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1550 // Use BL to implement far jump.
1551 Br.MaxDisp = (1 << 21) * 2;
1552 MI->setDesc(TII->get(ARM::tBfar));
1553 BBInfo[MBB->getNumber()].Size += 2;
1554 adjustBBOffsetsAfter(MBB);
1558 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1563 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1564 /// far away to fit in its displacement field. It is converted to an inverse
1565 /// conditional branch + an unconditional branch to the destination.
1567 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1568 MachineInstr *MI = Br.MI;
1569 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1571 // Add an unconditional branch to the destination and invert the branch
1572 // condition to jump over it:
1578 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1579 CC = ARMCC::getOppositeCondition(CC);
1580 unsigned CCReg = MI->getOperand(2).getReg();
1582 // If the branch is at the end of its MBB and that has a fall-through block,
1583 // direct the updated conditional branch to the fall-through block. Otherwise,
1584 // split the MBB before the next instruction.
1585 MachineBasicBlock *MBB = MI->getParent();
1586 MachineInstr *BMI = &MBB->back();
1587 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1591 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1592 BMI->getOpcode() == Br.UncondBr) {
1593 // Last MI in the BB is an unconditional branch. Can we simply invert the
1594 // condition and swap destinations:
1600 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1601 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1602 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1604 BMI->getOperand(0).setMBB(DestBB);
1605 MI->getOperand(0).setMBB(NewDest);
1606 MI->getOperand(1).setImm(CC);
1613 splitBlockBeforeInstr(MI);
1614 // No need for the branch to the next block. We're adding an unconditional
1615 // branch to the destination.
1616 int delta = TII->GetInstSizeInBytes(&MBB->back());
1617 BBInfo[MBB->getNumber()].Size -= delta;
1618 MBB->back().eraseFromParent();
1619 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1621 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
1623 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1624 << " also invert condition and change dest. to BB#"
1625 << NextBB->getNumber() << "\n");
1627 // Insert a new conditional branch and a new unconditional branch.
1628 // Also update the ImmBranch as well as adding a new entry for the new branch.
1629 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1630 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1631 Br.MI = &MBB->back();
1632 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1634 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1635 .addImm(ARMCC::AL).addReg(0);
1637 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1638 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1639 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1640 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1642 // Remove the old conditional branch. It may or may not still be in MBB.
1643 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1644 MI->eraseFromParent();
1645 adjustBBOffsetsAfter(MBB);
1649 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1650 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1651 /// to do this if tBfar is not used.
1652 bool ARMConstantIslands::undoLRSpillRestore() {
1653 bool MadeChange = false;
1654 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1655 MachineInstr *MI = PushPopMIs[i];
1656 // First two operands are predicates.
1657 if (MI->getOpcode() == ARM::tPOP_RET &&
1658 MI->getOperand(2).getReg() == ARM::PC &&
1659 MI->getNumExplicitOperands() == 3) {
1660 // Create the new insn and copy the predicate from the old.
1661 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1662 .addOperand(MI->getOperand(0))
1663 .addOperand(MI->getOperand(1));
1664 MI->eraseFromParent();
1671 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
1672 // below may shrink MI.
1674 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1675 switch(MI->getOpcode()) {
1676 // optimizeThumb2Instructions.
1677 case ARM::t2LEApcrel:
1679 // optimizeThumb2Branches.
1683 // optimizeThumb2JumpTables.
1690 bool ARMConstantIslands::optimizeThumb2Instructions() {
1691 bool MadeChange = false;
1693 // Shrink ADR and LDR from constantpool.
1694 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1695 CPUser &U = CPUsers[i];
1696 unsigned Opcode = U.MI->getOpcode();
1697 unsigned NewOpc = 0;
1702 case ARM::t2LEApcrel:
1703 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1704 NewOpc = ARM::tLEApcrel;
1710 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1711 NewOpc = ARM::tLDRpci;
1721 unsigned UserOffset = getUserOffset(U);
1722 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1724 // Be conservative with inline asm.
1725 if (!U.KnownAlignment)
1728 // FIXME: Check if offset is multiple of scale if scale is not 4.
1729 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1730 DEBUG(dbgs() << "Shrink: " << *U.MI);
1731 U.MI->setDesc(TII->get(NewOpc));
1732 MachineBasicBlock *MBB = U.MI->getParent();
1733 BBInfo[MBB->getNumber()].Size -= 2;
1734 adjustBBOffsetsAfter(MBB);
1740 MadeChange |= optimizeThumb2Branches();
1741 MadeChange |= optimizeThumb2JumpTables();
1745 bool ARMConstantIslands::optimizeThumb2Branches() {
1746 bool MadeChange = false;
1748 // The order in which branches appear in ImmBranches is approximately their
1749 // order within the function body. By visiting later branches first, we reduce
1750 // the distance between earlier forward branches and their targets, making it
1751 // more likely that the cbn?z optimization, which can only apply to forward
1752 // branches, will succeed.
1753 for (unsigned i = ImmBranches.size(); i != 0; --i) {
1754 ImmBranch &Br = ImmBranches[i-1];
1755 unsigned Opcode = Br.MI->getOpcode();
1756 unsigned NewOpc = 0;
1774 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1775 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1776 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1777 DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1778 Br.MI->setDesc(TII->get(NewOpc));
1779 MachineBasicBlock *MBB = Br.MI->getParent();
1780 BBInfo[MBB->getNumber()].Size -= 2;
1781 adjustBBOffsetsAfter(MBB);
1787 Opcode = Br.MI->getOpcode();
1788 if (Opcode != ARM::tBcc)
1791 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1792 // so this transformation is not safe.
1793 if (!Br.MI->killsRegister(ARM::CPSR))
1797 unsigned PredReg = 0;
1798 ARMCC::CondCodes Pred = getInstrPredicate(Br.MI, PredReg);
1799 if (Pred == ARMCC::EQ)
1801 else if (Pred == ARMCC::NE)
1802 NewOpc = ARM::tCBNZ;
1805 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1806 // Check if the distance is within 126. Subtract starting offset by 2
1807 // because the cmp will be eliminated.
1808 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1809 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1810 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1811 MachineBasicBlock::iterator CmpMI = Br.MI;
1812 if (CmpMI != Br.MI->getParent()->begin()) {
1814 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1815 unsigned Reg = CmpMI->getOperand(0).getReg();
1816 Pred = getInstrPredicate(CmpMI, PredReg);
1817 if (Pred == ARMCC::AL &&
1818 CmpMI->getOperand(1).getImm() == 0 &&
1819 isARMLowRegister(Reg)) {
1820 MachineBasicBlock *MBB = Br.MI->getParent();
1821 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1822 MachineInstr *NewBR =
1823 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1824 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1825 CmpMI->eraseFromParent();
1826 Br.MI->eraseFromParent();
1828 BBInfo[MBB->getNumber()].Size -= 2;
1829 adjustBBOffsetsAfter(MBB);
1841 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1842 /// jumptables when it's possible.
1843 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1844 bool MadeChange = false;
1846 // FIXME: After the tables are shrunk, can we get rid some of the
1847 // constantpool tables?
1848 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1849 if (!MJTI) return false;
1851 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1852 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1853 MachineInstr *MI = T2JumpTables[i];
1854 const MCInstrDesc &MCID = MI->getDesc();
1855 unsigned NumOps = MCID.getNumOperands();
1856 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1857 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1858 unsigned JTI = JTOP.getIndex();
1859 assert(JTI < JT.size());
1862 bool HalfWordOk = true;
1863 unsigned JTOffset = getOffsetOf(MI) + 4;
1864 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1865 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1866 MachineBasicBlock *MBB = JTBBs[j];
1867 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1868 // Negative offset is not ok. FIXME: We should change BB layout to make
1869 // sure all the branches are forward.
1870 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1872 unsigned TBHLimit = ((1<<16)-1)*2;
1873 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1875 if (!ByteOk && !HalfWordOk)
1879 if (ByteOk || HalfWordOk) {
1880 MachineBasicBlock *MBB = MI->getParent();
1881 unsigned BaseReg = MI->getOperand(0).getReg();
1882 bool BaseRegKill = MI->getOperand(0).isKill();
1885 unsigned IdxReg = MI->getOperand(1).getReg();
1886 bool IdxRegKill = MI->getOperand(1).isKill();
1888 // Scan backwards to find the instruction that defines the base
1889 // register. Due to post-RA scheduling, we can't count on it
1890 // immediately preceding the branch instruction.
1891 MachineBasicBlock::iterator PrevI = MI;
1892 MachineBasicBlock::iterator B = MBB->begin();
1893 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1896 // If for some reason we didn't find it, we can't do anything, so
1897 // just skip this one.
1898 if (!PrevI->definesRegister(BaseReg))
1901 MachineInstr *AddrMI = PrevI;
1903 // Examine the instruction that calculates the jumptable entry address.
1904 // Make sure it only defines the base register and kills any uses
1905 // other than the index register.
1906 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1907 const MachineOperand &MO = AddrMI->getOperand(k);
1908 if (!MO.isReg() || !MO.getReg())
1910 if (MO.isDef() && MO.getReg() != BaseReg) {
1914 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1922 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1923 // that gave us the initial base register definition.
1924 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1927 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1928 // to delete it as well.
1929 MachineInstr *LeaMI = PrevI;
1930 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1931 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1932 LeaMI->getOperand(0).getReg() != BaseReg)
1938 DEBUG(dbgs() << "Shrink JT: " << *MI << " addr: " << *AddrMI
1939 << " lea: " << *LeaMI);
1940 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1941 MachineBasicBlock::iterator MI_JT = MI;
1942 MachineInstr *NewJTMI =
1943 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
1944 .addReg(IdxReg, getKillRegState(IdxRegKill))
1945 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1946 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1947 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI);
1948 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1949 // is 2-byte aligned. For now, asm printer will fix it up.
1950 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1951 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1952 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1953 OrigSize += TII->GetInstSizeInBytes(MI);
1955 AddrMI->eraseFromParent();
1956 LeaMI->eraseFromParent();
1957 MI->eraseFromParent();
1959 int delta = OrigSize - NewSize;
1960 BBInfo[MBB->getNumber()].Size -= delta;
1961 adjustBBOffsetsAfter(MBB);
1971 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
1972 /// jump tables always branch forwards, since that's what tbb and tbh need.
1973 bool ARMConstantIslands::reorderThumb2JumpTables() {
1974 bool MadeChange = false;
1976 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1977 if (!MJTI) return false;
1979 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1980 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1981 MachineInstr *MI = T2JumpTables[i];
1982 const MCInstrDesc &MCID = MI->getDesc();
1983 unsigned NumOps = MCID.getNumOperands();
1984 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1985 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1986 unsigned JTI = JTOP.getIndex();
1987 assert(JTI < JT.size());
1989 // We prefer if target blocks for the jump table come after the jump
1990 // instruction so we can use TB[BH]. Loop through the target blocks
1991 // and try to adjust them such that that's true.
1992 int JTNumber = MI->getParent()->getNumber();
1993 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1994 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1995 MachineBasicBlock *MBB = JTBBs[j];
1996 int DTNumber = MBB->getNumber();
1998 if (DTNumber < JTNumber) {
1999 // The destination precedes the switch. Try to move the block forward
2000 // so we have a positive offset.
2001 MachineBasicBlock *NewBB =
2002 adjustJTTargetBlockForward(MBB, MI->getParent());
2004 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2013 MachineBasicBlock *ARMConstantIslands::
2014 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2015 // If the destination block is terminated by an unconditional branch,
2016 // try to move it; otherwise, create a new block following the jump
2017 // table that branches back to the actual target. This is a very simple
2018 // heuristic. FIXME: We can definitely improve it.
2019 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2020 SmallVector<MachineOperand, 4> Cond;
2021 SmallVector<MachineOperand, 4> CondPrior;
2022 MachineFunction::iterator BBi = BB;
2023 MachineFunction::iterator OldPrior = std::prev(BBi);
2025 // If the block terminator isn't analyzable, don't try to move the block
2026 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2028 // If the block ends in an unconditional branch, move it. The prior block
2029 // has to have an analyzable terminator for us to move this one. Be paranoid
2030 // and make sure we're not trying to move the entry block of the function.
2031 if (!B && Cond.empty() && BB != MF->begin() &&
2032 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2033 BB->moveAfter(JTBB);
2034 OldPrior->updateTerminator();
2035 BB->updateTerminator();
2036 // Update numbering to account for the block being moved.
2037 MF->RenumberBlocks();
2042 // Create a new MBB for the code after the jump BB.
2043 MachineBasicBlock *NewBB =
2044 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2045 MachineFunction::iterator MBBI = JTBB; ++MBBI;
2046 MF->insert(MBBI, NewBB);
2048 // Add an unconditional branch from NewBB to BB.
2049 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2050 // correspond directly to anything in the source.
2051 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2052 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2053 .addImm(ARMCC::AL).addReg(0);
2055 // Update internal data structures to account for the newly inserted MBB.
2056 MF->RenumberBlocks(NewBB);
2059 NewBB->addSuccessor(BB);
2060 JTBB->removeSuccessor(BB);
2061 JTBB->addSuccessor(NewBB);