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/STLExtras.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.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/Config/llvm-config.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DebugLoc.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/Format.h"
51 #include "llvm/Support/MathExtras.h"
52 #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.
75 static cl::opt
<int> ConstantIslandsSmallOffset(
76 "mips-constant-islands-small-offset",
78 cl::desc("Make small offsets be this amount for testing purposes"),
81 // For testing purposes we tell it to not use relaxed load forms so that it
83 static cl::opt
<bool> NoLoadRelaxation(
84 "mips-constant-islands-no-load-relaxation",
86 cl::desc("Don't relax loads to long loads - for testing purposes"),
89 static unsigned int branchTargetOperand(MachineInstr
*MI
) {
90 switch (MI
->getOpcode()) {
99 case Mips::BeqzRxImm16
:
100 case Mips::BeqzRxImmX16
:
101 case Mips::BnezRxImm16
:
102 case Mips::BnezRxImmX16
:
105 llvm_unreachable("Unknown branch type");
108 static unsigned int longformBranchOpcode(unsigned int Opcode
) {
112 return Mips::BimmX16
;
115 return Mips::BteqzX16
;
118 return Mips::BtnezX16
;
121 case Mips::BeqzRxImm16
:
122 case Mips::BeqzRxImmX16
:
123 return Mips::BeqzRxImmX16
;
124 case Mips::BnezRxImm16
:
125 case Mips::BnezRxImmX16
:
126 return Mips::BnezRxImmX16
;
128 llvm_unreachable("Unknown branch type");
131 // FIXME: need to go through this whole constant islands port and check the math
132 // for branch ranges and clean this up and make some functions to calculate things
133 // that are done many times identically.
134 // Need to refactor some of the code to call this routine.
135 static unsigned int branchMaxOffsets(unsigned int Opcode
) {
136 unsigned Bits
, Scale
;
146 case Mips::BeqzRxImm16
:
150 case Mips::BeqzRxImmX16
:
154 case Mips::BnezRxImm16
:
158 case Mips::BnezRxImmX16
:
179 llvm_unreachable("Unknown branch type");
181 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
187 using Iter
= MachineBasicBlock::iterator
;
188 using ReverseIter
= MachineBasicBlock::reverse_iterator
;
190 /// MipsConstantIslands - Due to limited PC-relative displacements, Mips
191 /// requires constant pool entries to be scattered among the instructions
192 /// inside a function. To do this, it completely ignores the normal LLVM
193 /// constant pool; instead, it places constants wherever it feels like with
194 /// special instructions.
196 /// The terminology used in this pass includes:
197 /// Islands - Clumps of constants placed in the function.
198 /// Water - Potential places where an island could be formed.
199 /// CPE - A constant pool entry that has been placed somewhere, which
200 /// tracks a list of users.
202 class MipsConstantIslands
: public MachineFunctionPass
{
203 /// BasicBlockInfo - Information about the offset and size of a single
205 struct BasicBlockInfo
{
206 /// Offset - Distance from the beginning of the function to the beginning
207 /// of this basic block.
209 /// Offsets are computed assuming worst case padding before an aligned
210 /// block. This means that subtracting basic block offsets always gives a
211 /// conservative estimate of the real distance which may be smaller.
213 /// Because worst case padding is used, the computed offset of an aligned
214 /// block may not actually be aligned.
217 /// Size - Size of the basic block in bytes. If the block contains
218 /// inline assembly, this is a worst case estimate.
220 /// The size does not include any alignment padding whether from the
221 /// beginning of the block, or from an aligned jump table at the end.
224 BasicBlockInfo() = default;
226 // FIXME: ignore LogAlign for this patch
228 unsigned postOffset(unsigned LogAlign
= 0) const {
229 unsigned PO
= Offset
+ Size
;
234 std::vector
<BasicBlockInfo
> BBInfo
;
236 /// WaterList - A sorted list of basic blocks where islands could be placed
237 /// (i.e. blocks that don't fall through to the following block, due
238 /// to a return, unreachable, or unconditional branch).
239 std::vector
<MachineBasicBlock
*> WaterList
;
241 /// NewWaterList - The subset of WaterList that was created since the
242 /// previous iteration by inserting unconditional branches.
243 SmallSet
<MachineBasicBlock
*, 4> NewWaterList
;
245 using water_iterator
= std::vector
<MachineBasicBlock
*>::iterator
;
247 /// CPUser - One user of a constant pool, keeping the machine instruction
248 /// pointer, the constant pool being referenced, and the max displacement
249 /// allowed from the instruction to the CP. The HighWaterMark records the
250 /// highest basic block where a new CPEntry can be placed. To ensure this
251 /// pass terminates, the CP entries are initially placed at the end of the
252 /// function and then move monotonically to lower addresses. The
253 /// exception to this rule is when the current CP entry for a particular
254 /// CPUser is out of range, but there is another CP entry for the same
255 /// constant value in range. We want to use the existing in-range CP
256 /// entry, but if it later moves out of range, the search for new water
257 /// should resume where it left off. The HighWaterMark is used to record
262 MachineBasicBlock
*HighWaterMark
;
266 unsigned LongFormMaxDisp
; // mips16 has 16/32 bit instructions
267 // with different displacements
268 unsigned LongFormOpcode
;
273 CPUser(MachineInstr
*mi
, MachineInstr
*cpemi
, unsigned maxdisp
,
275 unsigned longformmaxdisp
, unsigned longformopcode
)
276 : MI(mi
), CPEMI(cpemi
), MaxDisp(maxdisp
),
277 LongFormMaxDisp(longformmaxdisp
), LongFormOpcode(longformopcode
),
279 HighWaterMark
= CPEMI
->getParent();
282 /// getMaxDisp - Returns the maximum displacement supported by MI.
283 unsigned getMaxDisp() const {
284 unsigned xMaxDisp
= ConstantIslandsSmallOffset
?
285 ConstantIslandsSmallOffset
: MaxDisp
;
289 void setMaxDisp(unsigned val
) {
293 unsigned getLongFormMaxDisp() const {
294 return LongFormMaxDisp
;
297 unsigned getLongFormOpcode() const {
298 return LongFormOpcode
;
302 /// CPUsers - Keep track of all of the machine instructions that use various
303 /// constant pools and their max displacement.
304 std::vector
<CPUser
> CPUsers
;
306 /// CPEntry - One per constant pool entry, keeping the machine instruction
307 /// pointer, the constpool index, and the number of CPUser's which
308 /// reference this entry.
314 CPEntry(MachineInstr
*cpemi
, unsigned cpi
, unsigned rc
= 0)
315 : CPEMI(cpemi
), CPI(cpi
), RefCount(rc
) {}
318 /// CPEntries - Keep track of all of the constant pool entry machine
319 /// instructions. For each original constpool index (i.e. those that
320 /// existed upon entry to this pass), it keeps a vector of entries.
321 /// Original elements are cloned as we go along; the clones are
322 /// put in the vector of the original element, but have distinct CPIs.
323 std::vector
<std::vector
<CPEntry
>> CPEntries
;
325 /// ImmBranch - One per immediate branch, keeping the machine instruction
326 /// pointer, conditional or unconditional, the max displacement,
327 /// and (if isCond is true) the corresponding unconditional branch
331 unsigned MaxDisp
: 31;
335 ImmBranch(MachineInstr
*mi
, unsigned maxdisp
, bool cond
, int ubr
)
336 : MI(mi
), MaxDisp(maxdisp
), isCond(cond
), UncondBr(ubr
) {}
339 /// ImmBranches - Keep track of all the immediate branch instructions.
341 std::vector
<ImmBranch
> ImmBranches
;
343 /// HasFarJump - True if any far jump instruction has been emitted during
344 /// the branch fix up pass.
347 const MipsSubtarget
*STI
= nullptr;
348 const Mips16InstrInfo
*TII
;
349 MipsFunctionInfo
*MFI
;
350 MachineFunction
*MF
= nullptr;
351 MachineConstantPool
*MCP
= nullptr;
353 unsigned PICLabelUId
;
354 bool PrescannedForConstants
= false;
356 void initPICLabelUId(unsigned UId
) {
360 unsigned createPICLabelUId() {
361 return PICLabelUId
++;
367 MipsConstantIslands() : MachineFunctionPass(ID
) {}
369 StringRef
getPassName() const override
{ return "Mips Constant Islands"; }
371 bool runOnMachineFunction(MachineFunction
&F
) override
;
373 MachineFunctionProperties
getRequiredProperties() const override
{
374 return MachineFunctionProperties().set(
375 MachineFunctionProperties::Property::NoVRegs
);
378 void doInitialPlacement(std::vector
<MachineInstr
*> &CPEMIs
);
379 CPEntry
*findConstPoolEntry(unsigned CPI
, const MachineInstr
*CPEMI
);
380 unsigned getCPELogAlign(const MachineInstr
&CPEMI
);
381 void initializeFunctionInfo(const std::vector
<MachineInstr
*> &CPEMIs
);
382 unsigned getOffsetOf(MachineInstr
*MI
) const;
383 unsigned getUserOffset(CPUser
&) const;
386 bool isOffsetInRange(unsigned UserOffset
, unsigned TrialOffset
,
387 unsigned Disp
, bool NegativeOK
);
388 bool isOffsetInRange(unsigned UserOffset
, unsigned TrialOffset
,
391 void computeBlockSize(MachineBasicBlock
*MBB
);
392 MachineBasicBlock
*splitBlockBeforeInstr(MachineInstr
&MI
);
393 void updateForInsertedWaterBlock(MachineBasicBlock
*NewBB
);
394 void adjustBBOffsetsAfter(MachineBasicBlock
*BB
);
395 bool decrementCPEReferenceCount(unsigned CPI
, MachineInstr
* CPEMI
);
396 int findInRangeCPEntry(CPUser
& U
, unsigned UserOffset
);
397 int findLongFormInRangeCPEntry(CPUser
& U
, unsigned UserOffset
);
398 bool findAvailableWater(CPUser
&U
, unsigned UserOffset
,
399 water_iterator
&WaterIter
);
400 void createNewWater(unsigned CPUserIndex
, unsigned UserOffset
,
401 MachineBasicBlock
*&NewMBB
);
402 bool handleConstantPoolUser(unsigned CPUserIndex
);
403 void removeDeadCPEMI(MachineInstr
*CPEMI
);
404 bool removeUnusedCPEntries();
405 bool isCPEntryInRange(MachineInstr
*MI
, unsigned UserOffset
,
406 MachineInstr
*CPEMI
, unsigned Disp
, bool NegOk
,
407 bool DoDump
= false);
408 bool isWaterInRange(unsigned UserOffset
, MachineBasicBlock
*Water
,
409 CPUser
&U
, unsigned &Growth
);
410 bool isBBInRange(MachineInstr
*MI
, MachineBasicBlock
*BB
, unsigned Disp
);
411 bool fixupImmediateBr(ImmBranch
&Br
);
412 bool fixupConditionalBr(ImmBranch
&Br
);
413 bool fixupUnconditionalBr(ImmBranch
&Br
);
415 void prescanForConstants();
418 } // end anonymous namespace
420 char MipsConstantIslands::ID
= 0;
422 bool MipsConstantIslands::isOffsetInRange
423 (unsigned UserOffset
, unsigned TrialOffset
,
425 return isOffsetInRange(UserOffset
, TrialOffset
,
426 U
.getMaxDisp(), U
.NegOk
);
429 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
430 /// print block size and offset information - debugging
431 LLVM_DUMP_METHOD
void MipsConstantIslands::dumpBBs() {
432 for (unsigned J
= 0, E
= BBInfo
.size(); J
!=E
; ++J
) {
433 const BasicBlockInfo
&BBI
= BBInfo
[J
];
434 dbgs() << format("%08x %bb.%u\t", BBI
.Offset
, J
)
435 << format(" size=%#x\n", BBInfo
[J
].Size
);
440 bool MipsConstantIslands::runOnMachineFunction(MachineFunction
&mf
) {
441 // The intention is for this to be a mips16 only pass for now
444 MCP
= mf
.getConstantPool();
445 STI
= &static_cast<const MipsSubtarget
&>(mf
.getSubtarget());
446 LLVM_DEBUG(dbgs() << "constant island machine function "
448 if (!STI
->inMips16Mode() || !MipsSubtarget::useConstantIslands()) {
451 TII
= (const Mips16InstrInfo
*)STI
->getInstrInfo();
452 MFI
= MF
->getInfo
<MipsFunctionInfo
>();
453 LLVM_DEBUG(dbgs() << "constant island processing "
456 // will need to make predermination if there is any constants we need to
457 // put in constant islands. TBD.
459 if (!PrescannedForConstants
) prescanForConstants();
462 // This pass invalidates liveness information when it splits basic blocks.
463 MF
->getRegInfo().invalidateLiveness();
465 // Renumber all of the machine basic blocks in the function, guaranteeing that
466 // the numbers agree with the position of the block in the function.
467 MF
->RenumberBlocks();
469 bool MadeChange
= false;
471 // Perform the initial placement of the constant pool entries. To start with,
472 // we put them all at the end of the function.
473 std::vector
<MachineInstr
*> CPEMIs
;
475 doInitialPlacement(CPEMIs
);
477 /// The next UID to take is the first unused one.
478 initPICLabelUId(CPEMIs
.size());
480 // Do the initial scan of the function, building up information about the
481 // sizes of each block, the location of all the water, and finding all of the
482 // constant pool users.
483 initializeFunctionInfo(CPEMIs
);
485 LLVM_DEBUG(dumpBBs());
487 /// Remove dead constant pool entries.
488 MadeChange
|= removeUnusedCPEntries();
490 // Iteratively place constant pool entries and fix up branches until there
492 unsigned NoCPIters
= 0, NoBRIters
= 0;
495 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters
<< '\n');
496 bool CPChange
= false;
497 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
)
498 CPChange
|= handleConstantPoolUser(i
);
499 if (CPChange
&& ++NoCPIters
> 30)
500 report_fatal_error("Constant Island pass failed to converge!");
501 LLVM_DEBUG(dumpBBs());
503 // Clear NewWaterList now. If we split a block for branches, it should
504 // appear as "new water" for the next iteration of constant pool placement.
505 NewWaterList
.clear();
507 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters
<< '\n');
508 bool BRChange
= false;
509 for (unsigned i
= 0, e
= ImmBranches
.size(); i
!= e
; ++i
)
510 BRChange
|= fixupImmediateBr(ImmBranches
[i
]);
511 if (BRChange
&& ++NoBRIters
> 30)
512 report_fatal_error("Branch Fix Up pass failed to converge!");
513 LLVM_DEBUG(dumpBBs());
514 if (!CPChange
&& !BRChange
)
519 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
529 /// doInitialPlacement - Perform the initial placement of the constant pool
530 /// entries. To start with, we put them all at the end of the function.
532 MipsConstantIslands::doInitialPlacement(std::vector
<MachineInstr
*> &CPEMIs
) {
533 // Create the basic block to hold the CPE's.
534 MachineBasicBlock
*BB
= MF
->CreateMachineBasicBlock();
537 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
538 unsigned MaxAlign
= Log2_32(MCP
->getConstantPoolAlignment());
540 // Mark the basic block as required by the const-pool.
541 // If AlignConstantIslands isn't set, use 4-byte alignment for everything.
542 BB
->setAlignment(AlignConstantIslands
? MaxAlign
: 2);
544 // The function needs to be as aligned as the basic blocks. The linker may
545 // move functions around based on their alignment.
546 MF
->ensureAlignment(BB
->getAlignment());
548 // Order the entries in BB by descending alignment. That ensures correct
549 // alignment of all entries as long as BB is sufficiently aligned. Keep
550 // track of the insertion point for each alignment. We are going to bucket
551 // sort the entries as they are created.
552 SmallVector
<MachineBasicBlock::iterator
, 8> InsPoint(MaxAlign
+ 1, BB
->end());
554 // Add all of the constants from the constant pool to the end block, use an
555 // identity mapping of CPI's to CPE's.
556 const std::vector
<MachineConstantPoolEntry
> &CPs
= MCP
->getConstants();
558 const DataLayout
&TD
= MF
->getDataLayout();
559 for (unsigned i
= 0, e
= CPs
.size(); i
!= e
; ++i
) {
560 unsigned Size
= TD
.getTypeAllocSize(CPs
[i
].getType());
561 assert(Size
>= 4 && "Too small constant pool entry");
562 unsigned Align
= CPs
[i
].getAlignment();
563 assert(isPowerOf2_32(Align
) && "Invalid alignment");
564 // Verify that all constant pool entries are a multiple of their alignment.
565 // If not, we would have to pad them out so that instructions stay aligned.
566 assert((Size
% Align
) == 0 && "CP Entry not multiple of 4 bytes!");
568 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
569 unsigned LogAlign
= Log2_32(Align
);
570 MachineBasicBlock::iterator InsAt
= InsPoint
[LogAlign
];
572 MachineInstr
*CPEMI
=
573 BuildMI(*BB
, InsAt
, DebugLoc(), TII
->get(Mips::CONSTPOOL_ENTRY
))
574 .addImm(i
).addConstantPoolIndex(i
).addImm(Size
);
576 CPEMIs
.push_back(CPEMI
);
578 // Ensure that future entries with higher alignment get inserted before
579 // CPEMI. This is bucket sort with iterators.
580 for (unsigned a
= LogAlign
+ 1; a
<= MaxAlign
; ++a
)
581 if (InsPoint
[a
] == InsAt
)
583 // Add a new CPEntry, but no corresponding CPUser yet.
584 CPEntries
.emplace_back(1, CPEntry(CPEMI
, i
));
586 LLVM_DEBUG(dbgs() << "Moved CPI#" << i
<< " to end of function, size = "
587 << Size
<< ", align = " << Align
<< '\n');
589 LLVM_DEBUG(BB
->dump());
592 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
593 /// into the block immediately after it.
594 static bool BBHasFallthrough(MachineBasicBlock
*MBB
) {
595 // Get the next machine basic block in the function.
596 MachineFunction::iterator MBBI
= MBB
->getIterator();
597 // Can't fall off end of function.
598 if (std::next(MBBI
) == MBB
->getParent()->end())
601 MachineBasicBlock
*NextBB
= &*std::next(MBBI
);
602 for (MachineBasicBlock::succ_iterator I
= MBB
->succ_begin(),
603 E
= MBB
->succ_end(); I
!= E
; ++I
)
610 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
611 /// look up the corresponding CPEntry.
612 MipsConstantIslands::CPEntry
613 *MipsConstantIslands::findConstPoolEntry(unsigned CPI
,
614 const MachineInstr
*CPEMI
) {
615 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
616 // Number of entries per constpool index should be small, just do a
618 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
619 if (CPEs
[i
].CPEMI
== CPEMI
)
625 /// getCPELogAlign - Returns the required alignment of the constant pool entry
626 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
627 unsigned MipsConstantIslands::getCPELogAlign(const MachineInstr
&CPEMI
) {
628 assert(CPEMI
.getOpcode() == Mips::CONSTPOOL_ENTRY
);
630 // Everything is 4-byte aligned unless AlignConstantIslands is set.
631 if (!AlignConstantIslands
)
634 unsigned CPI
= CPEMI
.getOperand(1).getIndex();
635 assert(CPI
< MCP
->getConstants().size() && "Invalid constant pool index.");
636 unsigned Align
= MCP
->getConstants()[CPI
].getAlignment();
637 assert(isPowerOf2_32(Align
) && "Invalid CPE alignment");
638 return Log2_32(Align
);
641 /// initializeFunctionInfo - Do the initial scan of the function, building up
642 /// information about the sizes of each block, the location of all the water,
643 /// and finding all of the constant pool users.
644 void MipsConstantIslands::
645 initializeFunctionInfo(const std::vector
<MachineInstr
*> &CPEMIs
) {
647 BBInfo
.resize(MF
->getNumBlockIDs());
649 // First thing, compute the size of all basic blocks, and see if the function
650 // has any inline assembly in it. If so, we have to be conservative about
651 // alignment assumptions, as we don't know for sure the size of any
652 // instructions in the inline assembly.
653 for (MachineFunction::iterator I
= MF
->begin(), E
= MF
->end(); I
!= E
; ++I
)
654 computeBlockSize(&*I
);
656 // Compute block offsets.
657 adjustBBOffsetsAfter(&MF
->front());
659 // Now go back through the instructions and build up our data structures.
660 for (MachineBasicBlock
&MBB
: *MF
) {
661 // If this block doesn't fall through into the next MBB, then this is
662 // 'water' that a constant pool island could be placed.
663 if (!BBHasFallthrough(&MBB
))
664 WaterList
.push_back(&MBB
);
665 for (MachineInstr
&MI
: MBB
) {
666 if (MI
.isDebugInstr())
669 int Opc
= MI
.getOpcode();
677 continue; // Ignore other branches for now
688 case Mips::BeqzRxImm16
:
694 case Mips::BeqzRxImmX16
:
700 case Mips::BnezRxImm16
:
706 case Mips::BnezRxImmX16
:
737 // Record this immediate branch.
738 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
739 ImmBranches
.push_back(ImmBranch(&MI
, MaxOffs
, isCond
, UOpc
));
742 if (Opc
== Mips::CONSTPOOL_ENTRY
)
745 // Scan the instructions for constant pool operands.
746 for (unsigned op
= 0, e
= MI
.getNumOperands(); op
!= e
; ++op
)
747 if (MI
.getOperand(op
).isCPI()) {
748 // We found one. The addressing mode tells us the max displacement
749 // from the PC that this instruction permits.
751 // Basic size info comes from the TSFlags field.
755 unsigned LongFormBits
= 0;
756 unsigned LongFormScale
= 0;
757 unsigned LongFormOpcode
= 0;
760 llvm_unreachable("Unknown addressing mode for CP reference!");
761 case Mips::LwRxPcTcp16
:
764 LongFormOpcode
= Mips::LwRxPcTcpX16
;
768 case Mips::LwRxPcTcpX16
:
774 // Remember that this is a user of a CP entry.
775 unsigned CPI
= MI
.getOperand(op
).getIndex();
776 MachineInstr
*CPEMI
= CPEMIs
[CPI
];
777 unsigned MaxOffs
= ((1 << Bits
)-1) * Scale
;
778 unsigned LongFormMaxOffs
= ((1 << LongFormBits
)-1) * LongFormScale
;
779 CPUsers
.push_back(CPUser(&MI
, CPEMI
, MaxOffs
, NegOk
, LongFormMaxOffs
,
782 // Increment corresponding CPEntry reference count.
783 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
784 assert(CPE
&& "Cannot find a corresponding CPEntry!");
787 // Instructions can only use one CP entry, don't bother scanning the
788 // rest of the operands.
795 /// computeBlockSize - Compute the size and some alignment information for MBB.
796 /// This function updates BBInfo directly.
797 void MipsConstantIslands::computeBlockSize(MachineBasicBlock
*MBB
) {
798 BasicBlockInfo
&BBI
= BBInfo
[MBB
->getNumber()];
801 for (const MachineInstr
&MI
: *MBB
)
802 BBI
.Size
+= TII
->getInstSizeInBytes(MI
);
805 /// getOffsetOf - Return the current offset of the specified machine instruction
806 /// from the start of the function. This offset changes as stuff is moved
807 /// around inside the function.
808 unsigned MipsConstantIslands::getOffsetOf(MachineInstr
*MI
) const {
809 MachineBasicBlock
*MBB
= MI
->getParent();
811 // The offset is composed of two things: the sum of the sizes of all MBB's
812 // before this instruction's block, and the offset from the start of the block
814 unsigned Offset
= BBInfo
[MBB
->getNumber()].Offset
;
816 // Sum instructions before MI in MBB.
817 for (MachineBasicBlock::iterator I
= MBB
->begin(); &*I
!= MI
; ++I
) {
818 assert(I
!= MBB
->end() && "Didn't find MI in its own basic block?");
819 Offset
+= TII
->getInstSizeInBytes(*I
);
824 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
826 static bool CompareMBBNumbers(const MachineBasicBlock
*LHS
,
827 const MachineBasicBlock
*RHS
) {
828 return LHS
->getNumber() < RHS
->getNumber();
831 /// updateForInsertedWaterBlock - When a block is newly inserted into the
832 /// machine function, it upsets all of the block numbers. Renumber the blocks
833 /// and update the arrays that parallel this numbering.
834 void MipsConstantIslands::updateForInsertedWaterBlock
835 (MachineBasicBlock
*NewBB
) {
836 // Renumber the MBB's to keep them consecutive.
837 NewBB
->getParent()->RenumberBlocks(NewBB
);
839 // Insert an entry into BBInfo to align it properly with the (newly
840 // renumbered) block numbers.
841 BBInfo
.insert(BBInfo
.begin() + NewBB
->getNumber(), BasicBlockInfo());
843 // Next, update WaterList. Specifically, we need to add NewMBB as having
844 // available water after it.
846 std::lower_bound(WaterList
.begin(), WaterList
.end(), NewBB
,
848 WaterList
.insert(IP
, NewBB
);
851 unsigned MipsConstantIslands::getUserOffset(CPUser
&U
) const {
852 return getOffsetOf(U
.MI
);
855 /// Split the basic block containing MI into two blocks, which are joined by
856 /// an unconditional branch. Update data structures and renumber blocks to
857 /// account for this change and returns the newly created block.
859 MipsConstantIslands::splitBlockBeforeInstr(MachineInstr
&MI
) {
860 MachineBasicBlock
*OrigBB
= MI
.getParent();
862 // Create a new MBB for the code after the OrigBB.
863 MachineBasicBlock
*NewBB
=
864 MF
->CreateMachineBasicBlock(OrigBB
->getBasicBlock());
865 MachineFunction::iterator MBBI
= ++OrigBB
->getIterator();
866 MF
->insert(MBBI
, NewBB
);
868 // Splice the instructions starting with MI over to NewBB.
869 NewBB
->splice(NewBB
->end(), OrigBB
, MI
, OrigBB
->end());
871 // Add an unconditional branch from OrigBB to NewBB.
872 // Note the new unconditional branch is not being recorded.
873 // There doesn't seem to be meaningful DebugInfo available; this doesn't
874 // correspond to anything in the source.
875 BuildMI(OrigBB
, DebugLoc(), TII
->get(Mips::Bimm16
)).addMBB(NewBB
);
878 // Update the CFG. All succs of OrigBB are now succs of NewBB.
879 NewBB
->transferSuccessors(OrigBB
);
881 // OrigBB branches to NewBB.
882 OrigBB
->addSuccessor(NewBB
);
884 // Update internal data structures to account for the newly inserted MBB.
885 // This is almost the same as updateForInsertedWaterBlock, except that
886 // the Water goes after OrigBB, not NewBB.
887 MF
->RenumberBlocks(NewBB
);
889 // Insert an entry into BBInfo to align it properly with the (newly
890 // renumbered) block numbers.
891 BBInfo
.insert(BBInfo
.begin() + NewBB
->getNumber(), BasicBlockInfo());
893 // Next, update WaterList. Specifically, we need to add OrigMBB as having
894 // available water after it (but not if it's already there, which happens
895 // when splitting before a conditional branch that is followed by an
896 // unconditional branch - in that case we want to insert NewBB).
898 std::lower_bound(WaterList
.begin(), WaterList
.end(), OrigBB
,
900 MachineBasicBlock
* WaterBB
= *IP
;
901 if (WaterBB
== OrigBB
)
902 WaterList
.insert(std::next(IP
), NewBB
);
904 WaterList
.insert(IP
, OrigBB
);
905 NewWaterList
.insert(OrigBB
);
907 // Figure out how large the OrigBB is. As the first half of the original
908 // block, it cannot contain a tablejump. The size includes
909 // the new jump we added. (It should be possible to do this without
910 // recounting everything, but it's very confusing, and this is rarely
912 computeBlockSize(OrigBB
);
914 // Figure out how large the NewMBB is. As the second half of the original
915 // block, it may contain a tablejump.
916 computeBlockSize(NewBB
);
918 // All BBOffsets following these blocks must be modified.
919 adjustBBOffsetsAfter(OrigBB
);
924 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
925 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
926 /// constant pool entry).
927 bool MipsConstantIslands::isOffsetInRange(unsigned UserOffset
,
928 unsigned TrialOffset
, unsigned MaxDisp
,
930 if (UserOffset
<= TrialOffset
) {
931 // User before the Trial.
932 if (TrialOffset
- UserOffset
<= MaxDisp
)
934 } else if (NegativeOK
) {
935 if (UserOffset
- TrialOffset
<= MaxDisp
)
941 /// isWaterInRange - Returns true if a CPE placed after the specified
942 /// Water (a basic block) will be in range for the specific MI.
944 /// Compute how much the function will grow by inserting a CPE after Water.
945 bool MipsConstantIslands::isWaterInRange(unsigned UserOffset
,
946 MachineBasicBlock
* Water
, CPUser
&U
,
948 unsigned CPELogAlign
= getCPELogAlign(*U
.CPEMI
);
949 unsigned CPEOffset
= BBInfo
[Water
->getNumber()].postOffset(CPELogAlign
);
950 unsigned NextBlockOffset
, NextBlockAlignment
;
951 MachineFunction::const_iterator NextBlock
= ++Water
->getIterator();
952 if (NextBlock
== MF
->end()) {
953 NextBlockOffset
= BBInfo
[Water
->getNumber()].postOffset();
954 NextBlockAlignment
= 0;
956 NextBlockOffset
= BBInfo
[NextBlock
->getNumber()].Offset
;
957 NextBlockAlignment
= NextBlock
->getAlignment();
959 unsigned Size
= U
.CPEMI
->getOperand(2).getImm();
960 unsigned CPEEnd
= CPEOffset
+ Size
;
962 // The CPE may be able to hide in the alignment padding before the next
963 // block. It may also cause more padding to be required if it is more aligned
964 // that the next block.
965 if (CPEEnd
> NextBlockOffset
) {
966 Growth
= CPEEnd
- NextBlockOffset
;
967 // Compute the padding that would go at the end of the CPE to align the next
969 Growth
+= OffsetToAlignment(CPEEnd
, 1ULL << NextBlockAlignment
);
971 // If the CPE is to be inserted before the instruction, that will raise
972 // the offset of the instruction. Also account for unknown alignment padding
973 // in blocks between CPE and the user.
974 if (CPEOffset
< UserOffset
)
975 UserOffset
+= Growth
;
977 // CPE fits in existing padding.
980 return isOffsetInRange(UserOffset
, CPEOffset
, U
);
983 /// isCPEntryInRange - Returns true if the distance between specific MI and
984 /// specific ConstPool entry instruction can fit in MI's displacement field.
985 bool MipsConstantIslands::isCPEntryInRange
986 (MachineInstr
*MI
, unsigned UserOffset
,
987 MachineInstr
*CPEMI
, unsigned MaxDisp
,
988 bool NegOk
, bool DoDump
) {
989 unsigned CPEOffset
= getOffsetOf(CPEMI
);
993 unsigned Block
= MI
->getParent()->getNumber();
994 const BasicBlockInfo
&BBI
= BBInfo
[Block
];
995 dbgs() << "User of CPE#" << CPEMI
->getOperand(0).getImm()
996 << " max delta=" << MaxDisp
997 << format(" insn address=%#x", UserOffset
) << " in "
998 << printMBBReference(*MI
->getParent()) << ": "
999 << format("%#x-%x\t", BBI
.Offset
, BBI
.postOffset()) << *MI
1000 << format("CPE address=%#x offset=%+d: ", CPEOffset
,
1001 int(CPEOffset
- UserOffset
));
1005 return isOffsetInRange(UserOffset
, CPEOffset
, MaxDisp
, NegOk
);
1009 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1010 /// unconditionally branches to its only successor.
1011 static bool BBIsJumpedOver(MachineBasicBlock
*MBB
) {
1012 if (MBB
->pred_size() != 1 || MBB
->succ_size() != 1)
1014 MachineBasicBlock
*Succ
= *MBB
->succ_begin();
1015 MachineBasicBlock
*Pred
= *MBB
->pred_begin();
1016 MachineInstr
*PredMI
= &Pred
->back();
1017 if (PredMI
->getOpcode() == Mips::Bimm16
)
1018 return PredMI
->getOperand(0).getMBB() == Succ
;
1023 void MipsConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock
*BB
) {
1024 unsigned BBNum
= BB
->getNumber();
1025 for(unsigned i
= BBNum
+ 1, e
= MF
->getNumBlockIDs(); i
< e
; ++i
) {
1026 // Get the offset and known bits at the end of the layout predecessor.
1027 // Include the alignment of the current block.
1028 unsigned Offset
= BBInfo
[i
- 1].Offset
+ BBInfo
[i
- 1].Size
;
1029 BBInfo
[i
].Offset
= Offset
;
1033 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1034 /// and instruction CPEMI, and decrement its refcount. If the refcount
1035 /// becomes 0 remove the entry and instruction. Returns true if we removed
1036 /// the entry, false if we didn't.
1037 bool MipsConstantIslands::decrementCPEReferenceCount(unsigned CPI
,
1038 MachineInstr
*CPEMI
) {
1039 // Find the old entry. Eliminate it if it is no longer used.
1040 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
1041 assert(CPE
&& "Unexpected!");
1042 if (--CPE
->RefCount
== 0) {
1043 removeDeadCPEMI(CPEMI
);
1044 CPE
->CPEMI
= nullptr;
1051 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1052 /// if not, see if an in-range clone of the CPE is in range, and if so,
1053 /// change the data structures so the user references the clone. Returns:
1054 /// 0 = no existing entry found
1055 /// 1 = entry found, and there were no code insertions or deletions
1056 /// 2 = entry found, and there were code insertions or deletions
1057 int MipsConstantIslands::findInRangeCPEntry(CPUser
& U
, unsigned UserOffset
)
1059 MachineInstr
*UserMI
= U
.MI
;
1060 MachineInstr
*CPEMI
= U
.CPEMI
;
1062 // Check to see if the CPE is already in-range.
1063 if (isCPEntryInRange(UserMI
, UserOffset
, CPEMI
, U
.getMaxDisp(), U
.NegOk
,
1065 LLVM_DEBUG(dbgs() << "In range\n");
1069 // No. Look for previously created clones of the CPE that are in range.
1070 unsigned CPI
= CPEMI
->getOperand(1).getIndex();
1071 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
1072 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
1073 // We already tried this one
1074 if (CPEs
[i
].CPEMI
== CPEMI
)
1076 // Removing CPEs can leave empty entries, skip
1077 if (CPEs
[i
].CPEMI
== nullptr)
1079 if (isCPEntryInRange(UserMI
, UserOffset
, CPEs
[i
].CPEMI
, U
.getMaxDisp(),
1081 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI
<< " with CPE#"
1082 << CPEs
[i
].CPI
<< "\n");
1083 // Point the CPUser node to the replacement
1084 U
.CPEMI
= CPEs
[i
].CPEMI
;
1085 // Change the CPI in the instruction operand to refer to the clone.
1086 for (unsigned j
= 0, e
= UserMI
->getNumOperands(); j
!= e
; ++j
)
1087 if (UserMI
->getOperand(j
).isCPI()) {
1088 UserMI
->getOperand(j
).setIndex(CPEs
[i
].CPI
);
1091 // Adjust the refcount of the clone...
1093 // ...and the original. If we didn't remove the old entry, none of the
1094 // addresses changed, so we don't need another pass.
1095 return decrementCPEReferenceCount(CPI
, CPEMI
) ? 2 : 1;
1101 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1102 /// This version checks if the longer form of the instruction can be used to
1103 /// to satisfy things.
1104 /// if not, see if an in-range clone of the CPE is in range, and if so,
1105 /// change the data structures so the user references the clone. Returns:
1106 /// 0 = no existing entry found
1107 /// 1 = entry found, and there were no code insertions or deletions
1108 /// 2 = entry found, and there were code insertions or deletions
1109 int MipsConstantIslands::findLongFormInRangeCPEntry
1110 (CPUser
& U
, unsigned UserOffset
)
1112 MachineInstr
*UserMI
= U
.MI
;
1113 MachineInstr
*CPEMI
= U
.CPEMI
;
1115 // Check to see if the CPE is already in-range.
1116 if (isCPEntryInRange(UserMI
, UserOffset
, CPEMI
,
1117 U
.getLongFormMaxDisp(), U
.NegOk
,
1119 LLVM_DEBUG(dbgs() << "In range\n");
1120 UserMI
->setDesc(TII
->get(U
.getLongFormOpcode()));
1121 U
.setMaxDisp(U
.getLongFormMaxDisp());
1122 return 2; // instruction is longer length now
1125 // No. Look for previously created clones of the CPE that are in range.
1126 unsigned CPI
= CPEMI
->getOperand(1).getIndex();
1127 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
1128 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
1129 // We already tried this one
1130 if (CPEs
[i
].CPEMI
== CPEMI
)
1132 // Removing CPEs can leave empty entries, skip
1133 if (CPEs
[i
].CPEMI
== nullptr)
1135 if (isCPEntryInRange(UserMI
, UserOffset
, CPEs
[i
].CPEMI
,
1136 U
.getLongFormMaxDisp(), U
.NegOk
)) {
1137 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI
<< " with CPE#"
1138 << CPEs
[i
].CPI
<< "\n");
1139 // Point the CPUser node to the replacement
1140 U
.CPEMI
= CPEs
[i
].CPEMI
;
1141 // Change the CPI in the instruction operand to refer to the clone.
1142 for (unsigned j
= 0, e
= UserMI
->getNumOperands(); j
!= e
; ++j
)
1143 if (UserMI
->getOperand(j
).isCPI()) {
1144 UserMI
->getOperand(j
).setIndex(CPEs
[i
].CPI
);
1147 // Adjust the refcount of the clone...
1149 // ...and the original. If we didn't remove the old entry, none of the
1150 // addresses changed, so we don't need another pass.
1151 return decrementCPEReferenceCount(CPI
, CPEMI
) ? 2 : 1;
1157 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1158 /// the specific unconditional branch instruction.
1159 static inline unsigned getUnconditionalBrDisp(int Opc
) {
1162 return ((1<<10)-1)*2;
1164 return ((1<<16)-1)*2;
1168 return ((1<<16)-1)*2;
1171 /// findAvailableWater - Look for an existing entry in the WaterList in which
1172 /// we can place the CPE referenced from U so it's within range of U's MI.
1173 /// Returns true if found, false if not. If it returns true, WaterIter
1174 /// is set to the WaterList entry.
1175 /// To ensure that this pass
1176 /// terminates, the CPE location for a particular CPUser is only allowed to
1177 /// move to a lower address, so search backward from the end of the list and
1178 /// prefer the first water that is in range.
1179 bool MipsConstantIslands::findAvailableWater(CPUser
&U
, unsigned UserOffset
,
1180 water_iterator
&WaterIter
) {
1181 if (WaterList
.empty())
1184 unsigned BestGrowth
= ~0u;
1185 for (water_iterator IP
= std::prev(WaterList
.end()), B
= WaterList
.begin();;
1187 MachineBasicBlock
* WaterBB
= *IP
;
1188 // Check if water is in range and is either at a lower address than the
1189 // current "high water mark" or a new water block that was created since
1190 // the previous iteration by inserting an unconditional branch. In the
1191 // latter case, we want to allow resetting the high water mark back to
1192 // this new water since we haven't seen it before. Inserting branches
1193 // should be relatively uncommon and when it does happen, we want to be
1194 // sure to take advantage of it for all the CPEs near that block, so that
1195 // we don't insert more branches than necessary.
1197 if (isWaterInRange(UserOffset
, WaterBB
, U
, Growth
) &&
1198 (WaterBB
->getNumber() < U
.HighWaterMark
->getNumber() ||
1199 NewWaterList
.count(WaterBB
)) && Growth
< BestGrowth
) {
1200 // This is the least amount of required padding seen so far.
1201 BestGrowth
= Growth
;
1203 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB
)
1204 << " Growth=" << Growth
<< '\n');
1206 // Keep looking unless it is perfect.
1207 if (BestGrowth
== 0)
1213 return BestGrowth
!= ~0u;
1216 /// createNewWater - No existing WaterList entry will work for
1217 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1218 /// block is used if in range, and the conditional branch munged so control
1219 /// flow is correct. Otherwise the block is split to create a hole with an
1220 /// unconditional branch around it. In either case NewMBB is set to a
1221 /// block following which the new island can be inserted (the WaterList
1222 /// is not adjusted).
1223 void MipsConstantIslands::createNewWater(unsigned CPUserIndex
,
1224 unsigned UserOffset
,
1225 MachineBasicBlock
*&NewMBB
) {
1226 CPUser
&U
= CPUsers
[CPUserIndex
];
1227 MachineInstr
*UserMI
= U
.MI
;
1228 MachineInstr
*CPEMI
= U
.CPEMI
;
1229 unsigned CPELogAlign
= getCPELogAlign(*CPEMI
);
1230 MachineBasicBlock
*UserMBB
= UserMI
->getParent();
1231 const BasicBlockInfo
&UserBBI
= BBInfo
[UserMBB
->getNumber()];
1233 // If the block does not end in an unconditional branch already, and if the
1234 // end of the block is within range, make new water there.
1235 if (BBHasFallthrough(UserMBB
)) {
1236 // Size of branch to insert.
1238 // Compute the offset where the CPE will begin.
1239 unsigned CPEOffset
= UserBBI
.postOffset(CPELogAlign
) + Delta
;
1241 if (isOffsetInRange(UserOffset
, CPEOffset
, U
)) {
1242 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB
)
1243 << format(", expected CPE offset %#x\n", CPEOffset
));
1244 NewMBB
= &*++UserMBB
->getIterator();
1245 // Add an unconditional branch from UserMBB to fallthrough block. Record
1246 // it for branch lengthening; this new branch will not get out of range,
1247 // but if the preceding conditional branch is out of range, the targets
1248 // will be exchanged, and the altered branch may be out of range, so the
1249 // machinery has to know about it.
1250 int UncondBr
= Mips::Bimm16
;
1251 BuildMI(UserMBB
, DebugLoc(), TII
->get(UncondBr
)).addMBB(NewMBB
);
1252 unsigned MaxDisp
= getUnconditionalBrDisp(UncondBr
);
1253 ImmBranches
.push_back(ImmBranch(&UserMBB
->back(),
1254 MaxDisp
, false, UncondBr
));
1255 BBInfo
[UserMBB
->getNumber()].Size
+= Delta
;
1256 adjustBBOffsetsAfter(UserMBB
);
1261 // What a big block. Find a place within the block to split it.
1263 // Try to split the block so it's fully aligned. Compute the latest split
1264 // point where we can add a 4-byte branch instruction, and then align to
1265 // LogAlign which is the largest possible alignment in the function.
1266 unsigned LogAlign
= MF
->getAlignment();
1267 assert(LogAlign
>= CPELogAlign
&& "Over-aligned constant pool entry");
1268 unsigned BaseInsertOffset
= UserOffset
+ U
.getMaxDisp();
1269 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1272 // The 4 in the following is for the unconditional branch we'll be inserting
1273 // Alignment of the island is handled
1274 // inside isOffsetInRange.
1275 BaseInsertOffset
-= 4;
1277 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset
)
1278 << " la=" << LogAlign
<< '\n');
1280 // This could point off the end of the block if we've already got constant
1281 // pool entries following this block; only the last one is in the water list.
1282 // Back past any possible branches (allow for a conditional and a maximally
1283 // long unconditional).
1284 if (BaseInsertOffset
+ 8 >= UserBBI
.postOffset()) {
1285 BaseInsertOffset
= UserBBI
.postOffset() - 8;
1286 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset
));
1288 unsigned EndInsertOffset
= BaseInsertOffset
+ 4 +
1289 CPEMI
->getOperand(2).getImm();
1290 MachineBasicBlock::iterator MI
= UserMI
;
1292 unsigned CPUIndex
= CPUserIndex
+1;
1293 unsigned NumCPUsers
= CPUsers
.size();
1294 //MachineInstr *LastIT = 0;
1295 for (unsigned Offset
= UserOffset
+ TII
->getInstSizeInBytes(*UserMI
);
1296 Offset
< BaseInsertOffset
;
1297 Offset
+= TII
->getInstSizeInBytes(*MI
), MI
= std::next(MI
)) {
1298 assert(MI
!= UserMBB
->end() && "Fell off end of block");
1299 if (CPUIndex
< NumCPUsers
&& CPUsers
[CPUIndex
].MI
== MI
) {
1300 CPUser
&U
= CPUsers
[CPUIndex
];
1301 if (!isOffsetInRange(Offset
, EndInsertOffset
, U
)) {
1302 // Shift intertion point by one unit of alignment so it is within reach.
1303 BaseInsertOffset
-= 1u << LogAlign
;
1304 EndInsertOffset
-= 1u << LogAlign
;
1306 // This is overly conservative, as we don't account for CPEMIs being
1307 // reused within the block, but it doesn't matter much. Also assume CPEs
1308 // are added in order with alignment padding. We may eventually be able
1309 // to pack the aligned CPEs better.
1310 EndInsertOffset
+= U
.CPEMI
->getOperand(2).getImm();
1315 NewMBB
= splitBlockBeforeInstr(*--MI
);
1318 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1319 /// is out-of-range. If so, pick up the constant pool value and move it some
1320 /// place in-range. Return true if we changed any addresses (thus must run
1321 /// another pass of branch lengthening), false otherwise.
1322 bool MipsConstantIslands::handleConstantPoolUser(unsigned CPUserIndex
) {
1323 CPUser
&U
= CPUsers
[CPUserIndex
];
1324 MachineInstr
*UserMI
= U
.MI
;
1325 MachineInstr
*CPEMI
= U
.CPEMI
;
1326 unsigned CPI
= CPEMI
->getOperand(1).getIndex();
1327 unsigned Size
= CPEMI
->getOperand(2).getImm();
1328 // Compute this only once, it's expensive.
1329 unsigned UserOffset
= getUserOffset(U
);
1331 // See if the current entry is within range, or there is a clone of it
1333 int result
= findInRangeCPEntry(U
, UserOffset
);
1334 if (result
==1) return false;
1335 else if (result
==2) return true;
1337 // Look for water where we can place this CPE.
1338 MachineBasicBlock
*NewIsland
= MF
->CreateMachineBasicBlock();
1339 MachineBasicBlock
*NewMBB
;
1341 if (findAvailableWater(U
, UserOffset
, IP
)) {
1342 LLVM_DEBUG(dbgs() << "Found water in range\n");
1343 MachineBasicBlock
*WaterBB
= *IP
;
1345 // If the original WaterList entry was "new water" on this iteration,
1346 // propagate that to the new island. This is just keeping NewWaterList
1347 // updated to match the WaterList, which will be updated below.
1348 if (NewWaterList
.erase(WaterBB
))
1349 NewWaterList
.insert(NewIsland
);
1351 // The new CPE goes before the following block (NewMBB).
1352 NewMBB
= &*++WaterBB
->getIterator();
1355 // we first see if a longer form of the instrucion could have reached
1356 // the constant. in that case we won't bother to split
1357 if (!NoLoadRelaxation
) {
1358 result
= findLongFormInRangeCPEntry(U
, UserOffset
);
1359 if (result
!= 0) return true;
1361 LLVM_DEBUG(dbgs() << "No water found\n");
1362 createNewWater(CPUserIndex
, UserOffset
, NewMBB
);
1364 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1365 // called while handling branches so that the water will be seen on the
1366 // next iteration for constant pools, but in this context, we don't want
1367 // it. Check for this so it will be removed from the WaterList.
1368 // Also remove any entry from NewWaterList.
1369 MachineBasicBlock
*WaterBB
= &*--NewMBB
->getIterator();
1370 IP
= llvm::find(WaterList
, WaterBB
);
1371 if (IP
!= WaterList
.end())
1372 NewWaterList
.erase(WaterBB
);
1374 // We are adding new water. Update NewWaterList.
1375 NewWaterList
.insert(NewIsland
);
1378 // Remove the original WaterList entry; we want subsequent insertions in
1379 // this vicinity to go after the one we're about to insert. This
1380 // considerably reduces the number of times we have to move the same CPE
1381 // more than once and is also important to ensure the algorithm terminates.
1382 if (IP
!= WaterList
.end())
1383 WaterList
.erase(IP
);
1385 // Okay, we know we can put an island before NewMBB now, do it!
1386 MF
->insert(NewMBB
->getIterator(), NewIsland
);
1388 // Update internal data structures to account for the newly inserted MBB.
1389 updateForInsertedWaterBlock(NewIsland
);
1391 // Decrement the old entry, and remove it if refcount becomes 0.
1392 decrementCPEReferenceCount(CPI
, CPEMI
);
1394 // No existing clone of this CPE is within range.
1395 // We will be generating a new clone. Get a UID for it.
1396 unsigned ID
= createPICLabelUId();
1398 // Now that we have an island to add the CPE to, clone the original CPE and
1399 // add it to the island.
1400 U
.HighWaterMark
= NewIsland
;
1401 U
.CPEMI
= BuildMI(NewIsland
, DebugLoc(), TII
->get(Mips::CONSTPOOL_ENTRY
))
1402 .addImm(ID
).addConstantPoolIndex(CPI
).addImm(Size
);
1403 CPEntries
[CPI
].push_back(CPEntry(U
.CPEMI
, ID
, 1));
1406 // Mark the basic block as aligned as required by the const-pool entry.
1407 NewIsland
->setAlignment(getCPELogAlign(*U
.CPEMI
));
1409 // Increase the size of the island block to account for the new entry.
1410 BBInfo
[NewIsland
->getNumber()].Size
+= Size
;
1411 adjustBBOffsetsAfter(&*--NewIsland
->getIterator());
1413 // Finally, change the CPI in the instruction operand to be ID.
1414 for (unsigned i
= 0, e
= UserMI
->getNumOperands(); i
!= e
; ++i
)
1415 if (UserMI
->getOperand(i
).isCPI()) {
1416 UserMI
->getOperand(i
).setIndex(ID
);
1421 dbgs() << " Moved CPE to #" << ID
<< " CPI=" << CPI
1422 << format(" offset=%#x\n", BBInfo
[NewIsland
->getNumber()].Offset
));
1427 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1428 /// sizes and offsets of impacted basic blocks.
1429 void MipsConstantIslands::removeDeadCPEMI(MachineInstr
*CPEMI
) {
1430 MachineBasicBlock
*CPEBB
= CPEMI
->getParent();
1431 unsigned Size
= CPEMI
->getOperand(2).getImm();
1432 CPEMI
->eraseFromParent();
1433 BBInfo
[CPEBB
->getNumber()].Size
-= Size
;
1434 // All succeeding offsets have the current size value added in, fix this.
1435 if (CPEBB
->empty()) {
1436 BBInfo
[CPEBB
->getNumber()].Size
= 0;
1438 // This block no longer needs to be aligned.
1439 CPEBB
->setAlignment(0);
1441 // Entries are sorted by descending alignment, so realign from the front.
1442 CPEBB
->setAlignment(getCPELogAlign(*CPEBB
->begin()));
1444 adjustBBOffsetsAfter(CPEBB
);
1445 // An island has only one predecessor BB and one successor BB. Check if
1446 // this BB's predecessor jumps directly to this BB's successor. This
1447 // shouldn't happen currently.
1448 assert(!BBIsJumpedOver(CPEBB
) && "How did this happen?");
1449 // FIXME: remove the empty blocks after all the work is done?
1452 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1454 bool MipsConstantIslands::removeUnusedCPEntries() {
1455 unsigned MadeChange
= false;
1456 for (unsigned i
= 0, e
= CPEntries
.size(); i
!= e
; ++i
) {
1457 std::vector
<CPEntry
> &CPEs
= CPEntries
[i
];
1458 for (unsigned j
= 0, ee
= CPEs
.size(); j
!= ee
; ++j
) {
1459 if (CPEs
[j
].RefCount
== 0 && CPEs
[j
].CPEMI
) {
1460 removeDeadCPEMI(CPEs
[j
].CPEMI
);
1461 CPEs
[j
].CPEMI
= nullptr;
1469 /// isBBInRange - Returns true if the distance between specific MI and
1470 /// specific BB can fit in MI's displacement field.
1471 bool MipsConstantIslands::isBBInRange
1472 (MachineInstr
*MI
,MachineBasicBlock
*DestBB
, unsigned MaxDisp
) {
1474 unsigned BrOffset
= getOffsetOf(MI
) + PCAdj
;
1475 unsigned DestOffset
= BBInfo
[DestBB
->getNumber()].Offset
;
1477 LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB
)
1478 << " from " << printMBBReference(*MI
->getParent())
1479 << " max delta=" << MaxDisp
<< " from " << getOffsetOf(MI
)
1480 << " to " << DestOffset
<< " offset "
1481 << int(DestOffset
- BrOffset
) << "\t" << *MI
);
1483 if (BrOffset
<= DestOffset
) {
1484 // Branch before the Dest.
1485 if (DestOffset
-BrOffset
<= MaxDisp
)
1488 if (BrOffset
-DestOffset
<= MaxDisp
)
1494 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1495 /// away to fit in its displacement field.
1496 bool MipsConstantIslands::fixupImmediateBr(ImmBranch
&Br
) {
1497 MachineInstr
*MI
= Br
.MI
;
1498 unsigned TargetOperand
= branchTargetOperand(MI
);
1499 MachineBasicBlock
*DestBB
= MI
->getOperand(TargetOperand
).getMBB();
1501 // Check to see if the DestBB is already in-range.
1502 if (isBBInRange(MI
, DestBB
, Br
.MaxDisp
))
1506 return fixupUnconditionalBr(Br
);
1507 return fixupConditionalBr(Br
);
1510 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1511 /// too far away to fit in its displacement field. If the LR register has been
1512 /// spilled in the epilogue, then we can use BL to implement a far jump.
1513 /// Otherwise, add an intermediate branch instruction to a branch.
1515 MipsConstantIslands::fixupUnconditionalBr(ImmBranch
&Br
) {
1516 MachineInstr
*MI
= Br
.MI
;
1517 MachineBasicBlock
*MBB
= MI
->getParent();
1518 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1519 // Use BL to implement far jump.
1520 unsigned BimmX16MaxDisp
= ((1 << 16)-1) * 2;
1521 if (isBBInRange(MI
, DestBB
, BimmX16MaxDisp
)) {
1522 Br
.MaxDisp
= BimmX16MaxDisp
;
1523 MI
->setDesc(TII
->get(Mips::BimmX16
));
1526 // need to give the math a more careful look here
1527 // this is really a segment address and not
1528 // a PC relative address. FIXME. But I think that
1529 // just reducing the bits by 1 as I've done is correct.
1530 // The basic block we are branching too much be longword aligned.
1531 // we know that RA is saved because we always save it right now.
1532 // this requirement will be relaxed later but we also have an alternate
1533 // way to implement this that I will implement that does not need jal.
1534 // We should have a way to back out this alignment restriction if we "can" later.
1535 // but it is not harmful.
1537 DestBB
->setAlignment(2);
1538 Br
.MaxDisp
= ((1<<24)-1) * 2;
1539 MI
->setDesc(TII
->get(Mips::JalB16
));
1541 BBInfo
[MBB
->getNumber()].Size
+= 2;
1542 adjustBBOffsetsAfter(MBB
);
1546 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI
);
1551 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1552 /// far away to fit in its displacement field. It is converted to an inverse
1553 /// conditional branch + an unconditional branch to the destination.
1555 MipsConstantIslands::fixupConditionalBr(ImmBranch
&Br
) {
1556 MachineInstr
*MI
= Br
.MI
;
1557 unsigned TargetOperand
= branchTargetOperand(MI
);
1558 MachineBasicBlock
*DestBB
= MI
->getOperand(TargetOperand
).getMBB();
1559 unsigned Opcode
= MI
->getOpcode();
1560 unsigned LongFormOpcode
= longformBranchOpcode(Opcode
);
1561 unsigned LongFormMaxOff
= branchMaxOffsets(LongFormOpcode
);
1563 // Check to see if the DestBB is already in-range.
1564 if (isBBInRange(MI
, DestBB
, LongFormMaxOff
)) {
1565 Br
.MaxDisp
= LongFormMaxOff
;
1566 MI
->setDesc(TII
->get(LongFormOpcode
));
1570 // Add an unconditional branch to the destination and invert the branch
1571 // condition to jump over it:
1578 // If the branch is at the end of its MBB and that has a fall-through block,
1579 // direct the updated conditional branch to the fall-through block. Otherwise,
1580 // split the MBB before the next instruction.
1581 MachineBasicBlock
*MBB
= MI
->getParent();
1582 MachineInstr
*BMI
= &MBB
->back();
1583 bool NeedSplit
= (BMI
!= MI
) || !BBHasFallthrough(MBB
);
1584 unsigned OppositeBranchOpcode
= TII
->getOppositeBranchOpc(Opcode
);
1588 if (std::next(MachineBasicBlock::iterator(MI
)) == std::prev(MBB
->end()) &&
1589 BMI
->isUnconditionalBranch()) {
1590 // Last MI in the BB is an unconditional branch. Can we simply invert the
1591 // condition and swap destinations:
1597 unsigned BMITargetOperand
= branchTargetOperand(BMI
);
1598 MachineBasicBlock
*NewDest
=
1599 BMI
->getOperand(BMITargetOperand
).getMBB();
1600 if (isBBInRange(MI
, NewDest
, Br
.MaxDisp
)) {
1602 dbgs() << " Invert Bcc condition and swap its destination with "
1604 MI
->setDesc(TII
->get(OppositeBranchOpcode
));
1605 BMI
->getOperand(BMITargetOperand
).setMBB(DestBB
);
1606 MI
->getOperand(TargetOperand
).setMBB(NewDest
);
1613 splitBlockBeforeInstr(*MI
);
1614 // No need for the branch to the next block. We're adding an unconditional
1615 // branch to the destination.
1616 int delta
= TII
->getInstSizeInBytes(MBB
->back());
1617 BBInfo
[MBB
->getNumber()].Size
-= delta
;
1618 MBB
->back().eraseFromParent();
1619 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1621 MachineBasicBlock
*NextBB
= &*++MBB
->getIterator();
1623 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB
)
1624 << " also invert condition and change dest. to "
1625 << printMBBReference(*NextBB
) << "\n");
1627 // Insert a new conditional branch and a new unconditional branch.
1628 // Also update the ImmBranch as well as adding a new entry for the new branch.
1629 if (MI
->getNumExplicitOperands() == 2) {
1630 BuildMI(MBB
, DebugLoc(), TII
->get(OppositeBranchOpcode
))
1631 .addReg(MI
->getOperand(0).getReg())
1634 BuildMI(MBB
, DebugLoc(), TII
->get(OppositeBranchOpcode
))
1637 Br
.MI
= &MBB
->back();
1638 BBInfo
[MBB
->getNumber()].Size
+= TII
->getInstSizeInBytes(MBB
->back());
1639 BuildMI(MBB
, DebugLoc(), TII
->get(Br
.UncondBr
)).addMBB(DestBB
);
1640 BBInfo
[MBB
->getNumber()].Size
+= TII
->getInstSizeInBytes(MBB
->back());
1641 unsigned MaxDisp
= getUnconditionalBrDisp(Br
.UncondBr
);
1642 ImmBranches
.push_back(ImmBranch(&MBB
->back(), MaxDisp
, false, Br
.UncondBr
));
1644 // Remove the old conditional branch. It may or may not still be in MBB.
1645 BBInfo
[MI
->getParent()->getNumber()].Size
-= TII
->getInstSizeInBytes(*MI
);
1646 MI
->eraseFromParent();
1647 adjustBBOffsetsAfter(MBB
);
1651 void MipsConstantIslands::prescanForConstants() {
1654 for (MachineFunction::iterator B
=
1655 MF
->begin(), E
= MF
->end(); B
!= E
; ++B
) {
1656 for (MachineBasicBlock::instr_iterator I
=
1657 B
->instr_begin(), EB
= B
->instr_end(); I
!= EB
; ++I
) {
1658 switch(I
->getDesc().getOpcode()) {
1659 case Mips::LwConstant32
: {
1660 PrescannedForConstants
= true;
1661 LLVM_DEBUG(dbgs() << "constant island constant " << *I
<< "\n");
1662 J
= I
->getNumOperands();
1663 LLVM_DEBUG(dbgs() << "num operands " << J
<< "\n");
1664 MachineOperand
& Literal
= I
->getOperand(1);
1665 if (Literal
.isImm()) {
1666 int64_t V
= Literal
.getImm();
1667 LLVM_DEBUG(dbgs() << "literal " << V
<< "\n");
1669 Type::getInt32Ty(MF
->getFunction().getContext());
1670 const Constant
*C
= ConstantInt::get(Int32Ty
, V
);
1671 unsigned index
= MCP
->getConstantPoolIndex(C
, 4);
1672 I
->getOperand(2).ChangeToImmediate(index
);
1673 LLVM_DEBUG(dbgs() << "constant island constant " << *I
<< "\n");
1674 I
->setDesc(TII
->get(Mips::LwRxPcTcp16
));
1675 I
->RemoveOperand(1);
1676 I
->RemoveOperand(1);
1677 I
->addOperand(MachineOperand::CreateCPI(index
, 0));
1678 I
->addOperand(MachineOperand::CreateImm(4));
1689 /// Returns a pass that converts branches to long branches.
1690 FunctionPass
*llvm::createMipsConstantIslandPass() {
1691 return new MipsConstantIslands();