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 //===----------------------------------------------------------------------===//
10 // This pass is used to make Pc relative loads of constants.
11 // For now, only Mips16 will use this.
13 // Loading constants inline is expensive on Mips16 and it's in general better
14 // to place the constant nearby in code space and then it can be loaded with a
15 // simple 16 bit load instruction.
17 // The constants can be not just numbers but addresses of functions and labels.
18 // This can be particularly helpful in static relocation mode for embedded
21 //===----------------------------------------------------------------------===//
24 #include "Mips16InstrInfo.h"
25 #include "MipsMachineFunction.h"
26 #include "MipsSubtarget.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFunctionPass.h"
36 #include "llvm/CodeGen/MachineInstr.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineOperand.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugLoc.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/Format.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
61 #define DEBUG_TYPE "mips-constant-islands"
63 STATISTIC(NumCPEs, "Number of constpool entries");
64 STATISTIC(NumSplit, "Number of uncond branches inserted");
65 STATISTIC(NumCBrFixed, "Number of cond branches fixed");
66 STATISTIC(NumUBrFixed, "Number of uncond branches fixed");
68 // FIXME: This option should be removed once it has received sufficient testing.
70 AlignConstantIslands("mips-align-constant-islands", cl::Hidden, cl::init(true),
71 cl::desc("Align constant islands in code"));
73 // Rather than do make check tests with huge amounts of code, we force
74 // the test to use this amount.
76 static cl::opt<int> ConstantIslandsSmallOffset(
77 "mips-constant-islands-small-offset",
79 cl::desc("Make small offsets be this amount for testing purposes"),
83 // For testing purposes we tell it to not use relaxed load forms so that it
86 static cl::opt<bool> NoLoadRelaxation(
87 "mips-constant-islands-no-load-relaxation",
89 cl::desc("Don't relax loads to long loads - for testing purposes"),
92 static unsigned int branchTargetOperand(MachineInstr *MI) {
93 switch (MI->getOpcode()) {
102 case Mips::BeqzRxImm16:
103 case Mips::BeqzRxImmX16:
104 case Mips::BnezRxImm16:
105 case Mips::BnezRxImmX16:
108 llvm_unreachable("Unknown branch type");
111 static unsigned int longformBranchOpcode(unsigned int Opcode) {
115 return Mips::BimmX16;
118 return Mips::BteqzX16;
121 return Mips::BtnezX16;
124 case Mips::BeqzRxImm16:
125 case Mips::BeqzRxImmX16:
126 return Mips::BeqzRxImmX16;
127 case Mips::BnezRxImm16:
128 case Mips::BnezRxImmX16:
129 return Mips::BnezRxImmX16;
131 llvm_unreachable("Unknown branch type");
135 // FIXME: need to go through this whole constant islands port and check the math
136 // for branch ranges and clean this up and make some functions to calculate things
137 // that are done many times identically.
138 // Need to refactor some of the code to call this routine.
140 static unsigned int branchMaxOffsets(unsigned int Opcode) {
141 unsigned Bits, Scale;
151 case Mips::BeqzRxImm16:
155 case Mips::BeqzRxImmX16:
159 case Mips::BnezRxImm16:
163 case Mips::BnezRxImmX16:
184 llvm_unreachable("Unknown branch type");
186 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
192 typedef MachineBasicBlock::iterator Iter;
193 typedef MachineBasicBlock::reverse_iterator ReverseIter;
195 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
196 /// requires constant pool entries to be scattered among the instructions
197 /// inside a function. To do this, it completely ignores the normal LLVM
198 /// constant pool; instead, it places constants wherever it feels like with
199 /// special instructions.
201 /// The terminology used in this pass includes:
202 /// Islands - Clumps of constants placed in the function.
203 /// Water - Potential places where an island could be formed.
204 /// CPE - A constant pool entry that has been placed somewhere, which
205 /// tracks a list of users.
207 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 BasicBlockInfo() = default;
231 // FIXME: ignore LogAlign for this patch
233 unsigned postOffset(unsigned LogAlign = 0) const {
234 unsigned PO = Offset + Size;
239 std::vector<BasicBlockInfo> BBInfo;
241 /// WaterList - A sorted list of basic blocks where islands could be placed
242 /// (i.e. blocks that don't fall through to the following block, due
243 /// to a return, unreachable, or unconditional branch).
244 std::vector<MachineBasicBlock*> WaterList;
246 /// NewWaterList - The subset of WaterList that was created since the
247 /// previous iteration by inserting unconditional branches.
248 SmallSet<MachineBasicBlock*, 4> NewWaterList;
250 typedef std::vector<MachineBasicBlock*>::iterator water_iterator;
252 /// CPUser - One user of a constant pool, keeping the machine instruction
253 /// pointer, the constant pool being referenced, and the max displacement
254 /// allowed from the instruction to the CP. The HighWaterMark records the
255 /// highest basic block where a new CPEntry can be placed. To ensure this
256 /// pass terminates, the CP entries are initially placed at the end of the
257 /// function and then move monotonically to lower addresses. The
258 /// exception to this rule is when the current CP entry for a particular
259 /// CPUser is out of range, but there is another CP entry for the same
260 /// constant value in range. We want to use the existing in-range CP
261 /// entry, but if it later moves out of range, the search for new water
262 /// should resume where it left off. The HighWaterMark is used to record
267 MachineBasicBlock *HighWaterMark;
271 unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions
272 // with different displacements
273 unsigned LongFormOpcode;
278 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp,
280 unsigned longformmaxdisp, unsigned longformopcode)
281 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp),
282 LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode),
284 HighWaterMark = CPEMI->getParent();
287 /// getMaxDisp - Returns the maximum displacement supported by MI.
288 unsigned getMaxDisp() const {
289 unsigned xMaxDisp = ConstantIslandsSmallOffset?
290 ConstantIslandsSmallOffset: MaxDisp;
294 void setMaxDisp(unsigned val) {
298 unsigned getLongFormMaxDisp() const {
299 return LongFormMaxDisp;
302 unsigned getLongFormOpcode() const {
303 return LongFormOpcode;
307 /// CPUsers - Keep track of all of the machine instructions that use various
308 /// constant pools and their max displacement.
309 std::vector<CPUser> CPUsers;
311 /// CPEntry - One per constant pool entry, keeping the machine instruction
312 /// pointer, the constpool index, and the number of CPUser's which
313 /// reference this entry.
319 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
320 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
323 /// CPEntries - Keep track of all of the constant pool entry machine
324 /// instructions. For each original constpool index (i.e. those that
325 /// existed upon entry to this pass), it keeps a vector of entries.
326 /// Original elements are cloned as we go along; the clones are
327 /// put in the vector of the original element, but have distinct CPIs.
328 std::vector<std::vector<CPEntry>> CPEntries;
330 /// ImmBranch - One per immediate branch, keeping the machine instruction
331 /// pointer, conditional or unconditional, the max displacement,
332 /// and (if isCond is true) the corresponding unconditional branch
336 unsigned MaxDisp : 31;
340 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr)
341 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
344 /// ImmBranches - Keep track of all the immediate branch instructions.
346 std::vector<ImmBranch> ImmBranches;
348 /// HasFarJump - True if any far jump instruction has been emitted during
349 /// the branch fix up pass.
352 const MipsSubtarget *STI = nullptr;
353 const Mips16InstrInfo *TII;
354 MipsFunctionInfo *MFI;
355 MachineFunction *MF = nullptr;
356 MachineConstantPool *MCP = nullptr;
358 unsigned PICLabelUId;
359 bool PrescannedForConstants = false;
361 void initPICLabelUId(unsigned UId) {
365 unsigned createPICLabelUId() {
366 return PICLabelUId++;
372 MipsConstantIslands() : MachineFunctionPass(ID) {}
374 StringRef getPassName() const override { return "Mips Constant Islands"; }
376 bool runOnMachineFunction(MachineFunction &F) override;
378 MachineFunctionProperties getRequiredProperties() const override {
379 return MachineFunctionProperties().set(
380 MachineFunctionProperties::Property::NoVRegs);
383 void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs);
384 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI);
385 unsigned getCPELogAlign(const MachineInstr &CPEMI);
386 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs);
387 unsigned getOffsetOf(MachineInstr *MI) const;
388 unsigned getUserOffset(CPUser&) const;
391 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
392 unsigned Disp, bool NegativeOK);
393 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
396 void computeBlockSize(MachineBasicBlock *MBB);
397 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
398 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB);
399 void adjustBBOffsetsAfter(MachineBasicBlock *BB);
400 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
401 int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
402 int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset);
403 bool findAvailableWater(CPUser&U, unsigned UserOffset,
404 water_iterator &WaterIter);
405 void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
406 MachineBasicBlock *&NewMBB);
407 bool handleConstantPoolUser(unsigned CPUserIndex);
408 void removeDeadCPEMI(MachineInstr *CPEMI);
409 bool removeUnusedCPEntries();
410 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
411 MachineInstr *CPEMI, unsigned Disp, bool NegOk,
412 bool DoDump = false);
413 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
414 CPUser &U, unsigned &Growth);
415 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
416 bool fixupImmediateBr(ImmBranch &Br);
417 bool fixupConditionalBr(ImmBranch &Br);
418 bool fixupUnconditionalBr(ImmBranch &Br);
420 void prescanForConstants();
423 char MipsConstantIslands::ID = 0;
425 } // end anonymous namespace
427 bool MipsConstantIslands::isOffsetInRange
428 (unsigned UserOffset, unsigned TrialOffset,
430 return isOffsetInRange(UserOffset, TrialOffset,
431 U.getMaxDisp(), U.NegOk);
434 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
435 /// print block size and offset information - debugging
436 LLVM_DUMP_METHOD void MipsConstantIslands::dumpBBs() {
437 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
438 const BasicBlockInfo &BBI = BBInfo[J];
439 dbgs() << format("%08x BB#%u\t", BBI.Offset, J)
440 << format(" size=%#x\n", BBInfo[J].Size);
445 bool MipsConstantIslands::runOnMachineFunction(MachineFunction &mf) {
446 // The intention is for this to be a mips16 only pass for now
449 MCP = mf.getConstantPool();
450 STI = &static_cast<const MipsSubtarget &>(mf.getSubtarget());
451 DEBUG(dbgs() << "constant island machine function " << "\n");
452 if (!STI->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
455 TII = (const Mips16InstrInfo *)STI->getInstrInfo();
456 MFI = MF->getInfo<MipsFunctionInfo>();
457 DEBUG(dbgs() << "constant island processing " << "\n");
459 // will need to make predermination if there is any constants we need to
460 // put in constant islands. TBD.
462 if (!PrescannedForConstants) prescanForConstants();
465 // This pass invalidates liveness information when it splits basic blocks.
466 MF->getRegInfo().invalidateLiveness();
468 // Renumber all of the machine basic blocks in the function, guaranteeing that
469 // the numbers agree with the position of the block in the function.
470 MF->RenumberBlocks();
472 bool MadeChange = false;
474 // Perform the initial placement of the constant pool entries. To start with,
475 // we put them all at the end of the function.
476 std::vector<MachineInstr*> CPEMIs;
478 doInitialPlacement(CPEMIs);
480 /// The next UID to take is the first unused one.
481 initPICLabelUId(CPEMIs.size());
483 // Do the initial scan of the function, building up information about the
484 // sizes of each block, the location of all the water, and finding all of the
485 // constant pool users.
486 initializeFunctionInfo(CPEMIs);
490 /// Remove dead constant pool entries.
491 MadeChange |= removeUnusedCPEntries();
493 // Iteratively place constant pool entries and fix up branches until there
495 unsigned NoCPIters = 0, NoBRIters = 0;
498 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n');
499 bool CPChange = false;
500 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i)
501 CPChange |= handleConstantPoolUser(i);
502 if (CPChange && ++NoCPIters > 30)
503 report_fatal_error("Constant Island pass failed to converge!");
506 // Clear NewWaterList now. If we split a block for branches, it should
507 // appear as "new water" for the next iteration of constant pool placement.
508 NewWaterList.clear();
510 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n');
511 bool BRChange = false;
512 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i)
513 BRChange |= fixupImmediateBr(ImmBranches[i]);
514 if (BRChange && ++NoBRIters > 30)
515 report_fatal_error("Branch Fix Up pass failed to converge!");
517 if (!CPChange && !BRChange)
522 DEBUG(dbgs() << '\n'; dumpBBs());
532 /// doInitialPlacement - Perform the initial placement of the constant pool
533 /// entries. To start with, we put them all at the end of the function.
535 MipsConstantIslands::doInitialPlacement(std::vector<MachineInstr*> &CPEMIs) {
536 // Create the basic block to hold the CPE's.
537 MachineBasicBlock *BB = MF->CreateMachineBasicBlock();
540 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
541 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
543 // Mark the basic block as required by the const-pool.
544 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
545 BB->setAlignment(AlignConstantIslands ? MaxAlign : 2);
547 // The function needs to be as aligned as the basic blocks. The linker may
548 // move functions around based on their alignment.
549 MF->ensureAlignment(BB->getAlignment());
551 // Order the entries in BB by descending alignment. That ensures correct
552 // alignment of all entries as long as BB is sufficiently aligned. Keep
553 // track of the insertion point for each alignment. We are going to bucket
554 // sort the entries as they are created.
555 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end());
557 // Add all of the constants from the constant pool to the end block, use an
558 // identity mapping of CPI's to CPE's.
559 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants();
561 const DataLayout &TD = MF->getDataLayout();
562 for (unsigned i = 0, e = CPs.size(); i != e; ++i) {
563 unsigned Size = TD.getTypeAllocSize(CPs[i].getType());
564 assert(Size >= 4 && "Too small constant pool entry");
565 unsigned Align = CPs[i].getAlignment();
566 assert(isPowerOf2_32(Align) && "Invalid alignment");
567 // Verify that all constant pool entries are a multiple of their alignment.
568 // If not, we would have to pad them out so that instructions stay aligned.
569 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!");
571 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
572 unsigned LogAlign = Log2_32(Align);
573 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign];
575 MachineInstr *CPEMI =
576 BuildMI(*BB, InsAt, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
577 .addImm(i).addConstantPoolIndex(i).addImm(Size);
579 CPEMIs.push_back(CPEMI);
581 // Ensure that future entries with higher alignment get inserted before
582 // CPEMI. This is bucket sort with iterators.
583 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a)
584 if (InsPoint[a] == InsAt)
586 // Add a new CPEntry, but no corresponding CPUser yet.
587 CPEntries.emplace_back(1, CPEntry(CPEMI, i));
589 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
590 << Size << ", align = " << Align <<'\n');
595 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
596 /// into the block immediately after it.
597 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
598 // Get the next machine basic block in the function.
599 MachineFunction::iterator MBBI = MBB->getIterator();
600 // Can't fall off end of function.
601 if (std::next(MBBI) == MBB->getParent()->end())
604 MachineBasicBlock *NextBB = &*std::next(MBBI);
605 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
606 E = MBB->succ_end(); I != E; ++I)
613 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
614 /// look up the corresponding CPEntry.
615 MipsConstantIslands::CPEntry
616 *MipsConstantIslands::findConstPoolEntry(unsigned CPI,
617 const MachineInstr *CPEMI) {
618 std::vector<CPEntry> &CPEs = CPEntries[CPI];
619 // Number of entries per constpool index should be small, just do a
621 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
622 if (CPEs[i].CPEMI == CPEMI)
628 /// getCPELogAlign - Returns the required alignment of the constant pool entry
629 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
630 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr &CPEMI) {
631 assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY);
633 // Everything is 4-byte aligned unless AlignConstantIslands is set.
634 if (!AlignConstantIslands)
637 unsigned CPI = CPEMI.getOperand(1).getIndex();
638 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index.");
639 unsigned Align = MCP->getConstants()[CPI].getAlignment();
640 assert(isPowerOf2_32(Align) && "Invalid CPE alignment");
641 return Log2_32(Align);
644 /// initializeFunctionInfo - Do the initial scan of the function, building up
645 /// information about the sizes of each block, the location of all the water,
646 /// and finding all of the constant pool users.
647 void MipsConstantIslands::
648 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) {
650 BBInfo.resize(MF->getNumBlockIDs());
652 // First thing, compute the size of all basic blocks, and see if the function
653 // has any inline assembly in it. If so, we have to be conservative about
654 // alignment assumptions, as we don't know for sure the size of any
655 // instructions in the inline assembly.
656 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I)
657 computeBlockSize(&*I);
659 // Compute block offsets.
660 adjustBBOffsetsAfter(&MF->front());
662 // Now go back through the instructions and build up our data structures.
663 for (MachineBasicBlock &MBB : *MF) {
664 // If this block doesn't fall through into the next MBB, then this is
665 // 'water' that a constant pool island could be placed.
666 if (!BBHasFallthrough(&MBB))
667 WaterList.push_back(&MBB);
668 for (MachineInstr &MI : MBB) {
669 if (MI.isDebugValue())
672 int Opc = MI.getOpcode();
680 continue; // Ignore other branches for now
691 case Mips::BeqzRxImm16:
697 case Mips::BeqzRxImmX16:
703 case Mips::BnezRxImm16:
709 case Mips::BnezRxImmX16:
740 // Record this immediate branch.
741 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
742 ImmBranches.push_back(ImmBranch(&MI, MaxOffs, isCond, UOpc));
745 if (Opc == Mips::CONSTPOOL_ENTRY)
748 // Scan the instructions for constant pool operands.
749 for (unsigned op = 0, e = MI.getNumOperands(); op != e; ++op)
750 if (MI.getOperand(op).isCPI()) {
752 // We found one. The addressing mode tells us the max displacement
753 // from the PC that this instruction permits.
755 // Basic size info comes from the TSFlags field.
759 unsigned LongFormBits = 0;
760 unsigned LongFormScale = 0;
761 unsigned LongFormOpcode = 0;
764 llvm_unreachable("Unknown addressing mode for CP reference!");
765 case Mips::LwRxPcTcp16:
768 LongFormOpcode = Mips::LwRxPcTcpX16;
772 case Mips::LwRxPcTcpX16:
778 // Remember that this is a user of a CP entry.
779 unsigned CPI = MI.getOperand(op).getIndex();
780 MachineInstr *CPEMI = CPEMIs[CPI];
781 unsigned MaxOffs = ((1 << Bits)-1) * Scale;
782 unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale;
783 CPUsers.push_back(CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs,
786 // Increment corresponding CPEntry reference count.
787 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
788 assert(CPE && "Cannot find a corresponding CPEntry!");
791 // Instructions can only use one CP entry, don't bother scanning the
792 // rest of the operands.
799 /// computeBlockSize - Compute the size and some alignment information for MBB.
800 /// This function updates BBInfo directly.
801 void MipsConstantIslands::computeBlockSize(MachineBasicBlock *MBB) {
802 BasicBlockInfo &BBI = BBInfo[MBB->getNumber()];
805 for (const MachineInstr &MI : *MBB)
806 BBI.Size += TII->getInstSizeInBytes(MI);
809 /// getOffsetOf - Return the current offset of the specified machine instruction
810 /// from the start of the function. This offset changes as stuff is moved
811 /// around inside the function.
812 unsigned MipsConstantIslands::getOffsetOf(MachineInstr *MI) const {
813 MachineBasicBlock *MBB = MI->getParent();
815 // The offset is composed of two things: the sum of the sizes of all MBB's
816 // before this instruction's block, and the offset from the start of the block
818 unsigned Offset = BBInfo[MBB->getNumber()].Offset;
820 // Sum instructions before MI in MBB.
821 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
822 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
823 Offset += TII->getInstSizeInBytes(*I);
828 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
830 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
831 const MachineBasicBlock *RHS) {
832 return LHS->getNumber() < RHS->getNumber();
835 /// updateForInsertedWaterBlock - When a block is newly inserted into the
836 /// machine function, it upsets all of the block numbers. Renumber the blocks
837 /// and update the arrays that parallel this numbering.
838 void MipsConstantIslands::updateForInsertedWaterBlock
839 (MachineBasicBlock *NewBB) {
840 // Renumber the MBB's to keep them consecutive.
841 NewBB->getParent()->RenumberBlocks(NewBB);
843 // Insert an entry into BBInfo to align it properly with the (newly
844 // renumbered) block numbers.
845 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
847 // Next, update WaterList. Specifically, we need to add NewMBB as having
848 // available water after it.
850 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
852 WaterList.insert(IP, NewBB);
855 unsigned MipsConstantIslands::getUserOffset(CPUser &U) const {
856 return getOffsetOf(U.MI);
859 /// Split the basic block containing MI into two blocks, which are joined by
860 /// an unconditional branch. Update data structures and renumber blocks to
861 /// account for this change and returns the newly created block.
863 MipsConstantIslands::splitBlockBeforeInstr(MachineInstr &MI) {
864 MachineBasicBlock *OrigBB = MI.getParent();
866 // Create a new MBB for the code after the OrigBB.
867 MachineBasicBlock *NewBB =
868 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
869 MachineFunction::iterator MBBI = ++OrigBB->getIterator();
870 MF->insert(MBBI, NewBB);
872 // Splice the instructions starting with MI over to NewBB.
873 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
875 // Add an unconditional branch from OrigBB to NewBB.
876 // Note the new unconditional branch is not being recorded.
877 // There doesn't seem to be meaningful DebugInfo available; this doesn't
878 // correspond to anything in the source.
879 BuildMI(OrigBB, DebugLoc(), TII->get(Mips::Bimm16)).addMBB(NewBB);
882 // Update the CFG. All succs of OrigBB are now succs of NewBB.
883 NewBB->transferSuccessors(OrigBB);
885 // OrigBB branches to NewBB.
886 OrigBB->addSuccessor(NewBB);
888 // Update internal data structures to account for the newly inserted MBB.
889 // This is almost the same as updateForInsertedWaterBlock, except that
890 // the Water goes after OrigBB, not NewBB.
891 MF->RenumberBlocks(NewBB);
893 // Insert an entry into BBInfo to align it properly with the (newly
894 // renumbered) block numbers.
895 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
897 // Next, update WaterList. Specifically, we need to add OrigMBB as having
898 // available water after it (but not if it's already there, which happens
899 // when splitting before a conditional branch that is followed by an
900 // unconditional branch - in that case we want to insert NewBB).
902 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
904 MachineBasicBlock* WaterBB = *IP;
905 if (WaterBB == OrigBB)
906 WaterList.insert(std::next(IP), NewBB);
908 WaterList.insert(IP, OrigBB);
909 NewWaterList.insert(OrigBB);
911 // Figure out how large the OrigBB is. As the first half of the original
912 // block, it cannot contain a tablejump. The size includes
913 // the new jump we added. (It should be possible to do this without
914 // recounting everything, but it's very confusing, and this is rarely
916 computeBlockSize(OrigBB);
918 // Figure out how large the NewMBB is. As the second half of the original
919 // block, it may contain a tablejump.
920 computeBlockSize(NewBB);
922 // All BBOffsets following these blocks must be modified.
923 adjustBBOffsetsAfter(OrigBB);
928 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
929 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
930 /// constant pool entry).
931 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset,
932 unsigned TrialOffset, unsigned MaxDisp,
934 if (UserOffset <= TrialOffset) {
935 // User before the Trial.
936 if (TrialOffset - UserOffset <= MaxDisp)
938 } else if (NegativeOK) {
939 if (UserOffset - TrialOffset <= MaxDisp)
945 /// isWaterInRange - Returns true if a CPE placed after the specified
946 /// Water (a basic block) will be in range for the specific MI.
948 /// Compute how much the function will grow by inserting a CPE after Water.
949 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset,
950 MachineBasicBlock* Water, CPUser &U,
952 unsigned CPELogAlign = getCPELogAlign(*U.CPEMI);
953 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
954 unsigned NextBlockOffset, NextBlockAlignment;
955 MachineFunction::const_iterator NextBlock = ++Water->getIterator();
956 if (NextBlock == MF->end()) {
957 NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
958 NextBlockAlignment = 0;
960 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
961 NextBlockAlignment = NextBlock->getAlignment();
963 unsigned Size = U.CPEMI->getOperand(2).getImm();
964 unsigned CPEEnd = CPEOffset + Size;
966 // The CPE may be able to hide in the alignment padding before the next
967 // block. It may also cause more padding to be required if it is more aligned
968 // that the next block.
969 if (CPEEnd > NextBlockOffset) {
970 Growth = CPEEnd - NextBlockOffset;
971 // Compute the padding that would go at the end of the CPE to align the next
973 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
975 // If the CPE is to be inserted before the instruction, that will raise
976 // the offset of the instruction. Also account for unknown alignment padding
977 // in blocks between CPE and the user.
978 if (CPEOffset < UserOffset)
979 UserOffset += Growth;
981 // CPE fits in existing padding.
984 return isOffsetInRange(UserOffset, CPEOffset, U);
987 /// isCPEntryInRange - Returns true if the distance between specific MI and
988 /// specific ConstPool entry instruction can fit in MI's displacement field.
989 bool MipsConstantIslands::isCPEntryInRange
990 (MachineInstr *MI, unsigned UserOffset,
991 MachineInstr *CPEMI, unsigned MaxDisp,
992 bool NegOk, bool DoDump) {
993 unsigned CPEOffset = getOffsetOf(CPEMI);
997 unsigned Block = MI->getParent()->getNumber();
998 const BasicBlockInfo &BBI = BBInfo[Block];
999 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1000 << " max delta=" << MaxDisp
1001 << format(" insn address=%#x", UserOffset)
1002 << " in BB#" << Block << ": "
1003 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1004 << format("CPE address=%#x offset=%+d: ", CPEOffset,
1005 int(CPEOffset-UserOffset));
1009 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1013 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1014 /// unconditionally branches to its only successor.
1015 static bool BBIsJumpedOver(MachineBasicBlock *MBB) {
1016 if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1018 MachineBasicBlock *Succ = *MBB->succ_begin();
1019 MachineBasicBlock *Pred = *MBB->pred_begin();
1020 MachineInstr *PredMI = &Pred->back();
1021 if (PredMI->getOpcode() == Mips::Bimm16)
1022 return PredMI->getOperand(0).getMBB() == Succ;
1027 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1028 unsigned BBNum = BB->getNumber();
1029 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1030 // Get the offset and known bits at the end of the layout predecessor.
1031 // Include the alignment of the current block.
1032 unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size;
1033 BBInfo[i].Offset = Offset;
1037 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1038 /// and instruction CPEMI, and decrement its refcount. If the refcount
1039 /// becomes 0 remove the entry and instruction. Returns true if we removed
1040 /// the entry, false if we didn't.
1042 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1043 MachineInstr *CPEMI) {
1044 // Find the old entry. Eliminate it if it is no longer used.
1045 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1046 assert(CPE && "Unexpected!");
1047 if (--CPE->RefCount == 0) {
1048 removeDeadCPEMI(CPEMI);
1049 CPE->CPEMI = nullptr;
1056 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1057 /// if not, see if an in-range clone of the CPE is in range, and if so,
1058 /// change the data structures so the user references the clone. Returns:
1059 /// 0 = no existing entry found
1060 /// 1 = entry found, and there were no code insertions or deletions
1061 /// 2 = entry found, and there were code insertions or deletions
1062 int MipsConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset)
1064 MachineInstr *UserMI = U.MI;
1065 MachineInstr *CPEMI = U.CPEMI;
1067 // Check to see if the CPE is already in-range.
1068 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1070 DEBUG(dbgs() << "In range\n");
1074 // No. Look for previously created clones of the CPE that are in range.
1075 unsigned CPI = CPEMI->getOperand(1).getIndex();
1076 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1077 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1078 // We already tried this one
1079 if (CPEs[i].CPEMI == CPEMI)
1081 // Removing CPEs can leave empty entries, skip
1082 if (CPEs[i].CPEMI == nullptr)
1084 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1086 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1087 << CPEs[i].CPI << "\n");
1088 // Point the CPUser node to the replacement
1089 U.CPEMI = CPEs[i].CPEMI;
1090 // Change the CPI in the instruction operand to refer to the clone.
1091 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1092 if (UserMI->getOperand(j).isCPI()) {
1093 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1096 // Adjust the refcount of the clone...
1098 // ...and the original. If we didn't remove the old entry, none of the
1099 // addresses changed, so we don't need another pass.
1100 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1106 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1107 /// This version checks if the longer form of the instruction can be used to
1108 /// to satisfy things.
1109 /// if not, see if an in-range clone of the CPE is in range, and if so,
1110 /// change the data structures so the user references the clone. Returns:
1111 /// 0 = no existing entry found
1112 /// 1 = entry found, and there were no code insertions or deletions
1113 /// 2 = entry found, and there were code insertions or deletions
1114 int MipsConstantIslands::findLongFormInRangeCPEntry
1115 (CPUser& U, unsigned UserOffset)
1117 MachineInstr *UserMI = U.MI;
1118 MachineInstr *CPEMI = U.CPEMI;
1120 // Check to see if the CPE is already in-range.
1121 if (isCPEntryInRange(UserMI, UserOffset, CPEMI,
1122 U.getLongFormMaxDisp(), U.NegOk,
1124 DEBUG(dbgs() << "In range\n");
1125 UserMI->setDesc(TII->get(U.getLongFormOpcode()));
1126 U.setMaxDisp(U.getLongFormMaxDisp());
1127 return 2; // instruction is longer length now
1130 // No. Look for previously created clones of the CPE that are in range.
1131 unsigned CPI = CPEMI->getOperand(1).getIndex();
1132 std::vector<CPEntry> &CPEs = CPEntries[CPI];
1133 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1134 // We already tried this one
1135 if (CPEs[i].CPEMI == CPEMI)
1137 // Removing CPEs can leave empty entries, skip
1138 if (CPEs[i].CPEMI == nullptr)
1140 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI,
1141 U.getLongFormMaxDisp(), U.NegOk)) {
1142 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1143 << CPEs[i].CPI << "\n");
1144 // Point the CPUser node to the replacement
1145 U.CPEMI = CPEs[i].CPEMI;
1146 // Change the CPI in the instruction operand to refer to the clone.
1147 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1148 if (UserMI->getOperand(j).isCPI()) {
1149 UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1152 // Adjust the refcount of the clone...
1154 // ...and the original. If we didn't remove the old entry, none of the
1155 // addresses changed, so we don't need another pass.
1156 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1162 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1163 /// the specific unconditional branch instruction.
1164 static inline unsigned getUnconditionalBrDisp(int Opc) {
1167 return ((1<<10)-1)*2;
1169 return ((1<<16)-1)*2;
1173 return ((1<<16)-1)*2;
1176 /// findAvailableWater - Look for an existing entry in the WaterList in which
1177 /// we can place the CPE referenced from U so it's within range of U's MI.
1178 /// Returns true if found, false if not. If it returns true, WaterIter
1179 /// is set to the WaterList entry.
1180 /// To ensure that this pass
1181 /// terminates, the CPE location for a particular CPUser is only allowed to
1182 /// move to a lower address, so search backward from the end of the list and
1183 /// prefer the first water that is in range.
1184 bool MipsConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1185 water_iterator &WaterIter) {
1186 if (WaterList.empty())
1189 unsigned BestGrowth = ~0u;
1190 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1192 MachineBasicBlock* WaterBB = *IP;
1193 // Check if water is in range and is either at a lower address than the
1194 // current "high water mark" or a new water block that was created since
1195 // the previous iteration by inserting an unconditional branch. In the
1196 // latter case, we want to allow resetting the high water mark back to
1197 // this new water since we haven't seen it before. Inserting branches
1198 // should be relatively uncommon and when it does happen, we want to be
1199 // sure to take advantage of it for all the CPEs near that block, so that
1200 // we don't insert more branches than necessary.
1202 if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1203 (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1204 NewWaterList.count(WaterBB)) && Growth < BestGrowth) {
1205 // This is the least amount of required padding seen so far.
1206 BestGrowth = Growth;
1208 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber()
1209 << " Growth=" << Growth << '\n');
1211 // Keep looking unless it is perfect.
1212 if (BestGrowth == 0)
1218 return BestGrowth != ~0u;
1221 /// createNewWater - No existing WaterList entry will work for
1222 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1223 /// block is used if in range, and the conditional branch munged so control
1224 /// flow is correct. Otherwise the block is split to create a hole with an
1225 /// unconditional branch around it. In either case NewMBB is set to a
1226 /// block following which the new island can be inserted (the WaterList
1227 /// is not adjusted).
1228 void MipsConstantIslands::createNewWater(unsigned CPUserIndex,
1229 unsigned UserOffset,
1230 MachineBasicBlock *&NewMBB) {
1231 CPUser &U = CPUsers[CPUserIndex];
1232 MachineInstr *UserMI = U.MI;
1233 MachineInstr *CPEMI = U.CPEMI;
1234 unsigned CPELogAlign = getCPELogAlign(*CPEMI);
1235 MachineBasicBlock *UserMBB = UserMI->getParent();
1236 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1238 // If the block does not end in an unconditional branch already, and if the
1239 // end of the block is within range, make new water there.
1240 if (BBHasFallthrough(UserMBB)) {
1241 // Size of branch to insert.
1243 // Compute the offset where the CPE will begin.
1244 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1246 if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1247 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber()
1248 << format(", expected CPE offset %#x\n", CPEOffset));
1249 NewMBB = &*++UserMBB->getIterator();
1250 // Add an unconditional branch from UserMBB to fallthrough block. Record
1251 // it for branch lengthening; this new branch will not get out of range,
1252 // but if the preceding conditional branch is out of range, the targets
1253 // will be exchanged, and the altered branch may be out of range, so the
1254 // machinery has to know about it.
1255 int UncondBr = Mips::Bimm16;
1256 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1257 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1258 ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1259 MaxDisp, false, UncondBr));
1260 BBInfo[UserMBB->getNumber()].Size += Delta;
1261 adjustBBOffsetsAfter(UserMBB);
1266 // What a big block. Find a place within the block to split it.
1268 // Try to split the block so it's fully aligned. Compute the latest split
1269 // point where we can add a 4-byte branch instruction, and then align to
1270 // LogAlign which is the largest possible alignment in the function.
1271 unsigned LogAlign = MF->getAlignment();
1272 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1273 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp();
1274 DEBUG(dbgs() << format("Split in middle of big block before %#x",
1277 // The 4 in the following is for the unconditional branch we'll be inserting
1278 // Alignment of the island is handled
1279 // inside isOffsetInRange.
1280 BaseInsertOffset -= 4;
1282 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1283 << " la=" << LogAlign << '\n');
1285 // This could point off the end of the block if we've already got constant
1286 // pool entries following this block; only the last one is in the water list.
1287 // Back past any possible branches (allow for a conditional and a maximally
1288 // long unconditional).
1289 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1290 BaseInsertOffset = UserBBI.postOffset() - 8;
1291 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1293 unsigned EndInsertOffset = BaseInsertOffset + 4 +
1294 CPEMI->getOperand(2).getImm();
1295 MachineBasicBlock::iterator MI = UserMI;
1297 unsigned CPUIndex = CPUserIndex+1;
1298 unsigned NumCPUsers = CPUsers.size();
1299 //MachineInstr *LastIT = 0;
1300 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1301 Offset < BaseInsertOffset;
1302 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1303 assert(MI != UserMBB->end() && "Fell off end of block");
1304 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) {
1305 CPUser &U = CPUsers[CPUIndex];
1306 if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1307 // Shift intertion point by one unit of alignment so it is within reach.
1308 BaseInsertOffset -= 1u << LogAlign;
1309 EndInsertOffset -= 1u << LogAlign;
1311 // This is overly conservative, as we don't account for CPEMIs being
1312 // reused within the block, but it doesn't matter much. Also assume CPEs
1313 // are added in order with alignment padding. We may eventually be able
1314 // to pack the aligned CPEs better.
1315 EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1320 NewMBB = splitBlockBeforeInstr(*--MI);
1323 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1324 /// is out-of-range. If so, pick up the constant pool value and move it some
1325 /// place in-range. Return true if we changed any addresses (thus must run
1326 /// another pass of branch lengthening), false otherwise.
1327 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex) {
1328 CPUser &U = CPUsers[CPUserIndex];
1329 MachineInstr *UserMI = U.MI;
1330 MachineInstr *CPEMI = U.CPEMI;
1331 unsigned CPI = CPEMI->getOperand(1).getIndex();
1332 unsigned Size = CPEMI->getOperand(2).getImm();
1333 // Compute this only once, it's expensive.
1334 unsigned UserOffset = getUserOffset(U);
1336 // See if the current entry is within range, or there is a clone of it
1338 int result = findInRangeCPEntry(U, UserOffset);
1339 if (result==1) return false;
1340 else if (result==2) return true;
1342 // Look for water where we can place this CPE.
1343 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1344 MachineBasicBlock *NewMBB;
1346 if (findAvailableWater(U, UserOffset, IP)) {
1347 DEBUG(dbgs() << "Found water in range\n");
1348 MachineBasicBlock *WaterBB = *IP;
1350 // If the original WaterList entry was "new water" on this iteration,
1351 // propagate that to the new island. This is just keeping NewWaterList
1352 // updated to match the WaterList, which will be updated below.
1353 if (NewWaterList.erase(WaterBB))
1354 NewWaterList.insert(NewIsland);
1356 // The new CPE goes before the following block (NewMBB).
1357 NewMBB = &*++WaterBB->getIterator();
1360 // we first see if a longer form of the instrucion could have reached
1361 // the constant. in that case we won't bother to split
1362 if (!NoLoadRelaxation) {
1363 result = findLongFormInRangeCPEntry(U, UserOffset);
1364 if (result != 0) return true;
1366 DEBUG(dbgs() << "No water found\n");
1367 createNewWater(CPUserIndex, UserOffset, NewMBB);
1369 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1370 // called while handling branches so that the water will be seen on the
1371 // next iteration for constant pools, but in this context, we don't want
1372 // it. Check for this so it will be removed from the WaterList.
1373 // Also remove any entry from NewWaterList.
1374 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1375 IP = llvm::find(WaterList, WaterBB);
1376 if (IP != WaterList.end())
1377 NewWaterList.erase(WaterBB);
1379 // We are adding new water. Update NewWaterList.
1380 NewWaterList.insert(NewIsland);
1383 // Remove the original WaterList entry; we want subsequent insertions in
1384 // this vicinity to go after the one we're about to insert. This
1385 // considerably reduces the number of times we have to move the same CPE
1386 // more than once and is also important to ensure the algorithm terminates.
1387 if (IP != WaterList.end())
1388 WaterList.erase(IP);
1390 // Okay, we know we can put an island before NewMBB now, do it!
1391 MF->insert(NewMBB->getIterator(), NewIsland);
1393 // Update internal data structures to account for the newly inserted MBB.
1394 updateForInsertedWaterBlock(NewIsland);
1396 // Decrement the old entry, and remove it if refcount becomes 0.
1397 decrementCPEReferenceCount(CPI, CPEMI);
1399 // No existing clone of this CPE is within range.
1400 // We will be generating a new clone. Get a UID for it.
1401 unsigned ID = createPICLabelUId();
1403 // Now that we have an island to add the CPE to, clone the original CPE and
1404 // add it to the island.
1405 U.HighWaterMark = NewIsland;
1406 U.CPEMI = BuildMI(NewIsland, DebugLoc(), TII->get(Mips::CONSTPOOL_ENTRY))
1407 .addImm(ID).addConstantPoolIndex(CPI).addImm(Size);
1408 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1411 // Mark the basic block as aligned as required by the const-pool entry.
1412 NewIsland->setAlignment(getCPELogAlign(*U.CPEMI));
1414 // Increase the size of the island block to account for the new entry.
1415 BBInfo[NewIsland->getNumber()].Size += Size;
1416 adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1418 // Finally, change the CPI in the instruction operand to be ID.
1419 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1420 if (UserMI->getOperand(i).isCPI()) {
1421 UserMI->getOperand(i).setIndex(ID);
1425 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1426 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1431 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1432 /// sizes and offsets of impacted basic blocks.
1433 void MipsConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1434 MachineBasicBlock *CPEBB = CPEMI->getParent();
1435 unsigned Size = CPEMI->getOperand(2).getImm();
1436 CPEMI->eraseFromParent();
1437 BBInfo[CPEBB->getNumber()].Size -= Size;
1438 // All succeeding offsets have the current size value added in, fix this.
1439 if (CPEBB->empty()) {
1440 BBInfo[CPEBB->getNumber()].Size = 0;
1442 // This block no longer needs to be aligned.
1443 CPEBB->setAlignment(0);
1445 // Entries are sorted by descending alignment, so realign from the front.
1446 CPEBB->setAlignment(getCPELogAlign(*CPEBB->begin()));
1448 adjustBBOffsetsAfter(CPEBB);
1449 // An island has only one predecessor BB and one successor BB. Check if
1450 // this BB's predecessor jumps directly to this BB's successor. This
1451 // shouldn't happen currently.
1452 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1453 // FIXME: remove the empty blocks after all the work is done?
1456 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1458 bool MipsConstantIslands::removeUnusedCPEntries() {
1459 unsigned MadeChange = false;
1460 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1461 std::vector<CPEntry> &CPEs = CPEntries[i];
1462 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1463 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1464 removeDeadCPEMI(CPEs[j].CPEMI);
1465 CPEs[j].CPEMI = nullptr;
1473 /// isBBInRange - Returns true if the distance between specific MI and
1474 /// specific BB can fit in MI's displacement field.
1475 bool MipsConstantIslands::isBBInRange
1476 (MachineInstr *MI,MachineBasicBlock *DestBB, unsigned MaxDisp) {
1478 unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1479 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1481 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
1482 << " from BB#" << MI->getParent()->getNumber()
1483 << " max delta=" << MaxDisp
1484 << " from " << getOffsetOf(MI) << " to " << DestOffset
1485 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI);
1487 if (BrOffset <= DestOffset) {
1488 // Branch before the Dest.
1489 if (DestOffset-BrOffset <= MaxDisp)
1492 if (BrOffset-DestOffset <= MaxDisp)
1498 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1499 /// away to fit in its displacement field.
1500 bool MipsConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1501 MachineInstr *MI = Br.MI;
1502 unsigned TargetOperand = branchTargetOperand(MI);
1503 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1505 // Check to see if the DestBB is already in-range.
1506 if (isBBInRange(MI, DestBB, Br.MaxDisp))
1510 return fixupUnconditionalBr(Br);
1511 return fixupConditionalBr(Br);
1514 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1515 /// too far away to fit in its displacement field. If the LR register has been
1516 /// spilled in the epilogue, then we can use BL to implement a far jump.
1517 /// Otherwise, add an intermediate branch instruction to a branch.
1519 MipsConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1520 MachineInstr *MI = Br.MI;
1521 MachineBasicBlock *MBB = MI->getParent();
1522 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1523 // Use BL to implement far jump.
1524 unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2;
1525 if (isBBInRange(MI, DestBB, BimmX16MaxDisp)) {
1526 Br.MaxDisp = BimmX16MaxDisp;
1527 MI->setDesc(TII->get(Mips::BimmX16));
1530 // need to give the math a more careful look here
1531 // this is really a segment address and not
1532 // a PC relative address. FIXME. But I think that
1533 // just reducing the bits by 1 as I've done is correct.
1534 // The basic block we are branching too much be longword aligned.
1535 // we know that RA is saved because we always save it right now.
1536 // this requirement will be relaxed later but we also have an alternate
1537 // way to implement this that I will implement that does not need jal.
1538 // We should have a way to back out this alignment restriction if we "can" later.
1539 // but it is not harmful.
1541 DestBB->setAlignment(2);
1542 Br.MaxDisp = ((1<<24)-1) * 2;
1543 MI->setDesc(TII->get(Mips::JalB16));
1545 BBInfo[MBB->getNumber()].Size += 2;
1546 adjustBBOffsetsAfter(MBB);
1550 DEBUG(dbgs() << " Changed B to long jump " << *MI);
1555 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1556 /// far away to fit in its displacement field. It is converted to an inverse
1557 /// conditional branch + an unconditional branch to the destination.
1559 MipsConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1560 MachineInstr *MI = Br.MI;
1561 unsigned TargetOperand = branchTargetOperand(MI);
1562 MachineBasicBlock *DestBB = MI->getOperand(TargetOperand).getMBB();
1563 unsigned Opcode = MI->getOpcode();
1564 unsigned LongFormOpcode = longformBranchOpcode(Opcode);
1565 unsigned LongFormMaxOff = branchMaxOffsets(LongFormOpcode);
1567 // Check to see if the DestBB is already in-range.
1568 if (isBBInRange(MI, DestBB, LongFormMaxOff)) {
1569 Br.MaxDisp = LongFormMaxOff;
1570 MI->setDesc(TII->get(LongFormOpcode));
1574 // Add an unconditional branch to the destination and invert the branch
1575 // condition to jump over it:
1582 // If the branch is at the end of its MBB and that has a fall-through block,
1583 // direct the updated conditional branch to the fall-through block. Otherwise,
1584 // split the MBB before the next instruction.
1585 MachineBasicBlock *MBB = MI->getParent();
1586 MachineInstr *BMI = &MBB->back();
1587 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1588 unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opcode);
1592 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1593 BMI->isUnconditionalBranch()) {
1594 // Last MI in the BB is an unconditional branch. Can we simply invert the
1595 // condition and swap destinations:
1601 unsigned BMITargetOperand = branchTargetOperand(BMI);
1602 MachineBasicBlock *NewDest =
1603 BMI->getOperand(BMITargetOperand).getMBB();
1604 if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1605 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with "
1607 MI->setDesc(TII->get(OppositeBranchOpcode));
1608 BMI->getOperand(BMITargetOperand).setMBB(DestBB);
1609 MI->getOperand(TargetOperand).setMBB(NewDest);
1616 splitBlockBeforeInstr(*MI);
1617 // No need for the branch to the next block. We're adding an unconditional
1618 // branch to the destination.
1619 int delta = TII->getInstSizeInBytes(MBB->back());
1620 BBInfo[MBB->getNumber()].Size -= delta;
1621 MBB->back().eraseFromParent();
1622 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1624 MachineBasicBlock *NextBB = &*++MBB->getIterator();
1626 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
1627 << " also invert condition and change dest. to BB#"
1628 << NextBB->getNumber() << "\n");
1630 // Insert a new conditional branch and a new unconditional branch.
1631 // Also update the ImmBranch as well as adding a new entry for the new branch.
1632 if (MI->getNumExplicitOperands() == 2) {
1633 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1634 .addReg(MI->getOperand(0).getReg())
1637 BuildMI(MBB, DebugLoc(), TII->get(OppositeBranchOpcode))
1640 Br.MI = &MBB->back();
1641 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1642 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1643 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1644 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1645 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1647 // Remove the old conditional branch. It may or may not still be in MBB.
1648 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1649 MI->eraseFromParent();
1650 adjustBBOffsetsAfter(MBB);
1654 void MipsConstantIslands::prescanForConstants() {
1657 for (MachineFunction::iterator B =
1658 MF->begin(), E = MF->end(); B != E; ++B) {
1659 for (MachineBasicBlock::instr_iterator I =
1660 B->instr_begin(), EB = B->instr_end(); I != EB; ++I) {
1661 switch(I->getDesc().getOpcode()) {
1662 case Mips::LwConstant32: {
1663 PrescannedForConstants = true;
1664 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1665 J = I->getNumOperands();
1666 DEBUG(dbgs() << "num operands " << J << "\n");
1667 MachineOperand& Literal = I->getOperand(1);
1668 if (Literal.isImm()) {
1669 int64_t V = Literal.getImm();
1670 DEBUG(dbgs() << "literal " << V << "\n");
1672 Type::getInt32Ty(MF->getFunction()->getContext());
1673 const Constant *C = ConstantInt::get(Int32Ty, V);
1674 unsigned index = MCP->getConstantPoolIndex(C, 4);
1675 I->getOperand(2).ChangeToImmediate(index);
1676 DEBUG(dbgs() << "constant island constant " << *I << "\n");
1677 I->setDesc(TII->get(Mips::LwRxPcTcp16));
1678 I->RemoveOperand(1);
1679 I->RemoveOperand(1);
1680 I->addOperand(MachineOperand::CreateCPI(index, 0));
1681 I->addOperand(MachineOperand::CreateImm(4));
1692 /// Returns a pass that converts branches to long branches.
1693 FunctionPass *llvm::createMipsConstantIslandPass() {
1694 return new MipsConstantIslands();