1 //===-- MipsConstantIslandPass.cpp - Emit Pc Relative loads----------------===//
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 //===----------------------------------------------------------------------===//
11 // This pass is used to make Pc relative loads of constants.
12 // For now, only Mips16 will use this.
14 // Loading constants inline is expensive on Mips16 and it's in general better
15 // to place the constant nearby in code space and then it can be loaded with a
16 // simple 16 bit load instruction.
18 // The constants can be not just numbers but addresses of functions and labels.
19 // This can be particularly helpful in static relocation mode for embedded
24 #define DEBUG_TYPE "mips-constant-islands"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "MipsMachineFunction.h"
29 #include "MipsTargetMachine.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/InstIterator.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Support/Format.h"
49 STATISTIC(NumCPEs, "Number of constpool entries");
50 STATISTIC(NumSplit, "Number of uncond branches inserted");
51 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
52 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
54 // FIXME: This option should be removed once it has received sufficient testing.
56 AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
57 cl::desc("Align constant islands in code"));
60 // Rather than do make check tests with huge amounts of code, we force
61 // the test to use this amount.
63 static cl::opt<int> ConstantIslandsSmallOffset(
64 "mips-constant-islands-small-offset",
66 cl::desc("Make small offsets be this amount for testing purposes"),
73 typedef MachineBasicBlock::iterator Iter;
74 typedef MachineBasicBlock::reverse_iterator ReverseIter;
76 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
77 /// requires constant pool entries to be scattered among the instructions
78 /// inside a function. To do this, it completely ignores the normal LLVM
79 /// constant pool; instead, it places constants wherever it feels like with
80 /// special instructions.
82 /// The terminology used in this pass includes:
83 /// Islands - Clumps of constants placed in the function.
84 /// Water - Potential places where an island could be formed.
85 /// CPE - A constant pool entry that has been placed somewhere, which
86 /// tracks a list of users.
88 class MipsConstantIslands : public MachineFunctionPass {
90 /// BasicBlockInfo - Information about the offset and size of a single
92 struct BasicBlockInfo {
93 /// Offset - Distance from the beginning of the function to the beginning
94 /// of this basic block.
96 /// Offsets are computed assuming worst case padding before an aligned
97 /// block. This means that subtracting basic block offsets always gives a
98 /// conservative estimate of the real distance which may be smaller.
100 /// Because worst case padding is used, the computed offset of an aligned
101 /// block may not actually be aligned.
104 /// Size - Size of the basic block in bytes. If the block contains
105 /// inline assembly, this is a worst case estimate.
107 /// The size does not include any alignment padding whether from the
108 /// beginning of the block, or from an aligned jump table at the end.
111 // FIXME: ignore LogAlign for this patch
113 unsigned postOffset(unsigned LogAlign = 0) const {
114 unsigned PO = Offset + Size;
118 BasicBlockInfo() : Offset(0), Size(0) {}
122 std::vector<BasicBlockInfo> BBInfo;
124 /// WaterList - A sorted list of basic blocks where islands could be placed
125 /// (i.e. blocks that don't fall through to the following block, due
126 /// to a return, unreachable, or unconditional branch).
127 std::vector<MachineBasicBlock*> WaterList;
129 /// NewWaterList - The subset of WaterList that was created since the
130 /// previous iteration by inserting unconditional branches.
131 SmallSet<MachineBasicBlock*, 4> NewWaterList;
133 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
135 /// CPUser - One user of a constant pool, keeping the machine instruction
136 /// pointer, the constant pool being referenced, and the max displacement
137 /// allowed from the instruction to the CP. The HighWaterMark records the
138 /// highest basic block where a new CPEntry can be placed. To ensure this
139 /// pass terminates, the CP entries are initially placed at the end of the
140 /// function and then move monotonically to lower addresses. The
141 /// exception to this rule is when the current CP entry for a particular
142 /// CPUser is out of range, but there is another CP entry for the same
143 /// constant value in range. We want to use the existing in-range CP
144 /// entry, but if it later moves out of range, the search for new water
145 /// should resume where it left off. The HighWaterMark is used to record
150 MachineBasicBlock *HighWaterMark;
153 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
154 // with different displacements
155 unsigned LongFormOpcode;
158 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
160 unsigned longformmaxdisp, unsigned longformopcode)
161 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
162 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
164 HighWaterMark = CPEMI->getParent();
166 /// getMaxDisp - Returns the maximum displacement supported by MI.
167 unsigned getMaxDisp() const {
168 unsigned xMaxDisp = ConstantIslandsSmallOffset?
169 ConstantIslandsSmallOffset: MaxDisp;
172 unsigned getLongFormMaxDisp() const {
173 return LongFormMaxDisp;
175 unsigned getLongFormOpcode() const {
176 return LongFormOpcode;
180 /// CPUsers - Keep track of all of the machine instructions that use various
181 /// constant pools and their max displacement.
182 std::vector<CPUser> CPUsers;
184 /// CPEntry - One per constant pool entry, keeping the machine instruction
185 /// pointer, the constpool index, and the number of CPUser's which
186 /// reference this entry.
191 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
192 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
195 /// CPEntries - Keep track of all of the constant pool entry machine
196 /// instructions. For each original constpool index (i.e. those that
197 /// existed upon entry to this pass), it keeps a vector of entries.
198 /// Original elements are cloned as we go along; the clones are
199 /// put in the vector of the original element, but have distinct CPIs.
200 std::vector<std::vector<CPEntry> > CPEntries;
202 /// ImmBranch - One per immediate branch, keeping the machine instruction
203 /// pointer, conditional or unconditional, the max displacement,
204 /// and (if isCond is true) the corresponding unconditional branch
208 unsigned MaxDisp : 31;
211 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
212 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
215 /// ImmBranches - Keep track of all the immediate branch instructions.
217 std::vector<ImmBranch> ImmBranches;
219 /// HasFarJump - True if any far jump instruction has been emitted during
220 /// the branch fix up pass.
223 const TargetMachine &TM;
226 const MipsSubtarget *STI;
227 const MipsInstrInfo *TII;
228 MipsFunctionInfo *MFI;
230 MachineConstantPool *MCP;
232 unsigned PICLabelUId;
233 bool PrescannedForConstants;
235 void initPICLabelUId(unsigned UId) {
240 unsigned createPICLabelUId() {
241 return PICLabelUId++;
246 MipsConstantIslands(TargetMachine &tm)
247 : MachineFunctionPass(ID), TM(tm),
248 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
249 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
250 STI(&TM.getSubtarget<MipsSubtarget>()), MF(0), MCP(0),
251 PrescannedForConstants(false){}
253 virtual const char *getPassName() const {
254 return "Mips Constant Islands";
257 bool runOnMachineFunction(MachineFunction &F);
259 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
260 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
261 unsigned getCPELogAlign(const MachineInstr *CPEMI);
262 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
263 unsigned getOffsetOf(MachineInstr *MI) const;
264 unsigned getUserOffset(CPUser&) const;
268 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
269 unsigned Disp, bool NegativeOK);
270 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
273 bool isLongFormOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
276 void computeBlockSize(MachineBasicBlock *MBB);
277 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
278 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
279 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
280 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
281 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
282 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
283 bool findAvailableWater(CPUser&U, unsigned UserOffset,
284 water_iterator &WaterIter);
285 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
286 MachineBasicBlock *&NewMBB);
287 bool handleConstantPoolUser(unsigned CPUserIndex);
288 void removeDeadCPEMI(MachineInstr *CPEMI);
289 bool removeUnusedCPEntries();
290 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
291 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
292 bool DoDump = false);
293 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
294 CPUser &U, unsigned &Growth);
295 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
296 bool fixupImmediateBr(ImmBranch &Br);
297 bool fixupConditionalBr(ImmBranch &Br);
298 bool fixupUnconditionalBr(ImmBranch &Br);
300 void prescanForConstants();
306 char MipsConstantIslands::ID = 0;
307 } // end of anonymous namespace
310 bool MipsConstantIslands::isLongFormOffsetInRange
311 (unsigned UserOffset, unsigned TrialOffset,
313 return isOffsetInRange(UserOffset, TrialOffset,
314 U.getLongFormMaxDisp(), U.NegOk);
317 bool MipsConstantIslands::isOffsetInRange
318 (unsigned UserOffset, unsigned TrialOffset,
320 return isOffsetInRange(UserOffset, TrialOffset,
321 U.getMaxDisp(), U.NegOk);
323 /// print block size and offset information - debugging
324 void MipsConstantIslands::dumpBBs() {
326 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
327 const BasicBlockInfo &BBI = BBInfo[J];
328 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
329 << format(" size=%#x\n", BBInfo[J].Size);
333 /// createMipsLongBranchPass - Returns a pass that converts branches to long
335 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
336 return new MipsConstantIslands(tm);
339 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
340 // The intention is for this to be a mips16 only pass for now
343 MCP = mf.getConstantPool();
344 DEBUG(dbgs() << "constant island machine function " << "\n");
345 if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
346 !MipsSubtarget::useConstantIslands()) {
349 TII = (const MipsInstrInfo*)MF->getTarget().getInstrInfo();
350 MFI = MF->getInfo<MipsFunctionInfo>();
351 DEBUG(dbgs() << "constant island processing " << "\n");
353 // will need to make predermination if there is any constants we need to
354 // put in constant islands. TBD.
356 if (!PrescannedForConstants) prescanForConstants();
359 // This pass invalidates liveness information when it splits basic blocks.
360 MF->getRegInfo().invalidateLiveness();
362 // Renumber all of the machine basic blocks in the function, guaranteeing that
363 // the numbers agree with the position of the block in the function.
364 MF->RenumberBlocks();
366 bool MadeChange = false;
368 // Perform the initial placement of the constant pool entries. To start with,
369 // we put them all at the end of the function.
370 std::vector<MachineInstr*> CPEMIs;
372 doInitialPlacement(CPEMIs);
374 /// The next UID to take is the first unused one.
375 initPICLabelUId(CPEMIs.size());
377 // Do the initial scan of the function, building up information about the
378 // sizes of each block, the location of all the water, and finding all of the
379 // constant pool users.
380 initializeFunctionInfo(CPEMIs);
384 /// Remove dead constant pool entries.
385 MadeChange |= removeUnusedCPEntries();
387 // Iteratively place constant pool entries and fix up branches until there
389 unsigned NoCPIters = 0, NoBRIters = 0;
392 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
393 bool CPChange = false;
394 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
395 CPChange |= handleConstantPoolUser(i);
396 if (CPChange && ++NoCPIters > 30)
397 report_fatal_error("Constant Island pass failed to converge!");
400 // Clear NewWaterList now. If we split a block for branches, it should
401 // appear as "new water" for the next iteration of constant pool placement.
402 NewWaterList.clear();
404 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
405 bool BRChange = false;
407 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
408 BRChange |= fixupImmediateBr(ImmBranches[i]);
409 if (BRChange && ++NoBRIters > 30)
410 report_fatal_error("Branch Fix Up pass failed to converge!");
413 if (!CPChange && !BRChange)
418 DEBUG(dbgs() << '\n'; dumpBBs());
428 /// doInitialPlacement - Perform the initial placement of the constant pool
429 /// entries. To start with, we put them all at the end of the function.
431 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
432 // Create the basic block to hold the CPE's.
433 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
437 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
438 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
440 // Mark the basic block as required by the const-pool.
441 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
442 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
444 // The function needs to be as aligned as the basic blocks. The linker may
445 // move functions around based on their alignment.
446 MF->ensureAlignment(BB->getAlignment());
448 // Order the entries in BB by descending alignment. That ensures correct
449 // alignment of all entries as long as BB is sufficiently aligned. Keep
450 // track of the insertion point for each alignment. We are going to bucket
451 // sort the entries as they are created.
452 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
454 // Add all of the constants from the constant pool to the end block, use an
455 // identity mapping of CPI's to CPE's.
456 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
458 const DataLayout &TD = *MF->getTarget().getDataLayout();
459 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
460 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
461 assert(Size >= 4 && "Too small constant pool entry");
462 unsigned Align = CPs[i].getAlignment();
463 assert(isPowerOf2_32(Align) && "Invalid alignment");
464 // Verify that all constant pool entries are a multiple of their alignment.
465 // If not, we would have to pad them out so that instructions stay aligned.
466 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
468 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
469 unsigned LogAlign = Log2_32(Align);
470 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
472 MachineInstr *CPEMI =
473 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
474 .addImm(i).addConstantPoolIndex(i).addImm(Size);
476 CPEMIs.push_back(CPEMI);
478 // Ensure that future entries with higher alignment get inserted before
479 // CPEMI. This is bucket sort with iterators.
480 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
481 if (InsPoint[a] == InsAt)
483 // Add a new CPEntry, but no corresponding CPUser yet.
484 std::vector<CPEntry> CPEs;
485 CPEs.push_back(CPEntry(CPEMI, i));
486 CPEntries.push_back(CPEs);
488 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
489 << Size << ", align = " << Align <<'\n');
494 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
495 /// into the block immediately after it.
496 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
497 // Get the next machine basic block in the function.
498 MachineFunction::iterator MBBI = MBB;
499 // Can't fall off end of function.
500 if (llvm::next(MBBI) == MBB->getParent()->end())
503 MachineBasicBlock *NextBB = llvm::next(MBBI);
504 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
505 E = MBB->succ_end(); I != E; ++I)
512 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
513 /// look up the corresponding CPEntry.
514 MipsConstantIslands::CPEntry
515 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
516 const MachineInstr *CPEMI) {
517 std::vector<CPEntry> &CPEs = CPEntries[CPI];
518 // Number of entries per constpool index should be small, just do a
520 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
521 if (CPEs[i].CPEMI == CPEMI)
527 /// getCPELogAlign - Returns the required alignment of the constant pool entry
528 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
529 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
530 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
532 // Everything is 4-byte aligned unless AlignConstantIslands is set.
533 if (!AlignConstantIslands)
536 unsigned CPI = CPEMI->getOperand(1).getIndex();
537 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
538 unsigned Align = MCP->getConstants()[CPI].getAlignment();
539 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
540 return Log2_32(Align);
543 /// initializeFunctionInfo - Do the initial scan of the function, building up
544 /// information about the sizes of each block, the location of all the water,
545 /// and finding all of the constant pool users.
546 void MipsConstantIslands::
547 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
549 BBInfo.resize(MF->getNumBlockIDs());
551 // First thing, compute the size of all basic blocks, and see if the function
552 // has any inline assembly in it. If so, we have to be conservative about
553 // alignment assumptions, as we don't know for sure the size of any
554 // instructions in the inline assembly.
555 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
559 // Compute block offsets.
560 adjustBBOffsetsAfter(MF->begin());
562 // Now go back through the instructions and build up our data structures.
563 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
565 MachineBasicBlock &MBB = *MBBI;
567 // If this block doesn't fall through into the next MBB, then this is
568 // 'water' that a constant pool island could be placed.
569 if (!BBHasFallthrough(&MBB))
570 WaterList.push_back(&MBB);
571 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
573 if (I->isDebugValue())
576 int Opc = I->getOpcode();
585 continue; // Ignore other JT branches
587 // Record this immediate branch.
588 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
589 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
594 if (Opc == Mips::CONSTPOOL_ENTRY)
598 // Scan the instructions for constant pool operands.
599 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
600 if (I->getOperand(op).isCPI()) {
602 // We found one. The addressing mode tells us the max displacement
603 // from the PC that this instruction permits.
605 // Basic size info comes from the TSFlags field.
609 unsigned LongFormBits = 0;
610 unsigned LongFormScale = 0;
611 unsigned LongFormOpcode = 0;
614 llvm_unreachable("Unknown addressing mode for CP reference!");
615 case Mips::LwRxPcTcp16:
618 LongFormOpcode = Mips::LwRxPcTcpX16;
620 case Mips::LwRxPcTcpX16:
626 // Remember that this is a user of a CP entry.
627 unsigned CPI = I->getOperand(op).getIndex();
628 MachineInstr *CPEMI = CPEMIs[CPI];
629 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
630 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
631 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
632 LongFormMaxOffs, LongFormOpcode));
634 // Increment corresponding CPEntry reference count.
635 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
636 assert(CPE && "Cannot find a corresponding CPEntry!");
639 // Instructions can only use one CP entry, don't bother scanning the
640 // rest of the operands.
650 /// computeBlockSize - Compute the size and some alignment information for MBB.
651 /// This function updates BBInfo directly.
652 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
653 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
656 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
658 BBI.Size += TII->GetInstSizeInBytes(I);
662 /// getOffsetOf - Return the current offset of the specified machine instruction
663 /// from the start of the function. This offset changes as stuff is moved
664 /// around inside the function.
665 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
666 MachineBasicBlock *MBB = MI->getParent();
668 // The offset is composed of two things: the sum of the sizes of all MBB's
669 // before this instruction's block, and the offset from the start of the block
671 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
673 // Sum instructions before MI in MBB.
674 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
675 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
676 Offset += TII->GetInstSizeInBytes(I);
681 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
683 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
684 const MachineBasicBlock *RHS) {
685 return LHS->getNumber() < RHS->getNumber();
688 /// updateForInsertedWaterBlock - When a block is newly inserted into the
689 /// machine function, it upsets all of the block numbers. Renumber the blocks
690 /// and update the arrays that parallel this numbering.
691 void MipsConstantIslands::updateForInsertedWaterBlock
692 (MachineBasicBlock *NewBB) {
693 // Renumber the MBB's to keep them consecutive.
694 NewBB->getParent()->RenumberBlocks(NewBB);
696 // Insert an entry into BBInfo to align it properly with the (newly
697 // renumbered) block numbers.
698 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
700 // Next, update WaterList. Specifically, we need to add NewMBB as having
701 // available water after it.
703 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
705 WaterList.insert(IP, NewBB);
708 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
709 return getOffsetOf(U.MI);
712 /// Split the basic block containing MI into two blocks, which are joined by
713 /// an unconditional branch. Update data structures and renumber blocks to
714 /// account for this change and returns the newly created block.
715 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
717 MachineBasicBlock *OrigBB = MI->getParent();
719 // Create a new MBB for the code after the OrigBB.
720 MachineBasicBlock *NewBB =
721 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
722 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
723 MF->insert(MBBI, NewBB);
725 // Splice the instructions starting with MI over to NewBB.
726 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
728 // Add an unconditional branch from OrigBB to NewBB.
729 // Note the new unconditional branch is not being recorded.
730 // There doesn't seem to be meaningful DebugInfo available; this doesn't
731 // correspond to anything in the source.
732 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::BimmX16)).addMBB(NewBB);
735 // Update the CFG. All succs of OrigBB are now succs of NewBB.
736 NewBB->transferSuccessors(OrigBB);
738 // OrigBB branches to NewBB.
739 OrigBB->addSuccessor(NewBB);
741 // Update internal data structures to account for the newly inserted MBB.
742 // This is almost the same as updateForInsertedWaterBlock, except that
743 // the Water goes after OrigBB, not NewBB.
744 MF->RenumberBlocks(NewBB);
746 // Insert an entry into BBInfo to align it properly with the (newly
747 // renumbered) block numbers.
748 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
750 // Next, update WaterList. Specifically, we need to add OrigMBB as having
751 // available water after it (but not if it's already there, which happens
752 // when splitting before a conditional branch that is followed by an
753 // unconditional branch - in that case we want to insert NewBB).
755 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
757 MachineBasicBlock* WaterBB = *IP;
758 if (WaterBB == OrigBB)
759 WaterList.insert(llvm::next(IP), NewBB);
761 WaterList.insert(IP, OrigBB);
762 NewWaterList.insert(OrigBB);
764 // Figure out how large the OrigBB is. As the first half of the original
765 // block, it cannot contain a tablejump. The size includes
766 // the new jump we added. (It should be possible to do this without
767 // recounting everything, but it's very confusing, and this is rarely
769 computeBlockSize(OrigBB);
771 // Figure out how large the NewMBB is. As the second half of the original
772 // block, it may contain a tablejump.
773 computeBlockSize(NewBB);
775 // All BBOffsets following these blocks must be modified.
776 adjustBBOffsetsAfter(OrigBB);
783 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
784 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
785 /// constant pool entry).
786 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
787 unsigned TrialOffset, unsigned MaxDisp,
789 if (UserOffset <= TrialOffset) {
790 // User before the Trial.
791 if (TrialOffset - UserOffset <= MaxDisp)
793 } else if (NegativeOK) {
794 if (UserOffset - TrialOffset <= MaxDisp)
800 /// isWaterInRange - Returns true if a CPE placed after the specified
801 /// Water (a basic block) will be in range for the specific MI.
803 /// Compute how much the function will grow by inserting a CPE after Water.
804 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
805 MachineBasicBlock* Water, CPUser &U,
807 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
808 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
809 unsigned NextBlockOffset, NextBlockAlignment;
810 MachineFunction::const_iterator NextBlock = Water;
811 if (++NextBlock == MF->end()) {
812 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
813 NextBlockAlignment = 0;
815 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
816 NextBlockAlignment = NextBlock->getAlignment();
818 unsigned Size = U.CPEMI->getOperand(2).getImm();
819 unsigned CPEEnd = CPEOffset + Size;
821 // The CPE may be able to hide in the alignment padding before the next
822 // block. It may also cause more padding to be required if it is more aligned
823 // that the next block.
824 if (CPEEnd > NextBlockOffset) {
825 Growth = CPEEnd - NextBlockOffset;
826 // Compute the padding that would go at the end of the CPE to align the next
828 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
830 // If the CPE is to be inserted before the instruction, that will raise
831 // the offset of the instruction. Also account for unknown alignment padding
832 // in blocks between CPE and the user.
833 if (CPEOffset < UserOffset)
834 UserOffset += Growth;
836 // CPE fits in existing padding.
839 return isOffsetInRange(UserOffset, CPEOffset, U);
842 /// isCPEntryInRange - Returns true if the distance between specific MI and
843 /// specific ConstPool entry instruction can fit in MI's displacement field.
844 bool MipsConstantIslands::isCPEntryInRange
845 (MachineInstr *MI, unsigned UserOffset,
846 MachineInstr *CPEMI, unsigned MaxDisp,
847 bool NegOk, bool DoDump) {
848 unsigned CPEOffset = getOffsetOf(CPEMI);
852 unsigned Block = MI->getParent()->getNumber();
853 const BasicBlockInfo &BBI = BBInfo[Block];
854 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
855 << " max delta=" << MaxDisp
856 << format(" insn address=%#x", UserOffset)
857 << " in BB#" << Block << ": "
858 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
859 << format("CPE address=%#x offset=%+d: ", CPEOffset,
860 int(CPEOffset-UserOffset));
864 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
868 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
869 /// unconditionally branches to its only successor.
870 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
871 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
873 MachineBasicBlock *Succ = *MBB->succ_begin();
874 MachineBasicBlock *Pred = *MBB->pred_begin();
875 MachineInstr *PredMI = &Pred->back();
876 if (PredMI->getOpcode() == Mips::BimmX16)
877 return PredMI->getOperand(0).getMBB() == Succ;
882 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
883 unsigned BBNum = BB->getNumber();
884 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
885 // Get the offset and known bits at the end of the layout predecessor.
886 // Include the alignment of the current block.
887 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
888 BBInfo[i].Offset = Offset;
892 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
893 /// and instruction CPEMI, and decrement its refcount. If the refcount
894 /// becomes 0 remove the entry and instruction. Returns true if we removed
895 /// the entry, false if we didn't.
897 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
898 MachineInstr *CPEMI) {
899 // Find the old entry. Eliminate it if it is no longer used.
900 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
901 assert(CPE && "Unexpected!");
902 if (--CPE->RefCount == 0) {
903 removeDeadCPEMI(CPEMI);
911 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
912 /// if not, see if an in-range clone of the CPE is in range, and if so,
913 /// change the data structures so the user references the clone. Returns:
914 /// 0 = no existing entry found
915 /// 1 = entry found, and there were no code insertions or deletions
916 /// 2 = entry found, and there were code insertions or deletions
917 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
919 MachineInstr *UserMI = U.MI;
920 MachineInstr *CPEMI = U.CPEMI;
922 // Check to see if the CPE is already in-range.
923 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
925 DEBUG(dbgs() << "In range\n");
929 // No. Look for previously created clones of the CPE that are in range.
930 unsigned CPI = CPEMI->getOperand(1).getIndex();
931 std::vector<CPEntry> &CPEs = CPEntries[CPI];
932 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
933 // We already tried this one
934 if (CPEs[i].CPEMI == CPEMI)
936 // Removing CPEs can leave empty entries, skip
937 if (CPEs[i].CPEMI == NULL)
939 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
941 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
942 << CPEs[i].CPI << "\n");
943 // Point the CPUser node to the replacement
944 U.CPEMI = CPEs[i].CPEMI;
945 // Change the CPI in the instruction operand to refer to the clone.
946 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
947 if (UserMI->getOperand(j).isCPI()) {
948 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
951 // Adjust the refcount of the clone...
953 // ...and the original. If we didn't remove the old entry, none of the
954 // addresses changed, so we don't need another pass.
955 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
961 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
962 /// This version checks if the longer form of the instruction can be used to
963 /// to satisfy things.
964 /// if not, see if an in-range clone of the CPE is in range, and if so,
965 /// change the data structures so the user references the clone. Returns:
966 /// 0 = no existing entry found
967 /// 1 = entry found, and there were no code insertions or deletions
968 /// 2 = entry found, and there were code insertions or deletions
969 int MipsConstantIslands::findLongFormInRangeCPEntry
970 (CPUser& U, unsigned UserOffset)
972 MachineInstr *UserMI = U.MI;
973 MachineInstr *CPEMI = U.CPEMI;
975 // Check to see if the CPE is already in-range.
976 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
977 U.getLongFormMaxDisp(), U.NegOk,
979 DEBUG(dbgs() << "In range\n");
980 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
981 return 2; // instruction is longer length now
984 // No. Look for previously created clones of the CPE that are in range.
985 unsigned CPI = CPEMI->getOperand(1).getIndex();
986 std::vector<CPEntry> &CPEs = CPEntries[CPI];
987 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
988 // We already tried this one
989 if (CPEs[i].CPEMI == CPEMI)
991 // Removing CPEs can leave empty entries, skip
992 if (CPEs[i].CPEMI == NULL)
994 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
995 U.getLongFormMaxDisp(), U.NegOk)) {
996 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
997 << CPEs[i].CPI << "\n");
998 // Point the CPUser node to the replacement
999 U.CPEMI = CPEs[i].CPEMI;
1000 // Change the CPI in the instruction operand to refer to the clone.
1001 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1002 if (UserMI->getOperand(j).isCPI()) {
1003 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1006 // Adjust the refcount of the clone...
1008 // ...and the original. If we didn't remove the old entry, none of the
1009 // addresses changed, so we don't need another pass.
1010 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1016 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1017 /// the specific unconditional branch instruction.
1018 static inline unsigned getUnconditionalBrDisp(int Opc) {
1021 return ((1<<16)-1)*2;
1025 return ((1<<16)-1)*2;
1028 /// findAvailableWater - Look for an existing entry in the WaterList in which
1029 /// we can place the CPE referenced from U so it's within range of U's MI.
1030 /// Returns true if found, false if not. If it returns true, WaterIter
1031 /// is set to the WaterList entry.
1032 /// To ensure that this pass
1033 /// terminates, the CPE location for a particular CPUser is only allowed to
1034 /// move to a lower address, so search backward from the end of the list and
1035 /// prefer the first water that is in range.
1036 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1037 water_iterator &WaterIter) {
1038 if (WaterList.empty())
1041 unsigned BestGrowth = ~0u;
1042 for (water_iterator IP = prior(WaterList.end()), B = WaterList.begin();;
1044 MachineBasicBlock* WaterBB = *IP;
1045 // Check if water is in range and is either at a lower address than the
1046 // current "high water mark" or a new water block that was created since
1047 // the previous iteration by inserting an unconditional branch. In the
1048 // latter case, we want to allow resetting the high water mark back to
1049 // this new water since we haven't seen it before. Inserting branches
1050 // should be relatively uncommon and when it does happen, we want to be
1051 // sure to take advantage of it for all the CPEs near that block, so that
1052 // we don't insert more branches than necessary.
1054 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1055 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1056 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1057 // This is the least amount of required padding seen so far.
1058 BestGrowth = Growth;
1060 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1061 << " Growth=" << Growth << '\n');
1063 // Keep looking unless it is perfect.
1064 if (BestGrowth == 0)
1070 return BestGrowth != ~0u;
1073 /// createNewWater - No existing WaterList entry will work for
1074 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1075 /// block is used if in range, and the conditional branch munged so control
1076 /// flow is correct. Otherwise the block is split to create a hole with an
1077 /// unconditional branch around it. In either case NewMBB is set to a
1078 /// block following which the new island can be inserted (the WaterList
1079 /// is not adjusted).
1080 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1081 unsigned UserOffset,
1082 MachineBasicBlock *&NewMBB) {
1083 CPUser &U = CPUsers[CPUserIndex];
1084 MachineInstr *UserMI = U.MI;
1085 MachineInstr *CPEMI = U.CPEMI;
1086 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1087 MachineBasicBlock *UserMBB = UserMI->getParent();
1088 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1090 // If the block does not end in an unconditional branch already, and if the
1091 // end of the block is within range, make new water there.
1092 if (BBHasFallthrough(UserMBB)) {
1093 // Size of branch to insert.
1095 // Compute the offset where the CPE will begin.
1096 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1098 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1099 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1100 << format(", expected CPE offset %#x\n", CPEOffset));
1101 NewMBB = llvm::next(MachineFunction::iterator(UserMBB));
1102 // Add an unconditional branch from UserMBB to fallthrough block. Record
1103 // it for branch lengthening; this new branch will not get out of range,
1104 // but if the preceding conditional branch is out of range, the targets
1105 // will be exchanged, and the altered branch may be out of range, so the
1106 // machinery has to know about it.
1107 int UncondBr = Mips::BimmX16;
1108 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1109 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1110 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1111 MaxDisp, false, UncondBr));
1112 BBInfo[UserMBB->getNumber()].Size += Delta;
1113 adjustBBOffsetsAfter(UserMBB);
1118 // What a big block. Find a place within the block to split it.
1120 // Try to split the block so it's fully aligned. Compute the latest split
1121 // point where we can add a 4-byte branch instruction, and then align to
1122 // LogAlign which is the largest possible alignment in the function.
1123 unsigned LogAlign = MF->getAlignment();
1124 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1125 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1126 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1129 // The 4 in the following is for the unconditional branch we'll be inserting
1130 // Alignment of the island is handled
1131 // inside isOffsetInRange.
1132 BaseInsertOffset -= 4;
1134 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1135 << " la=" << LogAlign << '\n');
1137 // This could point off the end of the block if we've already got constant
1138 // pool entries following this block; only the last one is in the water list.
1139 // Back past any possible branches (allow for a conditional and a maximally
1140 // long unconditional).
1141 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1142 BaseInsertOffset = UserBBI.postOffset() - 8;
1143 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1145 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1146 CPEMI->getOperand(2).getImm();
1147 MachineBasicBlock::iterator MI = UserMI;
1149 unsigned CPUIndex = CPUserIndex+1;
1150 unsigned NumCPUsers = CPUsers.size();
1151 //MachineInstr *LastIT = 0;
1152 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1153 Offset < BaseInsertOffset;
1154 Offset += TII->GetInstSizeInBytes(MI),
1155 MI = llvm::next(MI)) {
1156 assert(MI != UserMBB->end() && "Fell off end of block");
1157 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1158 CPUser &U = CPUsers[CPUIndex];
1159 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1160 // Shift intertion point by one unit of alignment so it is within reach.
1161 BaseInsertOffset -= 1u << LogAlign;
1162 EndInsertOffset -= 1u << LogAlign;
1164 // This is overly conservative, as we don't account for CPEMIs being
1165 // reused within the block, but it doesn't matter much. Also assume CPEs
1166 // are added in order with alignment padding. We may eventually be able
1167 // to pack the aligned CPEs better.
1168 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1174 NewMBB = splitBlockBeforeInstr(MI);
1177 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1178 /// is out-of-range. If so, pick up the constant pool value and move it some
1179 /// place in-range. Return true if we changed any addresses (thus must run
1180 /// another pass of branch lengthening), false otherwise.
1181 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1182 CPUser &U = CPUsers[CPUserIndex];
1183 MachineInstr *UserMI = U.MI;
1184 MachineInstr *CPEMI = U.CPEMI;
1185 unsigned CPI = CPEMI->getOperand(1).getIndex();
1186 unsigned Size = CPEMI->getOperand(2).getImm();
1187 // Compute this only once, it's expensive.
1188 unsigned UserOffset = getUserOffset(U);
1190 // See if the current entry is within range, or there is a clone of it
1192 int result = findInRangeCPEntry(U, UserOffset);
1193 if (result==1) return false;
1194 else if (result==2) return true;
1197 // Look for water where we can place this CPE.
1198 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1199 MachineBasicBlock *NewMBB;
1201 if (findAvailableWater(U, UserOffset, IP)) {
1202 DEBUG(dbgs() << "Found water in range\n");
1203 MachineBasicBlock *WaterBB = *IP;
1205 // If the original WaterList entry was "new water" on this iteration,
1206 // propagate that to the new island. This is just keeping NewWaterList
1207 // updated to match the WaterList, which will be updated below.
1208 if (NewWaterList.erase(WaterBB))
1209 NewWaterList.insert(NewIsland);
1211 // The new CPE goes before the following block (NewMBB).
1212 NewMBB = llvm::next(MachineFunction::iterator(WaterBB));
1216 // we first see if a longer form of the instrucion could have reached
1217 // the constant. in that case we won't bother to split
1219 result = findLongFormInRangeCPEntry(U, UserOffset);
1221 DEBUG(dbgs() << "No water found\n");
1222 createNewWater(CPUserIndex, UserOffset, NewMBB);
1224 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1225 // called while handling branches so that the water will be seen on the
1226 // next iteration for constant pools, but in this context, we don't want
1227 // it. Check for this so it will be removed from the WaterList.
1228 // Also remove any entry from NewWaterList.
1229 MachineBasicBlock *WaterBB = prior(MachineFunction::iterator(NewMBB));
1230 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1231 if (IP != WaterList.end())
1232 NewWaterList.erase(WaterBB);
1234 // We are adding new water. Update NewWaterList.
1235 NewWaterList.insert(NewIsland);
1238 // Remove the original WaterList entry; we want subsequent insertions in
1239 // this vicinity to go after the one we're about to insert. This
1240 // considerably reduces the number of times we have to move the same CPE
1241 // more than once and is also important to ensure the algorithm terminates.
1242 if (IP != WaterList.end())
1243 WaterList.erase(IP);
1245 // Okay, we know we can put an island before NewMBB now, do it!
1246 MF->insert(NewMBB, NewIsland);
1248 // Update internal data structures to account for the newly inserted MBB.
1249 updateForInsertedWaterBlock(NewIsland);
1251 // Decrement the old entry, and remove it if refcount becomes 0.
1252 decrementCPEReferenceCount(CPI, CPEMI);
1254 // Now that we have an island to add the CPE to, clone the original CPE and
1255 // add it to the island.
1256 U.HighWaterMark = NewIsland;
1257 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1258 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1259 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1262 // Mark the basic block as aligned as required by the const-pool entry.
1263 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1265 // Increase the size of the island block to account for the new entry.
1266 BBInfo[NewIsland->getNumber()].Size += Size;
1267 adjustBBOffsetsAfter(llvm::prior(MachineFunction::iterator(NewIsland)));
1269 // No existing clone of this CPE is within range.
1270 // We will be generating a new clone. Get a UID for it.
1271 unsigned ID = createPICLabelUId();
1273 // Finally, change the CPI in the instruction operand to be ID.
1274 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1275 if (UserMI->getOperand(i).isCPI()) {
1276 UserMI->getOperand(i).setIndex(ID);
1280 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1281 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1286 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1287 /// sizes and offsets of impacted basic blocks.
1288 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1289 MachineBasicBlock *CPEBB = CPEMI->getParent();
1290 unsigned Size = CPEMI->getOperand(2).getImm();
1291 CPEMI->eraseFromParent();
1292 BBInfo[CPEBB->getNumber()].Size -= Size;
1293 // All succeeding offsets have the current size value added in, fix this.
1294 if (CPEBB->empty()) {
1295 BBInfo[CPEBB->getNumber()].Size = 0;
1297 // This block no longer needs to be aligned.
1298 CPEBB->setAlignment(0);
1300 // Entries are sorted by descending alignment, so realign from the front.
1301 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1303 adjustBBOffsetsAfter(CPEBB);
1304 // An island has only one predecessor BB and one successor BB. Check if
1305 // this BB's predecessor jumps directly to this BB's successor. This
1306 // shouldn't happen currently.
1307 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1308 // FIXME: remove the empty blocks after all the work is done?
1311 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1313 bool MipsConstantIslands::removeUnusedCPEntries() {
1314 unsigned MadeChange = false;
1315 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1316 std::vector<CPEntry> &CPEs = CPEntries[i];
1317 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1318 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1319 removeDeadCPEMI(CPEs[j].CPEMI);
1320 CPEs[j].CPEMI = NULL;
1328 /// isBBInRange - Returns true if the distance between specific MI and
1329 /// specific BB can fit in MI's displacement field.
1330 bool MipsConstantIslands::isBBInRange
1331 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1335 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1336 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1338 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1339 << " from BB#" << MI->getParent()->getNumber()
1340 << " max delta=" << MaxDisp
1341 << " from " << getOffsetOf(MI) << " to " << DestOffset
1342 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1344 if (BrOffset <= DestOffset) {
1345 // Branch before the Dest.
1346 if (DestOffset-BrOffset <= MaxDisp)
1349 if (BrOffset-DestOffset <= MaxDisp)
1355 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1356 /// away to fit in its displacement field.
1357 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1358 MachineInstr *MI = Br.MI;
1359 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1361 // Check to see if the DestBB is already in-range.
1362 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1366 return fixupUnconditionalBr(Br);
1367 return fixupConditionalBr(Br);
1370 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1371 /// too far away to fit in its displacement field. If the LR register has been
1372 /// spilled in the epilogue, then we can use BL to implement a far jump.
1373 /// Otherwise, add an intermediate branch instruction to a branch.
1375 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1376 MachineInstr *MI = Br.MI;
1377 MachineBasicBlock *MBB = MI->getParent();
1378 // Use BL to implement far jump.
1379 Br.MaxDisp = ((1 << 16)-1) * 2;
1380 MI->setDesc(TII->get(Mips::BimmX16));
1381 BBInfo[MBB->getNumber()].Size += 2;
1382 adjustBBOffsetsAfter(MBB);
1386 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1391 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1392 /// far away to fit in its displacement field. It is converted to an inverse
1393 /// conditional branch + an unconditional branch to the destination.
1395 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1396 MachineInstr *MI = Br.MI;
1397 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1399 // Add an unconditional branch to the destination and invert the branch
1400 // condition to jump over it:
1406 unsigned CCReg = 0; // FIXME
1407 unsigned CC=0; //FIXME
1409 // If the branch is at the end of its MBB and that has a fall-through block,
1410 // direct the updated conditional branch to the fall-through block. Otherwise,
1411 // split the MBB before the next instruction.
1412 MachineBasicBlock *MBB = MI->getParent();
1413 MachineInstr *BMI = &MBB->back();
1414 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1418 if (llvm::next(MachineBasicBlock::iterator(MI)) == prior(MBB->end()) &&
1419 BMI->getOpcode() == Br.UncondBr) {
1420 // Last MI in the BB is an unconditional branch. Can we simply invert the
1421 // condition and swap destinations:
1427 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1428 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1429 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1431 BMI->getOperand(0).setMBB(DestBB);
1432 MI->getOperand(0).setMBB(NewDest);
1439 splitBlockBeforeInstr(MI);
1440 // No need for the branch to the next block. We're adding an unconditional
1441 // branch to the destination.
1442 int delta = TII->GetInstSizeInBytes(&MBB->back());
1443 BBInfo[MBB->getNumber()].Size -= delta;
1444 MBB->back().eraseFromParent();
1445 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1447 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
1449 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1450 << " also invert condition and change dest. to BB#"
1451 << NextBB->getNumber() << "\n");
1453 // Insert a new conditional branch and a new unconditional branch.
1454 // Also update the ImmBranch as well as adding a new entry for the new branch.
1455 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1456 .addMBB(NextBB).addImm(CC).addReg(CCReg);
1457 Br.MI = &MBB->back();
1458 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1459 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1460 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1461 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1462 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1464 // Remove the old conditional branch. It may or may not still be in MBB.
1465 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1466 MI->eraseFromParent();
1467 adjustBBOffsetsAfter(MBB);
1472 void MipsConstantIslands::prescanForConstants() {
1475 PrescannedForConstants = true;
1476 for (MachineFunction::iterator B =
1477 MF->begin(), E = MF->end(); B != E; ++B) {
1478 for (MachineBasicBlock::instr_iterator I =
1479 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1480 switch(I->getDesc().getOpcode()) {
1481 case Mips::LwConstant32: {
1482 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1483 J = I->getNumOperands();
1484 DEBUG(dbgs() << "num operands " << J << "\n");
1485 MachineOperand& Literal = I->getOperand(1);
1486 if (Literal.isImm()) {
1487 int64_t V = Literal.getImm();
1488 DEBUG(dbgs() << "literal " << V << "\n");
1490 Type::getInt32Ty(MF->getFunction()->getContext());
1491 const Constant *C = ConstantInt::get(Int32Ty, V);
1492 unsigned index = MCP->getConstantPoolIndex(C, 4);
1493 I->getOperand(2).ChangeToImmediate(index);
1494 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1495 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1496 I->RemoveOperand(1);
1497 I->RemoveOperand(1);
1498 I->addOperand(MachineOperand::CreateCPI(index, 0));
1499 I->addOperand(MachineOperand::CreateImm(4));