LLVM  9.0.0svn
ARMConstantIslandPass.cpp
Go to the documentation of this file.
1 //===- ARMConstantIslandPass.cpp - ARM constant islands -------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBasicBlockInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.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"
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"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Format.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <iterator>
53 #include <utility>
54 #include <vector>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "arm-cp-islands"
59 
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");
72 
73 static cl::opt<bool>
74 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true),
75  cl::desc("Adjust basic block layout to better use TB[BH]"));
76 
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"));
80 
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"));
85 
86 namespace {
87 
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.
93  ///
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::vector<BasicBlockInfo> BBInfo;
101 
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;
106 
107  /// NewWaterList - The subset of WaterList that was created since the
108  /// previous iteration by inserting unconditional branches.
109  SmallSet<MachineBasicBlock*, 4> NewWaterList;
110 
111  using water_iterator = std::vector<MachineBasicBlock *>::iterator;
112 
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
124  /// that point.
125  struct CPUser {
126  MachineInstr *MI;
127  MachineInstr *CPEMI;
128  MachineBasicBlock *HighWaterMark;
129  unsigned MaxDisp;
130  bool NegOk;
131  bool IsSoImm;
132  bool KnownAlignment = false;
133 
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();
138  }
139 
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;
145  }
146  };
147 
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;
151 
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.
155  struct CPEntry {
156  MachineInstr *CPEMI;
157  unsigned CPI;
158  unsigned RefCount;
159 
160  CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0)
161  : CPEMI(cpemi), CPI(cpi), RefCount(rc) {}
162  };
163 
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.
169  ///
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;
174 
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;
178 
179  /// Maps a JT index to the LEA that actually uses the index to calculate its
180  /// base address.
181  DenseMap<int, int> JumpTableUserIndices;
182 
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
186  /// opcode.
187  struct ImmBranch {
188  MachineInstr *MI;
189  unsigned MaxDisp : 31;
190  bool isCond : 1;
191  unsigned UncondBr;
192 
193  ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr)
194  : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {}
195  };
196 
197  /// ImmBranches - Keep track of all the immediate branch instructions.
198  std::vector<ImmBranch> ImmBranches;
199 
200  /// PushPopMIs - Keep track of all the Thumb push / pop instructions.
202 
203  /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions.
204  SmallVector<MachineInstr*, 4> T2JumpTables;
205 
206  /// HasFarJump - True if any far jump instruction has been emitted during
207  /// the branch fix up pass.
208  bool HasFarJump;
209 
210  MachineFunction *MF;
211  MachineConstantPool *MCP;
212  const ARMBaseInstrInfo *TII;
213  const ARMSubtarget *STI;
214  ARMFunctionInfo *AFI;
215  bool isThumb;
216  bool isThumb1;
217  bool isThumb2;
218  bool isPositionIndependentOrROPI;
219 
220  public:
221  static char ID;
222 
223  ARMConstantIslands() : MachineFunctionPass(ID) {}
224 
225  bool runOnMachineFunction(MachineFunction &MF) override;
226 
227  MachineFunctionProperties getRequiredProperties() const override {
230  }
231 
232  StringRef getPassName() const override {
234  }
235 
236  private:
237  void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs);
238  void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs);
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  void adjustBBOffsetsAfter(MachineBasicBlock *BB);
247  bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI);
248  unsigned getCombinedIndex(const MachineInstr *CPEMI);
249  int findInRangeCPEntry(CPUser& U, unsigned UserOffset);
250  bool findAvailableWater(CPUser&U, unsigned UserOffset,
251  water_iterator &WaterIter, bool CloserWater);
252  void createNewWater(unsigned CPUserIndex, unsigned UserOffset,
253  MachineBasicBlock *&NewMBB);
254  bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater);
255  void removeDeadCPEMI(MachineInstr *CPEMI);
256  bool removeUnusedCPEntries();
257  bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
258  MachineInstr *CPEMI, unsigned Disp, bool NegOk,
259  bool DoDump = false);
260  bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water,
261  CPUser &U, unsigned &Growth);
262  bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
263  bool fixupImmediateBr(ImmBranch &Br);
264  bool fixupConditionalBr(ImmBranch &Br);
265  bool fixupUnconditionalBr(ImmBranch &Br);
266  bool undoLRSpillRestore();
267  bool optimizeThumb2Instructions();
268  bool optimizeThumb2Branches();
269  bool reorderThumb2JumpTables();
270  bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI,
271  unsigned &DeadSize, bool &CanDeleteLEA,
272  bool &BaseRegKill);
273  bool optimizeThumb2JumpTables();
274  MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB,
275  MachineBasicBlock *JTBB);
276 
277  unsigned getOffsetOf(MachineInstr *MI) const;
278  unsigned getUserOffset(CPUser&) const;
279  void dumpBBs();
280  void verify();
281 
282  bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
283  unsigned Disp, bool NegativeOK, bool IsSoImm = false);
284  bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset,
285  const CPUser &U) {
286  return isOffsetInRange(UserOffset, TrialOffset,
287  U.getMaxDisp(), U.NegOk, U.IsSoImm);
288  }
289  };
290 
291 } // end anonymous namespace
292 
293 char ARMConstantIslands::ID = 0;
294 
295 /// verify - check BBOffsets, BBSizes, alignment of islands
297 #ifndef NDEBUG
298  assert(std::is_sorted(MF->begin(), MF->end(),
299  [this](const MachineBasicBlock &LHS,
300  const MachineBasicBlock &RHS) {
301  return BBInfo[LHS.getNumber()].postOffset() <
302  BBInfo[RHS.getNumber()].postOffset();
303  }));
304  LLVM_DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n");
305  for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
306  CPUser &U = CPUsers[i];
307  unsigned UserOffset = getUserOffset(U);
308  // Verify offset using the real max displacement without the safety
309  // adjustment.
310  if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk,
311  /* DoDump = */ true)) {
312  LLVM_DEBUG(dbgs() << "OK\n");
313  continue;
314  }
315  LLVM_DEBUG(dbgs() << "Out of range.\n");
316  dumpBBs();
317  LLVM_DEBUG(MF->dump());
318  llvm_unreachable("Constant pool entry out of range!");
319  }
320 #endif
321 }
322 
323 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
324 /// print block size and offset information - debugging
325 LLVM_DUMP_METHOD void ARMConstantIslands::dumpBBs() {
326  LLVM_DEBUG({
327  for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) {
328  const BasicBlockInfo &BBI = BBInfo[J];
329  dbgs() << format("%08x %bb.%u\t", BBI.Offset, J)
330  << " kb=" << unsigned(BBI.KnownBits)
331  << " ua=" << unsigned(BBI.Unalign)
332  << " pa=" << unsigned(BBI.PostAlign)
333  << format(" size=%#x\n", BBInfo[J].Size);
334  }
335  });
336 }
337 #endif
338 
339 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) {
340  MF = &mf;
341  MCP = mf.getConstantPool();
342 
343  LLVM_DEBUG(dbgs() << "***** ARMConstantIslands: "
344  << MCP->getConstants().size() << " CP entries, aligned to "
345  << MCP->getConstantPoolAlignment() << " bytes *****\n");
346 
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>();
352 
353  isThumb = AFI->isThumbFunction();
354  isThumb1 = AFI->isThumb1OnlyFunction();
355  isThumb2 = AFI->isThumb2Function();
356 
357  HasFarJump = false;
358  bool GenerateTBB = isThumb2 || (isThumb1 && SynthesizeThumb1TBB);
359 
360  // This pass invalidates liveness information when it splits basic blocks.
362 
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();
366 
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();
377  }
378 
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;
382  if (!MCP->isEmpty())
383  doInitialConstPlacement(CPEMIs);
384 
385  if (MF->getJumpTableInfo())
386  doInitialJumpTablePlacement(CPEMIs);
387 
388  /// The next UID to take is the first unused one.
389  AFI->initPICLabelUId(CPEMIs.size());
390 
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);
395  CPEMIs.clear();
396  LLVM_DEBUG(dumpBBs());
397 
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);
402 
403  /// Remove dead constant pool entries.
404  MadeChange |= removeUnusedCPEntries();
405 
406  // Iteratively place constant pool entries and fix up branches until there
407  // is no change.
408  unsigned NoCPIters = 0, NoBRIters = 0;
409  while (true) {
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());
420 
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();
424 
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());
432 
433  if (!CPChange && !BRChange)
434  break;
435  MadeChange = true;
436  }
437 
438  // Shrink 32-bit Thumb2 load and store instructions.
439  if (isThumb2 && !STI->prefers32BitThumb())
440  MadeChange |= optimizeThumb2Instructions();
441 
442  // Shrink 32-bit branch instructions.
443  if (isThumb && STI->hasV8MBaselineOps())
444  MadeChange |= optimizeThumb2Branches();
445 
446  // Optimize jump tables using TBB / TBH.
447  if (GenerateTBB && !STI->genExecuteOnly())
448  MadeChange |= optimizeThumb2JumpTables();
449 
450  // After a while, this might be made debug-only, but it is not expensive.
451  verify();
452 
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();
457 
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);
464  }
465  }
466 
467  LLVM_DEBUG(dbgs() << '\n'; dumpBBs());
468 
469  BBInfo.clear();
470  WaterList.clear();
471  CPUsers.clear();
472  CPEntries.clear();
473  JumpTableEntryIndices.clear();
474  JumpTableUserIndices.clear();
475  ImmBranches.clear();
476  PushPopMIs.clear();
477  T2JumpTables.clear();
478 
479  return MadeChange;
480 }
481 
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.
484 void
485 ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) {
486  // Create the basic block to hold the CPE's.
488  MF->push_back(BB);
489 
490  // MachineConstantPool measures alignment in bytes. We measure in log2(bytes).
491  unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment());
492 
493  // Mark the basic block as required by the const-pool.
494  BB->setAlignment(MaxAlign);
495 
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());
499 
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());
505 
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();
509 
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!");
518 
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);
526 
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)
531  InsPoint[a] = CPEMI;
532 
533  // Add a new CPEntry, but no corresponding CPUser yet.
534  CPEntries.emplace_back(1, CPEntry(CPEMI, i));
535  ++NumCPEs;
536  LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = "
537  << Size << ", align = " << Align << '\n');
538  }
539  LLVM_DEBUG(BB->dump());
540 }
541 
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
546 /// position.
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();
552 
553  MachineBasicBlock *LastCorrectlyNumberedBB = nullptr;
554  for (MachineBasicBlock &MBB : *MF) {
555  auto MI = MBB.getLastNonDebugInstr();
556  if (MI == MBB.end())
557  continue;
558 
559  unsigned JTOpcode;
560  switch (MI->getOpcode()) {
561  default:
562  continue;
563  case ARM::BR_JTadd:
564  case ARM::BR_JTr:
565  case ARM::tBR_JTr:
566  case ARM::BR_JTm_i12:
567  case ARM::BR_JTm_rs:
568  JTOpcode = ARM::JUMPTABLE_ADDRS;
569  break;
570  case ARM::t2BR_JT:
571  JTOpcode = ARM::JUMPTABLE_INSTS;
572  break;
573  case ARM::tTBB_JT:
574  case ARM::t2TBB_JT:
575  JTOpcode = ARM::JUMPTABLE_TBB;
576  break;
577  case ARM::tTBH_JT:
578  case ARM::t2TBH_JT:
579  JTOpcode = ARM::JUMPTABLE_TBH;
580  break;
581  }
582 
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))
592  .addImm(i++)
593  .addJumpTableIndex(JTI)
594  .addImm(Size);
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;
600  }
601 
602  // If we did anything then we need to renumber the subsequent blocks.
603  if (LastCorrectlyNumberedBB)
604  MF->RenumberBlocks(LastCorrectlyNumberedBB);
605 }
606 
607 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
608 /// into the block immediately after it.
610  // Get the next machine basic block in the function.
612  // Can't fall off end of function.
613  if (std::next(MBBI) == MBB->getParent()->end())
614  return false;
615 
616  MachineBasicBlock *NextBB = &*std::next(MBBI);
617  if (!MBB->isSuccessor(NextBB))
618  return false;
619 
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;
624  bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
625  return TooDifficult || FBB == nullptr;
626 }
627 
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
635  // linear search.
636  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
637  if (CPEs[i].CPEMI == CPEMI)
638  return &CPEs[i];
639  }
640  return nullptr;
641 }
642 
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:
648  break;
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:
654  return 1;
655  case ARM::JUMPTABLE_ADDRS:
656  return 2;
657  default:
658  llvm_unreachable("unknown constpool entry kind");
659  }
660 
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);
666 }
667 
668 /// scanFunctionJumpTables - Do a scan of the function, building up
669 /// information about the sizes of each block and the locations of all
670 /// the jump tables.
671 void ARMConstantIslands::scanFunctionJumpTables() {
672  for (MachineBasicBlock &MBB : *MF) {
673  for (MachineInstr &I : MBB)
674  if (I.isBranch() &&
675  (I.getOpcode() == ARM::t2BR_JT || I.getOpcode() == ARM::tBR_JTr))
676  T2JumpTables.push_back(&I);
677  }
678 }
679 
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) {
685 
686  BBInfo = computeAllBlockSizes(MF);
687 
688  // The known bits of the entry block offset are determined by the function
689  // alignment.
690  BBInfo.front().KnownBits = MF->getAlignment();
691 
692  // Compute block offsets and known bits.
693  adjustBBOffsetsAfter(&MF->front());
694 
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);
701 
702  for (MachineInstr &I : MBB) {
703  if (I.isDebugInstr())
704  continue;
705 
706  unsigned Opc = I.getOpcode();
707  if (I.isBranch()) {
708  bool isCond = false;
709  unsigned Bits = 0;
710  unsigned Scale = 1;
711  int UOpc = Opc;
712  switch (Opc) {
713  default:
714  continue; // Ignore other JT branches
715  case ARM::t2BR_JT:
716  case ARM::tBR_JTr:
717  T2JumpTables.push_back(&I);
718  continue; // Does not get an entry in ImmBranches
719  case ARM::Bcc:
720  isCond = true;
721  UOpc = ARM::B;
723  case ARM::B:
724  Bits = 24;
725  Scale = 4;
726  break;
727  case ARM::tBcc:
728  isCond = true;
729  UOpc = ARM::tB;
730  Bits = 8;
731  Scale = 2;
732  break;
733  case ARM::tB:
734  Bits = 11;
735  Scale = 2;
736  break;
737  case ARM::t2Bcc:
738  isCond = true;
739  UOpc = ARM::t2B;
740  Bits = 20;
741  Scale = 2;
742  break;
743  case ARM::t2B:
744  Bits = 24;
745  Scale = 2;
746  break;
747  }
748 
749  // Record this immediate branch.
750  unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
751  ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc));
752  }
753 
754  if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET)
755  PushPopMIs.push_back(&I);
756 
757  if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS ||
758  Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB ||
759  Opc == ARM::JUMPTABLE_TBH)
760  continue;
761 
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.
767 
768  // Basic size info comes from the TSFlags field.
769  unsigned Bits = 0;
770  unsigned Scale = 1;
771  bool NegOk = false;
772  bool IsSoImm = false;
773 
774  switch (Opc) {
775  default:
776  llvm_unreachable("Unknown addressing mode for CP reference!");
777 
778  // Taking the address of a CP entry.
779  case ARM::LEApcrel:
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.
785  Bits = 8;
786  Scale = 4;
787  NegOk = true;
788  IsSoImm = true;
789  break;
790  case ARM::t2LEApcrel:
791  case ARM::t2LEApcrelJT:
792  Bits = 12;
793  NegOk = true;
794  break;
795  case ARM::tLEApcrel:
796  case ARM::tLEApcrelJT:
797  Bits = 8;
798  Scale = 4;
799  break;
800 
801  case ARM::LDRBi12:
802  case ARM::LDRi12:
803  case ARM::LDRcp:
804  case ARM::t2LDRpci:
805  case ARM::t2LDRHpci:
806  case ARM::t2LDRBpci:
807  Bits = 12; // +-offset_12
808  NegOk = true;
809  break;
810 
811  case ARM::tLDRpci:
812  Bits = 8;
813  Scale = 4; // +(offset_8*4)
814  break;
815 
816  case ARM::VLDRD:
817  case ARM::VLDRS:
818  Bits = 8;
819  Scale = 4; // +-(offset_8*4)
820  NegOk = true;
821  break;
822  case ARM::VLDRH:
823  Bits = 8;
824  Scale = 2; // +-(offset_8*2)
825  NegOk = true;
826  break;
827 
828  case ARM::tLDRHi:
829  Bits = 5;
830  Scale = 2; // +(offset_5*2)
831  break;
832  }
833 
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];
839  }
840 
841  MachineInstr *CPEMI = CPEMIs[CPI];
842  unsigned MaxOffs = ((1 << Bits)-1) * Scale;
843  CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm));
844 
845  // Increment corresponding CPEntry reference count.
846  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
847  assert(CPE && "Cannot find a corresponding CPEntry!");
848  CPE->RefCount++;
849 
850  // Instructions can only use one CP entry, don't bother scanning the
851  // rest of the operands.
852  break;
853  }
854  }
855  }
856 }
857 
858 /// getOffsetOf - Return the current offset of the specified machine instruction
859 /// from the start of the function. This offset changes as stuff is moved
860 /// around inside the function.
861 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const {
862  MachineBasicBlock *MBB = MI->getParent();
863 
864  // The offset is composed of two things: the sum of the sizes of all MBB's
865  // before this instruction's block, and the offset from the start of the block
866  // it is in.
867  unsigned Offset = BBInfo[MBB->getNumber()].Offset;
868 
869  // Sum instructions before MI in MBB.
870  for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
871  assert(I != MBB->end() && "Didn't find MI in its own basic block?");
872  Offset += TII->getInstSizeInBytes(*I);
873  }
874  return Offset;
875 }
876 
877 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB
878 /// ID.
879 static bool CompareMBBNumbers(const MachineBasicBlock *LHS,
880  const MachineBasicBlock *RHS) {
881  return LHS->getNumber() < RHS->getNumber();
882 }
883 
884 /// updateForInsertedWaterBlock - When a block is newly inserted into the
885 /// machine function, it upsets all of the block numbers. Renumber the blocks
886 /// and update the arrays that parallel this numbering.
887 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) {
888  // Renumber the MBB's to keep them consecutive.
889  NewBB->getParent()->RenumberBlocks(NewBB);
890 
891  // Insert an entry into BBInfo to align it properly with the (newly
892  // renumbered) block numbers.
893  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
894 
895  // Next, update WaterList. Specifically, we need to add NewMBB as having
896  // available water after it.
897  water_iterator IP =
898  std::lower_bound(WaterList.begin(), WaterList.end(), NewBB,
900  WaterList.insert(IP, NewBB);
901 }
902 
903 /// Split the basic block containing MI into two blocks, which are joined by
904 /// an unconditional branch. Update data structures and renumber blocks to
905 /// account for this change and returns the newly created block.
906 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) {
907  MachineBasicBlock *OrigBB = MI->getParent();
908 
909  // Create a new MBB for the code after the OrigBB.
910  MachineBasicBlock *NewBB =
911  MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
912  MachineFunction::iterator MBBI = ++OrigBB->getIterator();
913  MF->insert(MBBI, NewBB);
914 
915  // Splice the instructions starting with MI over to NewBB.
916  NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
917 
918  // Add an unconditional branch from OrigBB to NewBB.
919  // Note the new unconditional branch is not being recorded.
920  // There doesn't seem to be meaningful DebugInfo available; this doesn't
921  // correspond to anything in the source.
922  unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B;
923  if (!isThumb)
924  BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB);
925  else
926  BuildMI(OrigBB, DebugLoc(), TII->get(Opc))
927  .addMBB(NewBB)
928  .add(predOps(ARMCC::AL));
929  ++NumSplit;
930 
931  // Update the CFG. All succs of OrigBB are now succs of NewBB.
932  NewBB->transferSuccessors(OrigBB);
933 
934  // OrigBB branches to NewBB.
935  OrigBB->addSuccessor(NewBB);
936 
937  // Update internal data structures to account for the newly inserted MBB.
938  // This is almost the same as updateForInsertedWaterBlock, except that
939  // the Water goes after OrigBB, not NewBB.
940  MF->RenumberBlocks(NewBB);
941 
942  // Insert an entry into BBInfo to align it properly with the (newly
943  // renumbered) block numbers.
944  BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
945 
946  // Next, update WaterList. Specifically, we need to add OrigMBB as having
947  // available water after it (but not if it's already there, which happens
948  // when splitting before a conditional branch that is followed by an
949  // unconditional branch - in that case we want to insert NewBB).
950  water_iterator IP =
951  std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB,
953  MachineBasicBlock* WaterBB = *IP;
954  if (WaterBB == OrigBB)
955  WaterList.insert(std::next(IP), NewBB);
956  else
957  WaterList.insert(IP, OrigBB);
958  NewWaterList.insert(OrigBB);
959 
960  // Figure out how large the OrigBB is. As the first half of the original
961  // block, it cannot contain a tablejump. The size includes
962  // the new jump we added. (It should be possible to do this without
963  // recounting everything, but it's very confusing, and this is rarely
964  // executed.)
965  computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]);
966 
967  // Figure out how large the NewMBB is. As the second half of the original
968  // block, it may contain a tablejump.
969  computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]);
970 
971  // All BBOffsets following these blocks must be modified.
972  adjustBBOffsetsAfter(OrigBB);
973 
974  return NewBB;
975 }
976 
977 /// getUserOffset - Compute the offset of U.MI as seen by the hardware
978 /// displacement computation. Update U.KnownAlignment to match its current
979 /// basic block location.
980 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const {
981  unsigned UserOffset = getOffsetOf(U.MI);
982  const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()];
983  unsigned KnownBits = BBI.internalKnownBits();
984 
985  // The value read from PC is offset from the actual instruction address.
986  UserOffset += (isThumb ? 4 : 8);
987 
988  // Because of inline assembly, we may not know the alignment (mod 4) of U.MI.
989  // Make sure U.getMaxDisp() returns a constrained range.
990  U.KnownAlignment = (KnownBits >= 2);
991 
992  // On Thumb, offsets==2 mod 4 are rounded down by the hardware for
993  // purposes of the displacement computation; compensate for that here.
994  // For unknown alignments, getMaxDisp() constrains the range instead.
995  if (isThumb && U.KnownAlignment)
996  UserOffset &= ~3u;
997 
998  return UserOffset;
999 }
1000 
1001 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool
1002 /// reference) is within MaxDisp of TrialOffset (a proposed location of a
1003 /// constant pool entry).
1004 /// UserOffset is computed by getUserOffset above to include PC adjustments. If
1005 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be
1006 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that.
1007 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset,
1008  unsigned TrialOffset, unsigned MaxDisp,
1009  bool NegativeOK, bool IsSoImm) {
1010  if (UserOffset <= TrialOffset) {
1011  // User before the Trial.
1012  if (TrialOffset - UserOffset <= MaxDisp)
1013  return true;
1014  // FIXME: Make use full range of soimm values.
1015  } else if (NegativeOK) {
1016  if (UserOffset - TrialOffset <= MaxDisp)
1017  return true;
1018  // FIXME: Make use full range of soimm values.
1019  }
1020  return false;
1021 }
1022 
1023 /// isWaterInRange - Returns true if a CPE placed after the specified
1024 /// Water (a basic block) will be in range for the specific MI.
1025 ///
1026 /// Compute how much the function will grow by inserting a CPE after Water.
1027 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset,
1028  MachineBasicBlock* Water, CPUser &U,
1029  unsigned &Growth) {
1030  unsigned CPELogAlign = getCPELogAlign(U.CPEMI);
1031  unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign);
1032  unsigned NextBlockOffset, NextBlockAlignment;
1033  MachineFunction::const_iterator NextBlock = Water->getIterator();
1034  if (++NextBlock == MF->end()) {
1035  NextBlockOffset = BBInfo[Water->getNumber()].postOffset();
1036  NextBlockAlignment = 0;
1037  } else {
1038  NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset;
1039  NextBlockAlignment = NextBlock->getAlignment();
1040  }
1041  unsigned Size = U.CPEMI->getOperand(2).getImm();
1042  unsigned CPEEnd = CPEOffset + Size;
1043 
1044  // The CPE may be able to hide in the alignment padding before the next
1045  // block. It may also cause more padding to be required if it is more aligned
1046  // that the next block.
1047  if (CPEEnd > NextBlockOffset) {
1048  Growth = CPEEnd - NextBlockOffset;
1049  // Compute the padding that would go at the end of the CPE to align the next
1050  // block.
1051  Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment);
1052 
1053  // If the CPE is to be inserted before the instruction, that will raise
1054  // the offset of the instruction. Also account for unknown alignment padding
1055  // in blocks between CPE and the user.
1056  if (CPEOffset < UserOffset)
1057  UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign);
1058  } else
1059  // CPE fits in existing padding.
1060  Growth = 0;
1061 
1062  return isOffsetInRange(UserOffset, CPEOffset, U);
1063 }
1064 
1065 /// isCPEntryInRange - Returns true if the distance between specific MI and
1066 /// specific ConstPool entry instruction can fit in MI's displacement field.
1067 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset,
1068  MachineInstr *CPEMI, unsigned MaxDisp,
1069  bool NegOk, bool DoDump) {
1070  unsigned CPEOffset = getOffsetOf(CPEMI);
1071 
1072  if (DoDump) {
1073  LLVM_DEBUG({
1074  unsigned Block = MI->getParent()->getNumber();
1075  const BasicBlockInfo &BBI = BBInfo[Block];
1076  dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm()
1077  << " max delta=" << MaxDisp
1078  << format(" insn address=%#x", UserOffset) << " in "
1079  << printMBBReference(*MI->getParent()) << ": "
1080  << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI
1081  << format("CPE address=%#x offset=%+d: ", CPEOffset,
1082  int(CPEOffset - UserOffset));
1083  });
1084  }
1085 
1086  return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk);
1087 }
1088 
1089 #ifndef NDEBUG
1090 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor
1091 /// unconditionally branches to its only successor.
1093  if (MBB->pred_size() != 1 || MBB->succ_size() != 1)
1094  return false;
1095 
1096  MachineBasicBlock *Succ = *MBB->succ_begin();
1097  MachineBasicBlock *Pred = *MBB->pred_begin();
1098  MachineInstr *PredMI = &Pred->back();
1099  if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB
1100  || PredMI->getOpcode() == ARM::t2B)
1101  return PredMI->getOperand(0).getMBB() == Succ;
1102  return false;
1103 }
1104 #endif // NDEBUG
1105 
1106 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) {
1107  unsigned BBNum = BB->getNumber();
1108  for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) {
1109  // Get the offset and known bits at the end of the layout predecessor.
1110  // Include the alignment of the current block.
1111  unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment();
1112  unsigned Offset = BBInfo[i - 1].postOffset(LogAlign);
1113  unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign);
1114 
1115  // This is where block i begins. Stop if the offset is already correct,
1116  // and we have updated 2 blocks. This is the maximum number of blocks
1117  // changed before calling this function.
1118  if (i > BBNum + 2 &&
1119  BBInfo[i].Offset == Offset &&
1120  BBInfo[i].KnownBits == KnownBits)
1121  break;
1122 
1123  BBInfo[i].Offset = Offset;
1124  BBInfo[i].KnownBits = KnownBits;
1125  }
1126 }
1127 
1128 /// decrementCPEReferenceCount - find the constant pool entry with index CPI
1129 /// and instruction CPEMI, and decrement its refcount. If the refcount
1130 /// becomes 0 remove the entry and instruction. Returns true if we removed
1131 /// the entry, false if we didn't.
1132 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI,
1133  MachineInstr *CPEMI) {
1134  // Find the old entry. Eliminate it if it is no longer used.
1135  CPEntry *CPE = findConstPoolEntry(CPI, CPEMI);
1136  assert(CPE && "Unexpected!");
1137  if (--CPE->RefCount == 0) {
1138  removeDeadCPEMI(CPEMI);
1139  CPE->CPEMI = nullptr;
1140  --NumCPEs;
1141  return true;
1142  }
1143  return false;
1144 }
1145 
1146 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) {
1147  if (CPEMI->getOperand(1).isCPI())
1148  return CPEMI->getOperand(1).getIndex();
1149 
1150  return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()];
1151 }
1152 
1153 /// LookForCPEntryInRange - see if the currently referenced CPE is in range;
1154 /// if not, see if an in-range clone of the CPE is in range, and if so,
1155 /// change the data structures so the user references the clone. Returns:
1156 /// 0 = no existing entry found
1157 /// 1 = entry found, and there were no code insertions or deletions
1158 /// 2 = entry found, and there were code insertions or deletions
1159 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) {
1160  MachineInstr *UserMI = U.MI;
1161  MachineInstr *CPEMI = U.CPEMI;
1162 
1163  // Check to see if the CPE is already in-range.
1164  if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk,
1165  true)) {
1166  LLVM_DEBUG(dbgs() << "In range\n");
1167  return 1;
1168  }
1169 
1170  // No. Look for previously created clones of the CPE that are in range.
1171  unsigned CPI = getCombinedIndex(CPEMI);
1172  std::vector<CPEntry> &CPEs = CPEntries[CPI];
1173  for (unsigned i = 0, e = CPEs.size(); i != e; ++i) {
1174  // We already tried this one
1175  if (CPEs[i].CPEMI == CPEMI)
1176  continue;
1177  // Removing CPEs can leave empty entries, skip
1178  if (CPEs[i].CPEMI == nullptr)
1179  continue;
1180  if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(),
1181  U.NegOk)) {
1182  LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#"
1183  << CPEs[i].CPI << "\n");
1184  // Point the CPUser node to the replacement
1185  U.CPEMI = CPEs[i].CPEMI;
1186  // Change the CPI in the instruction operand to refer to the clone.
1187  for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j)
1188  if (UserMI->getOperand(j).isCPI()) {
1189  UserMI->getOperand(j).setIndex(CPEs[i].CPI);
1190  break;
1191  }
1192  // Adjust the refcount of the clone...
1193  CPEs[i].RefCount++;
1194  // ...and the original. If we didn't remove the old entry, none of the
1195  // addresses changed, so we don't need another pass.
1196  return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1;
1197  }
1198  }
1199  return 0;
1200 }
1201 
1202 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in
1203 /// the specific unconditional branch instruction.
1204 static inline unsigned getUnconditionalBrDisp(int Opc) {
1205  switch (Opc) {
1206  case ARM::tB:
1207  return ((1<<10)-1)*2;
1208  case ARM::t2B:
1209  return ((1<<23)-1)*2;
1210  default:
1211  break;
1212  }
1213 
1214  return ((1<<23)-1)*4;
1215 }
1216 
1217 /// findAvailableWater - Look for an existing entry in the WaterList in which
1218 /// we can place the CPE referenced from U so it's within range of U's MI.
1219 /// Returns true if found, false if not. If it returns true, WaterIter
1220 /// is set to the WaterList entry. For Thumb, prefer water that will not
1221 /// introduce padding to water that will. To ensure that this pass
1222 /// terminates, the CPE location for a particular CPUser is only allowed to
1223 /// move to a lower address, so search backward from the end of the list and
1224 /// prefer the first water that is in range.
1225 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset,
1226  water_iterator &WaterIter,
1227  bool CloserWater) {
1228  if (WaterList.empty())
1229  return false;
1230 
1231  unsigned BestGrowth = ~0u;
1232  // The nearest water without splitting the UserBB is right after it.
1233  // If the distance is still large (we have a big BB), then we need to split it
1234  // if we don't converge after certain iterations. This helps the following
1235  // situation to converge:
1236  // BB0:
1237  // Big BB
1238  // BB1:
1239  // Constant Pool
1240  // When a CP access is out of range, BB0 may be used as water. However,
1241  // inserting islands between BB0 and BB1 makes other accesses out of range.
1242  MachineBasicBlock *UserBB = U.MI->getParent();
1243  unsigned MinNoSplitDisp =
1244  BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI));
1245  if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2)
1246  return false;
1247  for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();;
1248  --IP) {
1249  MachineBasicBlock* WaterBB = *IP;
1250  // Check if water is in range and is either at a lower address than the
1251  // current "high water mark" or a new water block that was created since
1252  // the previous iteration by inserting an unconditional branch. In the
1253  // latter case, we want to allow resetting the high water mark back to
1254  // this new water since we haven't seen it before. Inserting branches
1255  // should be relatively uncommon and when it does happen, we want to be
1256  // sure to take advantage of it for all the CPEs near that block, so that
1257  // we don't insert more branches than necessary.
1258  // When CloserWater is true, we try to find the lowest address after (or
1259  // equal to) user MI's BB no matter of padding growth.
1260  unsigned Growth;
1261  if (isWaterInRange(UserOffset, WaterBB, U, Growth) &&
1262  (WaterBB->getNumber() < U.HighWaterMark->getNumber() ||
1263  NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) &&
1264  Growth < BestGrowth) {
1265  // This is the least amount of required padding seen so far.
1266  BestGrowth = Growth;
1267  WaterIter = IP;
1268  LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB)
1269  << " Growth=" << Growth << '\n');
1270 
1271  if (CloserWater && WaterBB == U.MI->getParent())
1272  return true;
1273  // Keep looking unless it is perfect and we're not looking for the lowest
1274  // possible address.
1275  if (!CloserWater && BestGrowth == 0)
1276  return true;
1277  }
1278  if (IP == B)
1279  break;
1280  }
1281  return BestGrowth != ~0u;
1282 }
1283 
1284 /// createNewWater - No existing WaterList entry will work for
1285 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the
1286 /// block is used if in range, and the conditional branch munged so control
1287 /// flow is correct. Otherwise the block is split to create a hole with an
1288 /// unconditional branch around it. In either case NewMBB is set to a
1289 /// block following which the new island can be inserted (the WaterList
1290 /// is not adjusted).
1291 void ARMConstantIslands::createNewWater(unsigned CPUserIndex,
1292  unsigned UserOffset,
1293  MachineBasicBlock *&NewMBB) {
1294  CPUser &U = CPUsers[CPUserIndex];
1295  MachineInstr *UserMI = U.MI;
1296  MachineInstr *CPEMI = U.CPEMI;
1297  unsigned CPELogAlign = getCPELogAlign(CPEMI);
1298  MachineBasicBlock *UserMBB = UserMI->getParent();
1299  const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()];
1300 
1301  // If the block does not end in an unconditional branch already, and if the
1302  // end of the block is within range, make new water there. (The addition
1303  // below is for the unconditional branch we will be adding: 4 bytes on ARM +
1304  // Thumb2, 2 on Thumb1.
1305  if (BBHasFallthrough(UserMBB)) {
1306  // Size of branch to insert.
1307  unsigned Delta = isThumb1 ? 2 : 4;
1308  // Compute the offset where the CPE will begin.
1309  unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta;
1310 
1311  if (isOffsetInRange(UserOffset, CPEOffset, U)) {
1312  LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB)
1313  << format(", expected CPE offset %#x\n", CPEOffset));
1314  NewMBB = &*++UserMBB->getIterator();
1315  // Add an unconditional branch from UserMBB to fallthrough block. Record
1316  // it for branch lengthening; this new branch will not get out of range,
1317  // but if the preceding conditional branch is out of range, the targets
1318  // will be exchanged, and the altered branch may be out of range, so the
1319  // machinery has to know about it.
1320  int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B;
1321  if (!isThumb)
1322  BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB);
1323  else
1324  BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr))
1325  .addMBB(NewMBB)
1326  .add(predOps(ARMCC::AL));
1327  unsigned MaxDisp = getUnconditionalBrDisp(UncondBr);
1328  ImmBranches.push_back(ImmBranch(&UserMBB->back(),
1329  MaxDisp, false, UncondBr));
1330  computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]);
1331  adjustBBOffsetsAfter(UserMBB);
1332  return;
1333  }
1334  }
1335 
1336  // What a big block. Find a place within the block to split it. This is a
1337  // little tricky on Thumb1 since instructions are 2 bytes and constant pool
1338  // entries are 4 bytes: if instruction I references island CPE, and
1339  // instruction I+1 references CPE', it will not work well to put CPE as far
1340  // forward as possible, since then CPE' cannot immediately follow it (that
1341  // location is 2 bytes farther away from I+1 than CPE was from I) and we'd
1342  // need to create a new island. So, we make a first guess, then walk through
1343  // the instructions between the one currently being looked at and the
1344  // possible insertion point, and make sure any other instructions that
1345  // reference CPEs will be able to use the same island area; if not, we back
1346  // up the insertion point.
1347 
1348  // Try to split the block so it's fully aligned. Compute the latest split
1349  // point where we can add a 4-byte branch instruction, and then align to
1350  // LogAlign which is the largest possible alignment in the function.
1351  unsigned LogAlign = MF->getAlignment();
1352  assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry");
1353  unsigned KnownBits = UserBBI.internalKnownBits();
1354  unsigned UPad = UnknownPadding(LogAlign, KnownBits);
1355  unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad;
1356  LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x",
1357  BaseInsertOffset));
1358 
1359  // The 4 in the following is for the unconditional branch we'll be inserting
1360  // (allows for long branch on Thumb1). Alignment of the island is handled
1361  // inside isOffsetInRange.
1362  BaseInsertOffset -= 4;
1363 
1364  LLVM_DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset)
1365  << " la=" << LogAlign << " kb=" << KnownBits
1366  << " up=" << UPad << '\n');
1367 
1368  // This could point off the end of the block if we've already got constant
1369  // pool entries following this block; only the last one is in the water list.
1370  // Back past any possible branches (allow for a conditional and a maximally
1371  // long unconditional).
1372  if (BaseInsertOffset + 8 >= UserBBI.postOffset()) {
1373  // Ensure BaseInsertOffset is larger than the offset of the instruction
1374  // following UserMI so that the loop which searches for the split point
1375  // iterates at least once.
1376  BaseInsertOffset =
1377  std::max(UserBBI.postOffset() - UPad - 8,
1378  UserOffset + TII->getInstSizeInBytes(*UserMI) + 1);
1379  LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset));
1380  }
1381  unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad +
1382  CPEMI->getOperand(2).getImm();
1383  MachineBasicBlock::iterator MI = UserMI;
1384  ++MI;
1385  unsigned CPUIndex = CPUserIndex+1;
1386  unsigned NumCPUsers = CPUsers.size();
1387  MachineInstr *LastIT = nullptr;
1388  for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI);
1389  Offset < BaseInsertOffset;
1390  Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) {
1391  assert(MI != UserMBB->end() && "Fell off end of block");
1392  if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) {
1393  CPUser &U = CPUsers[CPUIndex];
1394  if (!isOffsetInRange(Offset, EndInsertOffset, U)) {
1395  // Shift intertion point by one unit of alignment so it is within reach.
1396  BaseInsertOffset -= 1u << LogAlign;
1397  EndInsertOffset -= 1u << LogAlign;
1398  }
1399  // This is overly conservative, as we don't account for CPEMIs being
1400  // reused within the block, but it doesn't matter much. Also assume CPEs
1401  // are added in order with alignment padding. We may eventually be able
1402  // to pack the aligned CPEs better.
1403  EndInsertOffset += U.CPEMI->getOperand(2).getImm();
1404  CPUIndex++;
1405  }
1406 
1407  // Remember the last IT instruction.
1408  if (MI->getOpcode() == ARM::t2IT)
1409  LastIT = &*MI;
1410  }
1411 
1412  --MI;
1413 
1414  // Avoid splitting an IT block.
1415  if (LastIT) {
1416  unsigned PredReg = 0;
1417  ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg);
1418  if (CC != ARMCC::AL)
1419  MI = LastIT;
1420  }
1421 
1422  // Avoid splitting a MOVW+MOVT pair with a relocation on Windows.
1423  // On Windows, this instruction pair is covered by one single
1424  // IMAGE_REL_ARM_MOV32T relocation which covers both instructions. If a
1425  // constant island is injected inbetween them, the relocation will clobber
1426  // the instruction and fail to update the MOVT instruction.
1427  // (These instructions are bundled up until right before the ConstantIslands
1428  // pass.)
1429  if (STI->isTargetWindows() && isThumb && MI->getOpcode() == ARM::t2MOVTi16 &&
1430  (MI->getOperand(2).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1431  ARMII::MO_HI16) {
1432  --MI;
1433  assert(MI->getOpcode() == ARM::t2MOVi16 &&
1434  (MI->getOperand(1).getTargetFlags() & ARMII::MO_OPTION_MASK) ==
1435  ARMII::MO_LO16);
1436  }
1437 
1438  // We really must not split an IT block.
1439  LLVM_DEBUG(unsigned PredReg; assert(
1440  !isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL));
1441 
1442  NewMBB = splitBlockBeforeInstr(&*MI);
1443 }
1444 
1445 /// handleConstantPoolUser - Analyze the specified user, checking to see if it
1446 /// is out-of-range. If so, pick up the constant pool value and move it some
1447 /// place in-range. Return true if we changed any addresses (thus must run
1448 /// another pass of branch lengthening), false otherwise.
1449 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex,
1450  bool CloserWater) {
1451  CPUser &U = CPUsers[CPUserIndex];
1452  MachineInstr *UserMI = U.MI;
1453  MachineInstr *CPEMI = U.CPEMI;
1454  unsigned CPI = getCombinedIndex(CPEMI);
1455  unsigned Size = CPEMI->getOperand(2).getImm();
1456  // Compute this only once, it's expensive.
1457  unsigned UserOffset = getUserOffset(U);
1458 
1459  // See if the current entry is within range, or there is a clone of it
1460  // in range.
1461  int result = findInRangeCPEntry(U, UserOffset);
1462  if (result==1) return false;
1463  else if (result==2) return true;
1464 
1465  // No existing clone of this CPE is within range.
1466  // We will be generating a new clone. Get a UID for it.
1467  unsigned ID = AFI->createPICLabelUId();
1468 
1469  // Look for water where we can place this CPE.
1470  MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock();
1471  MachineBasicBlock *NewMBB;
1472  water_iterator IP;
1473  if (findAvailableWater(U, UserOffset, IP, CloserWater)) {
1474  LLVM_DEBUG(dbgs() << "Found water in range\n");
1475  MachineBasicBlock *WaterBB = *IP;
1476 
1477  // If the original WaterList entry was "new water" on this iteration,
1478  // propagate that to the new island. This is just keeping NewWaterList
1479  // updated to match the WaterList, which will be updated below.
1480  if (NewWaterList.erase(WaterBB))
1481  NewWaterList.insert(NewIsland);
1482 
1483  // The new CPE goes before the following block (NewMBB).
1484  NewMBB = &*++WaterBB->getIterator();
1485  } else {
1486  // No water found.
1487  LLVM_DEBUG(dbgs() << "No water found\n");
1488  createNewWater(CPUserIndex, UserOffset, NewMBB);
1489 
1490  // splitBlockBeforeInstr adds to WaterList, which is important when it is
1491  // called while handling branches so that the water will be seen on the
1492  // next iteration for constant pools, but in this context, we don't want
1493  // it. Check for this so it will be removed from the WaterList.
1494  // Also remove any entry from NewWaterList.
1495  MachineBasicBlock *WaterBB = &*--NewMBB->getIterator();
1496  IP = find(WaterList, WaterBB);
1497  if (IP != WaterList.end())
1498  NewWaterList.erase(WaterBB);
1499 
1500  // We are adding new water. Update NewWaterList.
1501  NewWaterList.insert(NewIsland);
1502  }
1503  // Always align the new block because CP entries can be smaller than 4
1504  // bytes. Be careful not to decrease the existing alignment, e.g. NewMBB may
1505  // be an already aligned constant pool block.
1506  const unsigned Align = isThumb ? 1 : 2;
1507  if (NewMBB->getAlignment() < Align)
1508  NewMBB->setAlignment(Align);
1509 
1510  // Remove the original WaterList entry; we want subsequent insertions in
1511  // this vicinity to go after the one we're about to insert. This
1512  // considerably reduces the number of times we have to move the same CPE
1513  // more than once and is also important to ensure the algorithm terminates.
1514  if (IP != WaterList.end())
1515  WaterList.erase(IP);
1516 
1517  // Okay, we know we can put an island before NewMBB now, do it!
1518  MF->insert(NewMBB->getIterator(), NewIsland);
1519 
1520  // Update internal data structures to account for the newly inserted MBB.
1521  updateForInsertedWaterBlock(NewIsland);
1522 
1523  // Now that we have an island to add the CPE to, clone the original CPE and
1524  // add it to the island.
1525  U.HighWaterMark = NewIsland;
1526  U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc())
1527  .addImm(ID)
1528  .add(CPEMI->getOperand(1))
1529  .addImm(Size);
1530  CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1));
1531  ++NumCPEs;
1532 
1533  // Decrement the old entry, and remove it if refcount becomes 0.
1534  decrementCPEReferenceCount(CPI, CPEMI);
1535 
1536  // Mark the basic block as aligned as required by the const-pool entry.
1537  NewIsland->setAlignment(getCPELogAlign(U.CPEMI));
1538 
1539  // Increase the size of the island block to account for the new entry.
1540  BBInfo[NewIsland->getNumber()].Size += Size;
1541  adjustBBOffsetsAfter(&*--NewIsland->getIterator());
1542 
1543  // Finally, change the CPI in the instruction operand to be ID.
1544  for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i)
1545  if (UserMI->getOperand(i).isCPI()) {
1546  UserMI->getOperand(i).setIndex(ID);
1547  break;
1548  }
1549 
1550  LLVM_DEBUG(
1551  dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI
1552  << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset));
1553 
1554  return true;
1555 }
1556 
1557 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update
1558 /// sizes and offsets of impacted basic blocks.
1559 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) {
1560  MachineBasicBlock *CPEBB = CPEMI->getParent();
1561  unsigned Size = CPEMI->getOperand(2).getImm();
1562  CPEMI->eraseFromParent();
1563  BBInfo[CPEBB->getNumber()].Size -= Size;
1564  // All succeeding offsets have the current size value added in, fix this.
1565  if (CPEBB->empty()) {
1566  BBInfo[CPEBB->getNumber()].Size = 0;
1567 
1568  // This block no longer needs to be aligned.
1569  CPEBB->setAlignment(0);
1570  } else
1571  // Entries are sorted by descending alignment, so realign from the front.
1572  CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin()));
1573 
1574  adjustBBOffsetsAfter(CPEBB);
1575  // An island has only one predecessor BB and one successor BB. Check if
1576  // this BB's predecessor jumps directly to this BB's successor. This
1577  // shouldn't happen currently.
1578  assert(!BBIsJumpedOver(CPEBB) && "How did this happen?");
1579  // FIXME: remove the empty blocks after all the work is done?
1580 }
1581 
1582 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts
1583 /// are zero.
1584 bool ARMConstantIslands::removeUnusedCPEntries() {
1585  unsigned MadeChange = false;
1586  for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) {
1587  std::vector<CPEntry> &CPEs = CPEntries[i];
1588  for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) {
1589  if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) {
1590  removeDeadCPEMI(CPEs[j].CPEMI);
1591  CPEs[j].CPEMI = nullptr;
1592  MadeChange = true;
1593  }
1594  }
1595  }
1596  return MadeChange;
1597 }
1598 
1599 /// isBBInRange - Returns true if the distance between specific MI and
1600 /// specific BB can fit in MI's displacement field.
1601 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB,
1602  unsigned MaxDisp) {
1603  unsigned PCAdj = isThumb ? 4 : 8;
1604  unsigned BrOffset = getOffsetOf(MI) + PCAdj;
1605  unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1606 
1607  LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB)
1608  << " from " << printMBBReference(*MI->getParent())
1609  << " max delta=" << MaxDisp << " from " << getOffsetOf(MI)
1610  << " to " << DestOffset << " offset "
1611  << int(DestOffset - BrOffset) << "\t" << *MI);
1612 
1613  if (BrOffset <= DestOffset) {
1614  // Branch before the Dest.
1615  if (DestOffset-BrOffset <= MaxDisp)
1616  return true;
1617  } else {
1618  if (BrOffset-DestOffset <= MaxDisp)
1619  return true;
1620  }
1621  return false;
1622 }
1623 
1624 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far
1625 /// away to fit in its displacement field.
1626 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) {
1627  MachineInstr *MI = Br.MI;
1628  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1629 
1630  // Check to see if the DestBB is already in-range.
1631  if (isBBInRange(MI, DestBB, Br.MaxDisp))
1632  return false;
1633 
1634  if (!Br.isCond)
1635  return fixupUnconditionalBr(Br);
1636  return fixupConditionalBr(Br);
1637 }
1638 
1639 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is
1640 /// too far away to fit in its displacement field. If the LR register has been
1641 /// spilled in the epilogue, then we can use BL to implement a far jump.
1642 /// Otherwise, add an intermediate branch instruction to a branch.
1643 bool
1644 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) {
1645  MachineInstr *MI = Br.MI;
1646  MachineBasicBlock *MBB = MI->getParent();
1647  if (!isThumb1)
1648  llvm_unreachable("fixupUnconditionalBr is Thumb1 only!");
1649 
1650  if (!AFI->isLRSpilled())
1651  report_fatal_error("underestimated function size");
1652 
1653  // Use BL to implement far jump.
1654  Br.MaxDisp = (1 << 21) * 2;
1655  MI->setDesc(TII->get(ARM::tBfar));
1656  BBInfo[MBB->getNumber()].Size += 2;
1657  adjustBBOffsetsAfter(MBB);
1658  HasFarJump = true;
1659  ++NumUBrFixed;
1660 
1661  LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI);
1662 
1663  return true;
1664 }
1665 
1666 /// fixupConditionalBr - Fix up a conditional branch whose destination is too
1667 /// far away to fit in its displacement field. It is converted to an inverse
1668 /// conditional branch + an unconditional branch to the destination.
1669 bool
1670 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) {
1671  MachineInstr *MI = Br.MI;
1672  MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
1673 
1674  // Add an unconditional branch to the destination and invert the branch
1675  // condition to jump over it:
1676  // blt L1
1677  // =>
1678  // bge L2
1679  // b L1
1680  // L2:
1682  CC = ARMCC::getOppositeCondition(CC);
1683  unsigned CCReg = MI->getOperand(2).getReg();
1684 
1685  // If the branch is at the end of its MBB and that has a fall-through block,
1686  // direct the updated conditional branch to the fall-through block. Otherwise,
1687  // split the MBB before the next instruction.
1688  MachineBasicBlock *MBB = MI->getParent();
1689  MachineInstr *BMI = &MBB->back();
1690  bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
1691 
1692  ++NumCBrFixed;
1693  if (BMI != MI) {
1694  if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) &&
1695  BMI->getOpcode() == Br.UncondBr) {
1696  // Last MI in the BB is an unconditional branch. Can we simply invert the
1697  // condition and swap destinations:
1698  // beq L1
1699  // b L2
1700  // =>
1701  // bne L2
1702  // b L1
1703  MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
1704  if (isBBInRange(MI, NewDest, Br.MaxDisp)) {
1705  LLVM_DEBUG(
1706  dbgs() << " Invert Bcc condition and swap its destination with "
1707  << *BMI);
1708  BMI->getOperand(0).setMBB(DestBB);
1709  MI->getOperand(0).setMBB(NewDest);
1710  MI->getOperand(1).setImm(CC);
1711  return true;
1712  }
1713  }
1714  }
1715 
1716  if (NeedSplit) {
1717  splitBlockBeforeInstr(MI);
1718  // No need for the branch to the next block. We're adding an unconditional
1719  // branch to the destination.
1720  int delta = TII->getInstSizeInBytes(MBB->back());
1721  BBInfo[MBB->getNumber()].Size -= delta;
1722  MBB->back().eraseFromParent();
1723 
1724  // The conditional successor will be swapped between the BBs after this, so
1725  // update CFG.
1726  MBB->addSuccessor(DestBB);
1727  std::next(MBB->getIterator())->removeSuccessor(DestBB);
1728 
1729  // BBInfo[SplitBB].Offset is wrong temporarily, fixed below
1730  }
1731  MachineBasicBlock *NextBB = &*++MBB->getIterator();
1732 
1733  LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB)
1734  << " also invert condition and change dest. to "
1735  << printMBBReference(*NextBB) << "\n");
1736 
1737  // Insert a new conditional branch and a new unconditional branch.
1738  // Also update the ImmBranch as well as adding a new entry for the new branch.
1739  BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode()))
1740  .addMBB(NextBB).addImm(CC).addReg(CCReg);
1741  Br.MI = &MBB->back();
1742  BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1743  if (isThumb)
1744  BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr))
1745  .addMBB(DestBB)
1746  .add(predOps(ARMCC::AL));
1747  else
1748  BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB);
1749  BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back());
1750  unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr);
1751  ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr));
1752 
1753  // Remove the old conditional branch. It may or may not still be in MBB.
1754  BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI);
1755  MI->eraseFromParent();
1756  adjustBBOffsetsAfter(MBB);
1757  return true;
1758 }
1759 
1760 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills
1761 /// LR / restores LR to pc. FIXME: This is done here because it's only possible
1762 /// to do this if tBfar is not used.
1763 bool ARMConstantIslands::undoLRSpillRestore() {
1764  bool MadeChange = false;
1765  for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) {
1766  MachineInstr *MI = PushPopMIs[i];
1767  // First two operands are predicates.
1768  if (MI->getOpcode() == ARM::tPOP_RET &&
1769  MI->getOperand(2).getReg() == ARM::PC &&
1770  MI->getNumExplicitOperands() == 3) {
1771  // Create the new insn and copy the predicate from the old.
1772  BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET))
1773  .add(MI->getOperand(0))
1774  .add(MI->getOperand(1));
1775  MI->eraseFromParent();
1776  MadeChange = true;
1777  } else if (MI->getOpcode() == ARM::tPUSH &&
1778  MI->getOperand(2).getReg() == ARM::LR &&
1779  MI->getNumExplicitOperands() == 3) {
1780  // Just remove the push.
1781  MI->eraseFromParent();
1782  MadeChange = true;
1783  }
1784  }
1785  return MadeChange;
1786 }
1787 
1788 bool ARMConstantIslands::optimizeThumb2Instructions() {
1789  bool MadeChange = false;
1790 
1791  // Shrink ADR and LDR from constantpool.
1792  for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) {
1793  CPUser &U = CPUsers[i];
1794  unsigned Opcode = U.MI->getOpcode();
1795  unsigned NewOpc = 0;
1796  unsigned Scale = 1;
1797  unsigned Bits = 0;
1798  switch (Opcode) {
1799  default: break;
1800  case ARM::t2LEApcrel:
1801  if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1802  NewOpc = ARM::tLEApcrel;
1803  Bits = 8;
1804  Scale = 4;
1805  }
1806  break;
1807  case ARM::t2LDRpci:
1808  if (isARMLowRegister(U.MI->getOperand(0).getReg())) {
1809  NewOpc = ARM::tLDRpci;
1810  Bits = 8;
1811  Scale = 4;
1812  }
1813  break;
1814  }
1815 
1816  if (!NewOpc)
1817  continue;
1818 
1819  unsigned UserOffset = getUserOffset(U);
1820  unsigned MaxOffs = ((1 << Bits) - 1) * Scale;
1821 
1822  // Be conservative with inline asm.
1823  if (!U.KnownAlignment)
1824  MaxOffs -= 2;
1825 
1826  // FIXME: Check if offset is multiple of scale if scale is not 4.
1827  if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) {
1828  LLVM_DEBUG(dbgs() << "Shrink: " << *U.MI);
1829  U.MI->setDesc(TII->get(NewOpc));
1830  MachineBasicBlock *MBB = U.MI->getParent();
1831  BBInfo[MBB->getNumber()].Size -= 2;
1832  adjustBBOffsetsAfter(MBB);
1833  ++NumT2CPShrunk;
1834  MadeChange = true;
1835  }
1836  }
1837 
1838  return MadeChange;
1839 }
1840 
1841 bool ARMConstantIslands::optimizeThumb2Branches() {
1842  bool MadeChange = false;
1843 
1844  // The order in which branches appear in ImmBranches is approximately their
1845  // order within the function body. By visiting later branches first, we reduce
1846  // the distance between earlier forward branches and their targets, making it
1847  // more likely that the cbn?z optimization, which can only apply to forward
1848  // branches, will succeed.
1849  for (unsigned i = ImmBranches.size(); i != 0; --i) {
1850  ImmBranch &Br = ImmBranches[i-1];
1851  unsigned Opcode = Br.MI->getOpcode();
1852  unsigned NewOpc = 0;
1853  unsigned Scale = 1;
1854  unsigned Bits = 0;
1855  switch (Opcode) {
1856  default: break;
1857  case ARM::t2B:
1858  NewOpc = ARM::tB;
1859  Bits = 11;
1860  Scale = 2;
1861  break;
1862  case ARM::t2Bcc:
1863  NewOpc = ARM::tBcc;
1864  Bits = 8;
1865  Scale = 2;
1866  break;
1867  }
1868  if (NewOpc) {
1869  unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale;
1870  MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1871  if (isBBInRange(Br.MI, DestBB, MaxOffs)) {
1872  LLVM_DEBUG(dbgs() << "Shrink branch: " << *Br.MI);
1873  Br.MI->setDesc(TII->get(NewOpc));
1874  MachineBasicBlock *MBB = Br.MI->getParent();
1875  BBInfo[MBB->getNumber()].Size -= 2;
1876  adjustBBOffsetsAfter(MBB);
1877  ++NumT2BrShrunk;
1878  MadeChange = true;
1879  }
1880  }
1881 
1882  Opcode = Br.MI->getOpcode();
1883  if (Opcode != ARM::tBcc)
1884  continue;
1885 
1886  // If the conditional branch doesn't kill CPSR, then CPSR can be liveout
1887  // so this transformation is not safe.
1888  if (!Br.MI->killsRegister(ARM::CPSR))
1889  continue;
1890 
1891  NewOpc = 0;
1892  unsigned PredReg = 0;
1893  ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg);
1894  if (Pred == ARMCC::EQ)
1895  NewOpc = ARM::tCBZ;
1896  else if (Pred == ARMCC::NE)
1897  NewOpc = ARM::tCBNZ;
1898  if (!NewOpc)
1899  continue;
1900  MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB();
1901  // Check if the distance is within 126. Subtract starting offset by 2
1902  // because the cmp will be eliminated.
1903  unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2;
1904  unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset;
1905  if (BrOffset >= DestOffset || (DestOffset - BrOffset) > 126)
1906  continue;
1907 
1908  // Search backwards to find a tCMPi8
1909  auto *TRI = STI->getRegisterInfo();
1910  MachineInstr *CmpMI = findCMPToFoldIntoCBZ(Br.MI, TRI);
1911  if (!CmpMI || CmpMI->getOpcode() != ARM::tCMPi8)
1912  continue;
1913 
1914  unsigned Reg = CmpMI->getOperand(0).getReg();
1915 
1916  // Check for Kill flags on Reg. If they are present remove them and set kill
1917  // on the new CBZ.
1918  MachineBasicBlock::iterator KillMI = Br.MI;
1919  bool RegKilled = false;
1920  do {
1921  --KillMI;
1922  if (KillMI->killsRegister(Reg, TRI)) {
1923  KillMI->clearRegisterKills(Reg, TRI);
1924  RegKilled = true;
1925  break;
1926  }
1927  } while (KillMI != CmpMI);
1928 
1929  // Create the new CBZ/CBNZ
1930  MachineBasicBlock *MBB = Br.MI->getParent();
1931  LLVM_DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI);
1932  MachineInstr *NewBR =
1933  BuildMI(*MBB, Br.MI, Br.MI->getDebugLoc(), TII->get(NewOpc))
1934  .addReg(Reg, getKillRegState(RegKilled))
1935  .addMBB(DestBB, Br.MI->getOperand(0).getTargetFlags());
1936  CmpMI->eraseFromParent();
1937  Br.MI->eraseFromParent();
1938  Br.MI = NewBR;
1939  BBInfo[MBB->getNumber()].Size -= 2;
1940  adjustBBOffsetsAfter(MBB);
1941  ++NumCBZ;
1942  MadeChange = true;
1943  }
1944 
1945  return MadeChange;
1946 }
1947 
1948 static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg,
1949  unsigned BaseReg) {
1950  if (I.getOpcode() != ARM::t2ADDrs)
1951  return false;
1952 
1953  if (I.getOperand(0).getReg() != EntryReg)
1954  return false;
1955 
1956  if (I.getOperand(1).getReg() != BaseReg)
1957  return false;
1958 
1959  // FIXME: what about CC and IdxReg?
1960  return true;
1961 }
1962 
1963 /// While trying to form a TBB/TBH instruction, we may (if the table
1964 /// doesn't immediately follow the BR_JT) need access to the start of the
1965 /// jump-table. We know one instruction that produces such a register; this
1966 /// function works out whether that definition can be preserved to the BR_JT,
1967 /// possibly by removing an intervening addition (which is usually needed to
1968 /// calculate the actual entry to jump to).
1969 bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI,
1970  MachineInstr *LEAMI,
1971  unsigned &DeadSize,
1972  bool &CanDeleteLEA,
1973  bool &BaseRegKill) {
1974  if (JumpMI->getParent() != LEAMI->getParent())
1975  return false;
1976 
1977  // Now we hope that we have at least these instructions in the basic block:
1978  // BaseReg = t2LEA ...
1979  // [...]
1980  // EntryReg = t2ADDrs BaseReg, ...
1981  // [...]
1982  // t2BR_JT EntryReg
1983  //
1984  // We have to be very conservative about what we recognise here though. The
1985  // main perturbing factors to watch out for are:
1986  // + Spills at any point in the chain: not direct problems but we would
1987  // expect a blocking Def of the spilled register so in practice what we
1988  // can do is limited.
1989  // + EntryReg == BaseReg: this is the one situation we should allow a Def
1990  // of BaseReg, but only if the t2ADDrs can be removed.
1991  // + Some instruction other than t2ADDrs computing the entry. Not seen in
1992  // the wild, but we should be careful.
1993  unsigned EntryReg = JumpMI->getOperand(0).getReg();
1994  unsigned BaseReg = LEAMI->getOperand(0).getReg();
1995 
1996  CanDeleteLEA = true;
1997  BaseRegKill = false;
1998  MachineInstr *RemovableAdd = nullptr;
2000  for (++I; &*I != JumpMI; ++I) {
2001  if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) {
2002  RemovableAdd = &*I;
2003  break;
2004  }
2005 
2006  for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2007  const MachineOperand &MO = I->getOperand(K);
2008  if (!MO.isReg() || !MO.getReg())
2009  continue;
2010  if (MO.isDef() && MO.getReg() == BaseReg)
2011  return false;
2012  if (MO.isUse() && MO.getReg() == BaseReg) {
2013  BaseRegKill = BaseRegKill || MO.isKill();
2014  CanDeleteLEA = false;
2015  }
2016  }
2017  }
2018 
2019  if (!RemovableAdd)
2020  return true;
2021 
2022  // Check the add really is removable, and that nothing else in the block
2023  // clobbers BaseReg.
2024  for (++I; &*I != JumpMI; ++I) {
2025  for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) {
2026  const MachineOperand &MO = I->getOperand(K);
2027  if (!MO.isReg() || !MO.getReg())
2028  continue;
2029  if (MO.isDef() && MO.getReg() == BaseReg)
2030  return false;
2031  if (MO.isUse() && MO.getReg() == EntryReg)
2032  RemovableAdd = nullptr;
2033  }
2034  }
2035 
2036  if (RemovableAdd) {
2037  RemovableAdd->eraseFromParent();
2038  DeadSize += isThumb2 ? 4 : 2;
2039  } else if (BaseReg == EntryReg) {
2040  // The add wasn't removable, but clobbered the base for the TBB. So we can't
2041  // preserve it.
2042  return false;
2043  }
2044 
2045  // We reached the end of the block without seeing another definition of
2046  // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be
2047  // used in the TBB/TBH if necessary.
2048  return true;
2049 }
2050 
2051 /// Returns whether CPEMI is the first instruction in the block
2052 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so,
2053 /// we can switch the first register to PC and usually remove the address
2054 /// calculation that preceded it.
2055 static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) {
2057  MachineFunction *MF = MBB->getParent();
2058  ++MBB;
2059 
2060  return MBB != MF->end() && MBB->begin() != MBB->end() &&
2061  &*MBB->begin() == CPEMI;
2062 }
2063 
2065  MachineInstr *JumpMI,
2066  unsigned &DeadSize) {
2067  // Remove a dead add between the LEA and JT, which used to compute EntryReg,
2068  // but the JT now uses PC. Finds the last ADD (if any) that def's EntryReg
2069  // and is not clobbered / used.
2070  MachineInstr *RemovableAdd = nullptr;
2071  unsigned EntryReg = JumpMI->getOperand(0).getReg();
2072 
2073  // Find the last ADD to set EntryReg
2075  for (++I; &*I != JumpMI; ++I) {
2076  if (I->getOpcode() == ARM::t2ADDrs && I->getOperand(0).getReg() == EntryReg)
2077  RemovableAdd = &*I;
2078  }
2079 
2080  if (!RemovableAdd)
2081  return;
2082 
2083  // Ensure EntryReg is not clobbered or used.
2084  MachineBasicBlock::iterator J(RemovableAdd);
2085  for (++J; &*J != JumpMI; ++J) {
2086  for (unsigned K = 0, E = J->getNumOperands(); K != E; ++K) {
2087  const MachineOperand &MO = J->getOperand(K);
2088  if (!MO.isReg() || !MO.getReg())
2089  continue;
2090  if (MO.isDef() && MO.getReg() == EntryReg)
2091  return;
2092  if (MO.isUse() && MO.getReg() == EntryReg)
2093  return;
2094  }
2095  }
2096 
2097  LLVM_DEBUG(dbgs() << "Removing Dead Add: " << *RemovableAdd);
2098  RemovableAdd->eraseFromParent();
2099  DeadSize += 4;
2100 }
2101 
2102 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller
2103 /// jumptables when it's possible.
2104 bool ARMConstantIslands::optimizeThumb2JumpTables() {
2105  bool MadeChange = false;
2106 
2107  // FIXME: After the tables are shrunk, can we get rid some of the
2108  // constantpool tables?
2109  MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2110  if (!MJTI) return false;
2111 
2112  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2113  for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2114  MachineInstr *MI = T2JumpTables[i];
2115  const MCInstrDesc &MCID = MI->getDesc();
2116  unsigned NumOps = MCID.getNumOperands();
2117  unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2118  MachineOperand JTOP = MI->getOperand(JTOpIdx);
2119  unsigned JTI = JTOP.getIndex();
2120  assert(JTI < JT.size());
2121 
2122  bool ByteOk = true;
2123  bool HalfWordOk = true;
2124  unsigned JTOffset = getOffsetOf(MI) + 4;
2125  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2126  for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2127  MachineBasicBlock *MBB = JTBBs[j];
2128  unsigned DstOffset = BBInfo[MBB->getNumber()].Offset;
2129  // Negative offset is not ok. FIXME: We should change BB layout to make
2130  // sure all the branches are forward.
2131  if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2)
2132  ByteOk = false;
2133  unsigned TBHLimit = ((1<<16)-1)*2;
2134  if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit)
2135  HalfWordOk = false;
2136  if (!ByteOk && !HalfWordOk)
2137  break;
2138  }
2139 
2140  if (!ByteOk && !HalfWordOk)
2141  continue;
2142 
2143  CPUser &User = CPUsers[JumpTableUserIndices[JTI]];
2144  MachineBasicBlock *MBB = MI->getParent();
2145  if (!MI->getOperand(0).isKill()) // FIXME: needed now?
2146  continue;
2147 
2148  unsigned DeadSize = 0;
2149  bool CanDeleteLEA = false;
2150  bool BaseRegKill = false;
2151 
2152  unsigned IdxReg = ~0U;
2153  bool IdxRegKill = true;
2154  if (isThumb2) {
2155  IdxReg = MI->getOperand(1).getReg();
2156  IdxRegKill = MI->getOperand(1).isKill();
2157 
2158  bool PreservedBaseReg =
2159  preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill);
2160  if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg)
2161  continue;
2162  } else {
2163  // We're in thumb-1 mode, so we must have something like:
2164  // %idx = tLSLri %idx, 2
2165  // %base = tLEApcrelJT
2166  // %t = tLDRr %base, %idx
2167  unsigned BaseReg = User.MI->getOperand(0).getReg();
2168 
2169  if (User.MI->getIterator() == User.MI->getParent()->begin())
2170  continue;
2171  MachineInstr *Shift = User.MI->getPrevNode();
2172  if (Shift->getOpcode() != ARM::tLSLri ||
2173  Shift->getOperand(3).getImm() != 2 ||
2174  !Shift->getOperand(2).isKill())
2175  continue;
2176  IdxReg = Shift->getOperand(2).getReg();
2177  unsigned ShiftedIdxReg = Shift->getOperand(0).getReg();
2178 
2179  // It's important that IdxReg is live until the actual TBB/TBH. Most of
2180  // the range is checked later, but the LEA might still clobber it and not
2181  // actually get removed.
2182  if (BaseReg == IdxReg && !jumpTableFollowsTB(MI, User.CPEMI))
2183  continue;
2184 
2185  MachineInstr *Load = User.MI->getNextNode();
2186  if (Load->getOpcode() != ARM::tLDRr)
2187  continue;
2188  if (Load->getOperand(1).getReg() != BaseReg ||
2189  Load->getOperand(2).getReg() != ShiftedIdxReg ||
2190  !Load->getOperand(2).isKill())
2191  continue;
2192 
2193  // If we're in PIC mode, there should be another ADD following.
2194  auto *TRI = STI->getRegisterInfo();
2195 
2196  // %base cannot be redefined after the load as it will appear before
2197  // TBB/TBH like:
2198  // %base =
2199  // %base =
2200  // tBB %base, %idx
2201  if (registerDefinedBetween(BaseReg, Load->getNextNode(), MBB->end(), TRI))
2202  continue;
2203 
2204  if (isPositionIndependentOrROPI) {
2205  MachineInstr *Add = Load->getNextNode();
2206  if (Add->getOpcode() != ARM::tADDrr ||
2207  Add->getOperand(2).getReg() != BaseReg ||
2208  Add->getOperand(3).getReg() != Load->getOperand(0).getReg() ||
2209  !Add->getOperand(3).isKill())
2210  continue;
2211  if (Add->getOperand(0).getReg() != MI->getOperand(0).getReg())
2212  continue;
2213  if (registerDefinedBetween(IdxReg, Add->getNextNode(), MI, TRI))
2214  // IdxReg gets redefined in the middle of the sequence.
2215  continue;
2216  Add->eraseFromParent();
2217  DeadSize += 2;
2218  } else {
2219  if (Load->getOperand(0).getReg() != MI->getOperand(0).getReg())
2220  continue;
2221  if (registerDefinedBetween(IdxReg, Load->getNextNode(), MI, TRI))
2222  // IdxReg gets redefined in the middle of the sequence.
2223  continue;
2224  }
2225 
2226  // Now safe to delete the load and lsl. The LEA will be removed later.
2227  CanDeleteLEA = true;
2228  Shift->eraseFromParent();
2229  Load->eraseFromParent();
2230  DeadSize += 4;
2231  }
2232 
2233  LLVM_DEBUG(dbgs() << "Shrink JT: " << *MI);
2234  MachineInstr *CPEMI = User.CPEMI;
2235  unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT;
2236  if (!isThumb2)
2237  Opc = ByteOk ? ARM::tTBB_JT : ARM::tTBH_JT;
2238 
2240  MachineInstr *NewJTMI =
2241  BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc))
2242  .addReg(User.MI->getOperand(0).getReg(),
2243  getKillRegState(BaseRegKill))
2244  .addReg(IdxReg, getKillRegState(IdxRegKill))
2245  .addJumpTableIndex(JTI, JTOP.getTargetFlags())
2246  .addImm(CPEMI->getOperand(0).getImm());
2247  LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << ": " << *NewJTMI);
2248 
2249  unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH;
2250  CPEMI->setDesc(TII->get(JTOpc));
2251 
2252  if (jumpTableFollowsTB(MI, User.CPEMI)) {
2253  NewJTMI->getOperand(0).setReg(ARM::PC);
2254  NewJTMI->getOperand(0).setIsKill(false);
2255 
2256  if (CanDeleteLEA) {
2257  if (isThumb2)
2258  RemoveDeadAddBetweenLEAAndJT(User.MI, MI, DeadSize);
2259 
2260  User.MI->eraseFromParent();
2261  DeadSize += isThumb2 ? 4 : 2;
2262 
2263  // The LEA was eliminated, the TBB instruction becomes the only new user
2264  // of the jump table.
2265  User.MI = NewJTMI;
2266  User.MaxDisp = 4;
2267  User.NegOk = false;
2268  User.IsSoImm = false;
2269  User.KnownAlignment = false;
2270  } else {
2271  // The LEA couldn't be eliminated, so we must add another CPUser to
2272  // record the TBB or TBH use.
2273  int CPEntryIdx = JumpTableEntryIndices[JTI];
2274  auto &CPEs = CPEntries[CPEntryIdx];
2275  auto Entry =
2276  find_if(CPEs, [&](CPEntry &E) { return E.CPEMI == User.CPEMI; });
2277  ++Entry->RefCount;
2278  CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false));
2279  }
2280  }
2281 
2282  unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI);
2283  unsigned OrigSize = TII->getInstSizeInBytes(*MI);
2284  MI->eraseFromParent();
2285 
2286  int Delta = OrigSize - NewSize + DeadSize;
2287  BBInfo[MBB->getNumber()].Size -= Delta;
2288  adjustBBOffsetsAfter(MBB);
2289 
2290  ++NumTBs;
2291  MadeChange = true;
2292  }
2293 
2294  return MadeChange;
2295 }
2296 
2297 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that
2298 /// jump tables always branch forwards, since that's what tbb and tbh need.
2299 bool ARMConstantIslands::reorderThumb2JumpTables() {
2300  bool MadeChange = false;
2301 
2302  MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
2303  if (!MJTI) return false;
2304 
2305  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
2306  for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) {
2307  MachineInstr *MI = T2JumpTables[i];
2308  const MCInstrDesc &MCID = MI->getDesc();
2309  unsigned NumOps = MCID.getNumOperands();
2310  unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1);
2311  MachineOperand JTOP = MI->getOperand(JTOpIdx);
2312  unsigned JTI = JTOP.getIndex();
2313  assert(JTI < JT.size());
2314 
2315  // We prefer if target blocks for the jump table come after the jump
2316  // instruction so we can use TB[BH]. Loop through the target blocks
2317  // and try to adjust them such that that's true.
2318  int JTNumber = MI->getParent()->getNumber();
2319  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
2320  for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) {
2321  MachineBasicBlock *MBB = JTBBs[j];
2322  int DTNumber = MBB->getNumber();
2323 
2324  if (DTNumber < JTNumber) {
2325  // The destination precedes the switch. Try to move the block forward
2326  // so we have a positive offset.
2327  MachineBasicBlock *NewBB =
2328  adjustJTTargetBlockForward(MBB, MI->getParent());
2329  if (NewBB)
2330  MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB);
2331  MadeChange = true;
2332  }
2333  }
2334  }
2335 
2336  return MadeChange;
2337 }
2338 
2339 MachineBasicBlock *ARMConstantIslands::
2340 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) {
2341  // If the destination block is terminated by an unconditional branch,
2342  // try to move it; otherwise, create a new block following the jump
2343  // table that branches back to the actual target. This is a very simple
2344  // heuristic. FIXME: We can definitely improve it.
2345  MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
2349  MachineFunction::iterator OldPrior = std::prev(BBi);
2350 
2351  // If the block terminator isn't analyzable, don't try to move the block
2352  bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond);
2353 
2354  // If the block ends in an unconditional branch, move it. The prior block
2355  // has to have an analyzable terminator for us to move this one. Be paranoid
2356  // and make sure we're not trying to move the entry block of the function.
2357  if (!B && Cond.empty() && BB != &MF->front() &&
2358  !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) {
2359  BB->moveAfter(JTBB);
2360  OldPrior->updateTerminator();
2361  BB->updateTerminator();
2362  // Update numbering to account for the block being moved.
2363  MF->RenumberBlocks();
2364  ++NumJTMoved;
2365  return nullptr;
2366  }
2367 
2368  // Create a new MBB for the code after the jump BB.
2369  MachineBasicBlock *NewBB =
2370  MF->CreateMachineBasicBlock(JTBB->getBasicBlock());
2371  MachineFunction::iterator MBBI = ++JTBB->getIterator();
2372  MF->insert(MBBI, NewBB);
2373 
2374  // Add an unconditional branch from NewBB to BB.
2375  // There doesn't seem to be meaningful DebugInfo available; this doesn't
2376  // correspond directly to anything in the source.
2377  if (isThumb2)
2378  BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B))
2379  .addMBB(BB)
2380  .add(predOps(ARMCC::AL));
2381  else
2382  BuildMI(NewBB, DebugLoc(), TII->get(ARM::tB))
2383  .addMBB(BB)
2384  .add(predOps(ARMCC::AL));
2385 
2386  // Update internal data structures to account for the newly inserted MBB.
2387  MF->RenumberBlocks(NewBB);
2388 
2389  // Update the CFG.
2390  NewBB->addSuccessor(BB);
2391  JTBB->replaceSuccessor(BB, NewBB);
2392 
2393  ++NumJTInserted;
2394  return NewBB;
2395 }
2396 
2397 /// createARMConstantIslandPass - returns an instance of the constpool
2398 /// island pass.
2400  return new ARMConstantIslands();
2401 }
2402 
2403 INITIALIZE_PASS(ARMConstantIslands, "arm-cp-islands", ARM_CP_ISLANDS_OPT_NAME,
2404  false, false)
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1281
const MachineInstrBuilder & add(const MachineOperand &MO) const
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
const std::vector< MachineJumpTableEntry > & getJumpTables() const
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
MachineBasicBlock * getMBB() const
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:288
bool isEmpty() const
isEmpty - Return true if this constant pool contains no constants.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:473
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
void push_back(const T &Elt)
Definition: SmallVector.h:211
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:382
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
unsigned getReg() const
getReg - Returns the register number.
unsigned Reg
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:123
bool isPredicable(QueryType Type=AllInBundle) const
Return true if this instruction has a predicate operand that controls execution.
Definition: MachineInstr.h:686
unsigned Offset
Offset - Distance from the beginning of the function to the beginning of this basic block...
STATISTIC(NumFunctions, "Total number of functions")
void moveAfter(MachineBasicBlock *NewBefore)
unsigned const TargetRegisterInfo * TRI
A debug info location.
Definition: DebugLoc.h:33
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
#define op(i)
void dump() const
dump - Print the current MachineFunction to cerr, useful for debugger use.
void computeBlockSize(MachineFunction *MF, MachineBasicBlock *MBB, BasicBlockInfo &BBI)
bool erase(const T &V)
Definition: SmallSet.h:207
static bool isThumb(const MCSubtargetInfo &STI)
void setAlignment(unsigned Align)
Set alignment of the basic block.
bool ReplaceMBBInJumpTable(unsigned Idx, MachineBasicBlock *Old, MachineBasicBlock *New)
ReplaceMBBInJumpTable - If Old is a target of the jump tables, update the jump table to branch to New...
BasicBlockInfo - Information about the offset and size of a single basic block.
bool registerDefinedBetween(unsigned Reg, MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const TargetRegisterInfo *TRI)
Return true if Reg is defd between From and To.
static bool CompareMBBNumbers(const MachineBasicBlock *LHS, const MachineBasicBlock *RHS)
CompareMBBNumbers - Little predicate function to sort the WaterList by MBB ID.
static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg, unsigned BaseReg)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
const HexagonInstrInfo * TII
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
void eraseFromParent()
Unlink &#39;this&#39; from the containing basic block and delete it.
void setIndex(int Idx)
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
#define ARM_CP_ISLANDS_OPT_NAME
FunctionPass * createARMConstantIslandPass()
createARMConstantIslandPass - returns an instance of the constpool island pass.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:405
static std::array< MachineOperand, 2 > predOps(ARMCC::CondCodes Pred, unsigned PredReg=0)
Get the operands corresponding to the given Pred value.
void clear()
Definition: SmallSet.h:218
static cl::opt< bool > SynthesizeThumb1TBB("arm-synthesize-thumb-1-tbb", cl::Hidden, cl::init(true), cl::desc("Use compressed jump tables in Thumb-1 by synthesizing an " "equivalent to the TBB/TBH instructions"))
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
unsigned getKillRegState(bool B)
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
#define rc(i)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:432
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
unsigned getConstantPoolAlignment() const
getConstantPoolAlignment - Return the alignment required by the whole constant pool, of which the first element must be aligned.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:428
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
unsigned postOffset(unsigned LogAlign=0) const
Compute the offset immediately following this block.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Returns the size of the specified MachineInstr.
unsigned getAlignment() const
Return alignment of the basic block.
void ensureAlignment(unsigned A)
ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
void setMBB(MachineBasicBlock *MBB)
static bool BBIsJumpedOver(MachineBasicBlock *MBB)
BBIsJumpedOver - Return true of the specified basic block&#39;s only predecessor unconditionally branches...
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
void setImm(int64_t immVal)
void initPICLabelUId(unsigned UId)
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
self_iterator getIterator()
Definition: ilist_node.h:81
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:180
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1213
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
unsigned internalKnownBits() const
Compute the number of known offset bits internally to this block.
MachineInstr * findCMPToFoldIntoCBZ(MachineInstr *Br, const TargetRegisterInfo *TRI)
Search backwards from a tBcc to find a tCMPi8 against 0, meaning we can convert them to a tCBZ or tCB...
ARMCC::CondCodes getInstrPredicate(const MachineInstr &MI, unsigned &PredReg)
getInstrPredicate - If instruction is predicated, returns its predicate condition, otherwise returns AL.
size_t size() const
Definition: SmallVector.h:52
static wasm::ValType getType(const TargetRegisterClass *RC)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1206
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
MO_LO16 - On a symbol operand, this represents a relocation containing lower 16 bit of the address...
Definition: ARMBaseInfo.h:240
unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
void setIsKill(bool Val=true)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:33
const std::vector< MachineConstantPoolEntry > & getConstants() const
Iterator for intrusive lists based on ilist_node.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void setDesc(const MCInstrDesc &tid)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one...
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
ARMCC::CondCodes getITInstrPredicate(const MachineInstr &MI, unsigned &PredReg)
getITInstrPredicate - Valid only in Thumb2 mode.
unsigned UnknownPadding(unsigned LogAlign, unsigned KnownBits)
UnknownPadding - Return the worst case padding that could result from unknown offset bits...
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
Definition: FileCheck.cpp:124
MachineOperand class - Representation of each machine instruction operand.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
void updateTerminator()
Update the terminator instructions in block to account for changes to the layout. ...
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned char TargetFlags=0) const
APFloat neg(APFloat X)
Returns the negated value of the argument.
Definition: APFloat.h:1218
static cl::opt< bool > AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true), cl::desc("Adjust basic block layout to better use TB[BH]"))
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
int64_t getImm() const
unsigned pred_size() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:538
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
unsigned succ_size() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:253
MachineFunctionProperties & set(Property P)
void recordCPEClone(unsigned CPIdx, unsigned CPCloneIdx)
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:461
static bool isARMLowRegister(unsigned Reg)
isARMLowRegister - Returns true if the register is a low register (r0-r7).
Definition: ARMBaseInfo.h:160
Representation of each machine instruction.
Definition: MachineInstr.h:63
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
static CondCodes getOppositeCondition(CondCodes CC)
Definition: ARMBaseInfo.h:48
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
uint8_t Unalign
Unalign - When non-zero, the block contains instructions (inline asm) of unknown size.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB &#39;Other&#39; at the position From, and insert it into this MBB right before &#39;...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static bool BBHasFallthrough(MachineBasicBlock *MBB)
BBHasFallthrough - Return true if the specified basic block can fallthrough into the block immediatel...
ARMFunctionInfo - This class is derived from MachineFunctionInfo and contains private ARM-specific in...
void setReg(unsigned Reg)
Change the register this operand corresponds to.
#define I(x, y, z)
Definition: MD5.cpp:58
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
MO_OPTION_MASK - Most flags are mutually exclusive; this mask selects just that part of the flag set...
Definition: ARMBaseInfo.h:248
uint8_t KnownBits
KnownBits - The number of low bits in Offset that are known to be exact.
uint32_t Size
Definition: Profile.cpp:46
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
static unsigned getUnconditionalBrDisp(int Opc)
getUnconditionalBrDisp - Returns the maximum displacement that can fit in the specific unconditional ...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const MachineInstrBuilder & addJumpTableIndex(unsigned Idx, unsigned char TargetFlags=0) const
static cl::opt< unsigned > CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30), cl::desc("The max number of iteration for converge"))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI)
Returns whether CPEMI is the first instruction in the block immediately following JTMI (assumed to be...
void push_back(MachineBasicBlock *MBB)
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:250
uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: MathExtras.h:726
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
ppc ctr loops verify
static void RemoveDeadAddBetweenLEAAndJT(MachineInstr *LEAMI, MachineInstr *JumpMI, unsigned &DeadSize)
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
#define LLVM_DEBUG(X)
Definition: Debug.h:122
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
uint8_t PostAlign
PostAlign - When non-zero, the block terminator contains a .align directive, so the end of the block ...
MO_HI16 - On a symbol operand, this represents a relocation containing higher 16 bit of the address...
Definition: ARMBaseInfo.h:244
Properties which a MachineFunction may have at a given point in time.
std::vector< BasicBlockInfo > computeAllBlockSizes(MachineFunction *MF)
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:164