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 "Thumb2InstrInfo.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/Format.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
38 STATISTIC(NumCPEs, "Number of constpool entries");
39 STATISTIC(NumSplit, "Number of uncond branches inserted");
40 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
41 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
42 STATISTIC(NumTBs, "Number of table branches generated");
43 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk");
44 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk");
45 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed");
46 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved");
47 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted");
51 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
52 cl::desc("Adjust basic block layout to better use TB[BH]"));
54 // FIXME: This option should be removed once it has received sufficient testing.
56 AlignConstantIslands("arm-align-constant-islands", cl::Hidden, cl::init(true),
57 cl::desc("Align constant islands in code"));
59 /// UnknownPadding - Return the worst case padding that could result from
60 /// unknown offset bits. This does not include alignment padding caused by
61 /// known offset bits.
63 /// @param LogAlign log2(alignment)
64 /// @param KnownBits Number of known low offset bits.
65 static inline unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits) {
66 if (KnownBits < LogAlign)
67 return (1u << LogAlign) - (1u << KnownBits);
71 /// WorstCaseAlign - Assuming only the low KnownBits bits in Offset are exact,
72 /// add padding such that:
74 /// 1. The result is aligned to 1 << LogAlign.
76 /// 2. No other value of the unknown bits would require more padding.
78 /// This may add more padding than is required to satisfy just one of the
79 /// constraints. It is necessary to compute alignment this way to guarantee
80 /// that we don't underestimate the padding before an aligned block. If the
81 /// real padding before a block is larger than we think, constant pool entries
82 /// may go out of range.
83 static inline unsigned WorstCaseAlign(unsigned Offset, unsigned LogAlign,
85 // Add the worst possible padding that the unknown bits could cause.
86 Offset += UnknownPadding(LogAlign, KnownBits);
88 // Then align the result.
89 return RoundUpToAlignment(Offset, 1u << LogAlign);
93 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
94 /// requires constant pool entries to be scattered among the instructions
95 /// inside a function. To do this, it completely ignores the normal LLVM
96 /// constant pool; instead, it places constants wherever it feels like with
97 /// special instructions.
99 /// The terminology used in this pass includes:
100 /// Islands - Clumps of constants placed in the function.
101 /// Water - Potential places where an island could be formed.
102 /// CPE - A constant pool entry that has been placed somewhere, which
103 /// tracks a list of users.
104 class ARMConstantIslands : public MachineFunctionPass {
105 /// BasicBlockInfo - Information about the offset and size of a single
107 struct BasicBlockInfo {
108 /// Offset - Distance from the beginning of the function to the beginning
109 /// of this basic block.
111 /// The offset is always aligned as required by the basic block.
114 /// Size - Size of the basic block in bytes. If the block contains
115 /// inline assembly, this is a worst case estimate.
117 /// The size does not include any alignment padding whether from the
118 /// beginning of the block, or from an aligned jump table at the end.
121 /// KnownBits - The number of low bits in Offset that are known to be
122 /// exact. The remaining bits of Offset are an upper bound.
125 /// Unalign - When non-zero, the block contains instructions (inline asm)
126 /// of unknown size. The real size may be smaller than Size bytes by a
127 /// multiple of 1 << Unalign.
130 /// PostAlign - When non-zero, the block terminator contains a .align
131 /// directive, so the end of the block is aligned to 1 << PostAlign
135 BasicBlockInfo() : Offset(0), Size(0), KnownBits(0), Unalign(0),
138 /// Compute the number of known offset bits internally to this block.
139 /// This number should be used to predict worst case padding when
140 /// splitting the block.
141 unsigned internalKnownBits() const {
142 return Unalign ? Unalign : KnownBits;
145 /// Compute the offset immediately following this block. If LogAlign is
146 /// specified, return the offset the successor block will get if it has
148 unsigned postOffset(unsigned LogAlign = 0) const {
149 unsigned PO = Offset + Size;
150 unsigned LA = std::max(unsigned(PostAlign), LogAlign);
153 // Add alignment padding from the terminator.
154 return WorstCaseAlign(PO, LA, internalKnownBits());
157 /// Compute the number of known low bits of postOffset. If this block
158 /// contains inline asm, the number of known bits drops to the
159 /// instruction alignment. An aligned terminator may increase the number
161 /// If LogAlign is given, also consider the alignment of the next block.
162 unsigned postKnownBits(unsigned LogAlign = 0) const {
163 return std::max(std::max(unsigned(PostAlign), LogAlign),
164 internalKnownBits());
168 std::vector<BasicBlockInfo> BBInfo;
170 /// WaterList - A sorted list of basic blocks where islands could be placed
171 /// (i.e. blocks that don't fall through to the following block, due
172 /// to a return, unreachable, or unconditional branch).
173 std::vector<MachineBasicBlock*> WaterList;
175 /// NewWaterList - The subset of WaterList that was created since the
176 /// previous iteration by inserting unconditional branches.
177 SmallSet<MachineBasicBlock*, 4> NewWaterList;
179 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
181 /// CPUser - One user of a constant pool, keeping the machine instruction
182 /// pointer, the constant pool being referenced, and the max displacement
183 /// allowed from the instruction to the CP. The HighWaterMark records the
184 /// highest basic block where a new CPEntry can be placed. To ensure this
185 /// pass terminates, the CP entries are initially placed at the end of the
186 /// function and then move monotonically to lower addresses. The
187 /// exception to this rule is when the current CP entry for a particular
188 /// CPUser is out of range, but there is another CP entry for the same
189 /// constant value in range. We want to use the existing in-range CP
190 /// entry, but if it later moves out of range, the search for new water
191 /// should resume where it left off. The HighWaterMark is used to record
196 MachineBasicBlock *HighWaterMark;
203 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
204 bool neg, bool soimm)
205 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm),
206 KnownAlignment(false) {
207 HighWaterMark = CPEMI->getParent();
209 /// getMaxDisp - Returns the maximum displacement supported by MI.
210 /// Correct for unknown alignment.
211 unsigned getMaxDisp() const {
212 return KnownAlignment ? MaxDisp : MaxDisp - 2;
216 /// CPUsers - Keep track of all of the machine instructions that use various
217 /// constant pools and their max displacement.
218 std::vector<CPUser> CPUsers;
220 /// CPEntry - One per constant pool entry, keeping the machine instruction
221 /// pointer, the constpool index, and the number of CPUser's which
222 /// reference this entry.
227 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
228 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
231 /// CPEntries - Keep track of all of the constant pool entry machine
232 /// instructions. For each original constpool index (i.e. those that
233 /// existed upon entry to this pass), it keeps a vector of entries.
234 /// Original elements are cloned as we go along; the clones are
235 /// put in the vector of the original element, but have distinct CPIs.
236 std::vector<std::vector<CPEntry> > CPEntries;
238 /// ImmBranch - One per immediate branch, keeping the machine instruction
239 /// pointer, conditional or unconditional, the max displacement,
240 /// and (if isCond is true) the corresponding unconditional branch
244 unsigned MaxDisp : 31;
247 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
248 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
251 /// ImmBranches - Keep track of all the immediate branch instructions.
253 std::vector<ImmBranch> ImmBranches;
255 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
257 SmallVector<MachineInstr*, 4> PushPopMIs;
259 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
260 SmallVector<MachineInstr*, 4> T2JumpTables;
262 /// HasFarJump - True if any far jump instruction has been emitted during
263 /// the branch fix up pass.
267 MachineConstantPool *MCP;
268 const ARMBaseInstrInfo *TII;
269 const ARMSubtarget *STI;
270 ARMFunctionInfo *AFI;
276 ARMConstantIslands() : MachineFunctionPass(ID) {}
278 virtual bool runOnMachineFunction(MachineFunction &MF);
280 virtual const char *getPassName() const {
281 return "ARM constant island placement and branch shortening pass";
285 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
286 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
287 unsigned getCPELogAlign(const MachineInstr *CPEMI);
288 void scanFunctionJumpTables();
289 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
290 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
291 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
292 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
293 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
294 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
295 bool findAvailableWater(CPUser&U, unsigned UserOffset,
296 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 isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
303 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
304 bool DoDump = false);
305 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
306 CPUser &U, unsigned &Growth);
307 bool isBBInRange(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 isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
327 unsigned Disp, bool NegativeOK, bool IsSoImm = false);
328 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
330 return isOffsetInRange(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(isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp(),
352 U.NegOk) && "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 ARMBaseInstrInfo*)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 scanFunctionJumpTables();
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 initializeFunctionInfo(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 /// scanFunctionJumpTables - Do a scan of the function, building up
614 /// information about the sizes of each block and the locations of all
616 void ARMConstantIslands::scanFunctionJumpTables() {
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 /// initializeFunctionInfo - 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 initializeFunctionInfo(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 != MI; ++I) {
833 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
834 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 /// isOffsetInRange - 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::isOffsetInRange(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 /// isWaterInRange - 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::isWaterInRange(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 isOffsetInRange(UserOffset, CPEOffset, U);
1027 /// isCPEntryInRange - Returns true if the distance between specific MI and
1028 /// specific ConstPool entry instruction can fit in MI's displacement field.
1029 bool ARMConstantIslands::isCPEntryInRange(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 isOffsetInRange(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 /// decrementCPEReferenceCount - 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::decrementCPEReferenceCount(unsigned CPI,
1097 MachineInstr *CPEMI) {
1098 // Find the old entry. Eliminate it if it is no longer used.
1099 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1100 assert(CPE && "Unexpected!");
1101 if (--CPE->RefCount == 0) {
1102 removeDeadCPEMI(CPEMI);
1110 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1111 /// if not, see if an in-range clone of the CPE is in range, and if so,
1112 /// change the data structures so the user references the clone. Returns:
1113 /// 0 = no existing entry found
1114 /// 1 = entry found, and there were no code insertions or deletions
1115 /// 2 = entry found, and there were code insertions or deletions
1116 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1118 MachineInstr *UserMI = U.MI;
1119 MachineInstr *CPEMI = U.CPEMI;
1121 // Check to see if the CPE is already in-range.
1122 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1124 DEBUG(dbgs() << "In range\n");
1128 // No. Look for previously created clones of the CPE that are in range.
1129 unsigned CPI = CPEMI->getOperand(1).getIndex();
1130 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1131 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1132 // We already tried this one
1133 if (CPEs[i].CPEMI == CPEMI)
1135 // Removing CPEs can leave empty entries, skip
1136 if (CPEs[i].CPEMI == NULL)
1138 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1140 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1141 << CPEs[i].CPI << "\n");
1142 // Point the CPUser node to the replacement
1143 U.CPEMI = CPEs[i].CPEMI;
1144 // Change the CPI in the instruction operand to refer to the clone.
1145 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1146 if (UserMI->getOperand(j).isCPI()) {
1147 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1150 // Adjust the refcount of the clone...
1152 // ...and the original. If we didn't remove the old entry, none of the
1153 // addresses changed, so we don't need another pass.
1154 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1160 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1161 /// the specific unconditional branch instruction.
1162 static inline unsigned getUnconditionalBrDisp(int Opc) {
1165 return ((1<<10)-1)*2;
1167 return ((1<<23)-1)*2;
1172 return ((1<<23)-1)*4;
1175 /// findAvailableWater - Look for an existing entry in the WaterList in which
1176 /// we can place the CPE referenced from U so it's within range of U's MI.
1177 /// Returns true if found, false if not. If it returns true, WaterIter
1178 /// is set to the WaterList entry. For Thumb, prefer water that will not
1179 /// introduce padding to water that will. To ensure that this pass
1180 /// terminates, the CPE location for a particular CPUser is only allowed to
1181 /// move to a lower address, so search backward from the end of the list and
1182 /// prefer the first water that is in range.
1183 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1184 water_iterator &WaterIter) {
1185 if (WaterList.empty())
1188 unsigned BestGrowth = ~0u;
1189 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1191 MachineBasicBlock* WaterBB = *IP;
1192 // Check if water is in range and is either at a lower address than the
1193 // current "high water mark" or a new water block that was created since
1194 // the previous iteration by inserting an unconditional branch. In the
1195 // latter case, we want to allow resetting the high water mark back to
1196 // this new water since we haven't seen it before. Inserting branches
1197 // should be relatively uncommon and when it does happen, we want to be
1198 // sure to take advantage of it for all the CPEs near that block, so that
1199 // we don't insert more branches than necessary.
1201 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1202 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1203 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1204 // This is the least amount of required padding seen so far.
1205 BestGrowth = Growth;
1207 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1208 << " Growth=" << Growth << '\n');
1210 // Keep looking unless it is perfect.
1211 if (BestGrowth == 0)
1217 return BestGrowth != ~0u;
1220 /// createNewWater - No existing WaterList entry will work for
1221 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1222 /// block is used if in range, and the conditional branch munged so control
1223 /// flow is correct. Otherwise the block is split to create a hole with an
1224 /// unconditional branch around it. In either case NewMBB is set to a
1225 /// block following which the new island can be inserted (the WaterList
1226 /// is not adjusted).
1227 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1228 unsigned UserOffset,
1229 MachineBasicBlock *&NewMBB) {
1230 CPUser &U = CPUsers[CPUserIndex];
1231 MachineInstr *UserMI = U.MI;
1232 MachineInstr *CPEMI = U.CPEMI;
1233 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1234 MachineBasicBlock *UserMBB = UserMI->getParent();
1235 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1237 // If the block does not end in an unconditional branch already, and if the
1238 // end of the block is within range, make new water there. (The addition
1239 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1240 // Thumb2, 2 on Thumb1.
1241 if (BBHasFallthrough(UserMBB)) {
1242 // Size of branch to insert.
1243 unsigned Delta = isThumb1 ? 2 : 4;
1244 // End of UserBlock after adding a branch.
1245 unsigned UserBlockEnd = UserBBI.postOffset() + Delta;
1246 // Compute the offset where the CPE will begin.
1247 unsigned CPEOffset = WorstCaseAlign(UserBlockEnd, CPELogAlign,
1248 UserBBI.postKnownBits());
1250 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1251 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1252 << format(", expected CPE offset %#x\n", CPEOffset));
1253 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1254 // Add an unconditional branch from UserMBB to fallthrough block. Record
1255 // it for branch lengthening; this new branch will not get out of range,
1256 // but if the preceding conditional branch is out of range, the targets
1257 // will be exchanged, and the altered branch may be out of range, so the
1258 // machinery has to know about it.
1259 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1261 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1263 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB)
1264 .addImm(ARMCC::AL).addReg(0);
1265 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1266 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1267 MaxDisp, false, UncondBr));
1268 BBInfo[UserMBB->getNumber()].Size += Delta;
1269 adjustBBOffsetsAfter(UserMBB);
1274 // What a big block. Find a place within the block to split it. This is a
1275 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1276 // entries are 4 bytes: if instruction I references island CPE, and
1277 // instruction I+1 references CPE', it will not work well to put CPE as far
1278 // forward as possible, since then CPE' cannot immediately follow it (that
1279 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1280 // need to create a new island. So, we make a first guess, then walk through
1281 // the instructions between the one currently being looked at and the
1282 // possible insertion point, and make sure any other instructions that
1283 // reference CPEs will be able to use the same island area; if not, we back
1284 // up the insertion point.
1286 // Try to split the block so it's fully aligned. Compute the latest split
1287 // point where we can add a 4-byte branch instruction, and then
1288 // WorstCaseAlign to LogAlign.
1289 unsigned LogAlign = MF->getAlignment();
1290 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1291 unsigned KnownBits = UserBBI.internalKnownBits();
1292 unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1293 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1294 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1297 // Account for alignment and unknown padding.
1298 BaseInsertOffset &= ~((1u << LogAlign) - 1);
1299 BaseInsertOffset -= UPad;
1301 // The 4 in the following is for the unconditional branch we'll be inserting
1302 // (allows for long branch on Thumb1). Alignment of the island is handled
1303 // inside isOffsetInRange.
1304 BaseInsertOffset -= 4;
1306 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1307 << " la=" << LogAlign
1308 << " kb=" << KnownBits
1309 << " up=" << UPad << '\n');
1311 // This could point off the end of the block if we've already got constant
1312 // pool entries following this block; only the last one is in the water list.
1313 // Back past any possible branches (allow for a conditional and a maximally
1314 // long unconditional).
1315 if (BaseInsertOffset >= BBInfo[UserMBB->getNumber()+1].Offset)
1316 BaseInsertOffset = BBInfo[UserMBB->getNumber()+1].Offset -
1318 unsigned EndInsertOffset =
1319 WorstCaseAlign(BaseInsertOffset + 4, LogAlign, KnownBits) +
1320 CPEMI->getOperand(2).getImm();
1321 MachineBasicBlock::iterator MI = UserMI;
1323 unsigned CPUIndex = CPUserIndex+1;
1324 unsigned NumCPUsers = CPUsers.size();
1325 MachineInstr *LastIT = 0;
1326 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1327 Offset < BaseInsertOffset;
1328 Offset += TII->GetInstSizeInBytes(MI),
1329 MI = llvm::next(MI)) {
1330 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1331 CPUser &U = CPUsers[CPUIndex];
1332 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1333 // Shift intertion point by one unit of alignment so it is within reach.
1334 BaseInsertOffset -= 1u << LogAlign;
1335 EndInsertOffset -= 1u << LogAlign;
1337 // This is overly conservative, as we don't account for CPEMIs being
1338 // reused within the block, but it doesn't matter much. Also assume CPEs
1339 // are added in order with alignment padding. We may eventually be able
1340 // to pack the aligned CPEs better.
1341 EndInsertOffset = RoundUpToAlignment(EndInsertOffset,
1342 1u << getCPELogAlign(U.CPEMI)) +
1343 U.CPEMI->getOperand(2).getImm();
1347 // Remember the last IT instruction.
1348 if (MI->getOpcode() == ARM::t2IT)
1354 // Avoid splitting an IT block.
1356 unsigned PredReg = 0;
1357 ARMCC::CondCodes CC = llvm::getITInstrPredicate(MI, PredReg);
1358 if (CC != ARMCC::AL)
1361 NewMBB = splitBlockBeforeInstr(MI);
1364 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1365 /// is out-of-range. If so, pick up the constant pool value and move it some
1366 /// place in-range. Return true if we changed any addresses (thus must run
1367 /// another pass of branch lengthening), false otherwise.
1368 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1369 CPUser &U = CPUsers[CPUserIndex];
1370 MachineInstr *UserMI = U.MI;
1371 MachineInstr *CPEMI = U.CPEMI;
1372 unsigned CPI = CPEMI->getOperand(1).getIndex();
1373 unsigned Size = CPEMI->getOperand(2).getImm();
1374 // Compute this only once, it's expensive.
1375 unsigned UserOffset = getUserOffset(U);
1377 // See if the current entry is within range, or there is a clone of it
1379 int result = findInRangeCPEntry(U, UserOffset);
1380 if (result==1) return false;
1381 else if (result==2) return true;
1383 // No existing clone of this CPE is within range.
1384 // We will be generating a new clone. Get a UID for it.
1385 unsigned ID = AFI->createPICLabelUId();
1387 // Look for water where we can place this CPE.
1388 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1389 MachineBasicBlock *NewMBB;
1391 if (findAvailableWater(U, UserOffset, IP)) {
1392 DEBUG(dbgs() << "Found water in range\n");
1393 MachineBasicBlock *WaterBB = *IP;
1395 // If the original WaterList entry was "new water" on this iteration,
1396 // propagate that to the new island. This is just keeping NewWaterList
1397 // updated to match the WaterList, which will be updated below.
1398 if (NewWaterList.count(WaterBB)) {
1399 NewWaterList.erase(WaterBB);
1400 NewWaterList.insert(NewIsland);
1402 // The new CPE goes before the following block (NewMBB).
1403 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1407 DEBUG(dbgs() << "No water found\n");
1408 createNewWater(CPUserIndex, UserOffset, NewMBB);
1410 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1411 // called while handling branches so that the water will be seen on the
1412 // next iteration for constant pools, but in this context, we don't want
1413 // it. Check for this so it will be removed from the WaterList.
1414 // Also remove any entry from NewWaterList.
1415 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1416 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1417 if (IP != WaterList.end())
1418 NewWaterList.erase(WaterBB);
1420 // We are adding new water. Update NewWaterList.
1421 NewWaterList.insert(NewIsland);
1424 // Remove the original WaterList entry; we want subsequent insertions in
1425 // this vicinity to go after the one we're about to insert. This
1426 // considerably reduces the number of times we have to move the same CPE
1427 // more than once and is also important to ensure the algorithm terminates.
1428 if (IP != WaterList.end())
1429 WaterList.erase(IP);
1431 // Okay, we know we can put an island before NewMBB now, do it!
1432 MF->insert(NewMBB, NewIsland);
1434 // Update internal data structures to account for the newly inserted MBB.
1435 updateForInsertedWaterBlock(NewIsland);
1437 // Decrement the old entry, and remove it if refcount becomes 0.
1438 decrementCPEReferenceCount(CPI, CPEMI);
1440 // Now that we have an island to add the CPE to, clone the original CPE and
1441 // add it to the island.
1442 U.HighWaterMark = NewIsland;
1443 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY))
1444 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1445 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1448 // Mark the basic block as aligned as required by the const-pool entry.
1449 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1451 // Increase the size of the island block to account for the new entry.
1452 BBInfo[NewIsland->getNumber()].Size += Size;
1453 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1455 // Finally, change the CPI in the instruction operand to be ID.
1456 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1457 if (UserMI->getOperand(i).isCPI()) {
1458 UserMI->getOperand(i).setIndex(ID);
1462 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1463 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1468 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1469 /// sizes and offsets of impacted basic blocks.
1470 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1471 MachineBasicBlock *CPEBB = CPEMI->getParent();
1472 unsigned Size = CPEMI->getOperand(2).getImm();
1473 CPEMI->eraseFromParent();
1474 BBInfo[CPEBB->getNumber()].Size -= Size;
1475 // All succeeding offsets have the current size value added in, fix this.
1476 if (CPEBB->empty()) {
1477 BBInfo[CPEBB->getNumber()].Size = 0;
1479 // This block no longer needs to be aligned. <rdar://problem/10534709>.
1480 CPEBB->setAlignment(0);
1482 // Entries are sorted by descending alignment, so realign from the front.
1483 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1485 adjustBBOffsetsAfter(CPEBB);
1486 // An island has only one predecessor BB and one successor BB. Check if
1487 // this BB's predecessor jumps directly to this BB's successor. This
1488 // shouldn't happen currently.
1489 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1490 // FIXME: remove the empty blocks after all the work is done?
1493 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1495 bool ARMConstantIslands::removeUnusedCPEntries() {
1496 unsigned MadeChange = false;
1497 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1498 std::vector<CPEntry> &CPEs = CPEntries[i];
1499 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1500 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1501 removeDeadCPEMI(CPEs[j].CPEMI);
1502 CPEs[j].CPEMI = NULL;
1510 /// isBBInRange - Returns true if the distance between specific MI and
1511 /// specific BB can fit in MI's displacement field.
1512 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1514 unsigned PCAdj = isThumb ? 4 : 8;
1515 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1516 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1518 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1519 << " from BB#" << MI->getParent()->getNumber()
1520 << " max delta=" << MaxDisp
1521 << " from " << getOffsetOf(MI) << " to " << DestOffset
1522 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1524 if (BrOffset <= DestOffset) {
1525 // Branch before the Dest.
1526 if (DestOffset-BrOffset <= MaxDisp)
1529 if (BrOffset-DestOffset <= MaxDisp)
1535 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1536 /// away to fit in its displacement field.
1537 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1538 MachineInstr *MI = Br.MI;
1539 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1541 // Check to see if the DestBB is already in-range.
1542 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1546 return fixupUnconditionalBr(Br);
1547 return fixupConditionalBr(Br);
1550 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1551 /// too far away to fit in its displacement field. If the LR register has been
1552 /// spilled in the epilogue, then we can use BL to implement a far jump.
1553 /// Otherwise, add an intermediate branch instruction to a branch.
1555 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1556 MachineInstr *MI = Br.MI;
1557 MachineBasicBlock *MBB = MI->getParent();
1559 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1561 // Use BL to implement far jump.
1562 Br.MaxDisp = (1 << 21) * 2;
1563 MI->setDesc(TII->get(ARM::tBfar));
1564 BBInfo[MBB->getNumber()].Size += 2;
1565 adjustBBOffsetsAfter(MBB);
1569 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1574 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1575 /// far away to fit in its displacement field. It is converted to an inverse
1576 /// conditional branch + an unconditional branch to the destination.
1578 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1579 MachineInstr *MI = Br.MI;
1580 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1582 // Add an unconditional branch to the destination and invert the branch
1583 // condition to jump over it:
1589 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm();
1590 CC = ARMCC::getOppositeCondition(CC);
1591 unsigned CCReg = MI->getOperand(2).getReg();
1593 // If the branch is at the end of its MBB and that has a fall-through block,
1594 // direct the updated conditional branch to the fall-through block. Otherwise,
1595 // split the MBB before the next instruction.
1596 MachineBasicBlock *MBB = MI->getParent();
1597 MachineInstr *BMI = &MBB->back();
1598 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1602 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1603 BMI->getOpcode() == Br.UncondBr) {
1604 // Last MI in the BB is an unconditional branch. Can we simply invert the
1605 // condition and swap destinations:
1611 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1612 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1613 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1615 BMI->getOperand(0).setMBB(DestBB);
1616 MI->getOperand(0).setMBB(NewDest);
1617 MI->getOperand(1).setImm(CC);
1624 splitBlockBeforeInstr(MI);
1625 // No need for the branch to the next block. We're adding an unconditional
1626 // branch to the destination.
1627 int delta = TII->GetInstSizeInBytes(&MBB->back());
1628 BBInfo[MBB->getNumber()].Size -= delta;
1629 MBB->back().eraseFromParent();
1630 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1632 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1634 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1635 << " also invert condition and change dest. to BB#"
1636 << NextBB->getNumber() << "\n");
1638 // Insert a new conditional branch and a new unconditional branch.
1639 // Also update the ImmBranch as well as adding a new entry for the new branch.
1640 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1641 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1642 Br.MI = &MBB->back();
1643 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1645 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB)
1646 .addImm(ARMCC::AL).addReg(0);
1648 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1649 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1650 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1651 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1653 // Remove the old conditional branch. It may or may not still be in MBB.
1654 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1655 MI->eraseFromParent();
1656 adjustBBOffsetsAfter(MBB);
1660 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1661 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1662 /// to do this if tBfar is not used.
1663 bool ARMConstantIslands::undoLRSpillRestore() {
1664 bool MadeChange = false;
1665 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1666 MachineInstr *MI = PushPopMIs[i];
1667 // First two operands are predicates.
1668 if (MI->getOpcode() == ARM::tPOP_RET &&
1669 MI->getOperand(2).getReg() == ARM::PC &&
1670 MI->getNumExplicitOperands() == 3) {
1671 // Create the new insn and copy the predicate from the old.
1672 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1673 .addOperand(MI->getOperand(0))
1674 .addOperand(MI->getOperand(1));
1675 MI->eraseFromParent();
1682 // mayOptimizeThumb2Instruction - Returns true if optimizeThumb2Instructions
1683 // below may shrink MI.
1685 ARMConstantIslands::mayOptimizeThumb2Instruction(const MachineInstr *MI) const {
1686 switch(MI->getOpcode()) {
1687 // optimizeThumb2Instructions.
1688 case ARM::t2LEApcrel:
1690 // optimizeThumb2Branches.
1694 // optimizeThumb2JumpTables.
1701 bool ARMConstantIslands::optimizeThumb2Instructions() {
1702 bool MadeChange = false;
1704 // Shrink ADR and LDR from constantpool.
1705 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1706 CPUser &U = CPUsers[i];
1707 unsigned Opcode = U.MI->getOpcode();
1708 unsigned NewOpc = 0;
1713 case ARM::t2LEApcrel:
1714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1715 NewOpc = ARM::tLEApcrel;
1721 if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1722 NewOpc = ARM::tLDRpci;
1732 unsigned UserOffset = getUserOffset(U);
1733 unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1735 // Be conservative with inline asm.
1736 if (!U.KnownAlignment)
1739 // FIXME: Check if offset is multiple of scale if scale is not 4.
1740 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1741 U.MI->setDesc(TII->get(NewOpc));
1742 MachineBasicBlock *MBB = U.MI->getParent();
1743 BBInfo[MBB->getNumber()].Size -= 2;
1744 adjustBBOffsetsAfter(MBB);
1750 MadeChange |= optimizeThumb2Branches();
1751 MadeChange |= optimizeThumb2JumpTables();
1755 bool ARMConstantIslands::optimizeThumb2Branches() {
1756 bool MadeChange = false;
1758 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) {
1759 ImmBranch &Br = ImmBranches[i];
1760 unsigned Opcode = Br.MI->getOpcode();
1761 unsigned NewOpc = 0;
1779 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1780 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1781 if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1782 Br.MI->setDesc(TII->get(NewOpc));
1783 MachineBasicBlock *MBB = Br.MI->getParent();
1784 BBInfo[MBB->getNumber()].Size -= 2;
1785 adjustBBOffsetsAfter(MBB);
1791 Opcode = Br.MI->getOpcode();
1792 if (Opcode != ARM::tBcc)
1795 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1796 // so this transformation is not safe.
1797 if (!Br.MI->killsRegister(ARM::CPSR))
1801 unsigned PredReg = 0;
1802 ARMCC::CondCodes Pred = llvm::getInstrPredicate(Br.MI, PredReg);
1803 if (Pred == ARMCC::EQ)
1805 else if (Pred == ARMCC::NE)
1806 NewOpc = ARM::tCBNZ;
1809 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1810 // Check if the distance is within 126. Subtract starting offset by 2
1811 // because the cmp will be eliminated.
1812 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1813 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1814 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) {
1815 MachineBasicBlock::iterator CmpMI = Br.MI;
1816 if (CmpMI != Br.MI->getParent()->begin()) {
1818 if (CmpMI->getOpcode() == ARM::tCMPi8) {
1819 unsigned Reg = CmpMI->getOperand(0).getReg();
1820 Pred = llvm::getInstrPredicate(CmpMI, PredReg);
1821 if (Pred == ARMCC::AL &&
1822 CmpMI->getOperand(1).getImm() == 0 &&
1823 isARMLowRegister(Reg)) {
1824 MachineBasicBlock *MBB = Br.MI->getParent();
1825 MachineInstr *NewBR =
1826 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1827 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags());
1828 CmpMI->eraseFromParent();
1829 Br.MI->eraseFromParent();
1831 BBInfo[MBB->getNumber()].Size -= 2;
1832 adjustBBOffsetsAfter(MBB);
1844 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
1845 /// jumptables when it's possible.
1846 bool ARMConstantIslands::optimizeThumb2JumpTables() {
1847 bool MadeChange = false;
1849 // FIXME: After the tables are shrunk, can we get rid some of the
1850 // constantpool tables?
1851 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1852 if (MJTI == 0) return false;
1854 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1855 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1856 MachineInstr *MI = T2JumpTables[i];
1857 const MCInstrDesc &MCID = MI->getDesc();
1858 unsigned NumOps = MCID.getNumOperands();
1859 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1860 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1861 unsigned JTI = JTOP.getIndex();
1862 assert(JTI < JT.size());
1865 bool HalfWordOk = true;
1866 unsigned JTOffset = getOffsetOf(MI) + 4;
1867 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1868 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1869 MachineBasicBlock *MBB = JTBBs[j];
1870 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
1871 // Negative offset is not ok. FIXME: We should change BB layout to make
1872 // sure all the branches are forward.
1873 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
1875 unsigned TBHLimit = ((1<<16)-1)*2;
1876 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
1878 if (!ByteOk && !HalfWordOk)
1882 if (ByteOk || HalfWordOk) {
1883 MachineBasicBlock *MBB = MI->getParent();
1884 unsigned BaseReg = MI->getOperand(0).getReg();
1885 bool BaseRegKill = MI->getOperand(0).isKill();
1888 unsigned IdxReg = MI->getOperand(1).getReg();
1889 bool IdxRegKill = MI->getOperand(1).isKill();
1891 // Scan backwards to find the instruction that defines the base
1892 // register. Due to post-RA scheduling, we can't count on it
1893 // immediately preceding the branch instruction.
1894 MachineBasicBlock::iterator PrevI = MI;
1895 MachineBasicBlock::iterator B = MBB->begin();
1896 while (PrevI != B && !PrevI->definesRegister(BaseReg))
1899 // If for some reason we didn't find it, we can't do anything, so
1900 // just skip this one.
1901 if (!PrevI->definesRegister(BaseReg))
1904 MachineInstr *AddrMI = PrevI;
1906 // Examine the instruction that calculates the jumptable entry address.
1907 // Make sure it only defines the base register and kills any uses
1908 // other than the index register.
1909 for (unsigned k = 0, eee = AddrMI->getNumOperands(); k != eee; ++k) {
1910 const MachineOperand &MO = AddrMI->getOperand(k);
1911 if (!MO.isReg() || !MO.getReg())
1913 if (MO.isDef() && MO.getReg() != BaseReg) {
1917 if (MO.isUse() && !MO.isKill() && MO.getReg() != IdxReg) {
1925 // Now scan back again to find the tLEApcrel or t2LEApcrelJT instruction
1926 // that gave us the initial base register definition.
1927 for (--PrevI; PrevI != B && !PrevI->definesRegister(BaseReg); --PrevI)
1930 // The instruction should be a tLEApcrel or t2LEApcrelJT; we want
1931 // to delete it as well.
1932 MachineInstr *LeaMI = PrevI;
1933 if ((LeaMI->getOpcode() != ARM::tLEApcrelJT &&
1934 LeaMI->getOpcode() != ARM::t2LEApcrelJT) ||
1935 LeaMI->getOperand(0).getReg() != BaseReg)
1941 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
1942 MachineInstr *NewJTMI = BuildMI(MBB, MI->getDebugLoc(), TII->get(Opc))
1943 .addReg(IdxReg, getKillRegState(IdxRegKill))
1944 .addJumpTableIndex(JTI, JTOP.getTargetFlags())
1945 .addImm(MI->getOperand(JTOpIdx+1).getImm());
1946 // FIXME: Insert an "ALIGN" instruction to ensure the next instruction
1947 // is 2-byte aligned. For now, asm printer will fix it up.
1948 unsigned NewSize = TII->GetInstSizeInBytes(NewJTMI);
1949 unsigned OrigSize = TII->GetInstSizeInBytes(AddrMI);
1950 OrigSize += TII->GetInstSizeInBytes(LeaMI);
1951 OrigSize += TII->GetInstSizeInBytes(MI);
1953 AddrMI->eraseFromParent();
1954 LeaMI->eraseFromParent();
1955 MI->eraseFromParent();
1957 int delta = OrigSize - NewSize;
1958 BBInfo[MBB->getNumber()].Size -= delta;
1959 adjustBBOffsetsAfter(MBB);
1969 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
1970 /// jump tables always branch forwards, since that's what tbb and tbh need.
1971 bool ARMConstantIslands::reorderThumb2JumpTables() {
1972 bool MadeChange = false;
1974 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1975 if (MJTI == 0) return false;
1977 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1978 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
1979 MachineInstr *MI = T2JumpTables[i];
1980 const MCInstrDesc &MCID = MI->getDesc();
1981 unsigned NumOps = MCID.getNumOperands();
1982 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 3 : 2);
1983 MachineOperand JTOP = MI->getOperand(JTOpIdx);
1984 unsigned JTI = JTOP.getIndex();
1985 assert(JTI < JT.size());
1987 // We prefer if target blocks for the jump table come after the jump
1988 // instruction so we can use TB[BH]. Loop through the target blocks
1989 // and try to adjust them such that that's true.
1990 int JTNumber = MI->getParent()->getNumber();
1991 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1992 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
1993 MachineBasicBlock *MBB = JTBBs[j];
1994 int DTNumber = MBB->getNumber();
1996 if (DTNumber < JTNumber) {
1997 // The destination precedes the switch. Try to move the block forward
1998 // so we have a positive offset.
1999 MachineBasicBlock *NewBB =
2000 adjustJTTargetBlockForward(MBB, MI->getParent());
2002 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2011 MachineBasicBlock *ARMConstantIslands::
2012 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2013 // If the destination block is terminated by an unconditional branch,
2014 // try to move it; otherwise, create a new block following the jump
2015 // table that branches back to the actual target. This is a very simple
2016 // heuristic. FIXME: We can definitely improve it.
2017 MachineBasicBlock *TBB = 0, *FBB = 0;
2018 SmallVector<MachineOperand, 4> Cond;
2019 SmallVector<MachineOperand, 4> CondPrior;
2020 MachineFunction::iterator BBi = BB;
2021 MachineFunction::iterator OldPrior = prior(BBi);
2023 // If the block terminator isn't analyzable, don't try to move the block
2024 bool B = TII->AnalyzeBranch(*BB, TBB, FBB, Cond);
2026 // If the block ends in an unconditional branch, move it. The prior block
2027 // has to have an analyzable terminator for us to move this one. Be paranoid
2028 // and make sure we're not trying to move the entry block of the function.
2029 if (!B && Cond.empty() && BB != MF->begin() &&
2030 !TII->AnalyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2031 BB->moveAfter(JTBB);
2032 OldPrior->updateTerminator();
2033 BB->updateTerminator();
2034 // Update numbering to account for the block being moved.
2035 MF->RenumberBlocks();
2040 // Create a new MBB for the code after the jump BB.
2041 MachineBasicBlock *NewBB =
2042 MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2043 MachineFunction::iterator MBBI = JTBB; ++MBBI;
2044 MF->insert(MBBI, NewBB);
2046 // Add an unconditional branch from NewBB to BB.
2047 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2048 // correspond directly to anything in the source.
2049 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?");
2050 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB)
2051 .addImm(ARMCC::AL).addReg(0);
2053 // Update internal data structures to account for the newly inserted MBB.
2054 MF->RenumberBlocks(NewBB);
2057 NewBB->addSuccessor(BB);
2058 JTBB->removeSuccessor(BB);
2059 JTBB->addSuccessor(NewBB);