1 //===-- ARMConstantIslandPass.cpp - ARM constant islands --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under the
6 // University of Illinois Open Source 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 "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/Statistic.h"
32 STATISTIC(NumCPEs, "Number of constpool entries");
33 STATISTIC(NumSplit, "Number of uncond branches inserted");
34 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
35 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
38 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
39 /// requires constant pool entries to be scattered among the instructions
40 /// inside a function. To do this, it completely ignores the normal LLVM
41 /// constant pool; instead, it places constants wherever it feels like with
42 /// special instructions.
44 /// The terminology used in this pass includes:
45 /// Islands - Clumps of constants placed in the function.
46 /// Water - Potential places where an island could be formed.
47 /// CPE - A constant pool entry that has been placed somewhere, which
48 /// tracks a list of users.
49 class VISIBILITY_HIDDEN ARMConstantIslands : public MachineFunctionPass {
50 /// NextUID - Assign unique ID's to CPE's.
53 /// BBSizes - The size of each MachineBasicBlock in bytes of code, indexed
55 std::vector<unsigned> BBSizes;
57 /// BBOffsets - the offset of each MBB in bytes, starting from 0.
58 std::vector<unsigned> BBOffsets;
60 /// WaterList - A sorted list of basic blocks where islands could be placed
61 /// (i.e. blocks that don't fall through to the following block, due
62 /// to a return, unreachable, or unconditional branch).
63 std::vector<MachineBasicBlock*> WaterList;
65 /// CPUser - One user of a constant pool, keeping the machine instruction
66 /// pointer, the constant pool being referenced, and the max displacement
67 /// allowed from the instruction to the CP.
72 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp)
73 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp) {}
76 /// CPUsers - Keep track of all of the machine instructions that use various
77 /// constant pools and their max displacement.
78 std::vector<CPUser> CPUsers;
80 /// CPEntry - One per constant pool entry, keeping the machine instruction
81 /// pointer, the constpool index, and the number of CPUser's which
82 /// reference this entry.
87 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
88 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
91 /// CPEntries - Keep track of all of the constant pool entry machine
92 /// instructions. For each original constpool index (i.e. those that
93 /// existed upon entry to this pass), it keeps a vector of entries.
94 /// Original elements are cloned as we go along; the clones are
95 /// put in the vector of the original element, but have distinct CPIs.
96 std::vector<std::vector<CPEntry> > CPEntries;
98 /// ImmBranch - One per immediate branch, keeping the machine instruction
99 /// pointer, conditional or unconditional, the max displacement,
100 /// and (if isCond is true) the corresponding unconditional branch
104 unsigned MaxDisp : 31;
107 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
108 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
111 /// Branches - Keep track of all the immediate branch instructions.
113 std::vector<ImmBranch> ImmBranches;
115 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
117 SmallVector<MachineInstr*, 4> PushPopMIs;
119 /// HasFarJump - True if any far jump instruction has been emitted during
120 /// the branch fix up pass.
123 const TargetInstrInfo *TII;
124 const ARMFunctionInfo *AFI;
126 virtual bool runOnMachineFunction(MachineFunction &Fn);
128 virtual const char *getPassName() const {
129 return "ARM constant island placement and branch shortening pass";
133 void DoInitialPlacement(MachineFunction &Fn,
134 std::vector<MachineInstr*> &CPEMIs);
135 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
136 void InitialFunctionScan(MachineFunction &Fn,
137 const std::vector<MachineInstr*> &CPEMIs);
138 MachineBasicBlock *SplitBlockBeforeInstr(MachineInstr *MI);
139 void UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB);
140 void AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta);
141 bool DecrementOldEntry(unsigned CPI, MachineInstr* CPEMI, unsigned Size);
142 int LookForExistingCPEntry(CPUser& U, unsigned UserOffset);
143 bool HandleConstantPoolUser(MachineFunction &Fn, CPUser &U);
144 bool CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
145 MachineInstr *CPEMI, unsigned Disp,
147 bool WaterIsInRange(unsigned UserOffset, MachineBasicBlock *Water,
149 bool OffsetIsInRange(unsigned UserOffset, unsigned TrialOffset,
150 unsigned Disp, bool NegativeOK);
151 bool BBIsInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
152 bool FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br);
153 bool FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br);
154 bool FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br);
155 bool UndoLRSpillRestore();
157 unsigned GetOffsetOf(MachineInstr *MI) const;
161 /// createARMConstantIslandPass - returns an instance of the constpool
163 FunctionPass *llvm::createARMConstantIslandPass() {
164 return new ARMConstantIslands();
167 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &Fn) {
168 MachineConstantPool &MCP = *Fn.getConstantPool();
170 TII = Fn.getTarget().getInstrInfo();
171 AFI = Fn.getInfo<ARMFunctionInfo>();
175 // Renumber all of the machine basic blocks in the function, guaranteeing that
176 // the numbers agree with the position of the block in the function.
179 // Perform the initial placement of the constant pool entries. To start with,
180 // we put them all at the end of the function.
181 std::vector<MachineInstr*> CPEMIs;
183 DoInitialPlacement(Fn, CPEMIs);
185 /// The next UID to take is the first unused one.
186 NextUID = CPEMIs.size();
188 // Do the initial scan of the function, building up information about the
189 // sizes of each block, the location of all the water, and finding all of the
190 // constant pool users.
191 InitialFunctionScan(Fn, CPEMIs);
194 // Iteratively place constant pool entries and fix up branches until there
196 bool MadeChange = false;
199 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
200 Change |= HandleConstantPoolUser(Fn, CPUsers[i]);
201 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
202 Change |= FixUpImmediateBr(Fn, ImmBranches[i]);
208 // If LR has been forced spilled and no far jumps (i.e. BL) has been issued.
209 // Undo the spill / restore of LR if possible.
210 if (!HasFarJump && AFI->isLRForceSpilled() && AFI->isThumbFunction())
211 MadeChange |= UndoLRSpillRestore();
224 /// DoInitialPlacement - Perform the initial placement of the constant pool
225 /// entries. To start with, we put them all at the end of the function.
226 void ARMConstantIslands::DoInitialPlacement(MachineFunction &Fn,
227 std::vector<MachineInstr*> &CPEMIs){
228 // Create the basic block to hold the CPE's.
229 MachineBasicBlock *BB = new MachineBasicBlock();
230 Fn.getBasicBlockList().push_back(BB);
232 // Add all of the constants from the constant pool to the end block, use an
233 // identity mapping of CPI's to CPE's.
234 const std::vector<MachineConstantPoolEntry> &CPs =
235 Fn.getConstantPool()->getConstants();
237 const TargetData &TD = *Fn.getTarget().getTargetData();
238 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
239 unsigned Size = TD.getTypeSize(CPs[i].getType());
240 // Verify that all constant pool entries are a multiple of 4 bytes. If not,
241 // we would have to pad them out or something so that instructions stay
243 assert((Size & 3) == 0 && "CP Entry not multiple of 4 bytes!");
244 MachineInstr *CPEMI =
245 BuildMI(BB, TII->get(ARM::CONSTPOOL_ENTRY))
246 .addImm(i).addConstantPoolIndex(i).addImm(Size);
247 CPEMIs.push_back(CPEMI);
249 // Add a new CPEntry, but no corresponding CPUser yet.
250 std::vector<CPEntry> CPEs;
251 CPEs.push_back(CPEntry(CPEMI, i));
252 CPEntries.push_back(CPEs);
254 DOUT << "Moved CPI#" << i << " to end of function as #" << i << "\n";
258 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
259 /// into the block immediately after it.
260 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
261 // Get the next machine basic block in the function.
262 MachineFunction::iterator MBBI = MBB;
263 if (next(MBBI) == MBB->getParent()->end()) // Can't fall off end of function.
266 MachineBasicBlock *NextBB = next(MBBI);
267 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
268 E = MBB->succ_end(); I != E; ++I)
275 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
276 /// look up the corresponding CPEntry.
277 ARMConstantIslands::CPEntry
278 *ARMConstantIslands::findConstPoolEntry(unsigned CPI,
279 const MachineInstr *CPEMI) {
280 std::vector<CPEntry> &CPEs = CPEntries[CPI];
281 // Number of entries per constpool index should be small, just do a
283 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
284 if (CPEs[i].CPEMI == CPEMI)
290 /// InitialFunctionScan - Do the initial scan of the function, building up
291 /// information about the sizes of each block, the location of all the water,
292 /// and finding all of the constant pool users.
293 void ARMConstantIslands::InitialFunctionScan(MachineFunction &Fn,
294 const std::vector<MachineInstr*> &CPEMIs) {
296 for (MachineFunction::iterator MBBI = Fn.begin(), E = Fn.end();
298 MachineBasicBlock &MBB = *MBBI;
300 // If this block doesn't fall through into the next MBB, then this is
301 // 'water' that a constant pool island could be placed.
302 if (!BBHasFallthrough(&MBB))
303 WaterList.push_back(&MBB);
305 unsigned MBBSize = 0;
306 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
308 // Add instruction size to MBBSize.
309 MBBSize += ARM::GetInstSize(I);
311 int Opc = I->getOpcode();
312 if (TII->isBranch(Opc)) {
319 continue; // Ignore JT branches
340 // Record this immediate branch.
341 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
342 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
345 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
346 PushPopMIs.push_back(I);
348 // Scan the instructions for constant pool operands.
349 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
350 if (I->getOperand(op).isConstantPoolIndex()) {
351 // We found one. The addressing mode tells us the max displacement
352 // from the PC that this instruction permits.
354 // Basic size info comes from the TSFlags field.
357 unsigned TSFlags = I->getInstrDescriptor()->TSFlags;
358 switch (TSFlags & ARMII::AddrModeMask) {
360 // Constant pool entries can reach anything.
361 if (I->getOpcode() == ARM::CONSTPOOL_ENTRY)
363 assert(0 && "Unknown addressing mode for CP reference!");
364 case ARMII::AddrMode1: // AM1: 8 bits << 2
366 Scale = 4; // Taking the address of a CP entry.
368 case ARMII::AddrMode2:
369 Bits = 12; // +-offset_12
371 case ARMII::AddrMode3:
372 Bits = 8; // +-offset_8
374 // addrmode4 has no immediate offset.
375 case ARMII::AddrMode5:
377 Scale = 4; // +-(offset_8*4)
379 case ARMII::AddrModeT1:
380 Bits = 5; // +offset_5
382 case ARMII::AddrModeT2:
384 Scale = 2; // +(offset_5*2)
386 case ARMII::AddrModeT4:
388 Scale = 4; // +(offset_5*4)
390 case ARMII::AddrModeTs:
392 Scale = 4; // +(offset_8*4)
396 // Remember that this is a user of a CP entry.
397 unsigned CPI = I->getOperand(op).getConstantPoolIndex();
398 MachineInstr *CPEMI = CPEMIs[CPI];
399 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
400 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs));
402 // Increment corresponding CPEntry reference count.
403 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
404 assert(CPE && "Cannot find a corresponding CPEntry!");
407 // Instructions can only use one CP entry, don't bother scanning the
408 // rest of the operands.
413 // In thumb mode, if this block is a constpool island, pessimistically
414 // assume it needs to be padded by two byte so it's aligned on 4 byte
416 if (AFI->isThumbFunction() &&
418 MBB.begin()->getOpcode() == ARM::CONSTPOOL_ENTRY)
421 BBSizes.push_back(MBBSize);
422 BBOffsets.push_back(Offset);
427 /// GetOffsetOf - Return the current offset of the specified machine instruction
428 /// from the start of the function. This offset changes as stuff is moved
429 /// around inside the function.
430 unsigned ARMConstantIslands::GetOffsetOf(MachineInstr *MI) const {
431 MachineBasicBlock *MBB = MI->getParent();
433 // The offset is composed of two things: the sum of the sizes of all MBB's
434 // before this instruction's block, and the offset from the start of the block
436 unsigned Offset = BBOffsets[MBB->getNumber()];
438 // Sum instructions before MI in MBB.
439 for (MachineBasicBlock::iterator I = MBB->begin(); ; ++I) {
440 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
441 if (&*I == MI) return Offset;
442 Offset += ARM::GetInstSize(I);
446 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
448 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
449 const MachineBasicBlock *RHS) {
450 return LHS->getNumber() < RHS->getNumber();
453 /// UpdateForInsertedWaterBlock - When a block is newly inserted into the
454 /// machine function, it upsets all of the block numbers. Renumber the blocks
455 /// and update the arrays that parallel this numbering.
456 void ARMConstantIslands::UpdateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
457 // Renumber the MBB's to keep them consequtive.
458 NewBB->getParent()->RenumberBlocks(NewBB);
460 // Insert a size into BBSizes to align it properly with the (newly
461 // renumbered) block numbers.
462 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
464 // Likewise for BBOffsets.
465 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
467 // Next, update WaterList. Specifically, we need to add NewMBB as having
468 // available water after it.
469 std::vector<MachineBasicBlock*>::iterator IP =
470 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
472 WaterList.insert(IP, NewBB);
476 /// Split the basic block containing MI into two blocks, which are joined by
477 /// an unconditional branch. Update datastructures and renumber blocks to
478 /// account for this change and returns the newly created block.
479 MachineBasicBlock *ARMConstantIslands::SplitBlockBeforeInstr(MachineInstr *MI) {
480 MachineBasicBlock *OrigBB = MI->getParent();
481 bool isThumb = AFI->isThumbFunction();
483 // Create a new MBB for the code after the OrigBB.
484 MachineBasicBlock *NewBB = new MachineBasicBlock(OrigBB->getBasicBlock());
485 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
486 OrigBB->getParent()->getBasicBlockList().insert(MBBI, NewBB);
488 // Splice the instructions starting with MI over to NewBB.
489 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
491 // Add an unconditional branch from OrigBB to NewBB.
492 // Note the new unconditional branch is not being recorded.
493 BuildMI(OrigBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewBB);
496 // Update the CFG. All succs of OrigBB are now succs of NewBB.
497 while (!OrigBB->succ_empty()) {
498 MachineBasicBlock *Succ = *OrigBB->succ_begin();
499 OrigBB->removeSuccessor(Succ);
500 NewBB->addSuccessor(Succ);
502 // This pass should be run after register allocation, so there should be no
503 // PHI nodes to update.
504 assert((Succ->empty() || Succ->begin()->getOpcode() != TargetInstrInfo::PHI)
505 && "PHI nodes should be eliminated by now!");
508 // OrigBB branches to NewBB.
509 OrigBB->addSuccessor(NewBB);
511 // Update internal data structures to account for the newly inserted MBB.
512 // This is almost the same as UpdateForInsertedWaterBlock, except that
513 // the Water goes after OrigBB, not NewBB.
514 NewBB->getParent()->RenumberBlocks(NewBB);
516 // Insert a size into BBSizes to align it properly with the (newly
517 // renumbered) block numbers.
518 BBSizes.insert(BBSizes.begin()+NewBB->getNumber(), 0);
520 // Likewise for BBOffsets.
521 BBOffsets.insert(BBOffsets.begin()+NewBB->getNumber(), 0);
523 // Next, update WaterList. Specifically, we need to add OrigMBB as having
524 // available water after it (but not if it's already there, which happens
525 // when splitting before a conditional branch that is followed by an
526 // unconditional branch - in that case we want to insert NewBB).
527 std::vector<MachineBasicBlock*>::iterator IP =
528 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
530 MachineBasicBlock* WaterBB = *IP;
531 if (WaterBB == OrigBB)
532 WaterList.insert(next(IP), NewBB);
534 WaterList.insert(IP, OrigBB);
536 // Figure out how large the first NewMBB is.
537 unsigned NewBBSize = 0;
538 for (MachineBasicBlock::iterator I = NewBB->begin(), E = NewBB->end();
540 NewBBSize += ARM::GetInstSize(I);
542 unsigned OrigBBI = OrigBB->getNumber();
543 unsigned NewBBI = NewBB->getNumber();
544 // Set the size of NewBB in BBSizes.
545 BBSizes[NewBBI] = NewBBSize;
547 // We removed instructions from UserMBB, subtract that off from its size.
548 // Add 2 or 4 to the block to count the unconditional branch we added to it.
549 unsigned delta = isThumb ? 2 : 4;
550 BBSizes[OrigBBI] -= NewBBSize - delta;
552 // ...and adjust BBOffsets for NewBB accordingly.
553 BBOffsets[NewBBI] = BBOffsets[OrigBBI] + BBSizes[OrigBBI];
555 // All BBOffsets following these blocks must be modified.
556 AdjustBBOffsetsAfter(NewBB, delta);
561 /// OffsetIsInRange - Checks whether UserOffset is within MaxDisp of
563 bool ARMConstantIslands::OffsetIsInRange(unsigned UserOffset,
564 unsigned TrialOffset, unsigned MaxDisp, bool NegativeOK) {
565 if (UserOffset <= TrialOffset) {
566 // User before the Trial.
567 if (TrialOffset-UserOffset <= MaxDisp)
569 } else if (NegativeOK) {
570 if (UserOffset-TrialOffset <= MaxDisp)
576 /// WaterIsInRange - Returns true if a CPE placed after the specified
577 /// Water (a basic block) will be in range for the specific MI.
579 bool ARMConstantIslands::WaterIsInRange(unsigned UserOffset,
580 MachineBasicBlock* Water, unsigned MaxDisp)
582 bool isThumb = AFI->isThumbFunction();
583 unsigned CPEOffset = BBOffsets[Water->getNumber()] +
584 BBSizes[Water->getNumber()];
585 // If the Water is a constpool island, it has already been aligned.
589 Water->begin()->getOpcode() != ARM::CONSTPOOL_ENTRY))
592 return OffsetIsInRange (UserOffset, CPEOffset, MaxDisp, !isThumb);
595 /// CPEIsInRange - Returns true if the distance between specific MI and
596 /// specific ConstPool entry instruction can fit in MI's displacement field.
597 bool ARMConstantIslands::CPEIsInRange(MachineInstr *MI, unsigned UserOffset,
599 unsigned MaxDisp, bool DoDump) {
600 // In thumb mode, pessimistically assumes the .align 2 before the first CPE
601 // in the island adds two byte padding.
602 bool isThumb = AFI->isThumbFunction();
603 unsigned AlignAdj = isThumb ? 2 : 0;
604 unsigned CPEOffset = GetOffsetOf(CPEMI) + AlignAdj;
607 DOUT << "User of CPE#" << CPEMI->getOperand(0).getImm()
608 << " max delta=" << MaxDisp
609 << " insn address=" << UserOffset
610 << " CPE address=" << CPEOffset
611 << " offset=" << int(CPEOffset-UserOffset) << "\t" << *MI;
614 return OffsetIsInRange(UserOffset, CPEOffset, MaxDisp, !isThumb);
617 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
618 /// unconditionally branches to its only successor.
619 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
620 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
623 MachineBasicBlock *Succ = *MBB->succ_begin();
624 MachineBasicBlock *Pred = *MBB->pred_begin();
625 MachineInstr *PredMI = &Pred->back();
626 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB)
627 return PredMI->getOperand(0).getMBB() == Succ;
631 void ARMConstantIslands::AdjustBBOffsetsAfter(MachineBasicBlock *BB, int delta)
633 MachineFunction::iterator MBBI = BB->getParent()->end();
634 for(unsigned i=BB->getNumber()+1; i<BB->getParent()->getNumBlockIDs(); i++)
635 BBOffsets[i] += delta;
638 /// DecrementOldEntry - find the constant pool entry with index CPI
639 /// and instruction CPEMI, and decrement its refcount. If the refcount
640 /// becomes 0 remove the entry and instruction. Returns true if we removed
641 /// the entry, false if we didn't.
643 bool ARMConstantIslands::DecrementOldEntry(unsigned CPI, MachineInstr *CPEMI,
645 // Find the old entry. Eliminate it if it is no longer used.
646 CPEntry *OldCPE = findConstPoolEntry(CPI, CPEMI);
647 assert(OldCPE && "Unexpected!");
648 if (--OldCPE->RefCount == 0) {
649 MachineBasicBlock *OldCPEBB = OldCPE->CPEMI->getParent();
650 if (OldCPEBB->empty()) {
651 // In thumb mode, the size of island is padded by two to compensate for
652 // the alignment requirement. Thus it will now be 2 when the block is
653 // empty, so fix this.
654 // All succeeding offsets have the current size value added in, fix this.
655 if (BBSizes[OldCPEBB->getNumber()] != 0) {
656 AdjustBBOffsetsAfter(OldCPEBB, -BBSizes[OldCPEBB->getNumber()]);
657 BBSizes[OldCPEBB->getNumber()] = 0;
659 // An island has only one predecessor BB and one successor BB. Check if
660 // this BB's predecessor jumps directly to this BB's successor. This
661 // shouldn't happen currently.
662 assert(!BBIsJumpedOver(OldCPEBB) && "How did this happen?");
663 // FIXME: remove the empty blocks after all the work is done?
665 BBSizes[OldCPEBB->getNumber()] -= Size;
666 // All succeeding offsets have the current size value added in, fix this.
667 AdjustBBOffsetsAfter(OldCPEBB, -Size);
669 OldCPE->CPEMI->eraseFromParent();
670 OldCPE->CPEMI = NULL;
677 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
678 /// if not, see if an in-range clone of the CPE is in range, and if so,
679 /// change the data structures so the user references the clone. Returns:
680 /// 0 = no existing entry found
681 /// 1 = entry found, and there were no code insertions or deletions
682 /// 2 = entry found, and there were code insertions or deletions
683 int ARMConstantIslands::LookForExistingCPEntry(CPUser& U, unsigned UserOffset)
685 MachineInstr *UserMI = U.MI;
686 MachineInstr *CPEMI = U.CPEMI;
688 // Check to see if the CPE is already in-range.
689 if (CPEIsInRange(UserMI, UserOffset, CPEMI, U.MaxDisp, true)) {
690 DOUT << "In range\n";
694 // No. Look for previously created clones of the CPE that are in range.
695 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
696 std::vector<CPEntry> &CPEs = CPEntries[CPI];
697 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
698 // We already tried this one
699 if (CPEs[i].CPEMI == CPEMI)
701 // Removing CPEs can leave empty entries, skip
702 if (CPEs[i].CPEMI == NULL)
704 if (CPEIsInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.MaxDisp, false)) {
705 DOUT << "Replacing CPE#" << CPI << " with CPE#" << CPEs[i].CPI << "\n";
706 // Point the CPUser node to the replacement
707 U.CPEMI = CPEs[i].CPEMI;
708 // Change the CPI in the instruction operand to refer to the clone.
709 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
710 if (UserMI->getOperand(j).isConstantPoolIndex()) {
711 UserMI->getOperand(j).setConstantPoolIndex(CPEs[i].CPI);
714 // Adjust the refcount of the clone...
716 // ...and the original. If we didn't remove the old entry, none of the
717 // addresses changed, so we don't need another pass.
718 unsigned Size = CPEMI->getOperand(2).getImm();
719 return DecrementOldEntry(CPI, CPEMI, Size) ? 2 : 1;
725 /// HandleConstantPoolUser - Analyze the specified user, checking to see if it
726 /// is out-of-range. If so, pick it up the constant pool value and move it some
727 /// place in-range. Return true if we changed any addresses (thus must run
728 /// another pass of branch lengthening), false otherwise.
729 bool ARMConstantIslands::HandleConstantPoolUser(MachineFunction &Fn, CPUser &U){
730 MachineInstr *UserMI = U.MI;
731 MachineInstr *CPEMI = U.CPEMI;
732 unsigned CPI = CPEMI->getOperand(1).getConstantPoolIndex();
733 unsigned Size = CPEMI->getOperand(2).getImm();
734 bool isThumb = AFI->isThumbFunction();
735 MachineBasicBlock *NewMBB;
736 // Compute this only once, it's expensive
737 unsigned UserOffset = GetOffsetOf(UserMI) + (isThumb ? 4 : 8);
739 // See if the current entry is within range, or there is a clone of it
741 int result = LookForExistingCPEntry(U, UserOffset);
742 if (result==1) return false;
743 else if (result==2) return true;
745 // No existing clone of this CPE is within range.
746 // We will be generating a new clone. Get a UID for it.
747 unsigned ID = NextUID++;
749 // Look for water where we can place this CPE. We look for the farthest one
750 // away that will work. Forward references only for now (although later
751 // we might find some that are backwards).
752 bool WaterFound = false;
753 if (!WaterList.empty()) {
754 for (std::vector<MachineBasicBlock*>::iterator IP = prior(WaterList.end()),
755 B = WaterList.begin();; --IP) {
756 MachineBasicBlock* WaterBB = *IP;
757 if (WaterIsInRange(UserOffset, WaterBB, U.MaxDisp)) {
759 DOUT << "found water in range\n";
760 // CPE goes before following block (NewMBB).
761 NewMBB = next(MachineFunction::iterator(WaterBB));
762 // Remove the original WaterList entry; we want subsequent
763 // insertions in this vicinity to go after the one we're
764 // about to insert. This considerably reduces the number
765 // of times we have to move the same CPE more than once.
777 DOUT << "No water found\n";
778 MachineBasicBlock *UserMBB = UserMI->getParent();
779 unsigned TrialOffset = BBOffsets[UserMBB->getNumber()] +
780 BBSizes[UserMBB->getNumber()] +
781 isThumb ? 2 : 4; /* for branch to be added */
783 // If the use is at the end of the block, or the end of the block
784 // is within range, make new water there. (If the block ends in
785 // an unconditional branch already, it is water, and is known to
786 // be out of range; so it's OK to assume above we'll be adding a Br.)
787 if (&UserMBB->back() == UserMI ||
788 OffsetIsInRange(UserOffset, TrialOffset, U.MaxDisp, !isThumb)) {
789 if (&UserMBB->back() == UserMI)
790 assert(BBHasFallthrough(UserMBB) && "Expected a fallthrough BB!");
791 NewMBB = next(MachineFunction::iterator(UserMBB));
792 // Add an unconditional branch from UserMBB to fallthrough block.
793 // Note the new unconditional branch is not being recorded.
794 BuildMI(UserMBB, TII->get(isThumb ? ARM::tB : ARM::B)).addMBB(NewMBB);
795 int delta = isThumb ? 2 : 4;
796 BBSizes[UserMBB->getNumber()] += delta;
797 AdjustBBOffsetsAfter(UserMBB, delta);
799 // What a big block. Find a place within the block to split it.
800 // This is a little tricky on Thumb since instructions are 2 bytes
801 // and constant pool entries are 4 bytes: if instruction I references
802 // island CPE, and instruction I+1 references CPE', it will
803 // not work well to put CPE as far forward as possible, since then
804 // CPE' cannot immediately follow it (that location is 2 bytes
805 // farther away from I+1 than CPE was from I) and we'd need to create
808 // Solution of last resort: split the user's MBB right after the user
809 // and insert a clone of the CPE into the newly created water.
810 MachineInstr *NextMI = next(MachineBasicBlock::iterator(UserMI));
811 NewMBB = SplitBlockBeforeInstr(NextMI);
815 // Okay, we know we can put an island before NewMBB now, do it!
816 MachineBasicBlock *NewIsland = new MachineBasicBlock();
817 Fn.getBasicBlockList().insert(NewMBB, NewIsland);
819 // Update internal data structures to account for the newly inserted MBB.
820 UpdateForInsertedWaterBlock(NewIsland);
822 // Decrement the old entry, and remove it if refcount becomes 0.
823 DecrementOldEntry(CPI, CPEMI, Size);
825 // Now that we have an island to add the CPE to, clone the original CPE and
826 // add it to the island.
827 U.CPEMI = BuildMI(NewIsland, TII->get(ARM::CONSTPOOL_ENTRY))
828 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
829 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
832 // Compensate for .align 2 in thumb mode.
833 if (isThumb) Size += 2;
834 // Increase the size of the island block to account for the new entry.
835 BBSizes[NewIsland->getNumber()] += Size;
836 BBOffsets[NewIsland->getNumber()] = BBOffsets[NewMBB->getNumber()];
837 AdjustBBOffsetsAfter(NewIsland, Size);
839 // Finally, change the CPI in the instruction operand to be ID.
840 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
841 if (UserMI->getOperand(i).isConstantPoolIndex()) {
842 UserMI->getOperand(i).setConstantPoolIndex(ID);
846 DOUT << " Moved CPE to #" << ID << " CPI=" << CPI << "\t" << *UserMI;
851 /// BBIsInRange - Returns true if the distance between specific MI and
852 /// specific BB can fit in MI's displacement field.
853 bool ARMConstantIslands::BBIsInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
855 unsigned PCAdj = AFI->isThumbFunction() ? 4 : 8;
856 unsigned BrOffset = GetOffsetOf(MI) + PCAdj;
857 unsigned DestOffset = BBOffsets[DestBB->getNumber()];
859 DOUT << "Branch of destination BB#" << DestBB->getNumber()
860 << " from BB#" << MI->getParent()->getNumber()
861 << " max delta=" << MaxDisp
862 << " at offset " << int(DestOffset-BrOffset) << "\t" << *MI;
864 return OffsetIsInRange(BrOffset, DestOffset, MaxDisp, true);
867 /// FixUpImmediateBr - Fix up an immediate branch whose destination is too far
868 /// away to fit in its displacement field.
869 bool ARMConstantIslands::FixUpImmediateBr(MachineFunction &Fn, ImmBranch &Br) {
870 MachineInstr *MI = Br.MI;
871 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
873 // Check to see if the DestBB is already in-range.
874 if (BBIsInRange(MI, DestBB, Br.MaxDisp))
878 return FixUpUnconditionalBr(Fn, Br);
879 return FixUpConditionalBr(Fn, Br);
882 /// FixUpUnconditionalBr - Fix up an unconditional branch whose destination is
883 /// too far away to fit in its displacement field. If the LR register has been
884 /// spilled in the epilogue, then we can use BL to implement a far jump.
885 /// Otherwise, add an intermediate branch instruction to to a branch.
887 ARMConstantIslands::FixUpUnconditionalBr(MachineFunction &Fn, ImmBranch &Br) {
888 MachineInstr *MI = Br.MI;
889 MachineBasicBlock *MBB = MI->getParent();
890 assert(AFI->isThumbFunction() && "Expected a Thumb function!");
892 // Use BL to implement far jump.
893 Br.MaxDisp = (1 << 21) * 2;
894 MI->setInstrDescriptor(TII->get(ARM::tBfar));
895 BBSizes[MBB->getNumber()] += 2;
896 AdjustBBOffsetsAfter(MBB, 2);
900 DOUT << " Changed B to long jump " << *MI;
905 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
906 /// the specific unconditional branch instruction.
907 static inline unsigned getUnconditionalBrDisp(int Opc) {
908 return (Opc == ARM::tB) ? (1<<10)*2 : (1<<23)*4;
911 /// FixUpConditionalBr - Fix up a conditional branch whose destination is too
912 /// far away to fit in its displacement field. It is converted to an inverse
913 /// conditional branch + an unconditional branch to the destination.
915 ARMConstantIslands::FixUpConditionalBr(MachineFunction &Fn, ImmBranch &Br) {
916 MachineInstr *MI = Br.MI;
917 MachineBasicBlock *DestBB = MI->getOperand(0).getMachineBasicBlock();
919 // Add a unconditional branch to the destination and invert the branch
920 // condition to jump over it:
926 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImmedValue();
927 CC = ARMCC::getOppositeCondition(CC);
929 // If the branch is at the end of its MBB and that has a fall-through block,
930 // direct the updated conditional branch to the fall-through block. Otherwise,
931 // split the MBB before the next instruction.
932 MachineBasicBlock *MBB = MI->getParent();
933 MachineInstr *BMI = &MBB->back();
934 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
938 if (next(MachineBasicBlock::iterator(MI)) == MBB->back() &&
939 BMI->getOpcode() == Br.UncondBr) {
940 // Last MI in the BB is a unconditional branch. Can we simply invert the
941 // condition and swap destinations:
947 MachineBasicBlock *NewDest = BMI->getOperand(0).getMachineBasicBlock();
948 if (BBIsInRange(MI, NewDest, Br.MaxDisp)) {
949 DOUT << " Invert Bcc condition and swap its destination with " << *BMI;
950 BMI->getOperand(0).setMachineBasicBlock(DestBB);
951 MI->getOperand(0).setMachineBasicBlock(NewDest);
952 MI->getOperand(1).setImm(CC);
959 SplitBlockBeforeInstr(MI);
960 // No need for the branch to the next block. We're adding a unconditional
961 // branch to the destination.
962 MBB->back().eraseFromParent();
964 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
966 DOUT << " Insert B to BB#" << DestBB->getNumber()
967 << " also invert condition and change dest. to BB#"
968 << NextBB->getNumber() << "\n";
970 // Insert a unconditional branch and replace the conditional branch.
971 // Also update the ImmBranch as well as adding a new entry for the new branch.
972 BuildMI(MBB, TII->get(MI->getOpcode())).addMBB(NextBB).addImm(CC);
973 Br.MI = &MBB->back();
974 BuildMI(MBB, TII->get(Br.UncondBr)).addMBB(DestBB);
975 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
976 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
977 MI->eraseFromParent();
979 // Increase the size of MBB to account for the new unconditional branch.
980 int delta = ARM::GetInstSize(&MBB->back());
981 BBSizes[MBB->getNumber()] += delta;
982 AdjustBBOffsetsAfter(MBB, delta);
986 /// UndoLRSpillRestore - Remove Thumb push / pop instructions that only spills
987 /// LR / restores LR to pc.
988 bool ARMConstantIslands::UndoLRSpillRestore() {
989 bool MadeChange = false;
990 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
991 MachineInstr *MI = PushPopMIs[i];
992 if (MI->getNumOperands() == 1) {
993 if (MI->getOpcode() == ARM::tPOP_RET &&
994 MI->getOperand(0).getReg() == ARM::PC)
995 BuildMI(MI->getParent(), TII->get(ARM::tBX_RET));
996 MI->eraseFromParent();