1 //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains a pass that splits the constant pool up into 'islands'
10 // which are scattered through-out the function. This is required due to the
11 // limited pc-relative displacements that ARM has.
13 //===----------------------------------------------------------------------===//
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBasicBlockInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMBaseInfo.h"
21 #include "Thumb2InstrInfo.h"
22 #include "Utils/ARMBaseInfo.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineOperand.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/Config/llvm-config.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/MC/MCInstrDesc.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
58 #define DEBUG_TYPE "arm-cp-islands"
60 #define ARM_CP_ISLANDS_OPT_NAME \
61 "ARM constant island placement and branch shortening pass"
62 STATISTIC(NumCPEs
, "Number of constpool entries");
63 STATISTIC(NumSplit
, "Number of uncond branches inserted");
64 STATISTIC(NumCBrFixed
, "Number of cond branches fixed");
65 STATISTIC(NumUBrFixed
, "Number of uncond branches fixed");
66 STATISTIC(NumTBs
, "Number of table branches generated");
67 STATISTIC(NumT2CPShrunk
, "Number of Thumb2 constantpool instructions shrunk");
68 STATISTIC(NumT2BrShrunk
, "Number of Thumb2 immediate branches shrunk");
69 STATISTIC(NumCBZ
, "Number of CBZ / CBNZ formed");
70 STATISTIC(NumJTMoved
, "Number of jump table destination blocks moved");
71 STATISTIC(NumJTInserted
, "Number of jump table intermediate blocks inserted");
74 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden
, cl::init(true),
75 cl::desc("Adjust basic block layout to better use TB[BH]"));
77 static cl::opt
<unsigned>
78 CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden
, cl::init(30),
79 cl::desc("The max number of iteration for converge"));
81 static cl::opt
<bool> SynthesizeThumb1TBB(
82 "arm-synthesize-thumb-1-tbb", cl::Hidden
, cl::init(true),
83 cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an "
84 "equivalent to the TBB/TBH instructions"));
88 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM
89 /// requires constant pool entries to be scattered among the instructions
90 /// inside a function. To do this, it completely ignores the normal LLVM
91 /// constant pool; instead, it places constants wherever it feels like with
92 /// special instructions.
94 /// The terminology used in this pass includes:
95 /// Islands - Clumps of constants placed in the function.
96 /// Water - Potential places where an island could be formed.
97 /// CPE - A constant pool entry that has been placed somewhere, which
98 /// tracks a list of users.
99 class ARMConstantIslands
: public MachineFunctionPass
{
100 std::unique_ptr
<ARMBasicBlockUtils
> BBUtils
= nullptr;
102 /// WaterList - A sorted list of basic blocks where islands could be placed
103 /// (i.e. blocks that don't fall through to the following block, due
104 /// to a return, unreachable, or unconditional branch).
105 std::vector
<MachineBasicBlock
*> WaterList
;
107 /// NewWaterList - The subset of WaterList that was created since the
108 /// previous iteration by inserting unconditional branches.
109 SmallSet
<MachineBasicBlock
*, 4> NewWaterList
;
111 using water_iterator
= std::vector
<MachineBasicBlock
*>::iterator
;
113 /// CPUser - One user of a constant pool, keeping the machine instruction
114 /// pointer, the constant pool being referenced, and the max displacement
115 /// allowed from the instruction to the CP. The HighWaterMark records the
116 /// highest basic block where a new CPEntry can be placed. To ensure this
117 /// pass terminates, the CP entries are initially placed at the end of the
118 /// function and then move monotonically to lower addresses. The
119 /// exception to this rule is when the current CP entry for a particular
120 /// CPUser is out of range, but there is another CP entry for the same
121 /// constant value in range. We want to use the existing in-range CP
122 /// entry, but if it later moves out of range, the search for new water
123 /// should resume where it left off. The HighWaterMark is used to record
128 MachineBasicBlock
*HighWaterMark
;
132 bool KnownAlignment
= false;
134 CPUser(MachineInstr
*mi
, MachineInstr
*cpemi
, unsigned maxdisp
,
135 bool neg
, bool soimm
)
136 : MI(mi
), CPEMI(cpemi
), MaxDisp(maxdisp
), NegOk(neg
), IsSoImm(soimm
) {
137 HighWaterMark
= CPEMI
->getParent();
140 /// getMaxDisp - Returns the maximum displacement supported by MI.
141 /// Correct for unknown alignment.
142 /// Conservatively subtract 2 bytes to handle weird alignment effects.
143 unsigned getMaxDisp() const {
144 return (KnownAlignment
? MaxDisp
: MaxDisp
- 2) - 2;
148 /// CPUsers - Keep track of all of the machine instructions that use various
149 /// constant pools and their max displacement.
150 std::vector
<CPUser
> CPUsers
;
152 /// CPEntry - One per constant pool entry, keeping the machine instruction
153 /// pointer, the constpool index, and the number of CPUser's which
154 /// reference this entry.
160 CPEntry(MachineInstr
*cpemi
, unsigned cpi
, unsigned rc
= 0)
161 : CPEMI(cpemi
), CPI(cpi
), RefCount(rc
) {}
164 /// CPEntries - Keep track of all of the constant pool entry machine
165 /// instructions. For each original constpool index (i.e. those that existed
166 /// upon entry to this pass), it keeps a vector of entries. Original
167 /// elements are cloned as we go along; the clones are put in the vector of
168 /// the original element, but have distinct CPIs.
170 /// The first half of CPEntries contains generic constants, the second half
171 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up
172 /// which vector it will be in here.
173 std::vector
<std::vector
<CPEntry
>> CPEntries
;
175 /// Maps a JT index to the offset in CPEntries containing copies of that
176 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity.
177 DenseMap
<int, int> JumpTableEntryIndices
;
179 /// Maps a JT index to the LEA that actually uses the index to calculate its
181 DenseMap
<int, int> JumpTableUserIndices
;
183 /// ImmBranch - One per immediate branch, keeping the machine instruction
184 /// pointer, conditional or unconditional, the max displacement,
185 /// and (if isCond is true) the corresponding unconditional branch
189 unsigned MaxDisp
: 31;
193 ImmBranch(MachineInstr
*mi
, unsigned maxdisp
, bool cond
, unsigned ubr
)
194 : MI(mi
), MaxDisp(maxdisp
), isCond(cond
), UncondBr(ubr
) {}
197 /// ImmBranches - Keep track of all the immediate branch instructions.
198 std::vector
<ImmBranch
> ImmBranches
;
200 /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
201 SmallVector
<MachineInstr
*, 4> PushPopMIs
;
203 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
204 SmallVector
<MachineInstr
*, 4> T2JumpTables
;
206 /// HasFarJump - True if any far jump instruction has been emitted during
207 /// the branch fix up pass.
211 MachineConstantPool
*MCP
;
212 const ARMBaseInstrInfo
*TII
;
213 const ARMSubtarget
*STI
;
214 ARMFunctionInfo
*AFI
;
218 bool isPositionIndependentOrROPI
;
223 ARMConstantIslands() : MachineFunctionPass(ID
) {}
225 bool runOnMachineFunction(MachineFunction
&MF
) override
;
227 MachineFunctionProperties
getRequiredProperties() const override
{
228 return MachineFunctionProperties().set(
229 MachineFunctionProperties::Property::NoVRegs
);
232 StringRef
getPassName() const override
{
233 return ARM_CP_ISLANDS_OPT_NAME
;
237 void doInitialConstPlacement(std::vector
<MachineInstr
*> &CPEMIs
);
238 void doInitialJumpTablePlacement(std::vector
<MachineInstr
*> &CPEMIs
);
239 bool BBHasFallthrough(MachineBasicBlock
*MBB
);
240 CPEntry
*findConstPoolEntry(unsigned CPI
, const MachineInstr
*CPEMI
);
241 unsigned getCPELogAlign(const MachineInstr
*CPEMI
);
242 void scanFunctionJumpTables();
243 void initializeFunctionInfo(const std::vector
<MachineInstr
*> &CPEMIs
);
244 MachineBasicBlock
*splitBlockBeforeInstr(MachineInstr
*MI
);
245 void updateForInsertedWaterBlock(MachineBasicBlock
*NewBB
);
246 bool decrementCPEReferenceCount(unsigned CPI
, MachineInstr
* CPEMI
);
247 unsigned getCombinedIndex(const MachineInstr
*CPEMI
);
248 int findInRangeCPEntry(CPUser
& U
, unsigned UserOffset
);
249 bool findAvailableWater(CPUser
&U
, unsigned UserOffset
,
250 water_iterator
&WaterIter
, bool CloserWater
);
251 void createNewWater(unsigned CPUserIndex
, unsigned UserOffset
,
252 MachineBasicBlock
*&NewMBB
);
253 bool handleConstantPoolUser(unsigned CPUserIndex
, bool CloserWater
);
254 void removeDeadCPEMI(MachineInstr
*CPEMI
);
255 bool removeUnusedCPEntries();
256 bool isCPEntryInRange(MachineInstr
*MI
, unsigned UserOffset
,
257 MachineInstr
*CPEMI
, unsigned Disp
, bool NegOk
,
258 bool DoDump
= false);
259 bool isWaterInRange(unsigned UserOffset
, MachineBasicBlock
*Water
,
260 CPUser
&U
, unsigned &Growth
);
261 bool fixupImmediateBr(ImmBranch
&Br
);
262 bool fixupConditionalBr(ImmBranch
&Br
);
263 bool fixupUnconditionalBr(ImmBranch
&Br
);
264 bool undoLRSpillRestore();
265 bool optimizeThumb2Instructions();
266 bool optimizeThumb2Branches();
267 bool reorderThumb2JumpTables();
268 bool preserveBaseRegister(MachineInstr
*JumpMI
, MachineInstr
*LEAMI
,
269 unsigned &DeadSize
, bool &CanDeleteLEA
,
271 bool optimizeThumb2JumpTables();
272 MachineBasicBlock
*adjustJTTargetBlockForward(MachineBasicBlock
*BB
,
273 MachineBasicBlock
*JTBB
);
275 unsigned getUserOffset(CPUser
&) const;
279 bool isOffsetInRange(unsigned UserOffset
, unsigned TrialOffset
,
280 unsigned Disp
, bool NegativeOK
, bool IsSoImm
= false);
281 bool isOffsetInRange(unsigned UserOffset
, unsigned TrialOffset
,
283 return isOffsetInRange(UserOffset
, TrialOffset
,
284 U
.getMaxDisp(), U
.NegOk
, U
.IsSoImm
);
288 } // end anonymous namespace
290 char ARMConstantIslands::ID
= 0;
292 /// verify - check BBOffsets, BBSizes, alignment of islands
293 void ARMConstantIslands::verify() {
295 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
296 assert(std::is_sorted(MF
->begin(), MF
->end(),
297 [&BBInfo
](const MachineBasicBlock
&LHS
,
298 const MachineBasicBlock
&RHS
) {
299 return BBInfo
[LHS
.getNumber()].postOffset() <
300 BBInfo
[RHS
.getNumber()].postOffset();
302 LLVM_DEBUG(dbgs() << "Verifying " << CPUsers
.size() << " CP users.\n");
303 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
) {
304 CPUser
&U
= CPUsers
[i
];
305 unsigned UserOffset
= getUserOffset(U
);
306 // Verify offset using the real max displacement without the safety
308 if (isCPEntryInRange(U
.MI
, UserOffset
, U
.CPEMI
, U
.getMaxDisp()+2, U
.NegOk
,
309 /* DoDump = */ true)) {
310 LLVM_DEBUG(dbgs() << "OK\n");
313 LLVM_DEBUG(dbgs() << "Out of range.\n");
315 LLVM_DEBUG(MF
->dump());
316 llvm_unreachable("Constant pool entry out of range!");
321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
322 /// print block size and offset information - debugging
323 LLVM_DUMP_METHOD
void ARMConstantIslands::dumpBBs() {
324 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
326 for (unsigned J
= 0, E
= BBInfo
.size(); J
!=E
; ++J
) {
327 const BasicBlockInfo
&BBI
= BBInfo
[J
];
328 dbgs() << format("%08x %bb.%u\t", BBI
.Offset
, J
)
329 << " kb=" << unsigned(BBI
.KnownBits
)
330 << " ua=" << unsigned(BBI
.Unalign
)
331 << " pa=" << unsigned(BBI
.PostAlign
)
332 << format(" size=%#x\n", BBInfo
[J
].Size
);
338 bool ARMConstantIslands::runOnMachineFunction(MachineFunction
&mf
) {
340 MCP
= mf
.getConstantPool();
341 BBUtils
= std::unique_ptr
<ARMBasicBlockUtils
>(new ARMBasicBlockUtils(mf
));
343 LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
344 << MCP
->getConstants().size() << " CP entries, aligned to "
345 << MCP
->getConstantPoolAlignment() << " bytes *****\n");
347 STI
= &static_cast<const ARMSubtarget
&>(MF
->getSubtarget());
348 TII
= STI
->getInstrInfo();
349 isPositionIndependentOrROPI
=
350 STI
->getTargetLowering()->isPositionIndependent() || STI
->isROPI();
351 AFI
= MF
->getInfo
<ARMFunctionInfo
>();
353 isThumb
= AFI
->isThumbFunction();
354 isThumb1
= AFI
->isThumb1OnlyFunction();
355 isThumb2
= AFI
->isThumb2Function();
358 bool GenerateTBB
= isThumb2
|| (isThumb1
&& SynthesizeThumb1TBB
);
360 // This pass invalidates liveness information when it splits basic blocks.
361 MF
->getRegInfo().invalidateLiveness();
363 // Renumber all of the machine basic blocks in the function, guaranteeing that
364 // the numbers agree with the position of the block in the function.
365 MF
->RenumberBlocks();
367 // Try to reorder and otherwise adjust the block layout to make good use
368 // of the TB[BH] instructions.
369 bool MadeChange
= false;
370 if (GenerateTBB
&& AdjustJumpTableBlocks
) {
371 scanFunctionJumpTables();
372 MadeChange
|= reorderThumb2JumpTables();
373 // Data is out of date, so clear it. It'll be re-computed later.
374 T2JumpTables
.clear();
375 // Blocks may have shifted around. Keep the numbering up to date.
376 MF
->RenumberBlocks();
379 // Perform the initial placement of the constant pool entries. To start with,
380 // we put them all at the end of the function.
381 std::vector
<MachineInstr
*> CPEMIs
;
383 doInitialConstPlacement(CPEMIs
);
385 if (MF
->getJumpTableInfo())
386 doInitialJumpTablePlacement(CPEMIs
);
388 /// The next UID to take is the first unused one.
389 AFI
->initPICLabelUId(CPEMIs
.size());
391 // Do the initial scan of the function, building up information about the
392 // sizes of each block, the location of all the water, and finding all of the
393 // constant pool users.
394 initializeFunctionInfo(CPEMIs
);
396 LLVM_DEBUG(dumpBBs());
398 // Functions with jump tables need an alignment of 4 because they use the ADR
399 // instruction, which aligns the PC to 4 bytes before adding an offset.
400 if (!T2JumpTables
.empty())
401 MF
->ensureAlignment(2);
403 /// Remove dead constant pool entries.
404 MadeChange
|= removeUnusedCPEntries();
406 // Iteratively place constant pool entries and fix up branches until there
408 unsigned NoCPIters
= 0, NoBRIters
= 0;
410 LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters
<< '\n');
411 bool CPChange
= false;
412 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
)
413 // For most inputs, it converges in no more than 5 iterations.
414 // If it doesn't end in 10, the input may have huge BB or many CPEs.
415 // In this case, we will try different heuristics.
416 CPChange
|= handleConstantPoolUser(i
, NoCPIters
>= CPMaxIteration
/ 2);
417 if (CPChange
&& ++NoCPIters
> CPMaxIteration
)
418 report_fatal_error("Constant Island pass failed to converge!");
419 LLVM_DEBUG(dumpBBs());
421 // Clear NewWaterList now. If we split a block for branches, it should
422 // appear as "new water" for the next iteration of constant pool placement.
423 NewWaterList
.clear();
425 LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters
<< '\n');
426 bool BRChange
= false;
427 for (unsigned i
= 0, e
= ImmBranches
.size(); i
!= e
; ++i
)
428 BRChange
|= fixupImmediateBr(ImmBranches
[i
]);
429 if (BRChange
&& ++NoBRIters
> 30)
430 report_fatal_error("Branch Fix Up pass failed to converge!");
431 LLVM_DEBUG(dumpBBs());
433 if (!CPChange
&& !BRChange
)
438 // Shrink 32-bit Thumb2 load and store instructions.
439 if (isThumb2
&& !STI
->prefers32BitThumb())
440 MadeChange
|= optimizeThumb2Instructions();
442 // Shrink 32-bit branch instructions.
443 if (isThumb
&& STI
->hasV8MBaselineOps())
444 MadeChange
|= optimizeThumb2Branches();
446 // Optimize jump tables using TBB / TBH.
447 if (GenerateTBB
&& !STI
->genExecuteOnly())
448 MadeChange
|= optimizeThumb2JumpTables();
450 // After a while, this might be made debug-only, but it is not expensive.
453 // If LR has been forced spilled and no far jump (i.e. BL) has been issued,
454 // undo the spill / restore of LR if possible.
455 if (isThumb
&& !HasFarJump
&& AFI
->isLRSpilledForFarJump())
456 MadeChange
|= undoLRSpillRestore();
458 // Save the mapping between original and cloned constpool entries.
459 for (unsigned i
= 0, e
= CPEntries
.size(); i
!= e
; ++i
) {
460 for (unsigned j
= 0, je
= CPEntries
[i
].size(); j
!= je
; ++j
) {
461 const CPEntry
& CPE
= CPEntries
[i
][j
];
462 if (CPE
.CPEMI
&& CPE
.CPEMI
->getOperand(1).isCPI())
463 AFI
->recordCPEClone(i
, CPE
.CPI
);
467 LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
473 JumpTableEntryIndices
.clear();
474 JumpTableUserIndices
.clear();
477 T2JumpTables
.clear();
482 /// Perform the initial placement of the regular constant pool entries.
483 /// To start with, we put them all at the end of the function.
485 ARMConstantIslands::doInitialConstPlacement(std::vector
<MachineInstr
*> &CPEMIs
) {
486 // Create the basic block to hold the CPE's.
487 MachineBasicBlock
*BB
= MF
->CreateMachineBasicBlock();
490 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
491 unsigned MaxAlign
= Log2_32(MCP
->getConstantPoolAlignment());
493 // Mark the basic block as required by the const-pool.
494 BB
->setAlignment(MaxAlign
);
496 // The function needs to be as aligned as the basic blocks. The linker may
497 // move functions around based on their alignment.
498 MF
->ensureAlignment(BB
->getAlignment());
500 // Order the entries in BB by descending alignment. That ensures correct
501 // alignment of all entries as long as BB is sufficiently aligned. Keep
502 // track of the insertion point for each alignment. We are going to bucket
503 // sort the entries as they are created.
504 SmallVector
<MachineBasicBlock::iterator
, 8> InsPoint(MaxAlign
+ 1, BB
->end());
506 // Add all of the constants from the constant pool to the end block, use an
507 // identity mapping of CPI's to CPE's.
508 const std::vector
<MachineConstantPoolEntry
> &CPs
= MCP
->getConstants();
510 const DataLayout
&TD
= MF
->getDataLayout();
511 for (unsigned i
= 0, e
= CPs
.size(); i
!= e
; ++i
) {
512 unsigned Size
= TD
.getTypeAllocSize(CPs
[i
].getType());
513 unsigned Align
= CPs
[i
].getAlignment();
514 assert(isPowerOf2_32(Align
) && "Invalid alignment");
515 // Verify that all constant pool entries are a multiple of their alignment.
516 // If not, we would have to pad them out so that instructions stay aligned.
517 assert((Size
% Align
) == 0 && "CP Entry not multiple of 4 bytes!");
519 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment.
520 unsigned LogAlign
= Log2_32(Align
);
521 MachineBasicBlock::iterator InsAt
= InsPoint
[LogAlign
];
522 MachineInstr
*CPEMI
=
523 BuildMI(*BB
, InsAt
, DebugLoc(), TII
->get(ARM::CONSTPOOL_ENTRY
))
524 .addImm(i
).addConstantPoolIndex(i
).addImm(Size
);
525 CPEMIs
.push_back(CPEMI
);
527 // Ensure that future entries with higher alignment get inserted before
528 // CPEMI. This is bucket sort with iterators.
529 for (unsigned a
= LogAlign
+ 1; a
<= MaxAlign
; ++a
)
530 if (InsPoint
[a
] == InsAt
)
533 // Add a new CPEntry, but no corresponding CPUser yet.
534 CPEntries
.emplace_back(1, CPEntry(CPEMI
, i
));
536 LLVM_DEBUG(dbgs() << "Moved CPI#" << i
<< " to end of function, size = "
537 << Size
<< ", align = " << Align
<< '\n');
539 LLVM_DEBUG(BB
->dump());
542 /// Do initial placement of the jump tables. Because Thumb2's TBB and TBH
543 /// instructions can be made more efficient if the jump table immediately
544 /// follows the instruction, it's best to place them immediately next to their
545 /// jumps to begin with. In almost all cases they'll never be moved from that
547 void ARMConstantIslands::doInitialJumpTablePlacement(
548 std::vector
<MachineInstr
*> &CPEMIs
) {
549 unsigned i
= CPEntries
.size();
550 auto MJTI
= MF
->getJumpTableInfo();
551 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
553 MachineBasicBlock
*LastCorrectlyNumberedBB
= nullptr;
554 for (MachineBasicBlock
&MBB
: *MF
) {
555 auto MI
= MBB
.getLastNonDebugInstr();
560 switch (MI
->getOpcode()) {
566 case ARM::BR_JTm_i12
:
568 JTOpcode
= ARM::JUMPTABLE_ADDRS
;
571 JTOpcode
= ARM::JUMPTABLE_INSTS
;
575 JTOpcode
= ARM::JUMPTABLE_TBB
;
579 JTOpcode
= ARM::JUMPTABLE_TBH
;
583 unsigned NumOps
= MI
->getDesc().getNumOperands();
584 MachineOperand JTOp
=
585 MI
->getOperand(NumOps
- (MI
->isPredicable() ? 2 : 1));
586 unsigned JTI
= JTOp
.getIndex();
587 unsigned Size
= JT
[JTI
].MBBs
.size() * sizeof(uint32_t);
588 MachineBasicBlock
*JumpTableBB
= MF
->CreateMachineBasicBlock();
589 MF
->insert(std::next(MachineFunction::iterator(MBB
)), JumpTableBB
);
590 MachineInstr
*CPEMI
= BuildMI(*JumpTableBB
, JumpTableBB
->begin(),
591 DebugLoc(), TII
->get(JTOpcode
))
593 .addJumpTableIndex(JTI
)
595 CPEMIs
.push_back(CPEMI
);
596 CPEntries
.emplace_back(1, CPEntry(CPEMI
, JTI
));
597 JumpTableEntryIndices
.insert(std::make_pair(JTI
, CPEntries
.size() - 1));
598 if (!LastCorrectlyNumberedBB
)
599 LastCorrectlyNumberedBB
= &MBB
;
602 // If we did anything then we need to renumber the subsequent blocks.
603 if (LastCorrectlyNumberedBB
)
604 MF
->RenumberBlocks(LastCorrectlyNumberedBB
);
607 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
608 /// into the block immediately after it.
609 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock
*MBB
) {
610 // Get the next machine basic block in the function.
611 MachineFunction::iterator MBBI
= MBB
->getIterator();
612 // Can't fall off end of function.
613 if (std::next(MBBI
) == MBB
->getParent()->end())
616 MachineBasicBlock
*NextBB
= &*std::next(MBBI
);
617 if (!MBB
->isSuccessor(NextBB
))
620 // Try to analyze the end of the block. A potential fallthrough may already
621 // have an unconditional branch for whatever reason.
622 MachineBasicBlock
*TBB
, *FBB
;
623 SmallVector
<MachineOperand
, 4> Cond
;
624 bool TooDifficult
= TII
->analyzeBranch(*MBB
, TBB
, FBB
, Cond
);
625 return TooDifficult
|| FBB
== nullptr;
628 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI,
629 /// look up the corresponding CPEntry.
630 ARMConstantIslands::CPEntry
*
631 ARMConstantIslands::findConstPoolEntry(unsigned CPI
,
632 const MachineInstr
*CPEMI
) {
633 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
634 // Number of entries per constpool index should be small, just do a
636 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
637 if (CPEs
[i
].CPEMI
== CPEMI
)
643 /// getCPELogAlign - Returns the required alignment of the constant pool entry
644 /// represented by CPEMI. Alignment is measured in log2(bytes) units.
645 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr
*CPEMI
) {
646 switch (CPEMI
->getOpcode()) {
647 case ARM::CONSTPOOL_ENTRY
:
649 case ARM::JUMPTABLE_TBB
:
650 return isThumb1
? 2 : 0;
651 case ARM::JUMPTABLE_TBH
:
652 return isThumb1
? 2 : 1;
653 case ARM::JUMPTABLE_INSTS
:
655 case ARM::JUMPTABLE_ADDRS
:
658 llvm_unreachable("unknown constpool entry kind");
661 unsigned CPI
= getCombinedIndex(CPEMI
);
662 assert(CPI
< MCP
->getConstants().size() && "Invalid constant pool index.");
663 unsigned Align
= MCP
->getConstants()[CPI
].getAlignment();
664 assert(isPowerOf2_32(Align
) && "Invalid CPE alignment");
665 return Log2_32(Align
);
668 /// scanFunctionJumpTables - Do a scan of the function, building up
669 /// information about the sizes of each block and the locations of all
671 void ARMConstantIslands::scanFunctionJumpTables() {
672 for (MachineBasicBlock
&MBB
: *MF
) {
673 for (MachineInstr
&I
: MBB
)
675 (I
.getOpcode() == ARM::t2BR_JT
|| I
.getOpcode() == ARM::tBR_JTr
))
676 T2JumpTables
.push_back(&I
);
680 /// initializeFunctionInfo - Do the initial scan of the function, building up
681 /// information about the sizes of each block, the location of all the water,
682 /// and finding all of the constant pool users.
683 void ARMConstantIslands::
684 initializeFunctionInfo(const std::vector
<MachineInstr
*> &CPEMIs
) {
686 BBUtils
->computeAllBlockSizes();
687 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
688 // The known bits of the entry block offset are determined by the function
690 BBInfo
.front().KnownBits
= MF
->getAlignment();
692 // Compute block offsets and known bits.
693 BBUtils
->adjustBBOffsetsAfter(&MF
->front());
695 // Now go back through the instructions and build up our data structures.
696 for (MachineBasicBlock
&MBB
: *MF
) {
697 // If this block doesn't fall through into the next MBB, then this is
698 // 'water' that a constant pool island could be placed.
699 if (!BBHasFallthrough(&MBB
))
700 WaterList
.push_back(&MBB
);
702 for (MachineInstr
&I
: MBB
) {
703 if (I
.isDebugInstr())
706 unsigned Opc
= I
.getOpcode();
714 continue; // Ignore other JT branches
717 T2JumpTables
.push_back(&I
);
718 continue; // Does not get an entry in ImmBranches
749 // Record this immediate branch.
750 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
751 ImmBranches
.push_back(ImmBranch(&I
, MaxOffs
, isCond
, UOpc
));
754 if (Opc
== ARM::tPUSH
|| Opc
== ARM::tPOP_RET
)
755 PushPopMIs
.push_back(&I
);
757 if (Opc
== ARM::CONSTPOOL_ENTRY
|| Opc
== ARM::JUMPTABLE_ADDRS
||
758 Opc
== ARM::JUMPTABLE_INSTS
|| Opc
== ARM::JUMPTABLE_TBB
||
759 Opc
== ARM::JUMPTABLE_TBH
)
762 // Scan the instructions for constant pool operands.
763 for (unsigned op
= 0, e
= I
.getNumOperands(); op
!= e
; ++op
)
764 if (I
.getOperand(op
).isCPI() || I
.getOperand(op
).isJTI()) {
765 // We found one. The addressing mode tells us the max displacement
766 // from the PC that this instruction permits.
768 // Basic size info comes from the TSFlags field.
772 bool IsSoImm
= false;
776 llvm_unreachable("Unknown addressing mode for CP reference!");
778 // Taking the address of a CP entry.
780 case ARM::LEApcrelJT
:
781 // This takes a SoImm, which is 8 bit immediate rotated. We'll
782 // pretend the maximum offset is 255 * 4. Since each instruction
783 // 4 byte wide, this is always correct. We'll check for other
784 // displacements that fits in a SoImm as well.
790 case ARM::t2LEApcrel
:
791 case ARM::t2LEApcrelJT
:
796 case ARM::tLEApcrelJT
:
807 Bits
= 12; // +-offset_12
813 Scale
= 4; // +(offset_8*4)
819 Scale
= 4; // +-(offset_8*4)
824 Scale
= 2; // +-(offset_8*2)
830 Scale
= 2; // +(offset_5*2)
834 // Remember that this is a user of a CP entry.
835 unsigned CPI
= I
.getOperand(op
).getIndex();
836 if (I
.getOperand(op
).isJTI()) {
837 JumpTableUserIndices
.insert(std::make_pair(CPI
, CPUsers
.size()));
838 CPI
= JumpTableEntryIndices
[CPI
];
841 MachineInstr
*CPEMI
= CPEMIs
[CPI
];
842 unsigned MaxOffs
= ((1 << Bits
)-1) * Scale
;
843 CPUsers
.push_back(CPUser(&I
, CPEMI
, MaxOffs
, NegOk
, IsSoImm
));
845 // Increment corresponding CPEntry reference count.
846 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
847 assert(CPE
&& "Cannot find a corresponding CPEntry!");
850 // Instructions can only use one CP entry, don't bother scanning the
851 // rest of the operands.
858 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
860 static bool CompareMBBNumbers(const MachineBasicBlock
*LHS
,
861 const MachineBasicBlock
*RHS
) {
862 return LHS
->getNumber() < RHS
->getNumber();
865 /// updateForInsertedWaterBlock - When a block is newly inserted into the
866 /// machine function, it upsets all of the block numbers. Renumber the blocks
867 /// and update the arrays that parallel this numbering.
868 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock
*NewBB
) {
869 // Renumber the MBB's to keep them consecutive.
870 NewBB
->getParent()->RenumberBlocks(NewBB
);
872 // Insert an entry into BBInfo to align it properly with the (newly
873 // renumbered) block numbers.
874 BBUtils
->insert(NewBB
->getNumber(), BasicBlockInfo());
876 // Next, update WaterList. Specifically, we need to add NewMBB as having
877 // available water after it.
878 water_iterator IP
= llvm::lower_bound(WaterList
, NewBB
, CompareMBBNumbers
);
879 WaterList
.insert(IP
, NewBB
);
882 /// Split the basic block containing MI into two blocks, which are joined by
883 /// an unconditional branch. Update data structures and renumber blocks to
884 /// account for this change and returns the newly created block.
885 MachineBasicBlock
*ARMConstantIslands::splitBlockBeforeInstr(MachineInstr
*MI
) {
886 MachineBasicBlock
*OrigBB
= MI
->getParent();
888 // Create a new MBB for the code after the OrigBB.
889 MachineBasicBlock
*NewBB
=
890 MF
->CreateMachineBasicBlock(OrigBB
->getBasicBlock());
891 MachineFunction::iterator MBBI
= ++OrigBB
->getIterator();
892 MF
->insert(MBBI
, NewBB
);
894 // Splice the instructions starting with MI over to NewBB.
895 NewBB
->splice(NewBB
->end(), OrigBB
, MI
, OrigBB
->end());
897 // Add an unconditional branch from OrigBB to NewBB.
898 // Note the new unconditional branch is not being recorded.
899 // There doesn't seem to be meaningful DebugInfo available; this doesn't
900 // correspond to anything in the source.
901 unsigned Opc
= isThumb
? (isThumb2
? ARM::t2B
: ARM::tB
) : ARM::B
;
903 BuildMI(OrigBB
, DebugLoc(), TII
->get(Opc
)).addMBB(NewBB
);
905 BuildMI(OrigBB
, DebugLoc(), TII
->get(Opc
))
907 .add(predOps(ARMCC::AL
));
910 // Update the CFG. All succs of OrigBB are now succs of NewBB.
911 NewBB
->transferSuccessors(OrigBB
);
913 // OrigBB branches to NewBB.
914 OrigBB
->addSuccessor(NewBB
);
916 // Update internal data structures to account for the newly inserted MBB.
917 // This is almost the same as updateForInsertedWaterBlock, except that
918 // the Water goes after OrigBB, not NewBB.
919 MF
->RenumberBlocks(NewBB
);
921 // Insert an entry into BBInfo to align it properly with the (newly
922 // renumbered) block numbers.
923 BBUtils
->insert(NewBB
->getNumber(), BasicBlockInfo());
925 // Next, update WaterList. Specifically, we need to add OrigMBB as having
926 // available water after it (but not if it's already there, which happens
927 // when splitting before a conditional branch that is followed by an
928 // unconditional branch - in that case we want to insert NewBB).
929 water_iterator IP
= llvm::lower_bound(WaterList
, OrigBB
, CompareMBBNumbers
);
930 MachineBasicBlock
* WaterBB
= *IP
;
931 if (WaterBB
== OrigBB
)
932 WaterList
.insert(std::next(IP
), NewBB
);
934 WaterList
.insert(IP
, OrigBB
);
935 NewWaterList
.insert(OrigBB
);
937 // Figure out how large the OrigBB is. As the first half of the original
938 // block, it cannot contain a tablejump. The size includes
939 // the new jump we added. (It should be possible to do this without
940 // recounting everything, but it's very confusing, and this is rarely
942 BBUtils
->computeBlockSize(OrigBB
);
944 // Figure out how large the NewMBB is. As the second half of the original
945 // block, it may contain a tablejump.
946 BBUtils
->computeBlockSize(NewBB
);
948 // All BBOffsets following these blocks must be modified.
949 BBUtils
->adjustBBOffsetsAfter(OrigBB
);
954 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
955 /// displacement computation. Update U.KnownAlignment to match its current
956 /// basic block location.
957 unsigned ARMConstantIslands::getUserOffset(CPUser
&U
) const {
958 unsigned UserOffset
= BBUtils
->getOffsetOf(U
.MI
);
960 SmallVectorImpl
<BasicBlockInfo
> &BBInfo
= BBUtils
->getBBInfo();
961 const BasicBlockInfo
&BBI
= BBInfo
[U
.MI
->getParent()->getNumber()];
962 unsigned KnownBits
= BBI
.internalKnownBits();
964 // The value read from PC is offset from the actual instruction address.
965 UserOffset
+= (isThumb
? 4 : 8);
967 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
968 // Make sure U.getMaxDisp() returns a constrained range.
969 U
.KnownAlignment
= (KnownBits
>= 2);
971 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
972 // purposes of the displacement computation; compensate for that here.
973 // For unknown alignments, getMaxDisp() constrains the range instead.
974 if (isThumb
&& U
.KnownAlignment
)
980 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
981 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
982 /// constant pool entry).
983 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
984 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
985 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
986 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset
,
987 unsigned TrialOffset
, unsigned MaxDisp
,
988 bool NegativeOK
, bool IsSoImm
) {
989 if (UserOffset
<= TrialOffset
) {
990 // User before the Trial.
991 if (TrialOffset
- UserOffset
<= MaxDisp
)
993 // FIXME: Make use full range of soimm values.
994 } else if (NegativeOK
) {
995 if (UserOffset
- TrialOffset
<= MaxDisp
)
997 // FIXME: Make use full range of soimm values.
1002 /// isWaterInRange - Returns true if a CPE placed after the specified
1003 /// Water (a basic block) will be in range for the specific MI.
1005 /// Compute how much the function will grow by inserting a CPE after Water.
1006 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset
,
1007 MachineBasicBlock
* Water
, CPUser
&U
,
1009 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1010 unsigned CPELogAlign
= getCPELogAlign(U
.CPEMI
);
1011 unsigned CPEOffset
= BBInfo
[Water
->getNumber()].postOffset(CPELogAlign
);
1012 unsigned NextBlockOffset
, NextBlockAlignment
;
1013 MachineFunction::const_iterator NextBlock
= Water
->getIterator();
1014 if (++NextBlock
== MF
->end()) {
1015 NextBlockOffset
= BBInfo
[Water
->getNumber()].postOffset();
1016 NextBlockAlignment
= 0;
1018 NextBlockOffset
= BBInfo
[NextBlock
->getNumber()].Offset
;
1019 NextBlockAlignment
= NextBlock
->getAlignment();
1021 unsigned Size
= U
.CPEMI
->getOperand(2).getImm();
1022 unsigned CPEEnd
= CPEOffset
+ Size
;
1024 // The CPE may be able to hide in the alignment padding before the next
1025 // block. It may also cause more padding to be required if it is more aligned
1026 // that the next block.
1027 if (CPEEnd
> NextBlockOffset
) {
1028 Growth
= CPEEnd
- NextBlockOffset
;
1029 // Compute the padding that would go at the end of the CPE to align the next
1031 Growth
+= OffsetToAlignment(CPEEnd
, 1ULL << NextBlockAlignment
);
1033 // If the CPE is to be inserted before the instruction, that will raise
1034 // the offset of the instruction. Also account for unknown alignment padding
1035 // in blocks between CPE and the user.
1036 if (CPEOffset
< UserOffset
)
1037 UserOffset
+= Growth
+ UnknownPadding(MF
->getAlignment(), CPELogAlign
);
1039 // CPE fits in existing padding.
1042 return isOffsetInRange(UserOffset
, CPEOffset
, U
);
1045 /// isCPEntryInRange - Returns true if the distance between specific MI and
1046 /// specific ConstPool entry instruction can fit in MI's displacement field.
1047 bool ARMConstantIslands::isCPEntryInRange(MachineInstr
*MI
, unsigned UserOffset
,
1048 MachineInstr
*CPEMI
, unsigned MaxDisp
,
1049 bool NegOk
, bool DoDump
) {
1050 unsigned CPEOffset
= BBUtils
->getOffsetOf(CPEMI
);
1054 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1055 unsigned Block
= MI
->getParent()->getNumber();
1056 const BasicBlockInfo
&BBI
= BBInfo
[Block
];
1057 dbgs() << "User of CPE#" << CPEMI
->getOperand(0).getImm()
1058 << " max delta=" << MaxDisp
1059 << format(" insn address=%#x", UserOffset
) << " in "
1060 << printMBBReference(*MI
->getParent()) << ": "
1061 << format("%#x-%x\t", BBI
.Offset
, BBI
.postOffset()) << *MI
1062 << format("CPE address=%#x offset=%+d: ", CPEOffset
,
1063 int(CPEOffset
- UserOffset
));
1067 return isOffsetInRange(UserOffset
, CPEOffset
, MaxDisp
, NegOk
);
1071 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1072 /// unconditionally branches to its only successor.
1073 static bool BBIsJumpedOver(MachineBasicBlock
*MBB
) {
1074 if (MBB
->pred_size() != 1 || MBB
->succ_size() != 1)
1077 MachineBasicBlock
*Succ
= *MBB
->succ_begin();
1078 MachineBasicBlock
*Pred
= *MBB
->pred_begin();
1079 MachineInstr
*PredMI
= &Pred
->back();
1080 if (PredMI
->getOpcode() == ARM::B
|| PredMI
->getOpcode() == ARM::tB
1081 || PredMI
->getOpcode() == ARM::t2B
)
1082 return PredMI
->getOperand(0).getMBB() == Succ
;
1087 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1088 /// and instruction CPEMI, and decrement its refcount. If the refcount
1089 /// becomes 0 remove the entry and instruction. Returns true if we removed
1090 /// the entry, false if we didn't.
1091 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI
,
1092 MachineInstr
*CPEMI
) {
1093 // Find the old entry. Eliminate it if it is no longer used.
1094 CPEntry
*CPE
= findConstPoolEntry(CPI
, CPEMI
);
1095 assert(CPE
&& "Unexpected!");
1096 if (--CPE
->RefCount
== 0) {
1097 removeDeadCPEMI(CPEMI
);
1098 CPE
->CPEMI
= nullptr;
1105 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr
*CPEMI
) {
1106 if (CPEMI
->getOperand(1).isCPI())
1107 return CPEMI
->getOperand(1).getIndex();
1109 return JumpTableEntryIndices
[CPEMI
->getOperand(1).getIndex()];
1112 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1113 /// if not, see if an in-range clone of the CPE is in range, and if so,
1114 /// change the data structures so the user references the clone. Returns:
1115 /// 0 = no existing entry found
1116 /// 1 = entry found, and there were no code insertions or deletions
1117 /// 2 = entry found, and there were code insertions or deletions
1118 int ARMConstantIslands::findInRangeCPEntry(CPUser
& U
, unsigned UserOffset
) {
1119 MachineInstr
*UserMI
= U
.MI
;
1120 MachineInstr
*CPEMI
= U
.CPEMI
;
1122 // Check to see if the CPE is already in-range.
1123 if (isCPEntryInRange(UserMI
, UserOffset
, CPEMI
, U
.getMaxDisp(), U
.NegOk
,
1125 LLVM_DEBUG(dbgs() << "In range\n");
1129 // No. Look for previously created clones of the CPE that are in range.
1130 unsigned CPI
= getCombinedIndex(CPEMI
);
1131 std::vector
<CPEntry
> &CPEs
= CPEntries
[CPI
];
1132 for (unsigned i
= 0, e
= CPEs
.size(); i
!= e
; ++i
) {
1133 // We already tried this one
1134 if (CPEs
[i
].CPEMI
== CPEMI
)
1136 // Removing CPEs can leave empty entries, skip
1137 if (CPEs
[i
].CPEMI
== nullptr)
1139 if (isCPEntryInRange(UserMI
, UserOffset
, CPEs
[i
].CPEMI
, U
.getMaxDisp(),
1141 LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI
<< " with CPE#"
1142 << CPEs
[i
].CPI
<< "\n");
1143 // Point the CPUser node to the replacement
1144 U
.CPEMI
= CPEs
[i
].CPEMI
;
1145 // Change the CPI in the instruction operand to refer to the clone.
1146 for (unsigned j
= 0, e
= UserMI
->getNumOperands(); j
!= e
; ++j
)
1147 if (UserMI
->getOperand(j
).isCPI()) {
1148 UserMI
->getOperand(j
).setIndex(CPEs
[i
].CPI
);
1151 // Adjust the refcount of the clone...
1153 // ...and the original. If we didn't remove the old entry, none of the
1154 // addresses changed, so we don't need another pass.
1155 return decrementCPEReferenceCount(CPI
, CPEMI
) ? 2 : 1;
1161 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1162 /// the specific unconditional branch instruction.
1163 static inline unsigned getUnconditionalBrDisp(int Opc
) {
1166 return ((1<<10)-1)*2;
1168 return ((1<<23)-1)*2;
1173 return ((1<<23)-1)*4;
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. For Thumb, prefer water that will not
1180 /// introduce padding to water that will. 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 ARMConstantIslands::findAvailableWater(CPUser
&U
, unsigned UserOffset
,
1185 water_iterator
&WaterIter
,
1187 if (WaterList
.empty())
1190 unsigned BestGrowth
= ~0u;
1191 // The nearest water without splitting the UserBB is right after it.
1192 // If the distance is still large (we have a big BB), then we need to split it
1193 // if we don't converge after certain iterations. This helps the following
1194 // situation to converge:
1199 // When a CP access is out of range, BB0 may be used as water. However,
1200 // inserting islands between BB0 and BB1 makes other accesses out of range.
1201 MachineBasicBlock
*UserBB
= U
.MI
->getParent();
1202 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1203 unsigned MinNoSplitDisp
=
1204 BBInfo
[UserBB
->getNumber()].postOffset(getCPELogAlign(U
.CPEMI
));
1205 if (CloserWater
&& MinNoSplitDisp
> U
.getMaxDisp() / 2)
1207 for (water_iterator IP
= std::prev(WaterList
.end()), B
= WaterList
.begin();;
1209 MachineBasicBlock
* WaterBB
= *IP
;
1210 // Check if water is in range and is either at a lower address than the
1211 // current "high water mark" or a new water block that was created since
1212 // the previous iteration by inserting an unconditional branch. In the
1213 // latter case, we want to allow resetting the high water mark back to
1214 // this new water since we haven't seen it before. Inserting branches
1215 // should be relatively uncommon and when it does happen, we want to be
1216 // sure to take advantage of it for all the CPEs near that block, so that
1217 // we don't insert more branches than necessary.
1218 // When CloserWater is true, we try to find the lowest address after (or
1219 // equal to) user MI's BB no matter of padding growth.
1221 if (isWaterInRange(UserOffset
, WaterBB
, U
, Growth
) &&
1222 (WaterBB
->getNumber() < U
.HighWaterMark
->getNumber() ||
1223 NewWaterList
.count(WaterBB
) || WaterBB
== U
.MI
->getParent()) &&
1224 Growth
< BestGrowth
) {
1225 // This is the least amount of required padding seen so far.
1226 BestGrowth
= Growth
;
1228 LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB
)
1229 << " Growth=" << Growth
<< '\n');
1231 if (CloserWater
&& WaterBB
== U
.MI
->getParent())
1233 // Keep looking unless it is perfect and we're not looking for the lowest
1234 // possible address.
1235 if (!CloserWater
&& BestGrowth
== 0)
1241 return BestGrowth
!= ~0u;
1244 /// createNewWater - No existing WaterList entry will work for
1245 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1246 /// block is used if in range, and the conditional branch munged so control
1247 /// flow is correct. Otherwise the block is split to create a hole with an
1248 /// unconditional branch around it. In either case NewMBB is set to a
1249 /// block following which the new island can be inserted (the WaterList
1250 /// is not adjusted).
1251 void ARMConstantIslands::createNewWater(unsigned CPUserIndex
,
1252 unsigned UserOffset
,
1253 MachineBasicBlock
*&NewMBB
) {
1254 CPUser
&U
= CPUsers
[CPUserIndex
];
1255 MachineInstr
*UserMI
= U
.MI
;
1256 MachineInstr
*CPEMI
= U
.CPEMI
;
1257 unsigned CPELogAlign
= getCPELogAlign(CPEMI
);
1258 MachineBasicBlock
*UserMBB
= UserMI
->getParent();
1259 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1260 const BasicBlockInfo
&UserBBI
= BBInfo
[UserMBB
->getNumber()];
1262 // If the block does not end in an unconditional branch already, and if the
1263 // end of the block is within range, make new water there. (The addition
1264 // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1265 // Thumb2, 2 on Thumb1.
1266 if (BBHasFallthrough(UserMBB
)) {
1267 // Size of branch to insert.
1268 unsigned Delta
= isThumb1
? 2 : 4;
1269 // Compute the offset where the CPE will begin.
1270 unsigned CPEOffset
= UserBBI
.postOffset(CPELogAlign
) + Delta
;
1272 if (isOffsetInRange(UserOffset
, CPEOffset
, U
)) {
1273 LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB
)
1274 << format(", expected CPE offset %#x\n", CPEOffset
));
1275 NewMBB
= &*++UserMBB
->getIterator();
1276 // Add an unconditional branch from UserMBB to fallthrough block. Record
1277 // it for branch lengthening; this new branch will not get out of range,
1278 // but if the preceding conditional branch is out of range, the targets
1279 // will be exchanged, and the altered branch may be out of range, so the
1280 // machinery has to know about it.
1281 int UncondBr
= isThumb
? ((isThumb2
) ? ARM::t2B
: ARM::tB
) : ARM::B
;
1283 BuildMI(UserMBB
, DebugLoc(), TII
->get(UncondBr
)).addMBB(NewMBB
);
1285 BuildMI(UserMBB
, DebugLoc(), TII
->get(UncondBr
))
1287 .add(predOps(ARMCC::AL
));
1288 unsigned MaxDisp
= getUnconditionalBrDisp(UncondBr
);
1289 ImmBranches
.push_back(ImmBranch(&UserMBB
->back(),
1290 MaxDisp
, false, UncondBr
));
1291 BBUtils
->computeBlockSize(UserMBB
);
1292 BBUtils
->adjustBBOffsetsAfter(UserMBB
);
1297 // What a big block. Find a place within the block to split it. This is a
1298 // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1299 // entries are 4 bytes: if instruction I references island CPE, and
1300 // instruction I+1 references CPE', it will not work well to put CPE as far
1301 // forward as possible, since then CPE' cannot immediately follow it (that
1302 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1303 // need to create a new island. So, we make a first guess, then walk through
1304 // the instructions between the one currently being looked at and the
1305 // possible insertion point, and make sure any other instructions that
1306 // reference CPEs will be able to use the same island area; if not, we back
1307 // up the insertion point.
1309 // Try to split the block so it's fully aligned. Compute the latest split
1310 // point where we can add a 4-byte branch instruction, and then align to
1311 // LogAlign which is the largest possible alignment in the function.
1312 unsigned LogAlign
= MF
->getAlignment();
1313 assert(LogAlign
>= CPELogAlign
&& "Over-aligned constant pool entry");
1314 unsigned KnownBits
= UserBBI
.internalKnownBits();
1315 unsigned UPad
= UnknownPadding(LogAlign
, KnownBits
);
1316 unsigned BaseInsertOffset
= UserOffset
+ U
.getMaxDisp() - UPad
;
1317 LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1320 // The 4 in the following is for the unconditional branch we'll be inserting
1321 // (allows for long branch on Thumb1). Alignment of the island is handled
1322 // inside isOffsetInRange.
1323 BaseInsertOffset
-= 4;
1325 LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset
)
1326 << " la=" << LogAlign
<< " kb=" << KnownBits
1327 << " up=" << UPad
<< '\n');
1329 // This could point off the end of the block if we've already got constant
1330 // pool entries following this block; only the last one is in the water list.
1331 // Back past any possible branches (allow for a conditional and a maximally
1332 // long unconditional).
1333 if (BaseInsertOffset
+ 8 >= UserBBI
.postOffset()) {
1334 // Ensure BaseInsertOffset is larger than the offset of the instruction
1335 // following UserMI so that the loop which searches for the split point
1336 // iterates at least once.
1338 std::max(UserBBI
.postOffset() - UPad
- 8,
1339 UserOffset
+ TII
->getInstSizeInBytes(*UserMI
) + 1);
1340 // If the CP is referenced(ie, UserOffset) is in first four instructions
1341 // after IT, this recalculated BaseInsertOffset could be in the middle of
1342 // an IT block. If it is, change the BaseInsertOffset to just after the
1343 // IT block. This still make the CP Entry is in range becuase of the
1344 // following reasons.
1345 // 1. The initial BaseseInsertOffset calculated is (UserOffset +
1346 // U.getMaxDisp() - UPad).
1347 // 2. An IT block is only at most 4 instructions plus the "it" itself (18
1349 // 3. All the relevant instructions support much larger Maximum
1351 MachineBasicBlock::iterator I
= UserMI
;
1353 for (unsigned Offset
= UserOffset
+ TII
->getInstSizeInBytes(*UserMI
),
1355 I
->getOpcode() != ARM::t2IT
&&
1356 getITInstrPredicate(*I
, PredReg
) != ARMCC::AL
;
1357 Offset
+= TII
->getInstSizeInBytes(*I
), I
= std::next(I
)) {
1359 std::max(BaseInsertOffset
, Offset
+ TII
->getInstSizeInBytes(*I
) + 1);
1360 assert(I
!= UserMBB
->end() && "Fell off end of block");
1362 LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset
));
1364 unsigned EndInsertOffset
= BaseInsertOffset
+ 4 + UPad
+
1365 CPEMI
->getOperand(2).getImm();
1366 MachineBasicBlock::iterator MI
= UserMI
;
1368 unsigned CPUIndex
= CPUserIndex
+1;
1369 unsigned NumCPUsers
= CPUsers
.size();
1370 MachineInstr
*LastIT
= nullptr;
1371 for (unsigned Offset
= UserOffset
+ TII
->getInstSizeInBytes(*UserMI
);
1372 Offset
< BaseInsertOffset
;
1373 Offset
+= TII
->getInstSizeInBytes(*MI
), MI
= std::next(MI
)) {
1374 assert(MI
!= UserMBB
->end() && "Fell off end of block");
1375 if (CPUIndex
< NumCPUsers
&& CPUsers
[CPUIndex
].MI
== &*MI
) {
1376 CPUser
&U
= CPUsers
[CPUIndex
];
1377 if (!isOffsetInRange(Offset
, EndInsertOffset
, U
)) {
1378 // Shift intertion point by one unit of alignment so it is within reach.
1379 BaseInsertOffset
-= 1u << LogAlign
;
1380 EndInsertOffset
-= 1u << LogAlign
;
1382 // This is overly conservative, as we don't account for CPEMIs being
1383 // reused within the block, but it doesn't matter much. Also assume CPEs
1384 // are added in order with alignment padding. We may eventually be able
1385 // to pack the aligned CPEs better.
1386 EndInsertOffset
+= U
.CPEMI
->getOperand(2).getImm();
1390 // Remember the last IT instruction.
1391 if (MI
->getOpcode() == ARM::t2IT
)
1397 // Avoid splitting an IT block.
1399 unsigned PredReg
= 0;
1400 ARMCC::CondCodes CC
= getITInstrPredicate(*MI
, PredReg
);
1401 if (CC
!= ARMCC::AL
)
1405 // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1406 // On Windows, this instruction pair is covered by one single
1407 // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1408 // constant island is injected inbetween them, the relocation will clobber
1409 // the instruction and fail to update the MOVT instruction.
1410 // (These instructions are bundled up until right before the ConstantIslands
1412 if (STI
->isTargetWindows() && isThumb
&& MI
->getOpcode() == ARM::t2MOVTi16
&&
1413 (MI
->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK
) ==
1416 assert(MI
->getOpcode() == ARM::t2MOVi16
&&
1417 (MI
->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK
) ==
1421 // We really must not split an IT block.
1424 assert(!isThumb
|| getITInstrPredicate(*MI
, PredReg
) == ARMCC::AL
);
1426 NewMBB
= splitBlockBeforeInstr(&*MI
);
1429 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1430 /// is out-of-range. If so, pick up the constant pool value and move it some
1431 /// place in-range. Return true if we changed any addresses (thus must run
1432 /// another pass of branch lengthening), false otherwise.
1433 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex
,
1435 CPUser
&U
= CPUsers
[CPUserIndex
];
1436 MachineInstr
*UserMI
= U
.MI
;
1437 MachineInstr
*CPEMI
= U
.CPEMI
;
1438 unsigned CPI
= getCombinedIndex(CPEMI
);
1439 unsigned Size
= CPEMI
->getOperand(2).getImm();
1440 // Compute this only once, it's expensive.
1441 unsigned UserOffset
= getUserOffset(U
);
1443 // See if the current entry is within range, or there is a clone of it
1445 int result
= findInRangeCPEntry(U
, UserOffset
);
1446 if (result
==1) return false;
1447 else if (result
==2) return true;
1449 // No existing clone of this CPE is within range.
1450 // We will be generating a new clone. Get a UID for it.
1451 unsigned ID
= AFI
->createPICLabelUId();
1453 // Look for water where we can place this CPE.
1454 MachineBasicBlock
*NewIsland
= MF
->CreateMachineBasicBlock();
1455 MachineBasicBlock
*NewMBB
;
1457 if (findAvailableWater(U
, UserOffset
, IP
, CloserWater
)) {
1458 LLVM_DEBUG(dbgs() << "Found water in range\n");
1459 MachineBasicBlock
*WaterBB
= *IP
;
1461 // If the original WaterList entry was "new water" on this iteration,
1462 // propagate that to the new island. This is just keeping NewWaterList
1463 // updated to match the WaterList, which will be updated below.
1464 if (NewWaterList
.erase(WaterBB
))
1465 NewWaterList
.insert(NewIsland
);
1467 // The new CPE goes before the following block (NewMBB).
1468 NewMBB
= &*++WaterBB
->getIterator();
1471 LLVM_DEBUG(dbgs() << "No water found\n");
1472 createNewWater(CPUserIndex
, UserOffset
, NewMBB
);
1474 // splitBlockBeforeInstr adds to WaterList, which is important when it is
1475 // called while handling branches so that the water will be seen on the
1476 // next iteration for constant pools, but in this context, we don't want
1477 // it. Check for this so it will be removed from the WaterList.
1478 // Also remove any entry from NewWaterList.
1479 MachineBasicBlock
*WaterBB
= &*--NewMBB
->getIterator();
1480 IP
= find(WaterList
, WaterBB
);
1481 if (IP
!= WaterList
.end())
1482 NewWaterList
.erase(WaterBB
);
1484 // We are adding new water. Update NewWaterList.
1485 NewWaterList
.insert(NewIsland
);
1487 // Always align the new block because CP entries can be smaller than 4
1488 // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1489 // be an already aligned constant pool block.
1490 const unsigned Align
= isThumb
? 1 : 2;
1491 if (NewMBB
->getAlignment() < Align
)
1492 NewMBB
->setAlignment(Align
);
1494 // Remove the original WaterList entry; we want subsequent insertions in
1495 // this vicinity to go after the one we're about to insert. This
1496 // considerably reduces the number of times we have to move the same CPE
1497 // more than once and is also important to ensure the algorithm terminates.
1498 if (IP
!= WaterList
.end())
1499 WaterList
.erase(IP
);
1501 // Okay, we know we can put an island before NewMBB now, do it!
1502 MF
->insert(NewMBB
->getIterator(), NewIsland
);
1504 // Update internal data structures to account for the newly inserted MBB.
1505 updateForInsertedWaterBlock(NewIsland
);
1507 // Now that we have an island to add the CPE to, clone the original CPE and
1508 // add it to the island.
1509 U
.HighWaterMark
= NewIsland
;
1510 U
.CPEMI
= BuildMI(NewIsland
, DebugLoc(), CPEMI
->getDesc())
1512 .add(CPEMI
->getOperand(1))
1514 CPEntries
[CPI
].push_back(CPEntry(U
.CPEMI
, ID
, 1));
1517 // Decrement the old entry, and remove it if refcount becomes 0.
1518 decrementCPEReferenceCount(CPI
, CPEMI
);
1520 // Mark the basic block as aligned as required by the const-pool entry.
1521 NewIsland
->setAlignment(getCPELogAlign(U
.CPEMI
));
1523 // Increase the size of the island block to account for the new entry.
1524 BBUtils
->adjustBBSize(NewIsland
, Size
);
1525 BBUtils
->adjustBBOffsetsAfter(&*--NewIsland
->getIterator());
1527 // Finally, change the CPI in the instruction operand to be ID.
1528 for (unsigned i
= 0, e
= UserMI
->getNumOperands(); i
!= e
; ++i
)
1529 if (UserMI
->getOperand(i
).isCPI()) {
1530 UserMI
->getOperand(i
).setIndex(ID
);
1535 dbgs() << " Moved CPE to #" << ID
<< " CPI=" << CPI
1536 << format(" offset=%#x\n",
1537 BBUtils
->getBBInfo()[NewIsland
->getNumber()].Offset
));
1542 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1543 /// sizes and offsets of impacted basic blocks.
1544 void ARMConstantIslands::removeDeadCPEMI(MachineInstr
*CPEMI
) {
1545 MachineBasicBlock
*CPEBB
= CPEMI
->getParent();
1546 unsigned Size
= CPEMI
->getOperand(2).getImm();
1547 CPEMI
->eraseFromParent();
1548 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1549 BBUtils
->adjustBBSize(CPEBB
, -Size
);
1550 // All succeeding offsets have the current size value added in, fix this.
1551 if (CPEBB
->empty()) {
1552 BBInfo
[CPEBB
->getNumber()].Size
= 0;
1554 // This block no longer needs to be aligned.
1555 CPEBB
->setAlignment(0);
1557 // Entries are sorted by descending alignment, so realign from the front.
1558 CPEBB
->setAlignment(getCPELogAlign(&*CPEBB
->begin()));
1560 BBUtils
->adjustBBOffsetsAfter(CPEBB
);
1561 // An island has only one predecessor BB and one successor BB. Check if
1562 // this BB's predecessor jumps directly to this BB's successor. This
1563 // shouldn't happen currently.
1564 assert(!BBIsJumpedOver(CPEBB
) && "How did this happen?");
1565 // FIXME: remove the empty blocks after all the work is done?
1568 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1570 bool ARMConstantIslands::removeUnusedCPEntries() {
1571 unsigned MadeChange
= false;
1572 for (unsigned i
= 0, e
= CPEntries
.size(); i
!= e
; ++i
) {
1573 std::vector
<CPEntry
> &CPEs
= CPEntries
[i
];
1574 for (unsigned j
= 0, ee
= CPEs
.size(); j
!= ee
; ++j
) {
1575 if (CPEs
[j
].RefCount
== 0 && CPEs
[j
].CPEMI
) {
1576 removeDeadCPEMI(CPEs
[j
].CPEMI
);
1577 CPEs
[j
].CPEMI
= nullptr;
1586 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1587 /// away to fit in its displacement field.
1588 bool ARMConstantIslands::fixupImmediateBr(ImmBranch
&Br
) {
1589 MachineInstr
*MI
= Br
.MI
;
1590 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1592 // Check to see if the DestBB is already in-range.
1593 if (BBUtils
->isBBInRange(MI
, DestBB
, Br
.MaxDisp
))
1597 return fixupUnconditionalBr(Br
);
1598 return fixupConditionalBr(Br
);
1601 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1602 /// too far away to fit in its displacement field. If the LR register has been
1603 /// spilled in the epilogue, then we can use BL to implement a far jump.
1604 /// Otherwise, add an intermediate branch instruction to a branch.
1606 ARMConstantIslands::fixupUnconditionalBr(ImmBranch
&Br
) {
1607 MachineInstr
*MI
= Br
.MI
;
1608 MachineBasicBlock
*MBB
= MI
->getParent();
1610 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1612 if (!AFI
->isLRSpilled())
1613 report_fatal_error("underestimated function size");
1615 // Use BL to implement far jump.
1616 Br
.MaxDisp
= (1 << 21) * 2;
1617 MI
->setDesc(TII
->get(ARM::tBfar
));
1618 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1619 BBInfo
[MBB
->getNumber()].Size
+= 2;
1620 BBUtils
->adjustBBOffsetsAfter(MBB
);
1624 LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI
);
1629 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1630 /// far away to fit in its displacement field. It is converted to an inverse
1631 /// conditional branch + an unconditional branch to the destination.
1633 ARMConstantIslands::fixupConditionalBr(ImmBranch
&Br
) {
1634 MachineInstr
*MI
= Br
.MI
;
1635 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
1637 // Add an unconditional branch to the destination and invert the branch
1638 // condition to jump over it:
1644 ARMCC::CondCodes CC
= (ARMCC::CondCodes
)MI
->getOperand(1).getImm();
1645 CC
= ARMCC::getOppositeCondition(CC
);
1646 unsigned CCReg
= MI
->getOperand(2).getReg();
1648 // If the branch is at the end of its MBB and that has a fall-through block,
1649 // direct the updated conditional branch to the fall-through block. Otherwise,
1650 // split the MBB before the next instruction.
1651 MachineBasicBlock
*MBB
= MI
->getParent();
1652 MachineInstr
*BMI
= &MBB
->back();
1653 bool NeedSplit
= (BMI
!= MI
) || !BBHasFallthrough(MBB
);
1657 if (std::next(MachineBasicBlock::iterator(MI
)) == std::prev(MBB
->end()) &&
1658 BMI
->getOpcode() == Br
.UncondBr
) {
1659 // Last MI in the BB is an unconditional branch. Can we simply invert the
1660 // condition and swap destinations:
1666 MachineBasicBlock
*NewDest
= BMI
->getOperand(0).getMBB();
1667 if (BBUtils
->isBBInRange(MI
, NewDest
, Br
.MaxDisp
)) {
1669 dbgs() << " Invert Bcc condition and swap its destination with "
1671 BMI
->getOperand(0).setMBB(DestBB
);
1672 MI
->getOperand(0).setMBB(NewDest
);
1673 MI
->getOperand(1).setImm(CC
);
1680 splitBlockBeforeInstr(MI
);
1681 // No need for the branch to the next block. We're adding an unconditional
1682 // branch to the destination.
1683 int delta
= TII
->getInstSizeInBytes(MBB
->back());
1684 BBUtils
->adjustBBSize(MBB
, -delta
);
1685 MBB
->back().eraseFromParent();
1687 // The conditional successor will be swapped between the BBs after this, so
1689 MBB
->addSuccessor(DestBB
);
1690 std::next(MBB
->getIterator())->removeSuccessor(DestBB
);
1692 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1694 MachineBasicBlock
*NextBB
= &*++MBB
->getIterator();
1696 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB
)
1697 << " also invert condition and change dest. to "
1698 << printMBBReference(*NextBB
) << "\n");
1700 // Insert a new conditional branch and a new unconditional branch.
1701 // Also update the ImmBranch as well as adding a new entry for the new branch.
1702 BuildMI(MBB
, DebugLoc(), TII
->get(MI
->getOpcode()))
1703 .addMBB(NextBB
).addImm(CC
).addReg(CCReg
);
1704 Br
.MI
= &MBB
->back();
1705 BBUtils
->adjustBBSize(MBB
, TII
->getInstSizeInBytes(MBB
->back()));
1707 BuildMI(MBB
, DebugLoc(), TII
->get(Br
.UncondBr
))
1709 .add(predOps(ARMCC::AL
));
1711 BuildMI(MBB
, DebugLoc(), TII
->get(Br
.UncondBr
)).addMBB(DestBB
);
1712 BBUtils
->adjustBBSize(MBB
, TII
->getInstSizeInBytes(MBB
->back()));
1713 unsigned MaxDisp
= getUnconditionalBrDisp(Br
.UncondBr
);
1714 ImmBranches
.push_back(ImmBranch(&MBB
->back(), MaxDisp
, false, Br
.UncondBr
));
1716 // Remove the old conditional branch. It may or may not still be in MBB.
1717 BBUtils
->adjustBBSize(MI
->getParent(), -TII
->getInstSizeInBytes(*MI
));
1718 MI
->eraseFromParent();
1719 BBUtils
->adjustBBOffsetsAfter(MBB
);
1723 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1724 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1725 /// to do this if tBfar is not used.
1726 bool ARMConstantIslands::undoLRSpillRestore() {
1727 bool MadeChange
= false;
1728 for (unsigned i
= 0, e
= PushPopMIs
.size(); i
!= e
; ++i
) {
1729 MachineInstr
*MI
= PushPopMIs
[i
];
1730 // First two operands are predicates.
1731 if (MI
->getOpcode() == ARM::tPOP_RET
&&
1732 MI
->getOperand(2).getReg() == ARM::PC
&&
1733 MI
->getNumExplicitOperands() == 3) {
1734 // Create the new insn and copy the predicate from the old.
1735 BuildMI(MI
->getParent(), MI
->getDebugLoc(), TII
->get(ARM::tBX_RET
))
1736 .add(MI
->getOperand(0))
1737 .add(MI
->getOperand(1));
1738 MI
->eraseFromParent();
1740 } else if (MI
->getOpcode() == ARM::tPUSH
&&
1741 MI
->getOperand(2).getReg() == ARM::LR
&&
1742 MI
->getNumExplicitOperands() == 3) {
1743 // Just remove the push.
1744 MI
->eraseFromParent();
1751 bool ARMConstantIslands::optimizeThumb2Instructions() {
1752 bool MadeChange
= false;
1754 // Shrink ADR and LDR from constantpool.
1755 for (unsigned i
= 0, e
= CPUsers
.size(); i
!= e
; ++i
) {
1756 CPUser
&U
= CPUsers
[i
];
1757 unsigned Opcode
= U
.MI
->getOpcode();
1758 unsigned NewOpc
= 0;
1763 case ARM::t2LEApcrel
:
1764 if (isARMLowRegister(U
.MI
->getOperand(0).getReg())) {
1765 NewOpc
= ARM::tLEApcrel
;
1771 if (isARMLowRegister(U
.MI
->getOperand(0).getReg())) {
1772 NewOpc
= ARM::tLDRpci
;
1782 unsigned UserOffset
= getUserOffset(U
);
1783 unsigned MaxOffs
= ((1 << Bits
) - 1) * Scale
;
1785 // Be conservative with inline asm.
1786 if (!U
.KnownAlignment
)
1789 // FIXME: Check if offset is multiple of scale if scale is not 4.
1790 if (isCPEntryInRange(U
.MI
, UserOffset
, U
.CPEMI
, MaxOffs
, false, true)) {
1791 LLVM_DEBUG(dbgs() << "Shrink: " << *U
.MI
);
1792 U
.MI
->setDesc(TII
->get(NewOpc
));
1793 MachineBasicBlock
*MBB
= U
.MI
->getParent();
1794 BBUtils
->adjustBBSize(MBB
, -2);
1795 BBUtils
->adjustBBOffsetsAfter(MBB
);
1804 bool ARMConstantIslands::optimizeThumb2Branches() {
1805 bool MadeChange
= false;
1807 // The order in which branches appear in ImmBranches is approximately their
1808 // order within the function body. By visiting later branches first, we reduce
1809 // the distance between earlier forward branches and their targets, making it
1810 // more likely that the cbn?z optimization, which can only apply to forward
1811 // branches, will succeed.
1812 for (unsigned i
= ImmBranches
.size(); i
!= 0; --i
) {
1813 ImmBranch
&Br
= ImmBranches
[i
-1];
1814 unsigned Opcode
= Br
.MI
->getOpcode();
1815 unsigned NewOpc
= 0;
1832 unsigned MaxOffs
= ((1 << (Bits
-1))-1) * Scale
;
1833 MachineBasicBlock
*DestBB
= Br
.MI
->getOperand(0).getMBB();
1834 if (BBUtils
->isBBInRange(Br
.MI
, DestBB
, MaxOffs
)) {
1835 LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br
.MI
);
1836 Br
.MI
->setDesc(TII
->get(NewOpc
));
1837 MachineBasicBlock
*MBB
= Br
.MI
->getParent();
1838 BBUtils
->adjustBBSize(MBB
, -2);
1839 BBUtils
->adjustBBOffsetsAfter(MBB
);
1845 Opcode
= Br
.MI
->getOpcode();
1846 if (Opcode
!= ARM::tBcc
)
1849 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1850 // so this transformation is not safe.
1851 if (!Br
.MI
->killsRegister(ARM::CPSR
))
1855 unsigned PredReg
= 0;
1856 ARMCC::CondCodes Pred
= getInstrPredicate(*Br
.MI
, PredReg
);
1857 if (Pred
== ARMCC::EQ
)
1859 else if (Pred
== ARMCC::NE
)
1860 NewOpc
= ARM::tCBNZ
;
1863 MachineBasicBlock
*DestBB
= Br
.MI
->getOperand(0).getMBB();
1864 // Check if the distance is within 126. Subtract starting offset by 2
1865 // because the cmp will be eliminated.
1866 unsigned BrOffset
= BBUtils
->getOffsetOf(Br
.MI
) + 4 - 2;
1867 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
1868 unsigned DestOffset
= BBInfo
[DestBB
->getNumber()].Offset
;
1869 if (BrOffset
>= DestOffset
|| (DestOffset
- BrOffset
) > 126)
1872 // Search backwards to find a tCMPi8
1873 auto *TRI
= STI
->getRegisterInfo();
1874 MachineInstr
*CmpMI
= findCMPToFoldIntoCBZ(Br
.MI
, TRI
);
1875 if (!CmpMI
|| CmpMI
->getOpcode() != ARM::tCMPi8
)
1878 unsigned Reg
= CmpMI
->getOperand(0).getReg();
1880 // Check for Kill flags on Reg. If they are present remove them and set kill
1882 MachineBasicBlock::iterator KillMI
= Br
.MI
;
1883 bool RegKilled
= false;
1886 if (KillMI
->killsRegister(Reg
, TRI
)) {
1887 KillMI
->clearRegisterKills(Reg
, TRI
);
1891 } while (KillMI
!= CmpMI
);
1893 // Create the new CBZ/CBNZ
1894 MachineBasicBlock
*MBB
= Br
.MI
->getParent();
1895 LLVM_DEBUG(dbgs() << "Fold: " << *CmpMI
<< " and: " << *Br
.MI
);
1896 MachineInstr
*NewBR
=
1897 BuildMI(*MBB
, Br
.MI
, Br
.MI
->getDebugLoc(), TII
->get(NewOpc
))
1898 .addReg(Reg
, getKillRegState(RegKilled
))
1899 .addMBB(DestBB
, Br
.MI
->getOperand(0).getTargetFlags());
1900 CmpMI
->eraseFromParent();
1901 Br
.MI
->eraseFromParent();
1903 BBInfo
[MBB
->getNumber()].Size
-= 2;
1904 BBUtils
->adjustBBOffsetsAfter(MBB
);
1912 static bool isSimpleIndexCalc(MachineInstr
&I
, unsigned EntryReg
,
1914 if (I
.getOpcode() != ARM::t2ADDrs
)
1917 if (I
.getOperand(0).getReg() != EntryReg
)
1920 if (I
.getOperand(1).getReg() != BaseReg
)
1923 // FIXME: what about CC and IdxReg?
1927 /// While trying to form a TBB/TBH instruction, we may (if the table
1928 /// doesn't immediately follow the BR_JT) need access to the start of the
1929 /// jump-table. We know one instruction that produces such a register; this
1930 /// function works out whether that definition can be preserved to the BR_JT,
1931 /// possibly by removing an intervening addition (which is usually needed to
1932 /// calculate the actual entry to jump to).
1933 bool ARMConstantIslands::preserveBaseRegister(MachineInstr
*JumpMI
,
1934 MachineInstr
*LEAMI
,
1937 bool &BaseRegKill
) {
1938 if (JumpMI
->getParent() != LEAMI
->getParent())
1941 // Now we hope that we have at least these instructions in the basic block:
1942 // BaseReg = t2LEA ...
1944 // EntryReg = t2ADDrs BaseReg, ...
1948 // We have to be very conservative about what we recognise here though. The
1949 // main perturbing factors to watch out for are:
1950 // + Spills at any point in the chain: not direct problems but we would
1951 // expect a blocking Def of the spilled register so in practice what we
1952 // can do is limited.
1953 // + EntryReg == BaseReg: this is the one situation we should allow a Def
1954 // of BaseReg, but only if the t2ADDrs can be removed.
1955 // + Some instruction other than t2ADDrs computing the entry. Not seen in
1956 // the wild, but we should be careful.
1957 unsigned EntryReg
= JumpMI
->getOperand(0).getReg();
1958 unsigned BaseReg
= LEAMI
->getOperand(0).getReg();
1960 CanDeleteLEA
= true;
1961 BaseRegKill
= false;
1962 MachineInstr
*RemovableAdd
= nullptr;
1963 MachineBasicBlock::iterator
I(LEAMI
);
1964 for (++I
; &*I
!= JumpMI
; ++I
) {
1965 if (isSimpleIndexCalc(*I
, EntryReg
, BaseReg
)) {
1970 for (unsigned K
= 0, E
= I
->getNumOperands(); K
!= E
; ++K
) {
1971 const MachineOperand
&MO
= I
->getOperand(K
);
1972 if (!MO
.isReg() || !MO
.getReg())
1974 if (MO
.isDef() && MO
.getReg() == BaseReg
)
1976 if (MO
.isUse() && MO
.getReg() == BaseReg
) {
1977 BaseRegKill
= BaseRegKill
|| MO
.isKill();
1978 CanDeleteLEA
= false;
1986 // Check the add really is removable, and that nothing else in the block
1987 // clobbers BaseReg.
1988 for (++I
; &*I
!= JumpMI
; ++I
) {
1989 for (unsigned K
= 0, E
= I
->getNumOperands(); K
!= E
; ++K
) {
1990 const MachineOperand
&MO
= I
->getOperand(K
);
1991 if (!MO
.isReg() || !MO
.getReg())
1993 if (MO
.isDef() && MO
.getReg() == BaseReg
)
1995 if (MO
.isUse() && MO
.getReg() == EntryReg
)
1996 RemovableAdd
= nullptr;
2001 RemovableAdd
->eraseFromParent();
2002 DeadSize
+= isThumb2
? 4 : 2;
2003 } else if (BaseReg
== EntryReg
) {
2004 // The add wasn't removable, but clobbered the base for the TBB. So we can't
2009 // We reached the end of the block without seeing another definition of
2010 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2011 // used in the TBB/TBH if necessary.
2015 /// Returns whether CPEMI is the first instruction in the block
2016 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2017 /// we can switch the first register to PC and usually remove the address
2018 /// calculation that preceded it.
2019 static bool jumpTableFollowsTB(MachineInstr
*JTMI
, MachineInstr
*CPEMI
) {
2020 MachineFunction::iterator MBB
= JTMI
->getParent()->getIterator();
2021 MachineFunction
*MF
= MBB
->getParent();
2024 return MBB
!= MF
->end() && MBB
->begin() != MBB
->end() &&
2025 &*MBB
->begin() == CPEMI
;
2028 static void RemoveDeadAddBetweenLEAAndJT(MachineInstr
*LEAMI
,
2029 MachineInstr
*JumpMI
,
2030 unsigned &DeadSize
) {
2031 // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2032 // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2033 // and is not clobbered / used.
2034 MachineInstr
*RemovableAdd
= nullptr;
2035 unsigned EntryReg
= JumpMI
->getOperand(0).getReg();
2037 // Find the last ADD to set EntryReg
2038 MachineBasicBlock::iterator
I(LEAMI
);
2039 for (++I
; &*I
!= JumpMI
; ++I
) {
2040 if (I
->getOpcode() == ARM::t2ADDrs
&& I
->getOperand(0).getReg() == EntryReg
)
2047 // Ensure EntryReg is not clobbered or used.
2048 MachineBasicBlock::iterator
J(RemovableAdd
);
2049 for (++J
; &*J
!= JumpMI
; ++J
) {
2050 for (unsigned K
= 0, E
= J
->getNumOperands(); K
!= E
; ++K
) {
2051 const MachineOperand
&MO
= J
->getOperand(K
);
2052 if (!MO
.isReg() || !MO
.getReg())
2054 if (MO
.isDef() && MO
.getReg() == EntryReg
)
2056 if (MO
.isUse() && MO
.getReg() == EntryReg
)
2061 LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd
);
2062 RemovableAdd
->eraseFromParent();
2066 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
2067 /// jumptables when it's possible.
2068 bool ARMConstantIslands::optimizeThumb2JumpTables() {
2069 bool MadeChange
= false;
2071 // FIXME: After the tables are shrunk, can we get rid some of the
2072 // constantpool tables?
2073 MachineJumpTableInfo
*MJTI
= MF
->getJumpTableInfo();
2074 if (!MJTI
) return false;
2076 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
2077 for (unsigned i
= 0, e
= T2JumpTables
.size(); i
!= e
; ++i
) {
2078 MachineInstr
*MI
= T2JumpTables
[i
];
2079 const MCInstrDesc
&MCID
= MI
->getDesc();
2080 unsigned NumOps
= MCID
.getNumOperands();
2081 unsigned JTOpIdx
= NumOps
- (MI
->isPredicable() ? 2 : 1);
2082 MachineOperand JTOP
= MI
->getOperand(JTOpIdx
);
2083 unsigned JTI
= JTOP
.getIndex();
2084 assert(JTI
< JT
.size());
2087 bool HalfWordOk
= true;
2088 unsigned JTOffset
= BBUtils
->getOffsetOf(MI
) + 4;
2089 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[JTI
].MBBs
;
2090 BBInfoVector
&BBInfo
= BBUtils
->getBBInfo();
2091 for (unsigned j
= 0, ee
= JTBBs
.size(); j
!= ee
; ++j
) {
2092 MachineBasicBlock
*MBB
= JTBBs
[j
];
2093 unsigned DstOffset
= BBInfo
[MBB
->getNumber()].Offset
;
2094 // Negative offset is not ok. FIXME: We should change BB layout to make
2095 // sure all the branches are forward.
2096 if (ByteOk
&& (DstOffset
- JTOffset
) > ((1<<8)-1)*2)
2098 unsigned TBHLimit
= ((1<<16)-1)*2;
2099 if (HalfWordOk
&& (DstOffset
- JTOffset
) > TBHLimit
)
2101 if (!ByteOk
&& !HalfWordOk
)
2105 if (!ByteOk
&& !HalfWordOk
)
2108 CPUser
&User
= CPUsers
[JumpTableUserIndices
[JTI
]];
2109 MachineBasicBlock
*MBB
= MI
->getParent();
2110 if (!MI
->getOperand(0).isKill()) // FIXME: needed now?
2113 unsigned DeadSize
= 0;
2114 bool CanDeleteLEA
= false;
2115 bool BaseRegKill
= false;
2117 unsigned IdxReg
= ~0U;
2118 bool IdxRegKill
= true;
2120 IdxReg
= MI
->getOperand(1).getReg();
2121 IdxRegKill
= MI
->getOperand(1).isKill();
2123 bool PreservedBaseReg
=
2124 preserveBaseRegister(MI
, User
.MI
, DeadSize
, CanDeleteLEA
, BaseRegKill
);
2125 if (!jumpTableFollowsTB(MI
, User
.CPEMI
) && !PreservedBaseReg
)
2128 // We're in thumb-1 mode, so we must have something like:
2129 // %idx = tLSLri %idx, 2
2130 // %base = tLEApcrelJT
2131 // %t = tLDRr %base, %idx
2132 unsigned BaseReg
= User
.MI
->getOperand(0).getReg();
2134 if (User
.MI
->getIterator() == User
.MI
->getParent()->begin())
2136 MachineInstr
*Shift
= User
.MI
->getPrevNode();
2137 if (Shift
->getOpcode() != ARM::tLSLri
||
2138 Shift
->getOperand(3).getImm() != 2 ||
2139 !Shift
->getOperand(2).isKill())
2141 IdxReg
= Shift
->getOperand(2).getReg();
2142 unsigned ShiftedIdxReg
= Shift
->getOperand(0).getReg();
2144 // It's important that IdxReg is live until the actual TBB/TBH. Most of
2145 // the range is checked later, but the LEA might still clobber it and not
2146 // actually get removed.
2147 if (BaseReg
== IdxReg
&& !jumpTableFollowsTB(MI
, User
.CPEMI
))
2150 MachineInstr
*Load
= User
.MI
->getNextNode();
2151 if (Load
->getOpcode() != ARM::tLDRr
)
2153 if (Load
->getOperand(1).getReg() != BaseReg
||
2154 Load
->getOperand(2).getReg() != ShiftedIdxReg
||
2155 !Load
->getOperand(2).isKill())
2158 // If we're in PIC mode, there should be another ADD following.
2159 auto *TRI
= STI
->getRegisterInfo();
2161 // %base cannot be redefined after the load as it will appear before
2166 if (registerDefinedBetween(BaseReg
, Load
->getNextNode(), MBB
->end(), TRI
))
2169 if (isPositionIndependentOrROPI
) {
2170 MachineInstr
*Add
= Load
->getNextNode();
2171 if (Add
->getOpcode() != ARM::tADDrr
||
2172 Add
->getOperand(2).getReg() != BaseReg
||
2173 Add
->getOperand(3).getReg() != Load
->getOperand(0).getReg() ||
2174 !Add
->getOperand(3).isKill())
2176 if (Add
->getOperand(0).getReg() != MI
->getOperand(0).getReg())
2178 if (registerDefinedBetween(IdxReg
, Add
->getNextNode(), MI
, TRI
))
2179 // IdxReg gets redefined in the middle of the sequence.
2181 Add
->eraseFromParent();
2184 if (Load
->getOperand(0).getReg() != MI
->getOperand(0).getReg())
2186 if (registerDefinedBetween(IdxReg
, Load
->getNextNode(), MI
, TRI
))
2187 // IdxReg gets redefined in the middle of the sequence.
2191 // Now safe to delete the load and lsl. The LEA will be removed later.
2192 CanDeleteLEA
= true;
2193 Shift
->eraseFromParent();
2194 Load
->eraseFromParent();
2198 LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI
);
2199 MachineInstr
*CPEMI
= User
.CPEMI
;
2200 unsigned Opc
= ByteOk
? ARM::t2TBB_JT
: ARM::t2TBH_JT
;
2202 Opc
= ByteOk
? ARM::tTBB_JT
: ARM::tTBH_JT
;
2204 MachineBasicBlock::iterator MI_JT
= MI
;
2205 MachineInstr
*NewJTMI
=
2206 BuildMI(*MBB
, MI_JT
, MI
->getDebugLoc(), TII
->get(Opc
))
2207 .addReg(User
.MI
->getOperand(0).getReg(),
2208 getKillRegState(BaseRegKill
))
2209 .addReg(IdxReg
, getKillRegState(IdxRegKill
))
2210 .addJumpTableIndex(JTI
, JTOP
.getTargetFlags())
2211 .addImm(CPEMI
->getOperand(0).getImm());
2212 LLVM_DEBUG(dbgs() << printMBBReference(*MBB
) << ": " << *NewJTMI
);
2214 unsigned JTOpc
= ByteOk
? ARM::JUMPTABLE_TBB
: ARM::JUMPTABLE_TBH
;
2215 CPEMI
->setDesc(TII
->get(JTOpc
));
2217 if (jumpTableFollowsTB(MI
, User
.CPEMI
)) {
2218 NewJTMI
->getOperand(0).setReg(ARM::PC
);
2219 NewJTMI
->getOperand(0).setIsKill(false);
2223 RemoveDeadAddBetweenLEAAndJT(User
.MI
, MI
, DeadSize
);
2225 User
.MI
->eraseFromParent();
2226 DeadSize
+= isThumb2
? 4 : 2;
2228 // The LEA was eliminated, the TBB instruction becomes the only new user
2229 // of the jump table.
2233 User
.IsSoImm
= false;
2234 User
.KnownAlignment
= false;
2236 // The LEA couldn't be eliminated, so we must add another CPUser to
2237 // record the TBB or TBH use.
2238 int CPEntryIdx
= JumpTableEntryIndices
[JTI
];
2239 auto &CPEs
= CPEntries
[CPEntryIdx
];
2241 find_if(CPEs
, [&](CPEntry
&E
) { return E
.CPEMI
== User
.CPEMI
; });
2243 CPUsers
.emplace_back(CPUser(NewJTMI
, User
.CPEMI
, 4, false, false));
2247 unsigned NewSize
= TII
->getInstSizeInBytes(*NewJTMI
);
2248 unsigned OrigSize
= TII
->getInstSizeInBytes(*MI
);
2249 MI
->eraseFromParent();
2251 int Delta
= OrigSize
- NewSize
+ DeadSize
;
2252 BBInfo
[MBB
->getNumber()].Size
-= Delta
;
2253 BBUtils
->adjustBBOffsetsAfter(MBB
);
2262 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
2263 /// jump tables always branch forwards, since that's what tbb and tbh need.
2264 bool ARMConstantIslands::reorderThumb2JumpTables() {
2265 bool MadeChange
= false;
2267 MachineJumpTableInfo
*MJTI
= MF
->getJumpTableInfo();
2268 if (!MJTI
) return false;
2270 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
2271 for (unsigned i
= 0, e
= T2JumpTables
.size(); i
!= e
; ++i
) {
2272 MachineInstr
*MI
= T2JumpTables
[i
];
2273 const MCInstrDesc
&MCID
= MI
->getDesc();
2274 unsigned NumOps
= MCID
.getNumOperands();
2275 unsigned JTOpIdx
= NumOps
- (MI
->isPredicable() ? 2 : 1);
2276 MachineOperand JTOP
= MI
->getOperand(JTOpIdx
);
2277 unsigned JTI
= JTOP
.getIndex();
2278 assert(JTI
< JT
.size());
2280 // We prefer if target blocks for the jump table come after the jump
2281 // instruction so we can use TB[BH]. Loop through the target blocks
2282 // and try to adjust them such that that's true.
2283 int JTNumber
= MI
->getParent()->getNumber();
2284 const std::vector
<MachineBasicBlock
*> &JTBBs
= JT
[JTI
].MBBs
;
2285 for (unsigned j
= 0, ee
= JTBBs
.size(); j
!= ee
; ++j
) {
2286 MachineBasicBlock
*MBB
= JTBBs
[j
];
2287 int DTNumber
= MBB
->getNumber();
2289 if (DTNumber
< JTNumber
) {
2290 // The destination precedes the switch. Try to move the block forward
2291 // so we have a positive offset.
2292 MachineBasicBlock
*NewBB
=
2293 adjustJTTargetBlockForward(MBB
, MI
->getParent());
2295 MJTI
->ReplaceMBBInJumpTable(JTI
, JTBBs
[j
], NewBB
);
2304 MachineBasicBlock
*ARMConstantIslands::
2305 adjustJTTargetBlockForward(MachineBasicBlock
*BB
, MachineBasicBlock
*JTBB
) {
2306 // If the destination block is terminated by an unconditional branch,
2307 // try to move it; otherwise, create a new block following the jump
2308 // table that branches back to the actual target. This is a very simple
2309 // heuristic. FIXME: We can definitely improve it.
2310 MachineBasicBlock
*TBB
= nullptr, *FBB
= nullptr;
2311 SmallVector
<MachineOperand
, 4> Cond
;
2312 SmallVector
<MachineOperand
, 4> CondPrior
;
2313 MachineFunction::iterator BBi
= BB
->getIterator();
2314 MachineFunction::iterator OldPrior
= std::prev(BBi
);
2316 // If the block terminator isn't analyzable, don't try to move the block
2317 bool B
= TII
->analyzeBranch(*BB
, TBB
, FBB
, Cond
);
2319 // If the block ends in an unconditional branch, move it. The prior block
2320 // has to have an analyzable terminator for us to move this one. Be paranoid
2321 // and make sure we're not trying to move the entry block of the function.
2322 if (!B
&& Cond
.empty() && BB
!= &MF
->front() &&
2323 !TII
->analyzeBranch(*OldPrior
, TBB
, FBB
, CondPrior
)) {
2324 BB
->moveAfter(JTBB
);
2325 OldPrior
->updateTerminator();
2326 BB
->updateTerminator();
2327 // Update numbering to account for the block being moved.
2328 MF
->RenumberBlocks();
2333 // Create a new MBB for the code after the jump BB.
2334 MachineBasicBlock
*NewBB
=
2335 MF
->CreateMachineBasicBlock(JTBB
->getBasicBlock());
2336 MachineFunction::iterator MBBI
= ++JTBB
->getIterator();
2337 MF
->insert(MBBI
, NewBB
);
2339 // Add an unconditional branch from NewBB to BB.
2340 // There doesn't seem to be meaningful DebugInfo available; this doesn't
2341 // correspond directly to anything in the source.
2343 BuildMI(NewBB
, DebugLoc(), TII
->get(ARM::t2B
))
2345 .add(predOps(ARMCC::AL
));
2347 BuildMI(NewBB
, DebugLoc(), TII
->get(ARM::tB
))
2349 .add(predOps(ARMCC::AL
));
2351 // Update internal data structures to account for the newly inserted MBB.
2352 MF
->RenumberBlocks(NewBB
);
2355 NewBB
->addSuccessor(BB
);
2356 JTBB
->replaceSuccessor(BB
, NewBB
);
2362 /// createARMConstantIslandPass - returns an instance of the constpool
2364 FunctionPass
*llvm::createARMConstantIslandPass() {
2365 return new ARMConstantIslands();
2368 INITIALIZE_PASS(ARMConstantIslands
, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME
,