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 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "arm-cp-islands"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "Thumb2InstrInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/CommandLine.h"
39 STATISTIC(NumCPEs, "Number of constpool entries");
40 STATISTIC(NumSplit, "Number of uncond branches inserted");
41 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
42 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
43 STATISTIC(NumTBs, "Number of table branches generated");
44 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
45 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
46 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
47 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
48 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
52 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
53 cl::desc("Adjust basic block layout to better use TB[BH]"));
55 // FIXME: This option should be removed once it has received sufficient testing.
57 AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
58 cl::desc("Align constant islands in code"));
60 /// UnknownPadding - Return the worst case padding that could result from
61 /// unknown offset bits. This does not include alignment padding caused by
62 /// known offset bits.
64 /// @param LogAlign log2(alignment)
65 /// @param KnownBits Number of known low offset bits.
66 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
67 if (KnownBits < LogAlign)
68 return (1u << LogAlign) - (1u << KnownBits);
72 /// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
73 /// add padding such that:
75 /// 1. The result is aligned to 1 << LogAlign.
77 /// 2. No other value of the unknown bits would require more padding.
79 /// This may add more padding than is required to satisfy just one of the
80 /// constraints. It is necessary to compute alignment this way to guarantee
81 /// that we don't underestimate the padding before an aligned block. If the
82 /// real padding before a block is larger than we think, constant pool entries
83 /// may go out of range.
84 static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
86 // Add the worst possible padding that the unknown bits could cause.
87 Offset += UnknownPadding(LogAlign, KnownBits);
89 // Then align the result.
90 return RoundUpToAlignment(Offset, 1u << LogAlign);
94 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
95 /// requires constant pool entries to be scattered among the instructions
96 /// inside a function. To do this, it completely ignores the normal LLVM
97 /// constant pool; instead, it places constants wherever it feels like with
98 /// special instructions.
100 /// The terminology used in this pass includes:
101 /// Islands - Clumps of constants placed in the function.
102 /// Water - Potential places where an island could be formed.
103 /// CPE - A constant pool entry that has been placed somewhere, which
104 /// tracks a list of users.
105 class ARMConstantIslands : public MachineFunctionPass {
106 /// BasicBlockInfo - Information about the offset and size of a single
108 struct BasicBlockInfo {
109 /// Offset - Distance from the beginning of the function to the beginning
110 /// of this basic block.
112 /// The offset is always aligned as required by the basic block.
115 /// Size - Size of the basic block in bytes. If the block contains
116 /// inline assembly, this is a worst case estimate.
118 /// The size does not include any alignment padding whether from the
119 /// beginning of the block, or from an aligned jump table at the end.
122 /// KnownBits - The number of low bits in Offset that are known to be
123 /// exact. The remaining bits of Offset are an upper bound.
126 /// Unalign - When non-zero, the block contains instructions (inline asm)
127 /// of unknown size. The real size may be smaller than Size bytes by a
128 /// multiple of 1 << Unalign.
131 /// PostAlign - When non-zero, the block terminator contains a .align
132 /// directive, so the end of the block is aligned to 1 << PostAlign
136 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
139 /// Compute the number of known offset bits internally to this block.
140 /// This number should be used to predict worst case padding when
141 /// splitting the block.
142 unsigned internalKnownBits() const {
143 return Unalign ? Unalign : KnownBits;
146 /// Compute the offset immediately following this block. If LogAlign is
147 /// specified, return the offset the successor block will get if it has
149 unsigned postOffset(unsigned LogAlign = 0) const {
150 unsigned PO = Offset + Size;
151 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
154 // Add alignment padding from the terminator.
155 return WorstCaseAlign(PO, LA, internalKnownBits());
158 /// Compute the number of known low bits of postOffset. If this block
159 /// contains inline asm, the number of known bits drops to the
160 /// instruction alignment. An aligned terminator may increase the number
162 /// If LogAlign is given, also consider the alignment of the next block.
163 unsigned postKnownBits(unsigned LogAlign = 0) const {
164 return std::max(std::max(unsigned(PostAlign), LogAlign),
165 internalKnownBits());
169 std::vector<BasicBlockInfo> BBInfo;
171 /// WaterList - A sorted list of basic blocks where islands could be placed
172 /// (i.e. blocks that don't fall through to the following block, due
173 /// to a return, unreachable, or unconditional branch).
174 std::vector<MachineBasicBlock*> WaterList;
176 /// NewWaterList - The subset of WaterList that was created since the
177 /// previous iteration by inserting unconditional branches.
178 SmallSet<MachineBasicBlock*, 4> NewWaterList;
180 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
182 /// CPUser - One user of a constant pool, keeping the machine instruction
183 /// pointer, the constant pool being referenced, and the max displacement
184 /// allowed from the instruction to the CP. The HighWaterMark records the
185 /// highest basic block where a new CPEntry can be placed. To ensure this
186 /// pass terminates, the CP entries are initially placed at the end of the
187 /// function and then move monotonically to lower addresses. The
188 /// exception to this rule is when the current CP entry for a particular
189 /// CPUser is out of range, but there is another CP entry for the same
190 /// constant value in range. We want to use the existing in-range CP
191 /// entry, but if it later moves out of range, the search for new water
192 /// should resume where it left off. The HighWaterMark is used to record
197 MachineBasicBlock *HighWaterMark;
204 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
205 bool neg, bool soimm)
206 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
207 KnownAlignment(false) {
208 HighWaterMark = CPEMI->getParent();
210 /// getMaxDisp - Returns the maximum displacement supported by MI.
211 /// Correct for unknown alignment.
212 unsigned getMaxDisp() const {
213 return KnownAlignment ? MaxDisp : MaxDisp - 2;
217 /// CPUsers - Keep track of all of the machine instructions that use various
218 /// constant pools and their max displacement.
219 std::vector<CPUser> CPUsers;
221 /// CPEntry - One per constant pool entry, keeping the machine instruction
222 /// pointer, the constpool index, and the number of CPUser's which
223 /// reference this entry.
228 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
229 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
232 /// CPEntries - Keep track of all of the constant pool entry machine
233 /// instructions. For each original constpool index (i.e. those that
234 /// existed upon entry to this pass), it keeps a vector of entries.
235 /// Original elements are cloned as we go along; the clones are
236 /// put in the vector of the original element, but have distinct CPIs.
237 std::vector<std::vector<CPEntry> > CPEntries;
239 /// ImmBranch - One per immediate branch, keeping the machine instruction
240 /// pointer, conditional or unconditional, the max displacement,
241 /// and (if isCond is true) the corresponding unconditional branch
245 unsigned MaxDisp : 31;
248 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
249 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
252 /// ImmBranches - Keep track of all the immediate branch instructions.
254 std::vector<ImmBranch> ImmBranches;
256 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
258 SmallVector<MachineInstr*, 4> PushPopMIs;
260 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
261 SmallVector<MachineInstr*, 4> T2JumpTables;
263 /// HasFarJump - True if any far jump instruction has been emitted during
264 /// the branch fix up pass.
268 MachineConstantPool *MCP;
269 const ARMInstrInfo *TII;
270 const ARMSubtarget *STI;
271 ARMFunctionInfo *AFI;
277 ARMConstantIslands() : MachineFunctionPass(ID) {}
279 virtual bool runOnMachineFunction(MachineFunction &MF);
281 virtual const char *getPassName() const {
282 return "ARM constant island placement and branch shortening pass";
286 void DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
287 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
288 unsigned getCPELogAlign(const MachineInstr *CPEMI);
289 void JumpTableFunctionScan();
290 void InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs);
291 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
292 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
293 void AdjustBBOffsetsAfter(MachineBasicBlock *BB);
294 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI);
295 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
296 bool LookForWater(CPUser&U, unsigned UserOffset, water_iterator &WaterIter);
297 void CreateNewWater(unsigned CPUserIndex, unsigned UserOffset,
298 MachineBasicBlock *&NewMBB);
299 bool HandleConstantPoolUser(unsigned CPUserIndex);
300 void RemoveDeadCPEMI(MachineInstr *CPEMI);
301 bool RemoveUnusedCPEntries();
302 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
303 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
304 bool DoDump = false);
305 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
306 CPUser &U, unsigned &Growth);
307 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
308 bool FixUpImmediateBr(ImmBranch &Br);
309 bool FixUpConditionalBr(ImmBranch &Br);
310 bool FixUpUnconditionalBr(ImmBranch &Br);
311 bool UndoLRSpillRestore();
312 bool mayOptimizeThumb2Instruction(const MachineInstr *MI) const;
313 bool OptimizeThumb2Instructions();
314 bool OptimizeThumb2Branches();
315 bool ReorderThumb2JumpTables();
316 bool OptimizeThumb2JumpTables();
317 MachineBasicBlock *AdjustJTTargetBlockForward(MachineBasicBlock *BB,
318 MachineBasicBlock *JTBB);
320 void ComputeBlockSize(MachineBasicBlock *MBB);
321 unsigned GetOffsetOf(MachineInstr *MI) const;
322 unsigned GetUserOffset(CPUser&) const;
326 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
327 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
328 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
330 return OffsetIsInRange(UserOffset, TrialOffset,
331 U.getMaxDisp(), U.NegOk, U.IsSoImm);
334 char ARMConstantIslands::ID = 0;
337 /// verify - check BBOffsets, BBSizes, alignment of islands
338 void ARMConstantIslands::verify() {
340 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
342 MachineBasicBlock *MBB = MBBI;
343 unsigned Align = MBB->getAlignment();
344 unsigned MBBId = MBB->getNumber();
345 assert(BBInfo[MBBId].Offset % (1u << Align) == 0);
346 assert(!MBBId || BBInfo[MBBId - 1].postOffset() <= BBInfo[MBBId].Offset);
348 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
349 CPUser &U = CPUsers[i];
350 unsigned UserOffset = GetUserOffset(U);
351 assert(CPEIsInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp(), U.NegOk) &&
352 "Constant pool entry out of range!");
357 /// print block size and offset information - debugging
358 void ARMConstantIslands::dumpBBs() {
360 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
361 const BasicBlockInfo &BBI = BBInfo[J];
362 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
363 << " kb=" << unsigned(BBI.KnownBits)
364 << " ua=" << unsigned(BBI.Unalign)
365 << " pa=" << unsigned(BBI.PostAlign)
366 << format(" size=%#x\n", BBInfo[J].Size);
371 /// createARMConstantIslandPass - returns an instance of the constpool
373 FunctionPass *llvm::createARMConstantIslandPass() {
374 return new ARMConstantIslands();
377 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
379 MCP = mf.getConstantPool();
381 DEBUG(dbgs() << "***** ARMConstantIslands: "
382 << MCP->getConstants().size() << " CP entries, aligned to "
383 << MCP->getConstantPoolAlignment() << " bytes *****\n");
385 TII = (const ARMInstrInfo*)MF->getTarget().getInstrInfo();
386 AFI = MF->getInfo<ARMFunctionInfo>();
387 STI = &MF->getTarget().getSubtarget<ARMSubtarget>();
389 isThumb = AFI->isThumbFunction();
390 isThumb1 = AFI->isThumb1OnlyFunction();
391 isThumb2 = AFI->isThumb2Function();
395 // Renumber all of the machine basic blocks in the function, guaranteeing that
396 // the numbers agree with the position of the block in the function.
397 MF->RenumberBlocks();
399 // Try to reorder and otherwise adjust the block layout to make good use
400 // of the TB[BH] instructions.
401 bool MadeChange = false;
402 if (isThumb2 && AdjustJumpTableBlocks) {
403 JumpTableFunctionScan();
404 MadeChange |= ReorderThumb2JumpTables();
405 // Data is out of date, so clear it. It'll be re-computed later.
406 T2JumpTables.clear();
407 // Blocks may have shifted around. Keep the numbering up to date.
408 MF->RenumberBlocks();
411 // Thumb1 functions containing constant pools get 4-byte alignment.
412 // This is so we can keep exact track of where the alignment padding goes.
414 // ARM and Thumb2 functions need to be 4-byte aligned.
416 MF->EnsureAlignment(2); // 2 = log2(4)
418 // Perform the initial placement of the constant pool entries. To start with,
419 // we put them all at the end of the function.
420 std::vector<MachineInstr*> CPEMIs;
422 DoInitialPlacement(CPEMIs);
424 /// The next UID to take is the first unused one.
425 AFI->initPICLabelUId(CPEMIs.size());
427 // Do the initial scan of the function, building up information about the
428 // sizes of each block, the location of all the water, and finding all of the
429 // constant pool users.
430 InitialFunctionScan(CPEMIs);
435 /// Remove dead constant pool entries.
436 MadeChange |= RemoveUnusedCPEntries();
438 // Iteratively place constant pool entries and fix up branches until there
440 unsigned NoCPIters = 0, NoBRIters = 0;
442 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
443 bool CPChange = false;
444 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
445 CPChange |= HandleConstantPoolUser(i);
446 if (CPChange && ++NoCPIters > 30)
447 report_fatal_error("Constant Island pass failed to converge!");
450 // Clear NewWaterList now. If we split a block for branches, it should
451 // appear as "new water" for the next iteration of constant pool placement.
452 NewWaterList.clear();
454 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
455 bool BRChange = false;
456 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
457 BRChange |= FixUpImmediateBr(ImmBranches[i]);
458 if (BRChange && ++NoBRIters > 30)
459 report_fatal_error("Branch Fix Up pass failed to converge!");
462 if (!CPChange && !BRChange)
467 // Shrink 32-bit Thumb2 branch, load, and store instructions.
468 if (isThumb2 && !STI->prefers32BitThumb())
469 MadeChange |= OptimizeThumb2Instructions();
471 // After a while, this might be made debug-only, but it is not expensive.
474 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
475 // undo the spill / restore of LR if possible.
476 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump())
477 MadeChange |= UndoLRSpillRestore();
479 // Save the mapping between original and cloned constpool entries.
480 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
481 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) {
482 const CPEntry & CPE = CPEntries[i][j];
483 AFI->recordCPEClone(i, CPE.CPI);
487 DEBUG(dbgs() << '\n'; dumpBBs());
495 T2JumpTables.clear();
500 /// DoInitialPlacement - Perform the initial placement of the constant pool
501 /// entries. To start with, we put them all at the end of the function.
503 ARMConstantIslands::DoInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
504 // Create the basic block to hold the CPE's.
505 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
508 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
509 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
511 // Mark the basic block as required by the const-pool.
512 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
513 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
515 // The function needs to be as aligned as the basic blocks. The linker may
516 // move functions around based on their alignment.
517 MF->EnsureAlignment(BB->getAlignment());
519 // Order the entries in BB by descending alignment. That ensures correct
520 // alignment of all entries as long as BB is sufficiently aligned. Keep
521 // track of the insertion point for each alignment. We are going to bucket
522 // sort the entries as they are created.
523 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
525 // Add all of the constants from the constant pool to the end block, use an
526 // identity mapping of CPI's to CPE's.
527 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
529 const TargetData &TD = *MF->getTarget().getTargetData();
530 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
531 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
532 assert(Size >= 4 && "Too small constant pool entry");
533 unsigned Align = CPs[i].getAlignment();
534 assert(isPowerOf2_32(Align) && "Invalid alignment");
535 // Verify that all constant pool entries are a multiple of their alignment.
536 // If not, we would have to pad them out so that instructions stay aligned.
537 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
539 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
540 unsigned LogAlign = Log2_32(Align);
541 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
542 MachineInstr *CPEMI =
543 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
544 .addImm(i).addConstantPoolIndex(i).addImm(Size);
545 CPEMIs.push_back(CPEMI);
547 // Ensure that future entries with higher alignment get inserted before
548 // CPEMI. This is bucket sort with iterators.
549 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
550 if (InsPoint[a] == InsAt)
553 // Add a new CPEntry, but no corresponding CPUser yet.
554 std::vector<CPEntry> CPEs;
555 CPEs.push_back(CPEntry(CPEMI, i));
556 CPEntries.push_back(CPEs);
558 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
559 << Size << ", align = " << Align <<'\n');
564 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
565 /// into the block immediately after it.
566 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
567 // Get the next machine basic block in the function.
568 MachineFunction::iterator MBBI = MBB;
569 // Can't fall off end of function.
570 if (llvm::next(MBBI) == MBB->getParent()->end())
573 MachineBasicBlock *NextBB = llvm::next(MBBI);
574 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
575 E = MBB->succ_end(); I != E; ++I)
582 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
583 /// look up the corresponding CPEntry.
584 ARMConstantIslands::CPEntry
585 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
586 const MachineInstr *CPEMI) {
587 std::vector<CPEntry> &CPEs = CPEntries[CPI];
588 // Number of entries per constpool index should be small, just do a
590 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
591 if (CPEs[i].CPEMI == CPEMI)
597 /// getCPELogAlign - Returns the required alignment of the constant pool entry
598 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
599 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
600 assert(CPEMI && CPEMI->getOpcode() == ARM::CONSTPOOL_ENTRY);
602 // Everything is 4-byte aligned unless AlignConstantIslands is set.
603 if (!AlignConstantIslands)
606 unsigned CPI = CPEMI->getOperand(1).getIndex();
607 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
608 unsigned Align = MCP->getConstants()[CPI].getAlignment();
609 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
610 return Log2_32(Align);
613 /// JumpTableFunctionScan - Do a scan of the function, building up
614 /// information about the sizes of each block and the locations of all
616 void ARMConstantIslands::JumpTableFunctionScan() {
617 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
619 MachineBasicBlock &MBB = *MBBI;
621 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
623 if (I->isBranch() && I->getOpcode() == ARM::t2BR_JT)
624 T2JumpTables.push_back(I);
628 /// InitialFunctionScan - Do the initial scan of the function, building up
629 /// information about the sizes of each block, the location of all the water,
630 /// and finding all of the constant pool users.
631 void ARMConstantIslands::
632 InitialFunctionScan(const std::vector<MachineInstr*> &CPEMIs) {
634 BBInfo.resize(MF->getNumBlockIDs());
636 // First thing, compute the size of all basic blocks, and see if the function
637 // has any inline assembly in it. If so, we have to be conservative about
638 // alignment assumptions, as we don't know for sure the size of any
639 // instructions in the inline assembly.
640 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
643 // The known bits of the entry block offset are determined by the function
645 BBInfo.front().KnownBits = MF->getAlignment();
647 // Compute block offsets and known bits.
648 AdjustBBOffsetsAfter(MF->begin());
650 // Now go back through the instructions and build up our data structures.
651 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
653 MachineBasicBlock &MBB = *MBBI;
655 // If this block doesn't fall through into the next MBB, then this is
656 // 'water' that a constant pool island could be placed.
657 if (!BBHasFallthrough(&MBB))
658 WaterList.push_back(&MBB);
660 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
662 if (I->isDebugValue())
665 int Opc = I->getOpcode();
673 continue; // Ignore other JT branches
675 T2JumpTables.push_back(I);
676 continue; // Does not get an entry in ImmBranches
707 // Record this immediate branch.
708 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
709 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
712 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
713 PushPopMIs.push_back(I);
715 if (Opc == ARM::CONSTPOOL_ENTRY)
718 // Scan the instructions for constant pool operands.
719 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
720 if (I->getOperand(op).isCPI()) {
721 // We found one. The addressing mode tells us the max displacement
722 // from the PC that this instruction permits.
724 // Basic size info comes from the TSFlags field.
728 bool IsSoImm = false;
732 llvm_unreachable("Unknown addressing mode for CP reference!");
734 // Taking the address of a CP entry.
736 // This takes a SoImm, which is 8 bit immediate rotated. We'll
737 // pretend the maximum offset is 255 * 4. Since each instruction
738 // 4 byte wide, this is always correct. We'll check for other
739 // displacements that fits in a SoImm as well.
745 case ARM::t2LEApcrel:
757 Bits = 12; // +-offset_12
763 Scale = 4; // +(offset_8*4)
769 Scale = 4; // +-(offset_8*4)
774 // Remember that this is a user of a CP entry.
775 unsigned CPI = I->getOperand(op).getIndex();
776 MachineInstr *CPEMI = CPEMIs[CPI];
777 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
778 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk, IsSoImm));
780 // Increment corresponding CPEntry reference count.
781 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
782 assert(CPE && "Cannot find a corresponding CPEntry!");
785 // Instructions can only use one CP entry, don't bother scanning the
786 // rest of the operands.
793 /// ComputeBlockSize - Compute the size and some alignment information for MBB.
794 /// This function updates BBInfo directly.
795 void ARMConstantIslands::ComputeBlockSize(MachineBasicBlock *MBB) {
796 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
801 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
803 BBI.Size += TII->GetInstSizeInBytes(I);
804 // For inline asm, GetInstSizeInBytes returns a conservative estimate.
805 // The actual size may be smaller, but still a multiple of the instr size.
806 if (I->isInlineAsm())
807 BBI.Unalign = isThumb ? 1 : 2;
808 // Also consider instructions that may be shrunk later.
809 else if (isThumb && mayOptimizeThumb2Instruction(I))
813 // tBR_JTr contains a .align 2 directive.
814 if (!MBB->empty() && MBB->back().getOpcode() == ARM::tBR_JTr) {
816 MBB->getParent()->EnsureAlignment(2);
820 /// GetOffsetOf - Return the current offset of the specified machine instruction
821 /// from the start of the function. This offset changes as stuff is moved
822 /// around inside the function.
823 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
824 MachineBasicBlock *MBB = MI->getParent();
826 // The offset is composed of two things: the sum of the sizes of all MBB's
827 // before this instruction's block, and the offset from the start of the block
829 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
831 // Sum instructions before MI in MBB.
832 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
833 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
834 if (&*I == MI) return Offset;
835 Offset += TII->GetInstSizeInBytes(I);
839 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
841 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
842 const MachineBasicBlock *RHS) {
843 return LHS->getNumber() < RHS->getNumber();
846 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
847 /// machine function, it upsets all of the block numbers. Renumber the blocks
848 /// and update the arrays that parallel this numbering.
849 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
850 // Renumber the MBB's to keep them consecutive.
851 NewBB->getParent()->RenumberBlocks(NewBB);
853 // Insert an entry into BBInfo to align it properly with the (newly
854 // renumbered) block numbers.
855 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
857 // Next, update WaterList. Specifically, we need to add NewMBB as having
858 // available water after it.
860 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
862 WaterList.insert(IP, NewBB);
866 /// Split the basic block containing MI into two blocks, which are joined by
867 /// an unconditional branch. Update data structures and renumber blocks to
868 /// account for this change and returns the newly created block.
869 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
870 MachineBasicBlock *OrigBB = MI->getParent();
872 // Create a new MBB for the code after the OrigBB.
873 MachineBasicBlock *NewBB =
874 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
875 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
876 MF->insert(MBBI, NewBB);
878 // Splice the instructions starting with MI over to NewBB.
879 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
881 // Add an unconditional branch from OrigBB to NewBB.
882 // Note the new unconditional branch is not being recorded.
883 // There doesn't seem to be meaningful DebugInfo available; this doesn't
884 // correspond to anything in the source.
885 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
887 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
889 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB)
890 .addImm(ARMCC::AL).addReg(0);
893 // Update the CFG. All succs of OrigBB are now succs of NewBB.
894 NewBB->transferSuccessors(OrigBB);
896 // OrigBB branches to NewBB.
897 OrigBB->addSuccessor(NewBB);
899 // Update internal data structures to account for the newly inserted MBB.
900 // This is almost the same as UpdateForInsertedWaterBlock, except that
901 // the Water goes after OrigBB, not NewBB.
902 MF->RenumberBlocks(NewBB);
904 // Insert an entry into BBInfo to align it properly with the (newly
905 // renumbered) block numbers.
906 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
908 // Next, update WaterList. Specifically, we need to add OrigMBB as having
909 // available water after it (but not if it's already there, which happens
910 // when splitting before a conditional branch that is followed by an
911 // unconditional branch - in that case we want to insert NewBB).
913 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
915 MachineBasicBlock* WaterBB = *IP;
916 if (WaterBB == OrigBB)
917 WaterList.insert(llvm::next(IP), NewBB);
919 WaterList.insert(IP, OrigBB);
920 NewWaterList.insert(OrigBB);
922 // Figure out how large the OrigBB is. As the first half of the original
923 // block, it cannot contain a tablejump. The size includes
924 // the new jump we added. (It should be possible to do this without
925 // recounting everything, but it's very confusing, and this is rarely
927 ComputeBlockSize(OrigBB);
929 // Figure out how large the NewMBB is. As the second half of the original
930 // block, it may contain a tablejump.
931 ComputeBlockSize(NewBB);
933 // All BBOffsets following these blocks must be modified.
934 AdjustBBOffsetsAfter(OrigBB);
939 /// GetUserOffset - Compute the offset of U.MI as seen by the hardware
940 /// displacement computation. Update U.KnownAlignment to match its current
941 /// basic block location.
942 unsigned ARMConstantIslands::GetUserOffset(CPUser &U) const {
943 unsigned UserOffset = GetOffsetOf(U.MI);
944 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
945 unsigned KnownBits = BBI.internalKnownBits();
947 // The value read from PC is offset from the actual instruction address.
948 UserOffset += (isThumb ? 4 : 8);
950 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
951 // Make sure U.getMaxDisp() returns a constrained range.
952 U.KnownAlignment = (KnownBits >= 2);
954 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
955 // purposes of the displacement computation; compensate for that here.
956 // For unknown alignments, getMaxDisp() constrains the range instead.
957 if (isThumb && U.KnownAlignment)
963 /// OffsetIsInRange - Checks whether UserOffset (the location of a constant pool
964 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
965 /// constant pool entry).
966 /// UserOffset is computed by GetUserOffset above to include PC adjustments. If
967 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
968 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
969 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
970 unsigned TrialOffset, unsigned MaxDisp,
971 bool NegativeOK, bool IsSoImm) {
972 if (UserOffset <= TrialOffset) {
973 // User before the Trial.
974 if (TrialOffset - UserOffset <= MaxDisp)
976 // FIXME: Make use full range of soimm values.
977 } else if (NegativeOK) {
978 if (UserOffset - TrialOffset <= MaxDisp)
980 // FIXME: Make use full range of soimm values.
985 /// WaterIsInRange - Returns true if a CPE placed after the specified
986 /// Water (a basic block) will be in range for the specific MI.
988 /// Compute how much the function will grow by inserting a CPE after Water.
989 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
990 MachineBasicBlock* Water, CPUser &U,
992 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
993 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
994 unsigned NextBlockOffset, NextBlockAlignment;
995 MachineFunction::const_iterator NextBlock = Water;
996 if (++NextBlock == MF->end()) {
997 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
998 NextBlockAlignment = 0;
1000 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1001 NextBlockAlignment = NextBlock->getAlignment();
1003 unsigned Size = U.CPEMI->getOperand(2).getImm();
1004 unsigned CPEEnd = CPEOffset + Size;
1006 // The CPE may be able to hide in the alignment padding before the next
1007 // block. It may also cause more padding to be required if it is more aligned
1008 // that the next block.
1009 if (CPEEnd > NextBlockOffset) {
1010 Growth = CPEEnd - NextBlockOffset;
1011 // Compute the padding that would go at the end of the CPE to align the next
1013 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
1015 // If the CPE is to be inserted before the instruction, that will raise
1016 // the offset of the instruction. Also account for unknown alignment padding
1017 // in blocks between CPE and the user.
1018 if (CPEOffset < UserOffset)
1019 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1021 // CPE fits in existing padding.
1024 return OffsetIsInRange(UserOffset, CPEOffset, U);
1027 /// CPEIsInRange - Returns true if the distance between specific MI and
1028 /// specific ConstPool entry instruction can fit in MI's displacement field.
1029 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
1030 MachineInstr *CPEMI, unsigned MaxDisp,
1031 bool NegOk, bool DoDump) {
1032 unsigned CPEOffset = GetOffsetOf(CPEMI);
1033 assert(CPEOffset % 4 == 0 && "Misaligned CPE");
1037 unsigned Block = MI->getParent()->getNumber();
1038 const BasicBlockInfo &BBI = BBInfo[Block];
1039 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1040 << " max delta=" << MaxDisp
1041 << format(" insn address=%#x", UserOffset)
1042 << " in BB#" << Block << ": "
1043 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1044 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1045 int(CPEOffset-UserOffset));
1049 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1053 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1054 /// unconditionally branches to its only successor.
1055 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1056 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1059 MachineBasicBlock *Succ = *MBB->succ_begin();
1060 MachineBasicBlock *Pred = *MBB->pred_begin();
1061 MachineInstr *PredMI = &Pred->back();
1062 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1063 || PredMI->getOpcode() == ARM::t2B)
1064 return PredMI->getOperand(0).getMBB() == Succ;
1069 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB) {
1070 unsigned BBNum = BB->getNumber();
1071 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1072 // Get the offset and known bits at the end of the layout predecessor.
1073 // Include the alignment of the current block.
1074 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1075 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1076 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1078 // This is where block i begins. Stop if the offset is already correct,
1079 // and we have updated 2 blocks. This is the maximum number of blocks
1080 // changed before calling this function.
1081 if (i > BBNum + 2 &&
1082 BBInfo[i].Offset == Offset &&
1083 BBInfo[i].KnownBits == KnownBits)
1086 BBInfo[i].Offset = Offset;
1087 BBInfo[i].KnownBits = KnownBits;
1091 /// DecrementOldEntry - find the constant pool entry with index CPI
1092 /// and instruction CPEMI, and decrement its refcount. If the refcount
1093 /// becomes 0 remove the entry and instruction. Returns true if we removed
1094 /// the entry, false if we didn't.
1096 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI) {
1097 // Find the old entry. Eliminate it if it is no longer used.
1098 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1099 assert(CPE && "Unexpected!");
1100 if (--CPE->RefCount == 0) {
1101 RemoveDeadCPEMI(CPEMI);
1109 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1110 /// if not, see if an in-range clone of the CPE is in range, and if so,
1111 /// change the data structures so the user references the clone. Returns:
1112 /// 0 = no existing entry found
1113 /// 1 = entry found, and there were no code insertions or deletions
1114 /// 2 = entry found, and there were code insertions or deletions
1115 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
1117 MachineInstr *UserMI = U.MI;
1118 MachineInstr *CPEMI = U.CPEMI;
1120 // Check to see if the CPE is already in-range.
1121 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk, true)) {
1122 DEBUG(dbgs() << "In range\n");
1126 // No. Look for previously created clones of the CPE that are in range.
1127 unsigned CPI = CPEMI->getOperand(1).getIndex();
1128 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1129 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1130 // We already tried this one
1131 if (CPEs[i].CPEMI == CPEMI)
1133 // Removing CPEs can leave empty entries, skip
1134 if (CPEs[i].CPEMI == NULL)
1136 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1138 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1139 << CPEs[i].CPI << "\n");
1140 // Point the CPUser node to the replacement
1141 U.CPEMI = CPEs[i].CPEMI;
1142 // Change the CPI in the instruction operand to refer to the clone.
1143 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1144 if (UserMI->getOperand(j).isCPI()) {
1145 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1148 // Adjust the refcount of the clone...
1150 // ...and the original. If we didn't remove the old entry, none of the
1151 // addresses changed, so we don't need another pass.
1152 return DecrementOldEntry(CPI, CPEMI) ? 2 : 1;
1158 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1159 /// the specific unconditional branch instruction.
1160 static inline unsigned getUnconditionalBrDisp(int Opc) {
1163 return ((1<<10)-1)*2;
1165 return ((1<<23)-1)*2;
1170 return ((1<<23)-1)*4;
1173 /// LookForWater - Look for an existing entry in the WaterList in which
1174 /// we can place the CPE referenced from U so it's within range of U's MI.
1175 /// Returns true if found, false if not. If it returns true, WaterIter
1176 /// is set to the WaterList entry. For Thumb, prefer water that will not
1177 /// introduce padding to water that will. To ensure that this pass
1178 /// terminates, the CPE location for a particular CPUser is only allowed to
1179 /// move to a lower address, so search backward from the end of the list and
1180 /// prefer the first water that is in range.
1181 bool ARMConstantIslands::LookForWater(CPUser &U, unsigned UserOffset,
1182 water_iterator &WaterIter) {
1183 if (WaterList.empty())
1186 unsigned BestGrowth = ~0u;
1187 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1189 MachineBasicBlock* WaterBB = *IP;
1190 // Check if water is in range and is either at a lower address than the
1191 // current "high water mark" or a new water block that was created since
1192 // the previous iteration by inserting an unconditional branch. In the
1193 // latter case, we want to allow resetting the high water mark back to
1194 // this new water since we haven't seen it before. Inserting branches
1195 // should be relatively uncommon and when it does happen, we want to be
1196 // sure to take advantage of it for all the CPEs near that block, so that
1197 // we don't insert more branches than necessary.
1199 if (WaterIsInRange(UserOffset, WaterBB, U, Growth) &&
1200 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1201 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1202 // This is the least amount of required padding seen so far.
1203 BestGrowth = Growth;
1205 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1206 << " Growth=" << Growth << '\n');
1208 // Keep looking unless it is perfect.
1209 if (BestGrowth == 0)
1215 return BestGrowth != ~0u;
1218 /// CreateNewWater - No existing WaterList entry will work for
1219 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1220 /// block is used if in range, and the conditional branch munged so control
1221 /// flow is correct. Otherwise the block is split to create a hole with an
1222 /// unconditional branch around it. In either case NewMBB is set to a
1223 /// block following which the new island can be inserted (the WaterList
1224 /// is not adjusted).
1225 void ARMConstantIslands::CreateNewWater(unsigned CPUserIndex,
1226 unsigned UserOffset,
1227 MachineBasicBlock *&NewMBB) {
1228 CPUser &U = CPUsers[CPUserIndex];
1229 MachineInstr *UserMI = U.MI;
1230 MachineInstr *CPEMI = U.CPEMI;
1231 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1232 MachineBasicBlock *UserMBB = UserMI->getParent();
1233 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1235 // If the block does not end in an unconditional branch already, and if the
1236 // end of the block is within range, make new water there. (The addition
1237 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1238 // Thumb2, 2 on Thumb1.
1239 if (BBHasFallthrough(UserMBB)) {
1240 // Size of branch to insert.
1241 unsigned Delta = isThumb1 ? 2 : 4;
1242 // End of UserBlock after adding a branch.
1243 unsigned UserBlockEnd = UserBBI.postOffset() + Delta;
1244 // Compute the offset where the CPE will begin.
1245 unsigned CPEOffset = WorstCaseAlign(UserBlockEnd, CPELogAlign,
1246 UserBBI.postKnownBits());
1248 if (OffsetIsInRange(UserOffset, CPEOffset, U)) {
1249 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1250 << format(", expected CPE offset %#x\n", CPEOffset));
1251 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1252 // Add an unconditional branch from UserMBB to fallthrough block. Record
1253 // it for branch lengthening; this new branch will not get out of range,
1254 // but if the preceding conditional branch is out of range, the targets
1255 // will be exchanged, and the altered branch may be out of range, so the
1256 // machinery has to know about it.
1257 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1259 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1261 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1262 .addImm(ARMCC::AL).addReg(0);
1263 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1264 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1265 MaxDisp, false, UncondBr));
1266 BBInfo[UserMBB->getNumber()].Size += Delta;
1267 AdjustBBOffsetsAfter(UserMBB);
1272 // What a big block. Find a place within the block to split it. This is a
1273 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1274 // entries are 4 bytes: if instruction I references island CPE, and
1275 // instruction I+1 references CPE', it will not work well to put CPE as far
1276 // forward as possible, since then CPE' cannot immediately follow it (that
1277 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1278 // need to create a new island. So, we make a first guess, then walk through
1279 // the instructions between the one currently being looked at and the
1280 // possible insertion point, and make sure any other instructions that
1281 // reference CPEs will be able to use the same island area; if not, we back
1282 // up the insertion point.
1284 // Try to split the block so it's fully aligned. Compute the latest split
1285 // point where we can add a 4-byte branch instruction, and then
1286 // WorstCaseAlign to LogAlign.
1287 unsigned LogAlign = MF->getAlignment();
1288 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1289 unsigned KnownBits = UserBBI.internalKnownBits();
1290 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1291 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1292 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1295 // Account for alignment and unknown padding.
1296 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1297 BaseInsertOffset -= UPad;
1299 // The 4 in the following is for the unconditional branch we'll be inserting
1300 // (allows for long branch on Thumb1). Alignment of the island is handled
1301 // inside OffsetIsInRange.
1302 BaseInsertOffset -= 4;
1304 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1305 << " la=" << LogAlign
1306 << " kb=" << KnownBits
1307 << " up=" << UPad << '\n');
1309 // This could point off the end of the block if we've already got constant
1310 // pool entries following this block; only the last one is in the water list.
1311 // Back past any possible branches (allow for a conditional and a maximally
1312 // long unconditional).
1313 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1314 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1316 unsigned EndInsertOffset =
1317 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1318 CPEMI->getOperand(2).getImm();
1319 MachineBasicBlock::iterator MI = UserMI;
1321 unsigned CPUIndex = CPUserIndex+1;
1322 unsigned NumCPUsers = CPUsers.size();
1323 MachineInstr *LastIT = 0;
1324 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1325 Offset < BaseInsertOffset;
1326 Offset += TII->GetInstSizeInBytes(MI),
1327 MI = llvm::next(MI)) {
1328 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1329 CPUser &U = CPUsers[CPUIndex];
1330 if (!OffsetIsInRange(Offset, EndInsertOffset, U)) {
1331 // Shift intertion point by one unit of alignment so it is within reach.
1332 BaseInsertOffset -= 1u << LogAlign;
1333 EndInsertOffset -= 1u << LogAlign;
1335 // This is overly conservative, as we don't account for CPEMIs being
1336 // reused within the block, but it doesn't matter much. Also assume CPEs
1337 // are added in order with alignment padding. We may eventually be able
1338 // to pack the aligned CPEs better.
1339 EndInsertOffset = RoundUpToAlignment(EndInsertOffset,
1340 1u << getCPELogAlign(U.CPEMI)) +
1341 U.CPEMI->getOperand(2).getImm();
1345 // Remember the last IT instruction.
1346 if (MI->getOpcode() == ARM::t2IT)
1352 // Avoid splitting an IT block.
1354 unsigned PredReg = 0;
1355 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1356 if (CC != ARMCC::AL)
1359 NewMBB = SplitBlockBeforeInstr(MI);
1362 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
1363 /// is out-of-range. If so, pick up the constant pool value and move it some
1364 /// place in-range. Return true if we changed any addresses (thus must run
1365 /// another pass of branch lengthening), false otherwise.
1366 bool ARMConstantIslands::HandleConstantPoolUser(unsigned CPUserIndex) {
1367 CPUser &U = CPUsers[CPUserIndex];
1368 MachineInstr *UserMI = U.MI;
1369 MachineInstr *CPEMI = U.CPEMI;
1370 unsigned CPI = CPEMI->getOperand(1).getIndex();
1371 unsigned Size = CPEMI->getOperand(2).getImm();
1372 // Compute this only once, it's expensive.
1373 unsigned UserOffset = GetUserOffset(U);
1375 // See if the current entry is within range, or there is a clone of it
1377 int result = LookForExistingCPEntry(U, UserOffset);
1378 if (result==1) return false;
1379 else if (result==2) return true;
1381 // No existing clone of this CPE is within range.
1382 // We will be generating a new clone. Get a UID for it.
1383 unsigned ID = AFI->createPICLabelUId();
1385 // Look for water where we can place this CPE.
1386 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1387 MachineBasicBlock *NewMBB;
1389 if (LookForWater(U, UserOffset, IP)) {
1390 DEBUG(dbgs() << "Found water in range\n");
1391 MachineBasicBlock *WaterBB = *IP;
1393 // If the original WaterList entry was "new water" on this iteration,
1394 // propagate that to the new island. This is just keeping NewWaterList
1395 // updated to match the WaterList, which will be updated below.
1396 if (NewWaterList.count(WaterBB)) {
1397 NewWaterList.erase(WaterBB);
1398 NewWaterList.insert(NewIsland);
1400 // The new CPE goes before the following block (NewMBB).
1401 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1405 DEBUG(dbgs() << "No water found\n");
1406 CreateNewWater(CPUserIndex, UserOffset, NewMBB);
1408 // SplitBlockBeforeInstr adds to WaterList, which is important when it is
1409 // called while handling branches so that the water will be seen on the
1410 // next iteration for constant pools, but in this context, we don't want
1411 // it. Check for this so it will be removed from the WaterList.
1412 // Also remove any entry from NewWaterList.
1413 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1414 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1415 if (IP != WaterList.end())
1416 NewWaterList.erase(WaterBB);
1418 // We are adding new water. Update NewWaterList.
1419 NewWaterList.insert(NewIsland);
1422 // Remove the original WaterList entry; we want subsequent insertions in
1423 // this vicinity to go after the one we're about to insert. This
1424 // considerably reduces the number of times we have to move the same CPE
1425 // more than once and is also important to ensure the algorithm terminates.
1426 if (IP != WaterList.end())
1427 WaterList.erase(IP);
1429 // Okay, we know we can put an island before NewMBB now, do it!
1430 MF->insert(NewMBB, NewIsland);
1432 // Update internal data structures to account for the newly inserted MBB.
1433 UpdateForInsertedWaterBlock(NewIsland);
1435 // Decrement the old entry, and remove it if refcount becomes 0.
1436 DecrementOldEntry(CPI, CPEMI);
1438 // Now that we have an island to add the CPE to, clone the original CPE and
1439 // add it to the island.
1440 U.HighWaterMark = NewIsland;
1441 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1442 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1443 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1446 // Mark the basic block as aligned as required by the const-pool entry.
1447 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1449 // Increase the size of the island block to account for the new entry.
1450 BBInfo[NewIsland->getNumber()].Size += Size;
1451 AdjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1453 // Finally, change the CPI in the instruction operand to be ID.
1454 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1455 if (UserMI->getOperand(i).isCPI()) {
1456 UserMI->getOperand(i).setIndex(ID);
1460 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1461 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1466 /// RemoveDeadCPEMI - Remove a dead constant pool entry instruction. Update
1467 /// sizes and offsets of impacted basic blocks.
1468 void ARMConstantIslands::RemoveDeadCPEMI(MachineInstr *CPEMI) {
1469 MachineBasicBlock *CPEBB = CPEMI->getParent();
1470 unsigned Size = CPEMI->getOperand(2).getImm();
1471 CPEMI->eraseFromParent();
1472 BBInfo[CPEBB->getNumber()].Size -= Size;
1473 // All succeeding offsets have the current size value added in, fix this.
1474 if (CPEBB->empty()) {
1475 BBInfo[CPEBB->getNumber()].Size = 0;
1477 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1478 CPEBB->setAlignment(0);
1480 // Entries are sorted by descending alignment, so realign from the front.
1481 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1483 AdjustBBOffsetsAfter(CPEBB);
1484 // An island has only one predecessor BB and one successor BB. Check if
1485 // this BB's predecessor jumps directly to this BB's successor. This
1486 // shouldn't happen currently.
1487 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1488 // FIXME: remove the empty blocks after all the work is done?
1491 /// RemoveUnusedCPEntries - Remove constant pool entries whose refcounts
1493 bool ARMConstantIslands::RemoveUnusedCPEntries() {
1494 unsigned MadeChange = false;
1495 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1496 std::vector<CPEntry> &CPEs = CPEntries[i];
1497 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1498 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1499 RemoveDeadCPEMI(CPEs[j].CPEMI);
1500 CPEs[j].CPEMI = NULL;
1508 /// BBIsInRange - Returns true if the distance between specific MI and
1509 /// specific BB can fit in MI's displacement field.
1510 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1512 unsigned PCAdj = isThumb ? 4 : 8;
1513 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
1514 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1516 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1517 << " from BB#" << MI->getParent()->getNumber()
1518 << " max delta=" << MaxDisp
1519 << " from " << GetOffsetOf(MI) << " to " << DestOffset
1520 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1522 if (BrOffset <= DestOffset) {
1523 // Branch before the Dest.
1524 if (DestOffset-BrOffset <= MaxDisp)
1527 if (BrOffset-DestOffset <= MaxDisp)
1533 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
1534 /// away to fit in its displacement field.
1535 bool ARMConstantIslands::FixUpImmediateBr(ImmBranch &Br) {
1536 MachineInstr *MI = Br.MI;
1537 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1539 // Check to see if the DestBB is already in-range.
1540 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
1544 return FixUpUnconditionalBr(Br);
1545 return FixUpConditionalBr(Br);
1548 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
1549 /// too far away to fit in its displacement field. If the LR register has been
1550 /// spilled in the epilogue, then we can use BL to implement a far jump.
1551 /// Otherwise, add an intermediate branch instruction to a branch.
1553 ARMConstantIslands::FixUpUnconditionalBr(ImmBranch &Br) {
1554 MachineInstr *MI = Br.MI;
1555 MachineBasicBlock *MBB = MI->getParent();
1557 llvm_unreachable("FixUpUnconditionalBr is Thumb1 only!");
1559 // Use BL to implement far jump.
1560 Br.MaxDisp = (1 << 21) * 2;
1561 MI->setDesc(TII->get(ARM::tBfar));
1562 BBInfo[MBB->getNumber()].Size += 2;
1563 AdjustBBOffsetsAfter(MBB);
1567 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1572 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
1573 /// far away to fit in its displacement field. It is converted to an inverse
1574 /// conditional branch + an unconditional branch to the destination.
1576 ARMConstantIslands::FixUpConditionalBr(ImmBranch &Br) {
1577 MachineInstr *MI = Br.MI;
1578 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1580 // Add an unconditional branch to the destination and invert the branch
1581 // condition to jump over it:
1587 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1588 CC = ARMCC::getOppositeCondition(CC);
1589 unsigned CCReg = MI->getOperand(2).getReg();
1591 // If the branch is at the end of its MBB and that has a fall-through block,
1592 // direct the updated conditional branch to the fall-through block. Otherwise,
1593 // split the MBB before the next instruction.
1594 MachineBasicBlock *MBB = MI->getParent();
1595 MachineInstr *BMI = &MBB->back();
1596 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1600 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1601 BMI->getOpcode() == Br.UncondBr) {
1602 // Last MI in the BB is an unconditional branch. Can we simply invert the
1603 // condition and swap destinations:
1609 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1610 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
1611 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1613 BMI->getOperand(0).setMBB(DestBB);
1614 MI->getOperand(0).setMBB(NewDest);
1615 MI->getOperand(1).setImm(CC);
1622 SplitBlockBeforeInstr(MI);
1623 // No need for the branch to the next block. We're adding an unconditional
1624 // branch to the destination.
1625 int delta = TII->GetInstSizeInBytes(&MBB->back());
1626 BBInfo[MBB->getNumber()].Size -= delta;
1627 MBB->back().eraseFromParent();
1628 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1630 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1632 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1633 << " also invert condition and change dest. to BB#"
1634 << NextBB->getNumber() << "\n");
1636 // Insert a new conditional branch and a new unconditional branch.
1637 // Also update the ImmBranch as well as adding a new entry for the new branch.
1638 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1639 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1640 Br.MI = &MBB->back();
1641 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1643 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1644 .addImm(ARMCC::AL).addReg(0);
1646 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1647 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1648 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1649 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1651 // Remove the old conditional branch. It may or may not still be in MBB.
1652 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1653 MI->eraseFromParent();
1654 AdjustBBOffsetsAfter(MBB);
1658 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1659 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1660 /// to do this if tBfar is not used.
1661 bool ARMConstantIslands::UndoLRSpillRestore() {
1662 bool MadeChange = false;
1663 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1664 MachineInstr *MI = PushPopMIs[i];
1665 // First two operands are predicates.
1666 if (MI->getOpcode() == ARM::tPOP_RET &&
1667 MI->getOperand(2).getReg() == ARM::PC &&
1668 MI->getNumExplicitOperands() == 3) {
1669 // Create the new insn and copy the predicate from the old.
1670 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1671 .addOperand(MI->getOperand(0))
1672 .addOperand(MI->getOperand(1));
1673 MI->eraseFromParent();
1680 // mayOptimizeThumb2Instruction - Returns true if OptimizeThumb2Instructions
1681 // below may shrink MI.
1683 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1684 switch(MI->getOpcode()) {
1685 // OptimizeThumb2Instructions.
1686 case ARM::t2LEApcrel:
1688 // OptimizeThumb2Branches.
1692 // OptimizeThumb2JumpTables.
1699 bool ARMConstantIslands::OptimizeThumb2Instructions() {
1700 bool MadeChange = false;
1702 // Shrink ADR and LDR from constantpool.
1703 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1704 CPUser &U = CPUsers[i];
1705 unsigned Opcode = U.MI->getOpcode();
1706 unsigned NewOpc = 0;
1711 case ARM::t2LEApcrel:
1712 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1713 NewOpc = ARM::tLEApcrel;
1719 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1720 NewOpc = ARM::tLDRpci;
1730 unsigned UserOffset = GetUserOffset(U);
1731 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1733 // Be conservative with inline asm.
1734 if (!U.KnownAlignment)
1737 // FIXME: Check if offset is multiple of scale if scale is not 4.
1738 if (CPEIsInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1739 U.MI->setDesc(TII->get(NewOpc));
1740 MachineBasicBlock *MBB = U.MI->getParent();
1741 BBInfo[MBB->getNumber()].Size -= 2;
1742 AdjustBBOffsetsAfter(MBB);
1748 MadeChange |= OptimizeThumb2Branches();
1749 MadeChange |= OptimizeThumb2JumpTables();
1753 bool ARMConstantIslands::OptimizeThumb2Branches() {
1754 bool MadeChange = false;
1756 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1757 ImmBranch &Br = ImmBranches[i];
1758 unsigned Opcode = Br.MI->getOpcode();
1759 unsigned NewOpc = 0;
1777 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1778 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1779 if (BBIsInRange(Br.MI, DestBB, MaxOffs)) {
1780 Br.MI->setDesc(TII->get(NewOpc));
1781 MachineBasicBlock *MBB = Br.MI->getParent();
1782 BBInfo[MBB->getNumber()].Size -= 2;
1783 AdjustBBOffsetsAfter(MBB);
1789 Opcode = Br.MI->getOpcode();
1790 if (Opcode != ARM::tBcc)
1793 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1794 // so this transformation is not safe.
1795 if (!Br.MI->killsRegister(ARM::CPSR))
1799 unsigned PredReg = 0;
1800 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1801 if (Pred == ARMCC::EQ)
1803 else if (Pred == ARMCC::NE)
1804 NewOpc = ARM::tCBNZ;
1807 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1808 // Check if the distance is within 126. Subtract starting offset by 2
1809 // because the cmp will be eliminated.
1810 unsigned BrOffset = GetOffsetOf(Br.MI) + 4 - 2;
1811 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1812 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1813 MachineBasicBlock::iterator CmpMI = Br.MI;
1814 if (CmpMI != Br.MI->getParent()->begin()) {
1816 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1817 unsigned Reg = CmpMI->getOperand(0).getReg();
1818 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1819 if (Pred == ARMCC::AL &&
1820 CmpMI->getOperand(1).getImm() == 0 &&
1821 isARMLowRegister(Reg)) {
1822 MachineBasicBlock *MBB = Br.MI->getParent();
1823 MachineInstr *NewBR =
1824 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1825 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1826 CmpMI->eraseFromParent();
1827 Br.MI->eraseFromParent();
1829 BBInfo[MBB->getNumber()].Size -= 2;
1830 AdjustBBOffsetsAfter(MBB);
1842 /// OptimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1843 /// jumptables when it's possible.
1844 bool ARMConstantIslands::OptimizeThumb2JumpTables() {
1845 bool MadeChange = false;
1847 // FIXME: After the tables are shrunk, can we get rid some of the
1848 // constantpool tables?
1849 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1850 if (MJTI == 0) return false;
1852 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1853 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1854 MachineInstr *MI = T2JumpTables[i];
1855 const MCInstrDesc &MCID = MI->getDesc();
1856 unsigned NumOps = MCID.getNumOperands();
1857 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1858 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1859 unsigned JTI = JTOP.getIndex();
1860 assert(JTI < JT.size());
1863 bool HalfWordOk = true;
1864 unsigned JTOffset = GetOffsetOf(MI) + 4;
1865 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1866 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1867 MachineBasicBlock *MBB = JTBBs[j];
1868 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1869 // Negative offset is not ok. FIXME: We should change BB layout to make
1870 // sure all the branches are forward.
1871 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1873 unsigned TBHLimit = ((1<<16)-1)*2;
1874 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1876 if (!ByteOk && !HalfWordOk)
1880 if (ByteOk || HalfWordOk) {
1881 MachineBasicBlock *MBB = MI->getParent();
1882 unsigned BaseReg = MI->getOperand(0).getReg();
1883 bool BaseRegKill = MI->getOperand(0).isKill();
1886 unsigned IdxReg = MI->getOperand(1).getReg();
1887 bool IdxRegKill = MI->getOperand(1).isKill();
1889 // Scan backwards to find the instruction that defines the base
1890 // register. Due to post-RA scheduling, we can't count on it
1891 // immediately preceding the branch instruction.
1892 MachineBasicBlock::iterator PrevI = MI;
1893 MachineBasicBlock::iterator B = MBB->begin();
1894 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1897 // If for some reason we didn't find it, we can't do anything, so
1898 // just skip this one.
1899 if (!PrevI->definesRegister(BaseReg))
1902 MachineInstr *AddrMI = PrevI;
1904 // Examine the instruction that calculates the jumptable entry address.
1905 // Make sure it only defines the base register and kills any uses
1906 // other than the index register.
1907 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1908 const MachineOperand &MO = AddrMI->getOperand(k);
1909 if (!MO.isReg() || !MO.getReg())
1911 if (MO.isDef() && MO.getReg() != BaseReg) {
1915 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1923 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1924 // that gave us the initial base register definition.
1925 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1928 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1929 // to delete it as well.
1930 MachineInstr *LeaMI = PrevI;
1931 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1932 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1933 LeaMI->getOperand(0).getReg() != BaseReg)
1939 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1940 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1941 .addReg(IdxReg, getKillRegState(IdxRegKill))
1942 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1943 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1944 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1945 // is 2-byte aligned. For now, asm printer will fix it up.
1946 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1947 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1948 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1949 OrigSize += TII->GetInstSizeInBytes(MI);
1951 AddrMI->eraseFromParent();
1952 LeaMI->eraseFromParent();
1953 MI->eraseFromParent();
1955 int delta = OrigSize - NewSize;
1956 BBInfo[MBB->getNumber()].Size -= delta;
1957 AdjustBBOffsetsAfter(MBB);
1967 /// ReorderThumb2JumpTables - Adjust the function's block layout to ensure that
1968 /// jump tables always branch forwards, since that's what tbb and tbh need.
1969 bool ARMConstantIslands::ReorderThumb2JumpTables() {
1970 bool MadeChange = false;
1972 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1973 if (MJTI == 0) return false;
1975 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1976 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1977 MachineInstr *MI = T2JumpTables[i];
1978 const MCInstrDesc &MCID = MI->getDesc();
1979 unsigned NumOps = MCID.getNumOperands();
1980 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1981 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1982 unsigned JTI = JTOP.getIndex();
1983 assert(JTI < JT.size());
1985 // We prefer if target blocks for the jump table come after the jump
1986 // instruction so we can use TB[BH]. Loop through the target blocks
1987 // and try to adjust them such that that's true.
1988 int JTNumber = MI->getParent()->getNumber();
1989 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1990 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1991 MachineBasicBlock *MBB = JTBBs[j];
1992 int DTNumber = MBB->getNumber();
1994 if (DTNumber < JTNumber) {
1995 // The destination precedes the switch. Try to move the block forward
1996 // so we have a positive offset.
1997 MachineBasicBlock *NewBB =
1998 AdjustJTTargetBlockForward(MBB, MI->getParent());
2000 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2009 MachineBasicBlock *ARMConstantIslands::
2010 AdjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB)
2012 // If the destination block is terminated by an unconditional branch,
2013 // try to move it; otherwise, create a new block following the jump
2014 // table that branches back to the actual target. This is a very simple
2015 // heuristic. FIXME: We can definitely improve it.
2016 MachineBasicBlock *TBB = 0, *FBB = 0;
2017 SmallVector<MachineOperand, 4> Cond;
2018 SmallVector<MachineOperand, 4> CondPrior;
2019 MachineFunction::iterator BBi = BB;
2020 MachineFunction::iterator OldPrior = prior(BBi);
2022 // If the block terminator isn't analyzable, don't try to move the block
2023 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2025 // If the block ends in an unconditional branch, move it. The prior block
2026 // has to have an analyzable terminator for us to move this one. Be paranoid
2027 // and make sure we're not trying to move the entry block of the function.
2028 if (!B && Cond.empty() && BB != MF->begin() &&
2029 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2030 BB->moveAfter(JTBB);
2031 OldPrior->updateTerminator();
2032 BB->updateTerminator();
2033 // Update numbering to account for the block being moved.
2034 MF->RenumberBlocks();
2039 // Create a new MBB for the code after the jump BB.
2040 MachineBasicBlock *NewBB =
2041 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2042 MachineFunction::iterator MBBI = JTBB; ++MBBI;
2043 MF->insert(MBBI, NewBB);
2045 // Add an unconditional branch from NewBB to BB.
2046 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2047 // correspond directly to anything in the source.
2048 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2049 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2050 .addImm(ARMCC::AL).addReg(0);
2052 // Update internal data structures to account for the newly inserted MBB.
2053 MF->RenumberBlocks(NewBB);
2056 NewBB->addSuccessor(BB);
2057 JTBB->removeSuccessor(BB);
2058 JTBB->addSuccessor(NewBB);