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
25 #include "MCTargetDesc/MipsBaseInfo.h"
26 #include "Mips16InstrInfo.h"
27 #include "MipsMachineFunction.h"
28 #include "MipsTargetMachine.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Format.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"
48 #define DEBUG_TYPE "mips-constant-islands"
50 STATISTIC(NumCPEs, "Number of constpool entries");
51 STATISTIC(NumSplit, "Number of uncond branches inserted");
52 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
53 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
55 // FIXME: This option should be removed once it has received sufficient testing.
57 AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
58 cl::desc("Align constant islands in code"));
61 // Rather than do make check tests with huge amounts of code, we force
62 // the test to use this amount.
64 static cl::opt<int> ConstantIslandsSmallOffset(
65 "mips-constant-islands-small-offset",
67 cl::desc("Make small offsets be this amount for testing purposes"),
71 // For testing purposes we tell it to not use relaxed load forms so that it
74 static cl::opt<bool> NoLoadRelaxation(
75 "mips-constant-islands-no-load-relaxation",
77 cl::desc("Don't relax loads to long loads - for testing purposes"),
80 static unsigned int branchTargetOperand(MachineInstr *MI) {
81 switch (MI->getOpcode()) {
90 case Mips::BeqzRxImm16:
91 case Mips::BeqzRxImmX16:
92 case Mips::BnezRxImm16:
93 case Mips::BnezRxImmX16:
96 llvm_unreachable("Unknown branch type");
99 static bool isUnconditionalBranch(unsigned int Opcode) {
101 default: return false;
109 static unsigned int longformBranchOpcode(unsigned int Opcode) {
113 return Mips::BimmX16;
116 return Mips::BteqzX16;
119 return Mips::BtnezX16;
122 case Mips::BeqzRxImm16:
123 case Mips::BeqzRxImmX16:
124 return Mips::BeqzRxImmX16;
125 case Mips::BnezRxImm16:
126 case Mips::BnezRxImmX16:
127 return Mips::BnezRxImmX16;
129 llvm_unreachable("Unknown branch type");
133 // FIXME: need to go through this whole constant islands port and check the math
134 // for branch ranges and clean this up and make some functions to calculate things
135 // that are done many times identically.
136 // Need to refactor some of the code to call this routine.
138 static unsigned int branchMaxOffsets(unsigned int Opcode) {
139 unsigned Bits, Scale;
149 case Mips::BeqzRxImm16:
153 case Mips::BeqzRxImmX16:
157 case Mips::BnezRxImm16:
161 case Mips::BnezRxImmX16:
182 llvm_unreachable("Unknown branch type");
184 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
191 typedef MachineBasicBlock::iterator Iter;
192 typedef MachineBasicBlock::reverse_iterator ReverseIter;
194 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
195 /// requires constant pool entries to be scattered among the instructions
196 /// inside a function. To do this, it completely ignores the normal LLVM
197 /// constant pool; instead, it places constants wherever it feels like with
198 /// special instructions.
200 /// The terminology used in this pass includes:
201 /// Islands - Clumps of constants placed in the function.
202 /// Water - Potential places where an island could be formed.
203 /// CPE - A constant pool entry that has been placed somewhere, which
204 /// tracks a list of users.
206 class MipsConstantIslands : public MachineFunctionPass {
208 /// BasicBlockInfo - Information about the offset and size of a single
210 struct BasicBlockInfo {
211 /// Offset - Distance from the beginning of the function to the beginning
212 /// of this basic block.
214 /// Offsets are computed assuming worst case padding before an aligned
215 /// block. This means that subtracting basic block offsets always gives a
216 /// conservative estimate of the real distance which may be smaller.
218 /// Because worst case padding is used, the computed offset of an aligned
219 /// block may not actually be aligned.
222 /// Size - Size of the basic block in bytes. If the block contains
223 /// inline assembly, this is a worst case estimate.
225 /// The size does not include any alignment padding whether from the
226 /// beginning of the block, or from an aligned jump table at the end.
229 // FIXME: ignore LogAlign for this patch
231 unsigned postOffset(unsigned LogAlign = 0) const {
232 unsigned PO = Offset + Size;
236 BasicBlockInfo() : Offset(0), Size(0) {}
240 std::vector<BasicBlockInfo> BBInfo;
242 /// WaterList - A sorted list of basic blocks where islands could be placed
243 /// (i.e. blocks that don't fall through to the following block, due
244 /// to a return, unreachable, or unconditional branch).
245 std::vector<MachineBasicBlock*> WaterList;
247 /// NewWaterList - The subset of WaterList that was created since the
248 /// previous iteration by inserting unconditional branches.
249 SmallSet<MachineBasicBlock*, 4> NewWaterList;
251 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
253 /// CPUser - One user of a constant pool, keeping the machine instruction
254 /// pointer, the constant pool being referenced, and the max displacement
255 /// allowed from the instruction to the CP. The HighWaterMark records the
256 /// highest basic block where a new CPEntry can be placed. To ensure this
257 /// pass terminates, the CP entries are initially placed at the end of the
258 /// function and then move monotonically to lower addresses. The
259 /// exception to this rule is when the current CP entry for a particular
260 /// CPUser is out of range, but there is another CP entry for the same
261 /// constant value in range. We want to use the existing in-range CP
262 /// entry, but if it later moves out of range, the search for new water
263 /// should resume where it left off. The HighWaterMark is used to record
268 MachineBasicBlock *HighWaterMark;
271 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
272 // with different displacements
273 unsigned LongFormOpcode;
276 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
278 unsigned longformmaxdisp, unsigned longformopcode)
279 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
280 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
282 HighWaterMark = CPEMI->getParent();
284 /// getMaxDisp - Returns the maximum displacement supported by MI.
285 unsigned getMaxDisp() const {
286 unsigned xMaxDisp = ConstantIslandsSmallOffset?
287 ConstantIslandsSmallOffset: MaxDisp;
290 void setMaxDisp(unsigned val) {
293 unsigned getLongFormMaxDisp() const {
294 return LongFormMaxDisp;
296 unsigned getLongFormOpcode() const {
297 return LongFormOpcode;
301 /// CPUsers - Keep track of all of the machine instructions that use various
302 /// constant pools and their max displacement.
303 std::vector<CPUser> CPUsers;
305 /// CPEntry - One per constant pool entry, keeping the machine instruction
306 /// pointer, the constpool index, and the number of CPUser's which
307 /// reference this entry.
312 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
313 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
316 /// CPEntries - Keep track of all of the constant pool entry machine
317 /// instructions. For each original constpool index (i.e. those that
318 /// existed upon entry to this pass), it keeps a vector of entries.
319 /// Original elements are cloned as we go along; the clones are
320 /// put in the vector of the original element, but have distinct CPIs.
321 std::vector<std::vector<CPEntry> > CPEntries;
323 /// ImmBranch - One per immediate branch, keeping the machine instruction
324 /// pointer, conditional or unconditional, the max displacement,
325 /// and (if isCond is true) the corresponding unconditional branch
329 unsigned MaxDisp : 31;
332 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
333 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
336 /// ImmBranches - Keep track of all the immediate branch instructions.
338 std::vector<ImmBranch> ImmBranches;
340 /// HasFarJump - True if any far jump instruction has been emitted during
341 /// the branch fix up pass.
344 const TargetMachine &TM;
347 const MipsSubtarget *STI;
348 const Mips16InstrInfo *TII;
349 MipsFunctionInfo *MFI;
351 MachineConstantPool *MCP;
353 unsigned PICLabelUId;
354 bool PrescannedForConstants;
356 void initPICLabelUId(unsigned UId) {
361 unsigned createPICLabelUId() {
362 return PICLabelUId++;
367 MipsConstantIslands(TargetMachine &tm)
368 : MachineFunctionPass(ID), TM(tm),
369 IsPIC(TM.getRelocationModel() == Reloc::PIC_),
370 ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
371 STI(&TM.getSubtarget<MipsSubtarget>()), MF(nullptr), MCP(nullptr),
372 PrescannedForConstants(false){}
374 const char *getPassName() const override {
375 return "Mips Constant Islands";
378 bool runOnMachineFunction(MachineFunction &F) override;
380 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
381 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
382 unsigned getCPELogAlign(const MachineInstr *CPEMI);
383 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
384 unsigned getOffsetOf(MachineInstr *MI) const;
385 unsigned getUserOffset(CPUser&) const;
388 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
389 unsigned Disp, bool NegativeOK);
390 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
393 void computeBlockSize(MachineBasicBlock *MBB);
394 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
395 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
396 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
397 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
398 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
399 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
400 bool findAvailableWater(CPUser&U, unsigned UserOffset,
401 water_iterator &WaterIter);
402 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
403 MachineBasicBlock *&NewMBB);
404 bool handleConstantPoolUser(unsigned CPUserIndex);
405 void removeDeadCPEMI(MachineInstr *CPEMI);
406 bool removeUnusedCPEntries();
407 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
408 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
409 bool DoDump = false);
410 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
411 CPUser &U, unsigned &Growth);
412 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
413 bool fixupImmediateBr(ImmBranch &Br);
414 bool fixupConditionalBr(ImmBranch &Br);
415 bool fixupUnconditionalBr(ImmBranch &Br);
417 void prescanForConstants();
423 char MipsConstantIslands::ID = 0;
424 } // end of anonymous namespace
426 bool MipsConstantIslands::isOffsetInRange
427 (unsigned UserOffset, unsigned TrialOffset,
429 return isOffsetInRange(UserOffset, TrialOffset,
430 U.getMaxDisp(), U.NegOk);
432 /// print block size and offset information - debugging
433 void MipsConstantIslands::dumpBBs() {
435 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
436 const BasicBlockInfo &BBI = BBInfo[J];
437 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
438 << format(" size=%#x\n", BBInfo[J].Size);
442 /// createMipsLongBranchPass - Returns a pass that converts branches to long
444 FunctionPass *llvm::createMipsConstantIslandPass(MipsTargetMachine &tm) {
445 return new MipsConstantIslands(tm);
448 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
449 // The intention is for this to be a mips16 only pass for now
452 MCP = mf.getConstantPool();
453 DEBUG(dbgs() << "constant island machine function " << "\n");
454 if (!TM.getSubtarget<MipsSubtarget>().inMips16Mode() ||
455 !MipsSubtarget::useConstantIslands()) {
458 TII = (const Mips16InstrInfo*)MF->getTarget().getInstrInfo();
459 MFI = MF->getInfo<MipsFunctionInfo>();
460 DEBUG(dbgs() << "constant island processing " << "\n");
462 // will need to make predermination if there is any constants we need to
463 // put in constant islands. TBD.
465 if (!PrescannedForConstants) prescanForConstants();
468 // This pass invalidates liveness information when it splits basic blocks.
469 MF->getRegInfo().invalidateLiveness();
471 // Renumber all of the machine basic blocks in the function, guaranteeing that
472 // the numbers agree with the position of the block in the function.
473 MF->RenumberBlocks();
475 bool MadeChange = false;
477 // Perform the initial placement of the constant pool entries. To start with,
478 // we put them all at the end of the function.
479 std::vector<MachineInstr*> CPEMIs;
481 doInitialPlacement(CPEMIs);
483 /// The next UID to take is the first unused one.
484 initPICLabelUId(CPEMIs.size());
486 // Do the initial scan of the function, building up information about the
487 // sizes of each block, the location of all the water, and finding all of the
488 // constant pool users.
489 initializeFunctionInfo(CPEMIs);
493 /// Remove dead constant pool entries.
494 MadeChange |= removeUnusedCPEntries();
496 // Iteratively place constant pool entries and fix up branches until there
498 unsigned NoCPIters = 0, NoBRIters = 0;
501 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
502 bool CPChange = false;
503 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
504 CPChange |= handleConstantPoolUser(i);
505 if (CPChange && ++NoCPIters > 30)
506 report_fatal_error("Constant Island pass failed to converge!");
509 // Clear NewWaterList now. If we split a block for branches, it should
510 // appear as "new water" for the next iteration of constant pool placement.
511 NewWaterList.clear();
513 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
514 bool BRChange = false;
515 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
516 BRChange |= fixupImmediateBr(ImmBranches[i]);
517 if (BRChange && ++NoBRIters > 30)
518 report_fatal_error("Branch Fix Up pass failed to converge!");
520 if (!CPChange && !BRChange)
525 DEBUG(dbgs() << '\n'; dumpBBs());
535 /// doInitialPlacement - Perform the initial placement of the constant pool
536 /// entries. To start with, we put them all at the end of the function.
538 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
539 // Create the basic block to hold the CPE's.
540 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
544 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
545 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
547 // Mark the basic block as required by the const-pool.
548 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
549 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
551 // The function needs to be as aligned as the basic blocks. The linker may
552 // move functions around based on their alignment.
553 MF->ensureAlignment(BB->getAlignment());
555 // Order the entries in BB by descending alignment. That ensures correct
556 // alignment of all entries as long as BB is sufficiently aligned. Keep
557 // track of the insertion point for each alignment. We are going to bucket
558 // sort the entries as they are created.
559 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
561 // Add all of the constants from the constant pool to the end block, use an
562 // identity mapping of CPI's to CPE's.
563 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
565 const DataLayout &TD = *MF->getTarget().getDataLayout();
566 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
567 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
568 assert(Size >= 4 && "Too small constant pool entry");
569 unsigned Align = CPs[i].getAlignment();
570 assert(isPowerOf2_32(Align) && "Invalid alignment");
571 // Verify that all constant pool entries are a multiple of their alignment.
572 // If not, we would have to pad them out so that instructions stay aligned.
573 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
575 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
576 unsigned LogAlign = Log2_32(Align);
577 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
579 MachineInstr *CPEMI =
580 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
581 .addImm(i).addConstantPoolIndex(i).addImm(Size);
583 CPEMIs.push_back(CPEMI);
585 // Ensure that future entries with higher alignment get inserted before
586 // CPEMI. This is bucket sort with iterators.
587 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
588 if (InsPoint[a] == InsAt)
590 // Add a new CPEntry, but no corresponding CPUser yet.
591 std::vector<CPEntry> CPEs;
592 CPEs.push_back(CPEntry(CPEMI, i));
593 CPEntries.push_back(CPEs);
595 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
596 << Size << ", align = " << Align <<'\n');
601 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
602 /// into the block immediately after it.
603 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
604 // Get the next machine basic block in the function.
605 MachineFunction::iterator MBBI = MBB;
606 // Can't fall off end of function.
607 if (std::next(MBBI) == MBB->getParent()->end())
610 MachineBasicBlock *NextBB = std::next(MBBI);
611 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
612 E = MBB->succ_end(); I != E; ++I)
619 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
620 /// look up the corresponding CPEntry.
621 MipsConstantIslands::CPEntry
622 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
623 const MachineInstr *CPEMI) {
624 std::vector<CPEntry> &CPEs = CPEntries[CPI];
625 // Number of entries per constpool index should be small, just do a
627 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
628 if (CPEs[i].CPEMI == CPEMI)
634 /// getCPELogAlign - Returns the required alignment of the constant pool entry
635 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
636 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) {
637 assert(CPEMI && CPEMI->getOpcode() == Mips::CONSTPOOL_ENTRY);
639 // Everything is 4-byte aligned unless AlignConstantIslands is set.
640 if (!AlignConstantIslands)
643 unsigned CPI = CPEMI->getOperand(1).getIndex();
644 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
645 unsigned Align = MCP->getConstants()[CPI].getAlignment();
646 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
647 return Log2_32(Align);
650 /// initializeFunctionInfo - Do the initial scan of the function, building up
651 /// information about the sizes of each block, the location of all the water,
652 /// and finding all of the constant pool users.
653 void MipsConstantIslands::
654 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
656 BBInfo.resize(MF->getNumBlockIDs());
658 // First thing, compute the size of all basic blocks, and see if the function
659 // has any inline assembly in it. If so, we have to be conservative about
660 // alignment assumptions, as we don't know for sure the size of any
661 // instructions in the inline assembly.
662 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
666 // Compute block offsets.
667 adjustBBOffsetsAfter(MF->begin());
669 // Now go back through the instructions and build up our data structures.
670 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
672 MachineBasicBlock &MBB = *MBBI;
674 // If this block doesn't fall through into the next MBB, then this is
675 // 'water' that a constant pool island could be placed.
676 if (!BBHasFallthrough(&MBB))
677 WaterList.push_back(&MBB);
678 for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
680 if (I->isDebugValue())
683 int Opc = I->getOpcode();
691 continue; // Ignore other branches for now
702 case Mips::BeqzRxImm16:
708 case Mips::BeqzRxImmX16:
714 case Mips::BnezRxImm16:
720 case Mips::BnezRxImmX16:
751 // Record this immediate branch.
752 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
753 ImmBranches.push_back(ImmBranch(I, MaxOffs, isCond, UOpc));
756 if (Opc == Mips::CONSTPOOL_ENTRY)
760 // Scan the instructions for constant pool operands.
761 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
762 if (I->getOperand(op).isCPI()) {
764 // We found one. The addressing mode tells us the max displacement
765 // from the PC that this instruction permits.
767 // Basic size info comes from the TSFlags field.
771 unsigned LongFormBits = 0;
772 unsigned LongFormScale = 0;
773 unsigned LongFormOpcode = 0;
776 llvm_unreachable("Unknown addressing mode for CP reference!");
777 case Mips::LwRxPcTcp16:
780 LongFormOpcode = Mips::LwRxPcTcpX16;
784 case Mips::LwRxPcTcpX16:
790 // Remember that this is a user of a CP entry.
791 unsigned CPI = I->getOperand(op).getIndex();
792 MachineInstr *CPEMI = CPEMIs[CPI];
793 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
794 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
795 CPUsers.push_back(CPUser(I, CPEMI, MaxOffs, NegOk,
796 LongFormMaxOffs, LongFormOpcode));
798 // Increment corresponding CPEntry reference count.
799 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
800 assert(CPE && "Cannot find a corresponding CPEntry!");
803 // Instructions can only use one CP entry, don't bother scanning the
804 // rest of the operands.
814 /// computeBlockSize - Compute the size and some alignment information for MBB.
815 /// This function updates BBInfo directly.
816 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
817 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
820 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
822 BBI.Size += TII->GetInstSizeInBytes(I);
826 /// getOffsetOf - Return the current offset of the specified machine instruction
827 /// from the start of the function. This offset changes as stuff is moved
828 /// around inside the function.
829 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
830 MachineBasicBlock *MBB = MI->getParent();
832 // The offset is composed of two things: the sum of the sizes of all MBB's
833 // before this instruction's block, and the offset from the start of the block
835 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
837 // Sum instructions before MI in MBB.
838 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
839 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
840 Offset += TII->GetInstSizeInBytes(I);
845 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
847 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
848 const MachineBasicBlock *RHS) {
849 return LHS->getNumber() < RHS->getNumber();
852 /// updateForInsertedWaterBlock - When a block is newly inserted into the
853 /// machine function, it upsets all of the block numbers. Renumber the blocks
854 /// and update the arrays that parallel this numbering.
855 void MipsConstantIslands::updateForInsertedWaterBlock
856 (MachineBasicBlock *NewBB) {
857 // Renumber the MBB's to keep them consecutive.
858 NewBB->getParent()->RenumberBlocks(NewBB);
860 // Insert an entry into BBInfo to align it properly with the (newly
861 // renumbered) block numbers.
862 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
864 // Next, update WaterList. Specifically, we need to add NewMBB as having
865 // available water after it.
867 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
869 WaterList.insert(IP, NewBB);
872 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
873 return getOffsetOf(U.MI);
876 /// Split the basic block containing MI into two blocks, which are joined by
877 /// an unconditional branch. Update data structures and renumber blocks to
878 /// account for this change and returns the newly created block.
879 MachineBasicBlock *MipsConstantIslands::splitBlockBeforeInstr
881 MachineBasicBlock *OrigBB = MI->getParent();
883 // Create a new MBB for the code after the OrigBB.
884 MachineBasicBlock *NewBB =
885 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
886 MachineFunction::iterator MBBI = OrigBB; ++MBBI;
887 MF->insert(MBBI, NewBB);
889 // Splice the instructions starting with MI over to NewBB.
890 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
892 // Add an unconditional branch from OrigBB to NewBB.
893 // Note the new unconditional branch is not being recorded.
894 // There doesn't seem to be meaningful DebugInfo available; this doesn't
895 // correspond to anything in the source.
896 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
899 // Update the CFG. All succs of OrigBB are now succs of NewBB.
900 NewBB->transferSuccessors(OrigBB);
902 // OrigBB branches to NewBB.
903 OrigBB->addSuccessor(NewBB);
905 // Update internal data structures to account for the newly inserted MBB.
906 // This is almost the same as updateForInsertedWaterBlock, except that
907 // the Water goes after OrigBB, not NewBB.
908 MF->RenumberBlocks(NewBB);
910 // Insert an entry into BBInfo to align it properly with the (newly
911 // renumbered) block numbers.
912 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
914 // Next, update WaterList. Specifically, we need to add OrigMBB as having
915 // available water after it (but not if it's already there, which happens
916 // when splitting before a conditional branch that is followed by an
917 // unconditional branch - in that case we want to insert NewBB).
919 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
921 MachineBasicBlock* WaterBB = *IP;
922 if (WaterBB == OrigBB)
923 WaterList.insert(std::next(IP), NewBB);
925 WaterList.insert(IP, OrigBB);
926 NewWaterList.insert(OrigBB);
928 // Figure out how large the OrigBB is. As the first half of the original
929 // block, it cannot contain a tablejump. The size includes
930 // the new jump we added. (It should be possible to do this without
931 // recounting everything, but it's very confusing, and this is rarely
933 computeBlockSize(OrigBB);
935 // Figure out how large the NewMBB is. As the second half of the original
936 // block, it may contain a tablejump.
937 computeBlockSize(NewBB);
939 // All BBOffsets following these blocks must be modified.
940 adjustBBOffsetsAfter(OrigBB);
947 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
948 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
949 /// constant pool entry).
950 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
951 unsigned TrialOffset, unsigned MaxDisp,
953 if (UserOffset <= TrialOffset) {
954 // User before the Trial.
955 if (TrialOffset - UserOffset <= MaxDisp)
957 } else if (NegativeOK) {
958 if (UserOffset - TrialOffset <= MaxDisp)
964 /// isWaterInRange - Returns true if a CPE placed after the specified
965 /// Water (a basic block) will be in range for the specific MI.
967 /// Compute how much the function will grow by inserting a CPE after Water.
968 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
969 MachineBasicBlock* Water, CPUser &U,
971 unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
972 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
973 unsigned NextBlockOffset, NextBlockAlignment;
974 MachineFunction::const_iterator NextBlock = Water;
975 if (++NextBlock == MF->end()) {
976 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
977 NextBlockAlignment = 0;
979 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
980 NextBlockAlignment = NextBlock->getAlignment();
982 unsigned Size = U.CPEMI->getOperand(2).getImm();
983 unsigned CPEEnd = CPEOffset + Size;
985 // The CPE may be able to hide in the alignment padding before the next
986 // block. It may also cause more padding to be required if it is more aligned
987 // that the next block.
988 if (CPEEnd > NextBlockOffset) {
989 Growth = CPEEnd - NextBlockOffset;
990 // Compute the padding that would go at the end of the CPE to align the next
992 Growth += OffsetToAlignment(CPEEnd, 1u << NextBlockAlignment);
994 // If the CPE is to be inserted before the instruction, that will raise
995 // the offset of the instruction. Also account for unknown alignment padding
996 // in blocks between CPE and the user.
997 if (CPEOffset < UserOffset)
998 UserOffset += Growth;
1000 // CPE fits in existing padding.
1003 return isOffsetInRange(UserOffset, CPEOffset, U);
1006 /// isCPEntryInRange - Returns true if the distance between specific MI and
1007 /// specific ConstPool entry instruction can fit in MI's displacement field.
1008 bool MipsConstantIslands::isCPEntryInRange
1009 (MachineInstr *MI, unsigned UserOffset,
1010 MachineInstr *CPEMI, unsigned MaxDisp,
1011 bool NegOk, bool DoDump) {
1012 unsigned CPEOffset = getOffsetOf(CPEMI);
1016 unsigned Block = MI->getParent()->getNumber();
1017 const BasicBlockInfo &BBI = BBInfo[Block];
1018 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1019 << " max delta=" << MaxDisp
1020 << format(" insn address=%#x", UserOffset)
1021 << " in BB#" << Block << ": "
1022 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1023 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1024 int(CPEOffset-UserOffset));
1028 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1032 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1033 /// unconditionally branches to its only successor.
1034 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1035 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1037 MachineBasicBlock *Succ = *MBB->succ_begin();
1038 MachineBasicBlock *Pred = *MBB->pred_begin();
1039 MachineInstr *PredMI = &Pred->back();
1040 if (PredMI->getOpcode() == Mips::Bimm16)
1041 return PredMI->getOperand(0).getMBB() == Succ;
1046 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1047 unsigned BBNum = BB->getNumber();
1048 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1049 // Get the offset and known bits at the end of the layout predecessor.
1050 // Include the alignment of the current block.
1051 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
1052 BBInfo[i].Offset = Offset;
1056 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1057 /// and instruction CPEMI, and decrement its refcount. If the refcount
1058 /// becomes 0 remove the entry and instruction. Returns true if we removed
1059 /// the entry, false if we didn't.
1061 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1062 MachineInstr *CPEMI) {
1063 // Find the old entry. Eliminate it if it is no longer used.
1064 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1065 assert(CPE && "Unexpected!");
1066 if (--CPE->RefCount == 0) {
1067 removeDeadCPEMI(CPEMI);
1068 CPE->CPEMI = nullptr;
1075 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1076 /// if not, see if an in-range clone of the CPE is in range, and if so,
1077 /// change the data structures so the user references the clone. Returns:
1078 /// 0 = no existing entry found
1079 /// 1 = entry found, and there were no code insertions or deletions
1080 /// 2 = entry found, and there were code insertions or deletions
1081 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1083 MachineInstr *UserMI = U.MI;
1084 MachineInstr *CPEMI = U.CPEMI;
1086 // Check to see if the CPE is already in-range.
1087 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1089 DEBUG(dbgs() << "In range\n");
1093 // No. Look for previously created clones of the CPE that are in range.
1094 unsigned CPI = CPEMI->getOperand(1).getIndex();
1095 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1096 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1097 // We already tried this one
1098 if (CPEs[i].CPEMI == CPEMI)
1100 // Removing CPEs can leave empty entries, skip
1101 if (CPEs[i].CPEMI == nullptr)
1103 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1105 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1106 << CPEs[i].CPI << "\n");
1107 // Point the CPUser node to the replacement
1108 U.CPEMI = CPEs[i].CPEMI;
1109 // Change the CPI in the instruction operand to refer to the clone.
1110 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1111 if (UserMI->getOperand(j).isCPI()) {
1112 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1115 // Adjust the refcount of the clone...
1117 // ...and the original. If we didn't remove the old entry, none of the
1118 // addresses changed, so we don't need another pass.
1119 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1125 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1126 /// This version checks if the longer form of the instruction can be used to
1127 /// to satisfy things.
1128 /// if not, see if an in-range clone of the CPE is in range, and if so,
1129 /// change the data structures so the user references the clone. Returns:
1130 /// 0 = no existing entry found
1131 /// 1 = entry found, and there were no code insertions or deletions
1132 /// 2 = entry found, and there were code insertions or deletions
1133 int MipsConstantIslands::findLongFormInRangeCPEntry
1134 (CPUser& U, unsigned UserOffset)
1136 MachineInstr *UserMI = U.MI;
1137 MachineInstr *CPEMI = U.CPEMI;
1139 // Check to see if the CPE is already in-range.
1140 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1141 U.getLongFormMaxDisp(), U.NegOk,
1143 DEBUG(dbgs() << "In range\n");
1144 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1145 U.setMaxDisp(U.getLongFormMaxDisp());
1146 return 2; // instruction is longer length now
1149 // No. Look for previously created clones of the CPE that are in range.
1150 unsigned CPI = CPEMI->getOperand(1).getIndex();
1151 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1152 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1153 // We already tried this one
1154 if (CPEs[i].CPEMI == CPEMI)
1156 // Removing CPEs can leave empty entries, skip
1157 if (CPEs[i].CPEMI == nullptr)
1159 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1160 U.getLongFormMaxDisp(), U.NegOk)) {
1161 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1162 << CPEs[i].CPI << "\n");
1163 // Point the CPUser node to the replacement
1164 U.CPEMI = CPEs[i].CPEMI;
1165 // Change the CPI in the instruction operand to refer to the clone.
1166 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1167 if (UserMI->getOperand(j).isCPI()) {
1168 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1171 // Adjust the refcount of the clone...
1173 // ...and the original. If we didn't remove the old entry, none of the
1174 // addresses changed, so we don't need another pass.
1175 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1181 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1182 /// the specific unconditional branch instruction.
1183 static inline unsigned getUnconditionalBrDisp(int Opc) {
1186 return ((1<<10)-1)*2;
1188 return ((1<<16)-1)*2;
1192 return ((1<<16)-1)*2;
1195 /// findAvailableWater - Look for an existing entry in the WaterList in which
1196 /// we can place the CPE referenced from U so it's within range of U's MI.
1197 /// Returns true if found, false if not. If it returns true, WaterIter
1198 /// is set to the WaterList entry.
1199 /// To ensure that this pass
1200 /// terminates, the CPE location for a particular CPUser is only allowed to
1201 /// move to a lower address, so search backward from the end of the list and
1202 /// prefer the first water that is in range.
1203 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1204 water_iterator &WaterIter) {
1205 if (WaterList.empty())
1208 unsigned BestGrowth = ~0u;
1209 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1211 MachineBasicBlock* WaterBB = *IP;
1212 // Check if water is in range and is either at a lower address than the
1213 // current "high water mark" or a new water block that was created since
1214 // the previous iteration by inserting an unconditional branch. In the
1215 // latter case, we want to allow resetting the high water mark back to
1216 // this new water since we haven't seen it before. Inserting branches
1217 // should be relatively uncommon and when it does happen, we want to be
1218 // sure to take advantage of it for all the CPEs near that block, so that
1219 // we don't insert more branches than necessary.
1221 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1222 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1223 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1224 // This is the least amount of required padding seen so far.
1225 BestGrowth = Growth;
1227 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1228 << " Growth=" << Growth << '\n');
1230 // Keep looking unless it is perfect.
1231 if (BestGrowth == 0)
1237 return BestGrowth != ~0u;
1240 /// createNewWater - No existing WaterList entry will work for
1241 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1242 /// block is used if in range, and the conditional branch munged so control
1243 /// flow is correct. Otherwise the block is split to create a hole with an
1244 /// unconditional branch around it. In either case NewMBB is set to a
1245 /// block following which the new island can be inserted (the WaterList
1246 /// is not adjusted).
1247 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1248 unsigned UserOffset,
1249 MachineBasicBlock *&NewMBB) {
1250 CPUser &U = CPUsers[CPUserIndex];
1251 MachineInstr *UserMI = U.MI;
1252 MachineInstr *CPEMI = U.CPEMI;
1253 unsigned CPELogAlign = getCPELogAlign(CPEMI);
1254 MachineBasicBlock *UserMBB = UserMI->getParent();
1255 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1257 // If the block does not end in an unconditional branch already, and if the
1258 // end of the block is within range, make new water there.
1259 if (BBHasFallthrough(UserMBB)) {
1260 // Size of branch to insert.
1262 // Compute the offset where the CPE will begin.
1263 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1265 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1266 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1267 << format(", expected CPE offset %#x\n", CPEOffset));
1268 NewMBB = std::next(MachineFunction::iterator(UserMBB));
1269 // Add an unconditional branch from UserMBB to fallthrough block. Record
1270 // it for branch lengthening; this new branch will not get out of range,
1271 // but if the preceding conditional branch is out of range, the targets
1272 // will be exchanged, and the altered branch may be out of range, so the
1273 // machinery has to know about it.
1274 int UncondBr = Mips::Bimm16;
1275 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1276 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1277 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1278 MaxDisp, false, UncondBr));
1279 BBInfo[UserMBB->getNumber()].Size += Delta;
1280 adjustBBOffsetsAfter(UserMBB);
1285 // What a big block. Find a place within the block to split it.
1287 // Try to split the block so it's fully aligned. Compute the latest split
1288 // point where we can add a 4-byte branch instruction, and then align to
1289 // LogAlign which is the largest possible alignment in the function.
1290 unsigned LogAlign = MF->getAlignment();
1291 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1292 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1293 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1296 // The 4 in the following is for the unconditional branch we'll be inserting
1297 // Alignment of the island is handled
1298 // inside isOffsetInRange.
1299 BaseInsertOffset -= 4;
1301 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1302 << " la=" << LogAlign << '\n');
1304 // This could point off the end of the block if we've already got constant
1305 // pool entries following this block; only the last one is in the water list.
1306 // Back past any possible branches (allow for a conditional and a maximally
1307 // long unconditional).
1308 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1309 BaseInsertOffset = UserBBI.postOffset() - 8;
1310 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1312 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1313 CPEMI->getOperand(2).getImm();
1314 MachineBasicBlock::iterator MI = UserMI;
1316 unsigned CPUIndex = CPUserIndex+1;
1317 unsigned NumCPUsers = CPUsers.size();
1318 //MachineInstr *LastIT = 0;
1319 for (unsigned Offset = UserOffset+TII->GetInstSizeInBytes(UserMI);
1320 Offset < BaseInsertOffset;
1321 Offset += TII->GetInstSizeInBytes(MI), MI = std::next(MI)) {
1322 assert(MI != UserMBB->end() && "Fell off end of block");
1323 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1324 CPUser &U = CPUsers[CPUIndex];
1325 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1326 // Shift intertion point by one unit of alignment so it is within reach.
1327 BaseInsertOffset -= 1u << LogAlign;
1328 EndInsertOffset -= 1u << LogAlign;
1330 // This is overly conservative, as we don't account for CPEMIs being
1331 // reused within the block, but it doesn't matter much. Also assume CPEs
1332 // are added in order with alignment padding. We may eventually be able
1333 // to pack the aligned CPEs better.
1334 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1340 NewMBB = splitBlockBeforeInstr(MI);
1343 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1344 /// is out-of-range. If so, pick up the constant pool value and move it some
1345 /// place in-range. Return true if we changed any addresses (thus must run
1346 /// another pass of branch lengthening), false otherwise.
1347 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1348 CPUser &U = CPUsers[CPUserIndex];
1349 MachineInstr *UserMI = U.MI;
1350 MachineInstr *CPEMI = U.CPEMI;
1351 unsigned CPI = CPEMI->getOperand(1).getIndex();
1352 unsigned Size = CPEMI->getOperand(2).getImm();
1353 // Compute this only once, it's expensive.
1354 unsigned UserOffset = getUserOffset(U);
1356 // See if the current entry is within range, or there is a clone of it
1358 int result = findInRangeCPEntry(U, UserOffset);
1359 if (result==1) return false;
1360 else if (result==2) return true;
1363 // Look for water where we can place this CPE.
1364 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1365 MachineBasicBlock *NewMBB;
1367 if (findAvailableWater(U, UserOffset, IP)) {
1368 DEBUG(dbgs() << "Found water in range\n");
1369 MachineBasicBlock *WaterBB = *IP;
1371 // If the original WaterList entry was "new water" on this iteration,
1372 // propagate that to the new island. This is just keeping NewWaterList
1373 // updated to match the WaterList, which will be updated below.
1374 if (NewWaterList.erase(WaterBB))
1375 NewWaterList.insert(NewIsland);
1377 // The new CPE goes before the following block (NewMBB).
1378 NewMBB = std::next(MachineFunction::iterator(WaterBB));
1382 // we first see if a longer form of the instrucion could have reached
1383 // the constant. in that case we won't bother to split
1384 if (!NoLoadRelaxation) {
1385 result = findLongFormInRangeCPEntry(U, UserOffset);
1386 if (result != 0) return true;
1388 DEBUG(dbgs() << "No water found\n");
1389 createNewWater(CPUserIndex, UserOffset, NewMBB);
1391 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1392 // called while handling branches so that the water will be seen on the
1393 // next iteration for constant pools, but in this context, we don't want
1394 // it. Check for this so it will be removed from the WaterList.
1395 // Also remove any entry from NewWaterList.
1396 MachineBasicBlock *WaterBB = std::prev(MachineFunction::iterator(NewMBB));
1397 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB);
1398 if (IP != WaterList.end())
1399 NewWaterList.erase(WaterBB);
1401 // We are adding new water. Update NewWaterList.
1402 NewWaterList.insert(NewIsland);
1405 // Remove the original WaterList entry; we want subsequent insertions in
1406 // this vicinity to go after the one we're about to insert. This
1407 // considerably reduces the number of times we have to move the same CPE
1408 // more than once and is also important to ensure the algorithm terminates.
1409 if (IP != WaterList.end())
1410 WaterList.erase(IP);
1412 // Okay, we know we can put an island before NewMBB now, do it!
1413 MF->insert(NewMBB, NewIsland);
1415 // Update internal data structures to account for the newly inserted MBB.
1416 updateForInsertedWaterBlock(NewIsland);
1418 // Decrement the old entry, and remove it if refcount becomes 0.
1419 decrementCPEReferenceCount(CPI, CPEMI);
1421 // No existing clone of this CPE is within range.
1422 // We will be generating a new clone. Get a UID for it.
1423 unsigned ID = createPICLabelUId();
1425 // Now that we have an island to add the CPE to, clone the original CPE and
1426 // add it to the island.
1427 U.HighWaterMark = NewIsland;
1428 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1429 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1430 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1433 // Mark the basic block as aligned as required by the const-pool entry.
1434 NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1436 // Increase the size of the island block to account for the new entry.
1437 BBInfo[NewIsland->getNumber()].Size += Size;
1438 adjustBBOffsetsAfter(std::prev(MachineFunction::iterator(NewIsland)));
1442 // Finally, change the CPI in the instruction operand to be ID.
1443 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1444 if (UserMI->getOperand(i).isCPI()) {
1445 UserMI->getOperand(i).setIndex(ID);
1449 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1450 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1455 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1456 /// sizes and offsets of impacted basic blocks.
1457 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1458 MachineBasicBlock *CPEBB = CPEMI->getParent();
1459 unsigned Size = CPEMI->getOperand(2).getImm();
1460 CPEMI->eraseFromParent();
1461 BBInfo[CPEBB->getNumber()].Size -= Size;
1462 // All succeeding offsets have the current size value added in, fix this.
1463 if (CPEBB->empty()) {
1464 BBInfo[CPEBB->getNumber()].Size = 0;
1466 // This block no longer needs to be aligned.
1467 CPEBB->setAlignment(0);
1469 // Entries are sorted by descending alignment, so realign from the front.
1470 CPEBB->setAlignment(getCPELogAlign(CPEBB->begin()));
1472 adjustBBOffsetsAfter(CPEBB);
1473 // An island has only one predecessor BB and one successor BB. Check if
1474 // this BB's predecessor jumps directly to this BB's successor. This
1475 // shouldn't happen currently.
1476 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1477 // FIXME: remove the empty blocks after all the work is done?
1480 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1482 bool MipsConstantIslands::removeUnusedCPEntries() {
1483 unsigned MadeChange = false;
1484 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1485 std::vector<CPEntry> &CPEs = CPEntries[i];
1486 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1487 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1488 removeDeadCPEMI(CPEs[j].CPEMI);
1489 CPEs[j].CPEMI = nullptr;
1497 /// isBBInRange - Returns true if the distance between specific MI and
1498 /// specific BB can fit in MI's displacement field.
1499 bool MipsConstantIslands::isBBInRange
1500 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1504 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1505 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1507 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1508 << " from BB#" << MI->getParent()->getNumber()
1509 << " max delta=" << MaxDisp
1510 << " from " << getOffsetOf(MI) << " to " << DestOffset
1511 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1513 if (BrOffset <= DestOffset) {
1514 // Branch before the Dest.
1515 if (DestOffset-BrOffset <= MaxDisp)
1518 if (BrOffset-DestOffset <= MaxDisp)
1524 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1525 /// away to fit in its displacement field.
1526 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1527 MachineInstr *MI = Br.MI;
1528 unsigned TargetOperand = branchTargetOperand(MI);
1529 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1531 // Check to see if the DestBB is already in-range.
1532 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1536 return fixupUnconditionalBr(Br);
1537 return fixupConditionalBr(Br);
1540 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1541 /// too far away to fit in its displacement field. If the LR register has been
1542 /// spilled in the epilogue, then we can use BL to implement a far jump.
1543 /// Otherwise, add an intermediate branch instruction to a branch.
1545 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1546 MachineInstr *MI = Br.MI;
1547 MachineBasicBlock *MBB = MI->getParent();
1548 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1549 // Use BL to implement far jump.
1550 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1551 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1552 Br.MaxDisp = BimmX16MaxDisp;
1553 MI->setDesc(TII->get(Mips::BimmX16));
1556 // need to give the math a more careful look here
1557 // this is really a segment address and not
1558 // a PC relative address. FIXME. But I think that
1559 // just reducing the bits by 1 as I've done is correct.
1560 // The basic block we are branching too much be longword aligned.
1561 // we know that RA is saved because we always save it right now.
1562 // this requirement will be relaxed later but we also have an alternate
1563 // way to implement this that I will implement that does not need jal.
1564 // We should have a way to back out this alignment restriction if we "can" later.
1565 // but it is not harmful.
1567 DestBB->setAlignment(2);
1568 Br.MaxDisp = ((1<<24)-1) * 2;
1569 MI->setDesc(TII->get(Mips::JalB16));
1571 BBInfo[MBB->getNumber()].Size += 2;
1572 adjustBBOffsetsAfter(MBB);
1576 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1582 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1583 /// far away to fit in its displacement field. It is converted to an inverse
1584 /// conditional branch + an unconditional branch to the destination.
1586 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1587 MachineInstr *MI = Br.MI;
1588 unsigned TargetOperand = branchTargetOperand(MI);
1589 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1590 unsigned Opcode = MI->getOpcode();
1591 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1592 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1594 // Check to see if the DestBB is already in-range.
1595 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1596 Br.MaxDisp = LongFormMaxOff;
1597 MI->setDesc(TII->get(LongFormOpcode));
1601 // Add an unconditional branch to the destination and invert the branch
1602 // condition to jump over it:
1609 // If the branch is at the end of its MBB and that has a fall-through block,
1610 // direct the updated conditional branch to the fall-through block. Otherwise,
1611 // split the MBB before the next instruction.
1612 MachineBasicBlock *MBB = MI->getParent();
1613 MachineInstr *BMI = &MBB->back();
1614 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1615 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
1619 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1620 isUnconditionalBranch(BMI->getOpcode())) {
1621 // Last MI in the BB is an unconditional branch. Can we simply invert the
1622 // condition and swap destinations:
1628 unsigned BMITargetOperand = branchTargetOperand(BMI);
1629 MachineBasicBlock *NewDest =
1630 BMI->getOperand(BMITargetOperand).getMBB();
1631 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1632 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1634 MI->setDesc(TII->get(OppositeBranchOpcode));
1635 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1636 MI->getOperand(TargetOperand).setMBB(NewDest);
1644 splitBlockBeforeInstr(MI);
1645 // No need for the branch to the next block. We're adding an unconditional
1646 // branch to the destination.
1647 int delta = TII->GetInstSizeInBytes(&MBB->back());
1648 BBInfo[MBB->getNumber()].Size -= delta;
1649 MBB->back().eraseFromParent();
1650 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1652 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
1654 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1655 << " also invert condition and change dest. to BB#"
1656 << NextBB->getNumber() << "\n");
1658 // Insert a new conditional branch and a new unconditional branch.
1659 // Also update the ImmBranch as well as adding a new entry for the new branch.
1660 if (MI->getNumExplicitOperands() == 2) {
1661 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1662 .addReg(MI->getOperand(0).getReg())
1665 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1668 Br.MI = &MBB->back();
1669 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1670 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1671 BBInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
1672 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1673 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1675 // Remove the old conditional branch. It may or may not still be in MBB.
1676 BBInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
1677 MI->eraseFromParent();
1678 adjustBBOffsetsAfter(MBB);
1683 void MipsConstantIslands::prescanForConstants() {
1686 for (MachineFunction::iterator B =
1687 MF->begin(), E = MF->end(); B != E; ++B) {
1688 for (MachineBasicBlock::instr_iterator I =
1689 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1690 switch(I->getDesc().getOpcode()) {
1691 case Mips::LwConstant32: {
1692 PrescannedForConstants = true;
1693 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1694 J = I->getNumOperands();
1695 DEBUG(dbgs() << "num operands " << J << "\n");
1696 MachineOperand& Literal = I->getOperand(1);
1697 if (Literal.isImm()) {
1698 int64_t V = Literal.getImm();
1699 DEBUG(dbgs() << "literal " << V << "\n");
1701 Type::getInt32Ty(MF->getFunction()->getContext());
1702 const Constant *C = ConstantInt::get(Int32Ty, V);
1703 unsigned index = MCP->getConstantPoolIndex(C, 4);
1704 I->getOperand(2).ChangeToImmediate(index);
1705 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1706 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1707 I->RemoveOperand(1);
1708 I->RemoveOperand(1);
1709 I->addOperand(MachineOperand::CreateCPI(index, 0));
1710 I->addOperand(MachineOperand::CreateImm(4));