1 //===-- ARMConstantIslandPass.cpp - ARM constant islands ------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains a pass that splits the constant pool up into 'islands' 11 // which are scattered through-out the function. This is required due to the 12 // limited pc-relative displacements that ARM has. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "ARM.h" 17 #include "ARMBasicBlockInfo.h" 18 #include "ARMMachineFunctionInfo.h" 19 #include "MCTargetDesc/ARMAddressingModes.h" 20 #include "Thumb2InstrInfo.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/CodeGen/MachineConstantPool.h" 26 #include "llvm/CodeGen/MachineFunctionPass.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/Format.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include <algorithm> 37 using namespace llvm; 38 39 #define DEBUG_TYPE "arm-cp-islands" 40 41 STATISTIC(NumCPEs, "Number of constpool entries"); 42 STATISTIC(NumSplit, "Number of uncond branches inserted"); 43 STATISTIC(NumCBrFixed, "Number of cond branches fixed"); 44 STATISTIC(NumUBrFixed, "Number of uncond branches fixed"); 45 STATISTIC(NumTBs, "Number of table branches generated"); 46 STATISTIC(NumT2CPShrunk, "Number of Thumb2 constantpool instructions shrunk"); 47 STATISTIC(NumT2BrShrunk, "Number of Thumb2 immediate branches shrunk"); 48 STATISTIC(NumCBZ, "Number of CBZ / CBNZ formed"); 49 STATISTIC(NumJTMoved, "Number of jump table destination blocks moved"); 50 STATISTIC(NumJTInserted, "Number of jump table intermediate blocks inserted"); 51 52 53 static cl::opt<bool> 54 AdjustJumpTableBlocks("arm-adjust-jump-tables", cl::Hidden, cl::init(true), 55 cl::desc("Adjust basic block layout to better use TB[BH]")); 56 57 static cl::opt<unsigned> 58 CPMaxIteration("arm-constant-island-max-iteration", cl::Hidden, cl::init(30), 59 cl::desc("The max number of iteration for converge")); 60 61 namespace { 62 /// ARMConstantIslands - Due to limited PC-relative displacements, ARM 63 /// requires constant pool entries to be scattered among the instructions 64 /// inside a function. To do this, it completely ignores the normal LLVM 65 /// constant pool; instead, it places constants wherever it feels like with 66 /// special instructions. 67 /// 68 /// The terminology used in this pass includes: 69 /// Islands - Clumps of constants placed in the function. 70 /// Water - Potential places where an island could be formed. 71 /// CPE - A constant pool entry that has been placed somewhere, which 72 /// tracks a list of users. 73 class ARMConstantIslands : public MachineFunctionPass { 74 75 std::vector<BasicBlockInfo> BBInfo; 76 77 /// WaterList - A sorted list of basic blocks where islands could be placed 78 /// (i.e. blocks that don't fall through to the following block, due 79 /// to a return, unreachable, or unconditional branch). 80 std::vector<MachineBasicBlock*> WaterList; 81 82 /// NewWaterList - The subset of WaterList that was created since the 83 /// previous iteration by inserting unconditional branches. 84 SmallSet<MachineBasicBlock*, 4> NewWaterList; 85 86 typedef std::vector<MachineBasicBlock*>::iterator water_iterator; 87 88 /// CPUser - One user of a constant pool, keeping the machine instruction 89 /// pointer, the constant pool being referenced, and the max displacement 90 /// allowed from the instruction to the CP. The HighWaterMark records the 91 /// highest basic block where a new CPEntry can be placed. To ensure this 92 /// pass terminates, the CP entries are initially placed at the end of the 93 /// function and then move monotonically to lower addresses. The 94 /// exception to this rule is when the current CP entry for a particular 95 /// CPUser is out of range, but there is another CP entry for the same 96 /// constant value in range. We want to use the existing in-range CP 97 /// entry, but if it later moves out of range, the search for new water 98 /// should resume where it left off. The HighWaterMark is used to record 99 /// that point. 100 struct CPUser { 101 MachineInstr *MI; 102 MachineInstr *CPEMI; 103 MachineBasicBlock *HighWaterMark; 104 unsigned MaxDisp; 105 bool NegOk; 106 bool IsSoImm; 107 bool KnownAlignment; 108 CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp, 109 bool neg, bool soimm) 110 : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), NegOk(neg), IsSoImm(soimm), 111 KnownAlignment(false) { 112 HighWaterMark = CPEMI->getParent(); 113 } 114 /// getMaxDisp - Returns the maximum displacement supported by MI. 115 /// Correct for unknown alignment. 116 /// Conservatively subtract 2 bytes to handle weird alignment effects. 117 unsigned getMaxDisp() const { 118 return (KnownAlignment ? MaxDisp : MaxDisp - 2) - 2; 119 } 120 }; 121 122 /// CPUsers - Keep track of all of the machine instructions that use various 123 /// constant pools and their max displacement. 124 std::vector<CPUser> CPUsers; 125 126 /// CPEntry - One per constant pool entry, keeping the machine instruction 127 /// pointer, the constpool index, and the number of CPUser's which 128 /// reference this entry. 129 struct CPEntry { 130 MachineInstr *CPEMI; 131 unsigned CPI; 132 unsigned RefCount; 133 CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0) 134 : CPEMI(cpemi), CPI(cpi), RefCount(rc) {} 135 }; 136 137 /// CPEntries - Keep track of all of the constant pool entry machine 138 /// instructions. For each original constpool index (i.e. those that existed 139 /// upon entry to this pass), it keeps a vector of entries. Original 140 /// elements are cloned as we go along; the clones are put in the vector of 141 /// the original element, but have distinct CPIs. 142 /// 143 /// The first half of CPEntries contains generic constants, the second half 144 /// contains jump tables. Use getCombinedIndex on a generic CPEMI to look up 145 /// which vector it will be in here. 146 std::vector<std::vector<CPEntry> > CPEntries; 147 148 /// Maps a JT index to the offset in CPEntries containing copies of that 149 /// table. The equivalent map for a CONSTPOOL_ENTRY is the identity. 150 DenseMap<int, int> JumpTableEntryIndices; 151 152 /// Maps a JT index to the LEA that actually uses the index to calculate its 153 /// base address. 154 DenseMap<int, int> JumpTableUserIndices; 155 156 /// ImmBranch - One per immediate branch, keeping the machine instruction 157 /// pointer, conditional or unconditional, the max displacement, 158 /// and (if isCond is true) the corresponding unconditional branch 159 /// opcode. 160 struct ImmBranch { 161 MachineInstr *MI; 162 unsigned MaxDisp : 31; 163 bool isCond : 1; 164 unsigned UncondBr; 165 ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, unsigned ubr) 166 : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {} 167 }; 168 169 /// ImmBranches - Keep track of all the immediate branch instructions. 170 /// 171 std::vector<ImmBranch> ImmBranches; 172 173 /// PushPopMIs - Keep track of all the Thumb push / pop instructions. 174 /// 175 SmallVector<MachineInstr*, 4> PushPopMIs; 176 177 /// T2JumpTables - Keep track of all the Thumb2 jumptable instructions. 178 SmallVector<MachineInstr*, 4> T2JumpTables; 179 180 /// HasFarJump - True if any far jump instruction has been emitted during 181 /// the branch fix up pass. 182 bool HasFarJump; 183 184 MachineFunction *MF; 185 MachineConstantPool *MCP; 186 const ARMBaseInstrInfo *TII; 187 const ARMSubtarget *STI; 188 ARMFunctionInfo *AFI; 189 bool isThumb; 190 bool isThumb1; 191 bool isThumb2; 192 public: 193 static char ID; 194 ARMConstantIslands() : MachineFunctionPass(ID) {} 195 196 bool runOnMachineFunction(MachineFunction &MF) override; 197 198 MachineFunctionProperties getRequiredProperties() const override { 199 return MachineFunctionProperties().set( 200 MachineFunctionProperties::Property::AllVRegsAllocated); 201 } 202 203 const char *getPassName() const override { 204 return "ARM constant island placement and branch shortening pass"; 205 } 206 207 private: 208 void doInitialConstPlacement(std::vector<MachineInstr *> &CPEMIs); 209 void doInitialJumpTablePlacement(std::vector<MachineInstr *> &CPEMIs); 210 bool BBHasFallthrough(MachineBasicBlock *MBB); 211 CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI); 212 unsigned getCPELogAlign(const MachineInstr *CPEMI); 213 void scanFunctionJumpTables(); 214 void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs); 215 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI); 216 void updateForInsertedWaterBlock(MachineBasicBlock *NewBB); 217 void adjustBBOffsetsAfter(MachineBasicBlock *BB); 218 bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI); 219 unsigned getCombinedIndex(const MachineInstr *CPEMI); 220 int findInRangeCPEntry(CPUser& U, unsigned UserOffset); 221 bool findAvailableWater(CPUser&U, unsigned UserOffset, 222 water_iterator &WaterIter, bool CloserWater); 223 void createNewWater(unsigned CPUserIndex, unsigned UserOffset, 224 MachineBasicBlock *&NewMBB); 225 bool handleConstantPoolUser(unsigned CPUserIndex, bool CloserWater); 226 void removeDeadCPEMI(MachineInstr *CPEMI); 227 bool removeUnusedCPEntries(); 228 bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, 229 MachineInstr *CPEMI, unsigned Disp, bool NegOk, 230 bool DoDump = false); 231 bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, 232 CPUser &U, unsigned &Growth); 233 bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp); 234 bool fixupImmediateBr(ImmBranch &Br); 235 bool fixupConditionalBr(ImmBranch &Br); 236 bool fixupUnconditionalBr(ImmBranch &Br); 237 bool undoLRSpillRestore(); 238 bool optimizeThumb2Instructions(); 239 bool optimizeThumb2Branches(); 240 bool reorderThumb2JumpTables(); 241 bool preserveBaseRegister(MachineInstr *JumpMI, MachineInstr *LEAMI, 242 unsigned &DeadSize, bool &CanDeleteLEA, 243 bool &BaseRegKill); 244 bool optimizeThumb2JumpTables(); 245 MachineBasicBlock *adjustJTTargetBlockForward(MachineBasicBlock *BB, 246 MachineBasicBlock *JTBB); 247 248 unsigned getOffsetOf(MachineInstr *MI) const; 249 unsigned getUserOffset(CPUser&) const; 250 void dumpBBs(); 251 void verify(); 252 253 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, 254 unsigned Disp, bool NegativeOK, bool IsSoImm = false); 255 bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, 256 const CPUser &U) { 257 return isOffsetInRange(UserOffset, TrialOffset, 258 U.getMaxDisp(), U.NegOk, U.IsSoImm); 259 } 260 }; 261 char ARMConstantIslands::ID = 0; 262 } 263 264 /// verify - check BBOffsets, BBSizes, alignment of islands 265 void ARMConstantIslands::verify() { 266 #ifndef NDEBUG 267 assert(std::is_sorted(MF->begin(), MF->end(), 268 [this](const MachineBasicBlock &LHS, 269 const MachineBasicBlock &RHS) { 270 return BBInfo[LHS.getNumber()].postOffset() < 271 BBInfo[RHS.getNumber()].postOffset(); 272 })); 273 DEBUG(dbgs() << "Verifying " << CPUsers.size() << " CP users.\n"); 274 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) { 275 CPUser &U = CPUsers[i]; 276 unsigned UserOffset = getUserOffset(U); 277 // Verify offset using the real max displacement without the safety 278 // adjustment. 279 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, U.getMaxDisp()+2, U.NegOk, 280 /* DoDump = */ true)) { 281 DEBUG(dbgs() << "OK\n"); 282 continue; 283 } 284 DEBUG(dbgs() << "Out of range.\n"); 285 dumpBBs(); 286 DEBUG(MF->dump()); 287 llvm_unreachable("Constant pool entry out of range!"); 288 } 289 #endif 290 } 291 292 /// print block size and offset information - debugging 293 void ARMConstantIslands::dumpBBs() { 294 DEBUG({ 295 for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) { 296 const BasicBlockInfo &BBI = BBInfo[J]; 297 dbgs() << format("%08x BB#%u\t", BBI.Offset, J) 298 << " kb=" << unsigned(BBI.KnownBits) 299 << " ua=" << unsigned(BBI.Unalign) 300 << " pa=" << unsigned(BBI.PostAlign) 301 << format(" size=%#x\n", BBInfo[J].Size); 302 } 303 }); 304 } 305 306 /// createARMConstantIslandPass - returns an instance of the constpool 307 /// island pass. 308 FunctionPass *llvm::createARMConstantIslandPass() { 309 return new ARMConstantIslands(); 310 } 311 312 bool ARMConstantIslands::runOnMachineFunction(MachineFunction &mf) { 313 MF = &mf; 314 MCP = mf.getConstantPool(); 315 316 DEBUG(dbgs() << "***** ARMConstantIslands: " 317 << MCP->getConstants().size() << " CP entries, aligned to " 318 << MCP->getConstantPoolAlignment() << " bytes *****\n"); 319 320 STI = &static_cast<const ARMSubtarget &>(MF->getSubtarget()); 321 TII = STI->getInstrInfo(); 322 AFI = MF->getInfo<ARMFunctionInfo>(); 323 324 isThumb = AFI->isThumbFunction(); 325 isThumb1 = AFI->isThumb1OnlyFunction(); 326 isThumb2 = AFI->isThumb2Function(); 327 328 HasFarJump = false; 329 330 // This pass invalidates liveness information when it splits basic blocks. 331 MF->getRegInfo().invalidateLiveness(); 332 333 // Renumber all of the machine basic blocks in the function, guaranteeing that 334 // the numbers agree with the position of the block in the function. 335 MF->RenumberBlocks(); 336 337 // Try to reorder and otherwise adjust the block layout to make good use 338 // of the TB[BH] instructions. 339 bool MadeChange = false; 340 if (isThumb2 && AdjustJumpTableBlocks) { 341 scanFunctionJumpTables(); 342 MadeChange |= reorderThumb2JumpTables(); 343 // Data is out of date, so clear it. It'll be re-computed later. 344 T2JumpTables.clear(); 345 // Blocks may have shifted around. Keep the numbering up to date. 346 MF->RenumberBlocks(); 347 } 348 349 // Perform the initial placement of the constant pool entries. To start with, 350 // we put them all at the end of the function. 351 std::vector<MachineInstr*> CPEMIs; 352 if (!MCP->isEmpty()) 353 doInitialConstPlacement(CPEMIs); 354 355 if (MF->getJumpTableInfo()) 356 doInitialJumpTablePlacement(CPEMIs); 357 358 /// The next UID to take is the first unused one. 359 AFI->initPICLabelUId(CPEMIs.size()); 360 361 // Do the initial scan of the function, building up information about the 362 // sizes of each block, the location of all the water, and finding all of the 363 // constant pool users. 364 initializeFunctionInfo(CPEMIs); 365 CPEMIs.clear(); 366 DEBUG(dumpBBs()); 367 368 // Functions with jump tables need an alignment of 4 because they use the ADR 369 // instruction, which aligns the PC to 4 bytes before adding an offset. 370 if (!T2JumpTables.empty()) 371 MF->ensureAlignment(2); 372 373 /// Remove dead constant pool entries. 374 MadeChange |= removeUnusedCPEntries(); 375 376 // Iteratively place constant pool entries and fix up branches until there 377 // is no change. 378 unsigned NoCPIters = 0, NoBRIters = 0; 379 while (true) { 380 DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n'); 381 bool CPChange = false; 382 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) 383 // For most inputs, it converges in no more than 5 iterations. 384 // If it doesn't end in 10, the input may have huge BB or many CPEs. 385 // In this case, we will try different heuristics. 386 CPChange |= handleConstantPoolUser(i, NoCPIters >= CPMaxIteration / 2); 387 if (CPChange && ++NoCPIters > CPMaxIteration) 388 report_fatal_error("Constant Island pass failed to converge!"); 389 DEBUG(dumpBBs()); 390 391 // Clear NewWaterList now. If we split a block for branches, it should 392 // appear as "new water" for the next iteration of constant pool placement. 393 NewWaterList.clear(); 394 395 DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n'); 396 bool BRChange = false; 397 for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) 398 BRChange |= fixupImmediateBr(ImmBranches[i]); 399 if (BRChange && ++NoBRIters > 30) 400 report_fatal_error("Branch Fix Up pass failed to converge!"); 401 DEBUG(dumpBBs()); 402 403 if (!CPChange && !BRChange) 404 break; 405 MadeChange = true; 406 } 407 408 // Shrink 32-bit Thumb2 load and store instructions. 409 if (isThumb2 && !STI->prefers32BitThumb()) 410 MadeChange |= optimizeThumb2Instructions(); 411 412 // Shrink 32-bit branch instructions. 413 if (isThumb && STI->hasV8MBaselineOps()) 414 MadeChange |= optimizeThumb2Branches(); 415 416 // Optimize jump tables using TBB / TBH. 417 if (isThumb2) 418 MadeChange |= optimizeThumb2JumpTables(); 419 420 // After a while, this might be made debug-only, but it is not expensive. 421 verify(); 422 423 // If LR has been forced spilled and no far jump (i.e. BL) has been issued, 424 // undo the spill / restore of LR if possible. 425 if (isThumb && !HasFarJump && AFI->isLRSpilledForFarJump()) 426 MadeChange |= undoLRSpillRestore(); 427 428 // Save the mapping between original and cloned constpool entries. 429 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) { 430 for (unsigned j = 0, je = CPEntries[i].size(); j != je; ++j) { 431 const CPEntry & CPE = CPEntries[i][j]; 432 if (CPE.CPEMI && CPE.CPEMI->getOperand(1).isCPI()) 433 AFI->recordCPEClone(i, CPE.CPI); 434 } 435 } 436 437 DEBUG(dbgs() << '\n'; dumpBBs()); 438 439 BBInfo.clear(); 440 WaterList.clear(); 441 CPUsers.clear(); 442 CPEntries.clear(); 443 JumpTableEntryIndices.clear(); 444 JumpTableUserIndices.clear(); 445 ImmBranches.clear(); 446 PushPopMIs.clear(); 447 T2JumpTables.clear(); 448 449 return MadeChange; 450 } 451 452 /// \brief Perform the initial placement of the regular constant pool entries. 453 /// To start with, we put them all at the end of the function. 454 void 455 ARMConstantIslands::doInitialConstPlacement(std::vector<MachineInstr*> &CPEMIs) { 456 // Create the basic block to hold the CPE's. 457 MachineBasicBlock *BB = MF->CreateMachineBasicBlock(); 458 MF->push_back(BB); 459 460 // MachineConstantPool measures alignment in bytes. We measure in log2(bytes). 461 unsigned MaxAlign = Log2_32(MCP->getConstantPoolAlignment()); 462 463 // Mark the basic block as required by the const-pool. 464 BB->setAlignment(MaxAlign); 465 466 // The function needs to be as aligned as the basic blocks. The linker may 467 // move functions around based on their alignment. 468 MF->ensureAlignment(BB->getAlignment()); 469 470 // Order the entries in BB by descending alignment. That ensures correct 471 // alignment of all entries as long as BB is sufficiently aligned. Keep 472 // track of the insertion point for each alignment. We are going to bucket 473 // sort the entries as they are created. 474 SmallVector<MachineBasicBlock::iterator, 8> InsPoint(MaxAlign + 1, BB->end()); 475 476 // Add all of the constants from the constant pool to the end block, use an 477 // identity mapping of CPI's to CPE's. 478 const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants(); 479 480 const DataLayout &TD = MF->getDataLayout(); 481 for (unsigned i = 0, e = CPs.size(); i != e; ++i) { 482 unsigned Size = TD.getTypeAllocSize(CPs[i].getType()); 483 assert(Size >= 4 && "Too small constant pool entry"); 484 unsigned Align = CPs[i].getAlignment(); 485 assert(isPowerOf2_32(Align) && "Invalid alignment"); 486 // Verify that all constant pool entries are a multiple of their alignment. 487 // If not, we would have to pad them out so that instructions stay aligned. 488 assert((Size % Align) == 0 && "CP Entry not multiple of 4 bytes!"); 489 490 // Insert CONSTPOOL_ENTRY before entries with a smaller alignment. 491 unsigned LogAlign = Log2_32(Align); 492 MachineBasicBlock::iterator InsAt = InsPoint[LogAlign]; 493 MachineInstr *CPEMI = 494 BuildMI(*BB, InsAt, DebugLoc(), TII->get(ARM::CONSTPOOL_ENTRY)) 495 .addImm(i).addConstantPoolIndex(i).addImm(Size); 496 CPEMIs.push_back(CPEMI); 497 498 // Ensure that future entries with higher alignment get inserted before 499 // CPEMI. This is bucket sort with iterators. 500 for (unsigned a = LogAlign + 1; a <= MaxAlign; ++a) 501 if (InsPoint[a] == InsAt) 502 InsPoint[a] = CPEMI; 503 504 // Add a new CPEntry, but no corresponding CPUser yet. 505 CPEntries.emplace_back(1, CPEntry(CPEMI, i)); 506 ++NumCPEs; 507 DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = " 508 << Size << ", align = " << Align <<'\n'); 509 } 510 DEBUG(BB->dump()); 511 } 512 513 /// \brief Do initial placement of the jump tables. Because Thumb2's TBB and TBH 514 /// instructions can be made more efficient if the jump table immediately 515 /// follows the instruction, it's best to place them immediately next to their 516 /// jumps to begin with. In almost all cases they'll never be moved from that 517 /// position. 518 void ARMConstantIslands::doInitialJumpTablePlacement( 519 std::vector<MachineInstr *> &CPEMIs) { 520 unsigned i = CPEntries.size(); 521 auto MJTI = MF->getJumpTableInfo(); 522 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 523 524 MachineBasicBlock *LastCorrectlyNumberedBB = nullptr; 525 for (MachineBasicBlock &MBB : *MF) { 526 auto MI = MBB.getLastNonDebugInstr(); 527 if (MI == MBB.end()) 528 continue; 529 530 unsigned JTOpcode; 531 switch (MI->getOpcode()) { 532 default: 533 continue; 534 case ARM::BR_JTadd: 535 case ARM::BR_JTr: 536 case ARM::tBR_JTr: 537 case ARM::BR_JTm: 538 JTOpcode = ARM::JUMPTABLE_ADDRS; 539 break; 540 case ARM::t2BR_JT: 541 JTOpcode = ARM::JUMPTABLE_INSTS; 542 break; 543 case ARM::t2TBB_JT: 544 JTOpcode = ARM::JUMPTABLE_TBB; 545 break; 546 case ARM::t2TBH_JT: 547 JTOpcode = ARM::JUMPTABLE_TBH; 548 break; 549 } 550 551 unsigned NumOps = MI->getDesc().getNumOperands(); 552 MachineOperand JTOp = 553 MI->getOperand(NumOps - (MI->isPredicable() ? 2 : 1)); 554 unsigned JTI = JTOp.getIndex(); 555 unsigned Size = JT[JTI].MBBs.size() * sizeof(uint32_t); 556 MachineBasicBlock *JumpTableBB = MF->CreateMachineBasicBlock(); 557 MF->insert(std::next(MachineFunction::iterator(MBB)), JumpTableBB); 558 MachineInstr *CPEMI = BuildMI(*JumpTableBB, JumpTableBB->begin(), 559 DebugLoc(), TII->get(JTOpcode)) 560 .addImm(i++) 561 .addJumpTableIndex(JTI) 562 .addImm(Size); 563 CPEMIs.push_back(CPEMI); 564 CPEntries.emplace_back(1, CPEntry(CPEMI, JTI)); 565 JumpTableEntryIndices.insert(std::make_pair(JTI, CPEntries.size() - 1)); 566 if (!LastCorrectlyNumberedBB) 567 LastCorrectlyNumberedBB = &MBB; 568 } 569 570 // If we did anything then we need to renumber the subsequent blocks. 571 if (LastCorrectlyNumberedBB) 572 MF->RenumberBlocks(LastCorrectlyNumberedBB); 573 } 574 575 /// BBHasFallthrough - Return true if the specified basic block can fallthrough 576 /// into the block immediately after it. 577 bool ARMConstantIslands::BBHasFallthrough(MachineBasicBlock *MBB) { 578 // Get the next machine basic block in the function. 579 MachineFunction::iterator MBBI = MBB->getIterator(); 580 // Can't fall off end of function. 581 if (std::next(MBBI) == MBB->getParent()->end()) 582 return false; 583 584 MachineBasicBlock *NextBB = &*std::next(MBBI); 585 if (std::find(MBB->succ_begin(), MBB->succ_end(), NextBB) == MBB->succ_end()) 586 return false; 587 588 // Try to analyze the end of the block. A potential fallthrough may already 589 // have an unconditional branch for whatever reason. 590 MachineBasicBlock *TBB, *FBB; 591 SmallVector<MachineOperand, 4> Cond; 592 bool TooDifficult = TII->analyzeBranch(*MBB, TBB, FBB, Cond); 593 return TooDifficult || FBB == nullptr; 594 } 595 596 /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI, 597 /// look up the corresponding CPEntry. 598 ARMConstantIslands::CPEntry 599 *ARMConstantIslands::findConstPoolEntry(unsigned CPI, 600 const MachineInstr *CPEMI) { 601 std::vector<CPEntry> &CPEs = CPEntries[CPI]; 602 // Number of entries per constpool index should be small, just do a 603 // linear search. 604 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) { 605 if (CPEs[i].CPEMI == CPEMI) 606 return &CPEs[i]; 607 } 608 return nullptr; 609 } 610 611 /// getCPELogAlign - Returns the required alignment of the constant pool entry 612 /// represented by CPEMI. Alignment is measured in log2(bytes) units. 613 unsigned ARMConstantIslands::getCPELogAlign(const MachineInstr *CPEMI) { 614 switch (CPEMI->getOpcode()) { 615 case ARM::CONSTPOOL_ENTRY: 616 break; 617 case ARM::JUMPTABLE_TBB: 618 return 0; 619 case ARM::JUMPTABLE_TBH: 620 case ARM::JUMPTABLE_INSTS: 621 return 1; 622 case ARM::JUMPTABLE_ADDRS: 623 return 2; 624 default: 625 llvm_unreachable("unknown constpool entry kind"); 626 } 627 628 unsigned CPI = getCombinedIndex(CPEMI); 629 assert(CPI < MCP->getConstants().size() && "Invalid constant pool index."); 630 unsigned Align = MCP->getConstants()[CPI].getAlignment(); 631 assert(isPowerOf2_32(Align) && "Invalid CPE alignment"); 632 return Log2_32(Align); 633 } 634 635 /// scanFunctionJumpTables - Do a scan of the function, building up 636 /// information about the sizes of each block and the locations of all 637 /// the jump tables. 638 void ARMConstantIslands::scanFunctionJumpTables() { 639 for (MachineBasicBlock &MBB : *MF) { 640 for (MachineInstr &I : MBB) 641 if (I.isBranch() && I.getOpcode() == ARM::t2BR_JT) 642 T2JumpTables.push_back(&I); 643 } 644 } 645 646 /// initializeFunctionInfo - Do the initial scan of the function, building up 647 /// information about the sizes of each block, the location of all the water, 648 /// and finding all of the constant pool users. 649 void ARMConstantIslands:: 650 initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs) { 651 652 BBInfo = computeAllBlockSizes(MF); 653 654 // The known bits of the entry block offset are determined by the function 655 // alignment. 656 BBInfo.front().KnownBits = MF->getAlignment(); 657 658 // Compute block offsets and known bits. 659 adjustBBOffsetsAfter(&MF->front()); 660 661 // Now go back through the instructions and build up our data structures. 662 for (MachineBasicBlock &MBB : *MF) { 663 // If this block doesn't fall through into the next MBB, then this is 664 // 'water' that a constant pool island could be placed. 665 if (!BBHasFallthrough(&MBB)) 666 WaterList.push_back(&MBB); 667 668 for (MachineInstr &I : MBB) { 669 if (I.isDebugValue()) 670 continue; 671 672 unsigned Opc = I.getOpcode(); 673 if (I.isBranch()) { 674 bool isCond = false; 675 unsigned Bits = 0; 676 unsigned Scale = 1; 677 int UOpc = Opc; 678 switch (Opc) { 679 default: 680 continue; // Ignore other JT branches 681 case ARM::t2BR_JT: 682 T2JumpTables.push_back(&I); 683 continue; // Does not get an entry in ImmBranches 684 case ARM::Bcc: 685 isCond = true; 686 UOpc = ARM::B; 687 // Fallthrough 688 case ARM::B: 689 Bits = 24; 690 Scale = 4; 691 break; 692 case ARM::tBcc: 693 isCond = true; 694 UOpc = ARM::tB; 695 Bits = 8; 696 Scale = 2; 697 break; 698 case ARM::tB: 699 Bits = 11; 700 Scale = 2; 701 break; 702 case ARM::t2Bcc: 703 isCond = true; 704 UOpc = ARM::t2B; 705 Bits = 20; 706 Scale = 2; 707 break; 708 case ARM::t2B: 709 Bits = 24; 710 Scale = 2; 711 break; 712 } 713 714 // Record this immediate branch. 715 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; 716 ImmBranches.push_back(ImmBranch(&I, MaxOffs, isCond, UOpc)); 717 } 718 719 if (Opc == ARM::tPUSH || Opc == ARM::tPOP_RET) 720 PushPopMIs.push_back(&I); 721 722 if (Opc == ARM::CONSTPOOL_ENTRY || Opc == ARM::JUMPTABLE_ADDRS || 723 Opc == ARM::JUMPTABLE_INSTS || Opc == ARM::JUMPTABLE_TBB || 724 Opc == ARM::JUMPTABLE_TBH) 725 continue; 726 727 // Scan the instructions for constant pool operands. 728 for (unsigned op = 0, e = I.getNumOperands(); op != e; ++op) 729 if (I.getOperand(op).isCPI() || I.getOperand(op).isJTI()) { 730 // We found one. The addressing mode tells us the max displacement 731 // from the PC that this instruction permits. 732 733 // Basic size info comes from the TSFlags field. 734 unsigned Bits = 0; 735 unsigned Scale = 1; 736 bool NegOk = false; 737 bool IsSoImm = false; 738 739 switch (Opc) { 740 default: 741 llvm_unreachable("Unknown addressing mode for CP reference!"); 742 743 // Taking the address of a CP entry. 744 case ARM::LEApcrel: 745 case ARM::LEApcrelJT: 746 // This takes a SoImm, which is 8 bit immediate rotated. We'll 747 // pretend the maximum offset is 255 * 4. Since each instruction 748 // 4 byte wide, this is always correct. We'll check for other 749 // displacements that fits in a SoImm as well. 750 Bits = 8; 751 Scale = 4; 752 NegOk = true; 753 IsSoImm = true; 754 break; 755 case ARM::t2LEApcrel: 756 case ARM::t2LEApcrelJT: 757 Bits = 12; 758 NegOk = true; 759 break; 760 case ARM::tLEApcrel: 761 case ARM::tLEApcrelJT: 762 Bits = 8; 763 Scale = 4; 764 break; 765 766 case ARM::LDRBi12: 767 case ARM::LDRi12: 768 case ARM::LDRcp: 769 case ARM::t2LDRpci: 770 Bits = 12; // +-offset_12 771 NegOk = true; 772 break; 773 774 case ARM::tLDRpci: 775 Bits = 8; 776 Scale = 4; // +(offset_8*4) 777 break; 778 779 case ARM::VLDRD: 780 case ARM::VLDRS: 781 Bits = 8; 782 Scale = 4; // +-(offset_8*4) 783 NegOk = true; 784 break; 785 } 786 787 // Remember that this is a user of a CP entry. 788 unsigned CPI = I.getOperand(op).getIndex(); 789 if (I.getOperand(op).isJTI()) { 790 JumpTableUserIndices.insert(std::make_pair(CPI, CPUsers.size())); 791 CPI = JumpTableEntryIndices[CPI]; 792 } 793 794 MachineInstr *CPEMI = CPEMIs[CPI]; 795 unsigned MaxOffs = ((1 << Bits)-1) * Scale; 796 CPUsers.push_back(CPUser(&I, CPEMI, MaxOffs, NegOk, IsSoImm)); 797 798 // Increment corresponding CPEntry reference count. 799 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); 800 assert(CPE && "Cannot find a corresponding CPEntry!"); 801 CPE->RefCount++; 802 803 // Instructions can only use one CP entry, don't bother scanning the 804 // rest of the operands. 805 break; 806 } 807 } 808 } 809 } 810 811 /// getOffsetOf - Return the current offset of the specified machine instruction 812 /// from the start of the function. This offset changes as stuff is moved 813 /// around inside the function. 814 unsigned ARMConstantIslands::getOffsetOf(MachineInstr *MI) const { 815 MachineBasicBlock *MBB = MI->getParent(); 816 817 // The offset is composed of two things: the sum of the sizes of all MBB's 818 // before this instruction's block, and the offset from the start of the block 819 // it is in. 820 unsigned Offset = BBInfo[MBB->getNumber()].Offset; 821 822 // Sum instructions before MI in MBB. 823 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) { 824 assert(I != MBB->end() && "Didn't find MI in its own basic block?"); 825 Offset += TII->getInstSizeInBytes(*I); 826 } 827 return Offset; 828 } 829 830 /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB 831 /// ID. 832 static bool CompareMBBNumbers(const MachineBasicBlock *LHS, 833 const MachineBasicBlock *RHS) { 834 return LHS->getNumber() < RHS->getNumber(); 835 } 836 837 /// updateForInsertedWaterBlock - When a block is newly inserted into the 838 /// machine function, it upsets all of the block numbers. Renumber the blocks 839 /// and update the arrays that parallel this numbering. 840 void ARMConstantIslands::updateForInsertedWaterBlock(MachineBasicBlock *NewBB) { 841 // Renumber the MBB's to keep them consecutive. 842 NewBB->getParent()->RenumberBlocks(NewBB); 843 844 // Insert an entry into BBInfo to align it properly with the (newly 845 // renumbered) block numbers. 846 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo()); 847 848 // Next, update WaterList. Specifically, we need to add NewMBB as having 849 // available water after it. 850 water_iterator IP = 851 std::lower_bound(WaterList.begin(), WaterList.end(), NewBB, 852 CompareMBBNumbers); 853 WaterList.insert(IP, NewBB); 854 } 855 856 857 /// Split the basic block containing MI into two blocks, which are joined by 858 /// an unconditional branch. Update data structures and renumber blocks to 859 /// account for this change and returns the newly created block. 860 MachineBasicBlock *ARMConstantIslands::splitBlockBeforeInstr(MachineInstr *MI) { 861 MachineBasicBlock *OrigBB = MI->getParent(); 862 863 // Create a new MBB for the code after the OrigBB. 864 MachineBasicBlock *NewBB = 865 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock()); 866 MachineFunction::iterator MBBI = ++OrigBB->getIterator(); 867 MF->insert(MBBI, NewBB); 868 869 // Splice the instructions starting with MI over to NewBB. 870 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end()); 871 872 // Add an unconditional branch from OrigBB to NewBB. 873 // Note the new unconditional branch is not being recorded. 874 // There doesn't seem to be meaningful DebugInfo available; this doesn't 875 // correspond to anything in the source. 876 unsigned Opc = isThumb ? (isThumb2 ? ARM::t2B : ARM::tB) : ARM::B; 877 if (!isThumb) 878 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB); 879 else 880 BuildMI(OrigBB, DebugLoc(), TII->get(Opc)).addMBB(NewBB) 881 .addImm(ARMCC::AL).addReg(0); 882 ++NumSplit; 883 884 // Update the CFG. All succs of OrigBB are now succs of NewBB. 885 NewBB->transferSuccessors(OrigBB); 886 887 // OrigBB branches to NewBB. 888 OrigBB->addSuccessor(NewBB); 889 890 // Update internal data structures to account for the newly inserted MBB. 891 // This is almost the same as updateForInsertedWaterBlock, except that 892 // the Water goes after OrigBB, not NewBB. 893 MF->RenumberBlocks(NewBB); 894 895 // Insert an entry into BBInfo to align it properly with the (newly 896 // renumbered) block numbers. 897 BBInfo.insert(BBInfo.begin() + NewBB->getNumber(), BasicBlockInfo()); 898 899 // Next, update WaterList. Specifically, we need to add OrigMBB as having 900 // available water after it (but not if it's already there, which happens 901 // when splitting before a conditional branch that is followed by an 902 // unconditional branch - in that case we want to insert NewBB). 903 water_iterator IP = 904 std::lower_bound(WaterList.begin(), WaterList.end(), OrigBB, 905 CompareMBBNumbers); 906 MachineBasicBlock* WaterBB = *IP; 907 if (WaterBB == OrigBB) 908 WaterList.insert(std::next(IP), NewBB); 909 else 910 WaterList.insert(IP, OrigBB); 911 NewWaterList.insert(OrigBB); 912 913 // Figure out how large the OrigBB is. As the first half of the original 914 // block, it cannot contain a tablejump. The size includes 915 // the new jump we added. (It should be possible to do this without 916 // recounting everything, but it's very confusing, and this is rarely 917 // executed.) 918 computeBlockSize(MF, OrigBB, BBInfo[OrigBB->getNumber()]); 919 920 // Figure out how large the NewMBB is. As the second half of the original 921 // block, it may contain a tablejump. 922 computeBlockSize(MF, NewBB, BBInfo[NewBB->getNumber()]); 923 924 // All BBOffsets following these blocks must be modified. 925 adjustBBOffsetsAfter(OrigBB); 926 927 return NewBB; 928 } 929 930 /// getUserOffset - Compute the offset of U.MI as seen by the hardware 931 /// displacement computation. Update U.KnownAlignment to match its current 932 /// basic block location. 933 unsigned ARMConstantIslands::getUserOffset(CPUser &U) const { 934 unsigned UserOffset = getOffsetOf(U.MI); 935 const BasicBlockInfo &BBI = BBInfo[U.MI->getParent()->getNumber()]; 936 unsigned KnownBits = BBI.internalKnownBits(); 937 938 // The value read from PC is offset from the actual instruction address. 939 UserOffset += (isThumb ? 4 : 8); 940 941 // Because of inline assembly, we may not know the alignment (mod 4) of U.MI. 942 // Make sure U.getMaxDisp() returns a constrained range. 943 U.KnownAlignment = (KnownBits >= 2); 944 945 // On Thumb, offsets==2 mod 4 are rounded down by the hardware for 946 // purposes of the displacement computation; compensate for that here. 947 // For unknown alignments, getMaxDisp() constrains the range instead. 948 if (isThumb && U.KnownAlignment) 949 UserOffset &= ~3u; 950 951 return UserOffset; 952 } 953 954 /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool 955 /// reference) is within MaxDisp of TrialOffset (a proposed location of a 956 /// constant pool entry). 957 /// UserOffset is computed by getUserOffset above to include PC adjustments. If 958 /// the mod 4 alignment of UserOffset is not known, the uncertainty must be 959 /// subtracted from MaxDisp instead. CPUser::getMaxDisp() does that. 960 bool ARMConstantIslands::isOffsetInRange(unsigned UserOffset, 961 unsigned TrialOffset, unsigned MaxDisp, 962 bool NegativeOK, bool IsSoImm) { 963 if (UserOffset <= TrialOffset) { 964 // User before the Trial. 965 if (TrialOffset - UserOffset <= MaxDisp) 966 return true; 967 // FIXME: Make use full range of soimm values. 968 } else if (NegativeOK) { 969 if (UserOffset - TrialOffset <= MaxDisp) 970 return true; 971 // FIXME: Make use full range of soimm values. 972 } 973 return false; 974 } 975 976 /// isWaterInRange - Returns true if a CPE placed after the specified 977 /// Water (a basic block) will be in range for the specific MI. 978 /// 979 /// Compute how much the function will grow by inserting a CPE after Water. 980 bool ARMConstantIslands::isWaterInRange(unsigned UserOffset, 981 MachineBasicBlock* Water, CPUser &U, 982 unsigned &Growth) { 983 unsigned CPELogAlign = getCPELogAlign(U.CPEMI); 984 unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(CPELogAlign); 985 unsigned NextBlockOffset, NextBlockAlignment; 986 MachineFunction::const_iterator NextBlock = Water->getIterator(); 987 if (++NextBlock == MF->end()) { 988 NextBlockOffset = BBInfo[Water->getNumber()].postOffset(); 989 NextBlockAlignment = 0; 990 } else { 991 NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset; 992 NextBlockAlignment = NextBlock->getAlignment(); 993 } 994 unsigned Size = U.CPEMI->getOperand(2).getImm(); 995 unsigned CPEEnd = CPEOffset + Size; 996 997 // The CPE may be able to hide in the alignment padding before the next 998 // block. It may also cause more padding to be required if it is more aligned 999 // that the next block. 1000 if (CPEEnd > NextBlockOffset) { 1001 Growth = CPEEnd - NextBlockOffset; 1002 // Compute the padding that would go at the end of the CPE to align the next 1003 // block. 1004 Growth += OffsetToAlignment(CPEEnd, 1ULL << NextBlockAlignment); 1005 1006 // If the CPE is to be inserted before the instruction, that will raise 1007 // the offset of the instruction. Also account for unknown alignment padding 1008 // in blocks between CPE and the user. 1009 if (CPEOffset < UserOffset) 1010 UserOffset += Growth + UnknownPadding(MF->getAlignment(), CPELogAlign); 1011 } else 1012 // CPE fits in existing padding. 1013 Growth = 0; 1014 1015 return isOffsetInRange(UserOffset, CPEOffset, U); 1016 } 1017 1018 /// isCPEntryInRange - Returns true if the distance between specific MI and 1019 /// specific ConstPool entry instruction can fit in MI's displacement field. 1020 bool ARMConstantIslands::isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, 1021 MachineInstr *CPEMI, unsigned MaxDisp, 1022 bool NegOk, bool DoDump) { 1023 unsigned CPEOffset = getOffsetOf(CPEMI); 1024 1025 if (DoDump) { 1026 DEBUG({ 1027 unsigned Block = MI->getParent()->getNumber(); 1028 const BasicBlockInfo &BBI = BBInfo[Block]; 1029 dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm() 1030 << " max delta=" << MaxDisp 1031 << format(" insn address=%#x", UserOffset) 1032 << " in BB#" << Block << ": " 1033 << format("%#x-%x\t", BBI.Offset, BBI.postOffset()) << *MI 1034 << format("CPE address=%#x offset=%+d: ", CPEOffset, 1035 int(CPEOffset-UserOffset)); 1036 }); 1037 } 1038 1039 return isOffsetInRange(UserOffset, CPEOffset, MaxDisp, NegOk); 1040 } 1041 1042 #ifndef NDEBUG 1043 /// BBIsJumpedOver - Return true of the specified basic block's only predecessor 1044 /// unconditionally branches to its only successor. 1045 static bool BBIsJumpedOver(MachineBasicBlock *MBB) { 1046 if (MBB->pred_size() != 1 || MBB->succ_size() != 1) 1047 return false; 1048 1049 MachineBasicBlock *Succ = *MBB->succ_begin(); 1050 MachineBasicBlock *Pred = *MBB->pred_begin(); 1051 MachineInstr *PredMI = &Pred->back(); 1052 if (PredMI->getOpcode() == ARM::B || PredMI->getOpcode() == ARM::tB 1053 || PredMI->getOpcode() == ARM::t2B) 1054 return PredMI->getOperand(0).getMBB() == Succ; 1055 return false; 1056 } 1057 #endif // NDEBUG 1058 1059 void ARMConstantIslands::adjustBBOffsetsAfter(MachineBasicBlock *BB) { 1060 unsigned BBNum = BB->getNumber(); 1061 for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) { 1062 // Get the offset and known bits at the end of the layout predecessor. 1063 // Include the alignment of the current block. 1064 unsigned LogAlign = MF->getBlockNumbered(i)->getAlignment(); 1065 unsigned Offset = BBInfo[i - 1].postOffset(LogAlign); 1066 unsigned KnownBits = BBInfo[i - 1].postKnownBits(LogAlign); 1067 1068 // This is where block i begins. Stop if the offset is already correct, 1069 // and we have updated 2 blocks. This is the maximum number of blocks 1070 // changed before calling this function. 1071 if (i > BBNum + 2 && 1072 BBInfo[i].Offset == Offset && 1073 BBInfo[i].KnownBits == KnownBits) 1074 break; 1075 1076 BBInfo[i].Offset = Offset; 1077 BBInfo[i].KnownBits = KnownBits; 1078 } 1079 } 1080 1081 /// decrementCPEReferenceCount - find the constant pool entry with index CPI 1082 /// and instruction CPEMI, and decrement its refcount. If the refcount 1083 /// becomes 0 remove the entry and instruction. Returns true if we removed 1084 /// the entry, false if we didn't. 1085 1086 bool ARMConstantIslands::decrementCPEReferenceCount(unsigned CPI, 1087 MachineInstr *CPEMI) { 1088 // Find the old entry. Eliminate it if it is no longer used. 1089 CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); 1090 assert(CPE && "Unexpected!"); 1091 if (--CPE->RefCount == 0) { 1092 removeDeadCPEMI(CPEMI); 1093 CPE->CPEMI = nullptr; 1094 --NumCPEs; 1095 return true; 1096 } 1097 return false; 1098 } 1099 1100 unsigned ARMConstantIslands::getCombinedIndex(const MachineInstr *CPEMI) { 1101 if (CPEMI->getOperand(1).isCPI()) 1102 return CPEMI->getOperand(1).getIndex(); 1103 1104 return JumpTableEntryIndices[CPEMI->getOperand(1).getIndex()]; 1105 } 1106 1107 /// LookForCPEntryInRange - see if the currently referenced CPE is in range; 1108 /// if not, see if an in-range clone of the CPE is in range, and if so, 1109 /// change the data structures so the user references the clone. Returns: 1110 /// 0 = no existing entry found 1111 /// 1 = entry found, and there were no code insertions or deletions 1112 /// 2 = entry found, and there were code insertions or deletions 1113 int ARMConstantIslands::findInRangeCPEntry(CPUser& U, unsigned UserOffset) 1114 { 1115 MachineInstr *UserMI = U.MI; 1116 MachineInstr *CPEMI = U.CPEMI; 1117 1118 // Check to see if the CPE is already in-range. 1119 if (isCPEntryInRange(UserMI, UserOffset, CPEMI, U.getMaxDisp(), U.NegOk, 1120 true)) { 1121 DEBUG(dbgs() << "In range\n"); 1122 return 1; 1123 } 1124 1125 // No. Look for previously created clones of the CPE that are in range. 1126 unsigned CPI = getCombinedIndex(CPEMI); 1127 std::vector<CPEntry> &CPEs = CPEntries[CPI]; 1128 for (unsigned i = 0, e = CPEs.size(); i != e; ++i) { 1129 // We already tried this one 1130 if (CPEs[i].CPEMI == CPEMI) 1131 continue; 1132 // Removing CPEs can leave empty entries, skip 1133 if (CPEs[i].CPEMI == nullptr) 1134 continue; 1135 if (isCPEntryInRange(UserMI, UserOffset, CPEs[i].CPEMI, U.getMaxDisp(), 1136 U.NegOk)) { 1137 DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" 1138 << CPEs[i].CPI << "\n"); 1139 // Point the CPUser node to the replacement 1140 U.CPEMI = CPEs[i].CPEMI; 1141 // Change the CPI in the instruction operand to refer to the clone. 1142 for (unsigned j = 0, e = UserMI->getNumOperands(); j != e; ++j) 1143 if (UserMI->getOperand(j).isCPI()) { 1144 UserMI->getOperand(j).setIndex(CPEs[i].CPI); 1145 break; 1146 } 1147 // Adjust the refcount of the clone... 1148 CPEs[i].RefCount++; 1149 // ...and the original. If we didn't remove the old entry, none of the 1150 // addresses changed, so we don't need another pass. 1151 return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1; 1152 } 1153 } 1154 return 0; 1155 } 1156 1157 /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in 1158 /// the specific unconditional branch instruction. 1159 static inline unsigned getUnconditionalBrDisp(int Opc) { 1160 switch (Opc) { 1161 case ARM::tB: 1162 return ((1<<10)-1)*2; 1163 case ARM::t2B: 1164 return ((1<<23)-1)*2; 1165 default: 1166 break; 1167 } 1168 1169 return ((1<<23)-1)*4; 1170 } 1171 1172 /// findAvailableWater - Look for an existing entry in the WaterList in which 1173 /// we can place the CPE referenced from U so it's within range of U's MI. 1174 /// Returns true if found, false if not. If it returns true, WaterIter 1175 /// is set to the WaterList entry. For Thumb, prefer water that will not 1176 /// introduce padding to water that will. To ensure that this pass 1177 /// terminates, the CPE location for a particular CPUser is only allowed to 1178 /// move to a lower address, so search backward from the end of the list and 1179 /// prefer the first water that is in range. 1180 bool ARMConstantIslands::findAvailableWater(CPUser &U, unsigned UserOffset, 1181 water_iterator &WaterIter, 1182 bool CloserWater) { 1183 if (WaterList.empty()) 1184 return false; 1185 1186 unsigned BestGrowth = ~0u; 1187 // The nearest water without splitting the UserBB is right after it. 1188 // If the distance is still large (we have a big BB), then we need to split it 1189 // if we don't converge after certain iterations. This helps the following 1190 // situation to converge: 1191 // BB0: 1192 // Big BB 1193 // BB1: 1194 // Constant Pool 1195 // When a CP access is out of range, BB0 may be used as water. However, 1196 // inserting islands between BB0 and BB1 makes other accesses out of range. 1197 MachineBasicBlock *UserBB = U.MI->getParent(); 1198 unsigned MinNoSplitDisp = 1199 BBInfo[UserBB->getNumber()].postOffset(getCPELogAlign(U.CPEMI)); 1200 if (CloserWater && MinNoSplitDisp > U.getMaxDisp() / 2) 1201 return false; 1202 for (water_iterator IP = std::prev(WaterList.end()), B = WaterList.begin();; 1203 --IP) { 1204 MachineBasicBlock* WaterBB = *IP; 1205 // Check if water is in range and is either at a lower address than the 1206 // current "high water mark" or a new water block that was created since 1207 // the previous iteration by inserting an unconditional branch. In the 1208 // latter case, we want to allow resetting the high water mark back to 1209 // this new water since we haven't seen it before. Inserting branches 1210 // should be relatively uncommon and when it does happen, we want to be 1211 // sure to take advantage of it for all the CPEs near that block, so that 1212 // we don't insert more branches than necessary. 1213 // When CloserWater is true, we try to find the lowest address after (or 1214 // equal to) user MI's BB no matter of padding growth. 1215 unsigned Growth; 1216 if (isWaterInRange(UserOffset, WaterBB, U, Growth) && 1217 (WaterBB->getNumber() < U.HighWaterMark->getNumber() || 1218 NewWaterList.count(WaterBB) || WaterBB == U.MI->getParent()) && 1219 Growth < BestGrowth) { 1220 // This is the least amount of required padding seen so far. 1221 BestGrowth = Growth; 1222 WaterIter = IP; 1223 DEBUG(dbgs() << "Found water after BB#" << WaterBB->getNumber() 1224 << " Growth=" << Growth << '\n'); 1225 1226 if (CloserWater && WaterBB == U.MI->getParent()) 1227 return true; 1228 // Keep looking unless it is perfect and we're not looking for the lowest 1229 // possible address. 1230 if (!CloserWater && BestGrowth == 0) 1231 return true; 1232 } 1233 if (IP == B) 1234 break; 1235 } 1236 return BestGrowth != ~0u; 1237 } 1238 1239 /// createNewWater - No existing WaterList entry will work for 1240 /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the 1241 /// block is used if in range, and the conditional branch munged so control 1242 /// flow is correct. Otherwise the block is split to create a hole with an 1243 /// unconditional branch around it. In either case NewMBB is set to a 1244 /// block following which the new island can be inserted (the WaterList 1245 /// is not adjusted). 1246 void ARMConstantIslands::createNewWater(unsigned CPUserIndex, 1247 unsigned UserOffset, 1248 MachineBasicBlock *&NewMBB) { 1249 CPUser &U = CPUsers[CPUserIndex]; 1250 MachineInstr *UserMI = U.MI; 1251 MachineInstr *CPEMI = U.CPEMI; 1252 unsigned CPELogAlign = getCPELogAlign(CPEMI); 1253 MachineBasicBlock *UserMBB = UserMI->getParent(); 1254 const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()]; 1255 1256 // If the block does not end in an unconditional branch already, and if the 1257 // end of the block is within range, make new water there. (The addition 1258 // below is for the unconditional branch we will be adding: 4 bytes on ARM + 1259 // Thumb2, 2 on Thumb1. 1260 if (BBHasFallthrough(UserMBB)) { 1261 // Size of branch to insert. 1262 unsigned Delta = isThumb1 ? 2 : 4; 1263 // Compute the offset where the CPE will begin. 1264 unsigned CPEOffset = UserBBI.postOffset(CPELogAlign) + Delta; 1265 1266 if (isOffsetInRange(UserOffset, CPEOffset, U)) { 1267 DEBUG(dbgs() << "Split at end of BB#" << UserMBB->getNumber() 1268 << format(", expected CPE offset %#x\n", CPEOffset)); 1269 NewMBB = &*++UserMBB->getIterator(); 1270 // Add an unconditional branch from UserMBB to fallthrough block. Record 1271 // it for branch lengthening; this new branch will not get out of range, 1272 // but if the preceding conditional branch is out of range, the targets 1273 // will be exchanged, and the altered branch may be out of range, so the 1274 // machinery has to know about it. 1275 int UncondBr = isThumb ? ((isThumb2) ? ARM::t2B : ARM::tB) : ARM::B; 1276 if (!isThumb) 1277 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB); 1278 else 1279 BuildMI(UserMBB, DebugLoc(), TII->get(UncondBr)).addMBB(NewMBB) 1280 .addImm(ARMCC::AL).addReg(0); 1281 unsigned MaxDisp = getUnconditionalBrDisp(UncondBr); 1282 ImmBranches.push_back(ImmBranch(&UserMBB->back(), 1283 MaxDisp, false, UncondBr)); 1284 computeBlockSize(MF, UserMBB, BBInfo[UserMBB->getNumber()]); 1285 adjustBBOffsetsAfter(UserMBB); 1286 return; 1287 } 1288 } 1289 1290 // What a big block. Find a place within the block to split it. This is a 1291 // little tricky on Thumb1 since instructions are 2 bytes and constant pool 1292 // entries are 4 bytes: if instruction I references island CPE, and 1293 // instruction I+1 references CPE', it will not work well to put CPE as far 1294 // forward as possible, since then CPE' cannot immediately follow it (that 1295 // location is 2 bytes farther away from I+1 than CPE was from I) and we'd 1296 // need to create a new island. So, we make a first guess, then walk through 1297 // the instructions between the one currently being looked at and the 1298 // possible insertion point, and make sure any other instructions that 1299 // reference CPEs will be able to use the same island area; if not, we back 1300 // up the insertion point. 1301 1302 // Try to split the block so it's fully aligned. Compute the latest split 1303 // point where we can add a 4-byte branch instruction, and then align to 1304 // LogAlign which is the largest possible alignment in the function. 1305 unsigned LogAlign = MF->getAlignment(); 1306 assert(LogAlign >= CPELogAlign && "Over-aligned constant pool entry"); 1307 unsigned KnownBits = UserBBI.internalKnownBits(); 1308 unsigned UPad = UnknownPadding(LogAlign, KnownBits); 1309 unsigned BaseInsertOffset = UserOffset + U.getMaxDisp() - UPad; 1310 DEBUG(dbgs() << format("Split in middle of big block before %#x", 1311 BaseInsertOffset)); 1312 1313 // The 4 in the following is for the unconditional branch we'll be inserting 1314 // (allows for long branch on Thumb1). Alignment of the island is handled 1315 // inside isOffsetInRange. 1316 BaseInsertOffset -= 4; 1317 1318 DEBUG(dbgs() << format(", adjusted to %#x", BaseInsertOffset) 1319 << " la=" << LogAlign 1320 << " kb=" << KnownBits 1321 << " up=" << UPad << '\n'); 1322 1323 // This could point off the end of the block if we've already got constant 1324 // pool entries following this block; only the last one is in the water list. 1325 // Back past any possible branches (allow for a conditional and a maximally 1326 // long unconditional). 1327 if (BaseInsertOffset + 8 >= UserBBI.postOffset()) { 1328 // Ensure BaseInsertOffset is larger than the offset of the instruction 1329 // following UserMI so that the loop which searches for the split point 1330 // iterates at least once. 1331 BaseInsertOffset = 1332 std::max(UserBBI.postOffset() - UPad - 8, 1333 UserOffset + TII->getInstSizeInBytes(*UserMI) + 1); 1334 DEBUG(dbgs() << format("Move inside block: %#x\n", BaseInsertOffset)); 1335 } 1336 unsigned EndInsertOffset = BaseInsertOffset + 4 + UPad + 1337 CPEMI->getOperand(2).getImm(); 1338 MachineBasicBlock::iterator MI = UserMI; 1339 ++MI; 1340 unsigned CPUIndex = CPUserIndex+1; 1341 unsigned NumCPUsers = CPUsers.size(); 1342 MachineInstr *LastIT = nullptr; 1343 for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(*UserMI); 1344 Offset < BaseInsertOffset; 1345 Offset += TII->getInstSizeInBytes(*MI), MI = std::next(MI)) { 1346 assert(MI != UserMBB->end() && "Fell off end of block"); 1347 if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == &*MI) { 1348 CPUser &U = CPUsers[CPUIndex]; 1349 if (!isOffsetInRange(Offset, EndInsertOffset, U)) { 1350 // Shift intertion point by one unit of alignment so it is within reach. 1351 BaseInsertOffset -= 1u << LogAlign; 1352 EndInsertOffset -= 1u << LogAlign; 1353 } 1354 // This is overly conservative, as we don't account for CPEMIs being 1355 // reused within the block, but it doesn't matter much. Also assume CPEs 1356 // are added in order with alignment padding. We may eventually be able 1357 // to pack the aligned CPEs better. 1358 EndInsertOffset += U.CPEMI->getOperand(2).getImm(); 1359 CPUIndex++; 1360 } 1361 1362 // Remember the last IT instruction. 1363 if (MI->getOpcode() == ARM::t2IT) 1364 LastIT = &*MI; 1365 } 1366 1367 --MI; 1368 1369 // Avoid splitting an IT block. 1370 if (LastIT) { 1371 unsigned PredReg = 0; 1372 ARMCC::CondCodes CC = getITInstrPredicate(*MI, PredReg); 1373 if (CC != ARMCC::AL) 1374 MI = LastIT; 1375 } 1376 1377 // We really must not split an IT block. 1378 DEBUG(unsigned PredReg; 1379 assert(!isThumb || getITInstrPredicate(*MI, PredReg) == ARMCC::AL)); 1380 1381 NewMBB = splitBlockBeforeInstr(&*MI); 1382 } 1383 1384 /// handleConstantPoolUser - Analyze the specified user, checking to see if it 1385 /// is out-of-range. If so, pick up the constant pool value and move it some 1386 /// place in-range. Return true if we changed any addresses (thus must run 1387 /// another pass of branch lengthening), false otherwise. 1388 bool ARMConstantIslands::handleConstantPoolUser(unsigned CPUserIndex, 1389 bool CloserWater) { 1390 CPUser &U = CPUsers[CPUserIndex]; 1391 MachineInstr *UserMI = U.MI; 1392 MachineInstr *CPEMI = U.CPEMI; 1393 unsigned CPI = getCombinedIndex(CPEMI); 1394 unsigned Size = CPEMI->getOperand(2).getImm(); 1395 // Compute this only once, it's expensive. 1396 unsigned UserOffset = getUserOffset(U); 1397 1398 // See if the current entry is within range, or there is a clone of it 1399 // in range. 1400 int result = findInRangeCPEntry(U, UserOffset); 1401 if (result==1) return false; 1402 else if (result==2) return true; 1403 1404 // No existing clone of this CPE is within range. 1405 // We will be generating a new clone. Get a UID for it. 1406 unsigned ID = AFI->createPICLabelUId(); 1407 1408 // Look for water where we can place this CPE. 1409 MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock(); 1410 MachineBasicBlock *NewMBB; 1411 water_iterator IP; 1412 if (findAvailableWater(U, UserOffset, IP, CloserWater)) { 1413 DEBUG(dbgs() << "Found water in range\n"); 1414 MachineBasicBlock *WaterBB = *IP; 1415 1416 // If the original WaterList entry was "new water" on this iteration, 1417 // propagate that to the new island. This is just keeping NewWaterList 1418 // updated to match the WaterList, which will be updated below. 1419 if (NewWaterList.erase(WaterBB)) 1420 NewWaterList.insert(NewIsland); 1421 1422 // The new CPE goes before the following block (NewMBB). 1423 NewMBB = &*++WaterBB->getIterator(); 1424 } else { 1425 // No water found. 1426 DEBUG(dbgs() << "No water found\n"); 1427 createNewWater(CPUserIndex, UserOffset, NewMBB); 1428 1429 // splitBlockBeforeInstr adds to WaterList, which is important when it is 1430 // called while handling branches so that the water will be seen on the 1431 // next iteration for constant pools, but in this context, we don't want 1432 // it. Check for this so it will be removed from the WaterList. 1433 // Also remove any entry from NewWaterList. 1434 MachineBasicBlock *WaterBB = &*--NewMBB->getIterator(); 1435 IP = std::find(WaterList.begin(), WaterList.end(), WaterBB); 1436 if (IP != WaterList.end()) 1437 NewWaterList.erase(WaterBB); 1438 1439 // We are adding new water. Update NewWaterList. 1440 NewWaterList.insert(NewIsland); 1441 } 1442 1443 // Remove the original WaterList entry; we want subsequent insertions in 1444 // this vicinity to go after the one we're about to insert. This 1445 // considerably reduces the number of times we have to move the same CPE 1446 // more than once and is also important to ensure the algorithm terminates. 1447 if (IP != WaterList.end()) 1448 WaterList.erase(IP); 1449 1450 // Okay, we know we can put an island before NewMBB now, do it! 1451 MF->insert(NewMBB->getIterator(), NewIsland); 1452 1453 // Update internal data structures to account for the newly inserted MBB. 1454 updateForInsertedWaterBlock(NewIsland); 1455 1456 // Now that we have an island to add the CPE to, clone the original CPE and 1457 // add it to the island. 1458 U.HighWaterMark = NewIsland; 1459 U.CPEMI = BuildMI(NewIsland, DebugLoc(), CPEMI->getDesc()) 1460 .addImm(ID).addOperand(CPEMI->getOperand(1)).addImm(Size); 1461 CPEntries[CPI].push_back(CPEntry(U.CPEMI, ID, 1)); 1462 ++NumCPEs; 1463 1464 // Decrement the old entry, and remove it if refcount becomes 0. 1465 decrementCPEReferenceCount(CPI, CPEMI); 1466 1467 // Mark the basic block as aligned as required by the const-pool entry. 1468 NewIsland->setAlignment(getCPELogAlign(U.CPEMI)); 1469 1470 // Increase the size of the island block to account for the new entry. 1471 BBInfo[NewIsland->getNumber()].Size += Size; 1472 adjustBBOffsetsAfter(&*--NewIsland->getIterator()); 1473 1474 // Finally, change the CPI in the instruction operand to be ID. 1475 for (unsigned i = 0, e = UserMI->getNumOperands(); i != e; ++i) 1476 if (UserMI->getOperand(i).isCPI()) { 1477 UserMI->getOperand(i).setIndex(ID); 1478 break; 1479 } 1480 1481 DEBUG(dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI 1482 << format(" offset=%#x\n", BBInfo[NewIsland->getNumber()].Offset)); 1483 1484 return true; 1485 } 1486 1487 /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update 1488 /// sizes and offsets of impacted basic blocks. 1489 void ARMConstantIslands::removeDeadCPEMI(MachineInstr *CPEMI) { 1490 MachineBasicBlock *CPEBB = CPEMI->getParent(); 1491 unsigned Size = CPEMI->getOperand(2).getImm(); 1492 CPEMI->eraseFromParent(); 1493 BBInfo[CPEBB->getNumber()].Size -= Size; 1494 // All succeeding offsets have the current size value added in, fix this. 1495 if (CPEBB->empty()) { 1496 BBInfo[CPEBB->getNumber()].Size = 0; 1497 1498 // This block no longer needs to be aligned. 1499 CPEBB->setAlignment(0); 1500 } else 1501 // Entries are sorted by descending alignment, so realign from the front. 1502 CPEBB->setAlignment(getCPELogAlign(&*CPEBB->begin())); 1503 1504 adjustBBOffsetsAfter(CPEBB); 1505 // An island has only one predecessor BB and one successor BB. Check if 1506 // this BB's predecessor jumps directly to this BB's successor. This 1507 // shouldn't happen currently. 1508 assert(!BBIsJumpedOver(CPEBB) && "How did this happen?"); 1509 // FIXME: remove the empty blocks after all the work is done? 1510 } 1511 1512 /// removeUnusedCPEntries - Remove constant pool entries whose refcounts 1513 /// are zero. 1514 bool ARMConstantIslands::removeUnusedCPEntries() { 1515 unsigned MadeChange = false; 1516 for (unsigned i = 0, e = CPEntries.size(); i != e; ++i) { 1517 std::vector<CPEntry> &CPEs = CPEntries[i]; 1518 for (unsigned j = 0, ee = CPEs.size(); j != ee; ++j) { 1519 if (CPEs[j].RefCount == 0 && CPEs[j].CPEMI) { 1520 removeDeadCPEMI(CPEs[j].CPEMI); 1521 CPEs[j].CPEMI = nullptr; 1522 MadeChange = true; 1523 } 1524 } 1525 } 1526 return MadeChange; 1527 } 1528 1529 /// isBBInRange - Returns true if the distance between specific MI and 1530 /// specific BB can fit in MI's displacement field. 1531 bool ARMConstantIslands::isBBInRange(MachineInstr *MI,MachineBasicBlock *DestBB, 1532 unsigned MaxDisp) { 1533 unsigned PCAdj = isThumb ? 4 : 8; 1534 unsigned BrOffset = getOffsetOf(MI) + PCAdj; 1535 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset; 1536 1537 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber() 1538 << " from BB#" << MI->getParent()->getNumber() 1539 << " max delta=" << MaxDisp 1540 << " from " << getOffsetOf(MI) << " to " << DestOffset 1541 << " offset " << int(DestOffset-BrOffset) << "\t" << *MI); 1542 1543 if (BrOffset <= DestOffset) { 1544 // Branch before the Dest. 1545 if (DestOffset-BrOffset <= MaxDisp) 1546 return true; 1547 } else { 1548 if (BrOffset-DestOffset <= MaxDisp) 1549 return true; 1550 } 1551 return false; 1552 } 1553 1554 /// fixupImmediateBr - Fix up an immediate branch whose destination is too far 1555 /// away to fit in its displacement field. 1556 bool ARMConstantIslands::fixupImmediateBr(ImmBranch &Br) { 1557 MachineInstr *MI = Br.MI; 1558 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB(); 1559 1560 // Check to see if the DestBB is already in-range. 1561 if (isBBInRange(MI, DestBB, Br.MaxDisp)) 1562 return false; 1563 1564 if (!Br.isCond) 1565 return fixupUnconditionalBr(Br); 1566 return fixupConditionalBr(Br); 1567 } 1568 1569 /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is 1570 /// too far away to fit in its displacement field. If the LR register has been 1571 /// spilled in the epilogue, then we can use BL to implement a far jump. 1572 /// Otherwise, add an intermediate branch instruction to a branch. 1573 bool 1574 ARMConstantIslands::fixupUnconditionalBr(ImmBranch &Br) { 1575 MachineInstr *MI = Br.MI; 1576 MachineBasicBlock *MBB = MI->getParent(); 1577 if (!isThumb1) 1578 llvm_unreachable("fixupUnconditionalBr is Thumb1 only!"); 1579 1580 // Use BL to implement far jump. 1581 Br.MaxDisp = (1 << 21) * 2; 1582 MI->setDesc(TII->get(ARM::tBfar)); 1583 BBInfo[MBB->getNumber()].Size += 2; 1584 adjustBBOffsetsAfter(MBB); 1585 HasFarJump = true; 1586 ++NumUBrFixed; 1587 1588 DEBUG(dbgs() << " Changed B to long jump " << *MI); 1589 1590 return true; 1591 } 1592 1593 /// fixupConditionalBr - Fix up a conditional branch whose destination is too 1594 /// far away to fit in its displacement field. It is converted to an inverse 1595 /// conditional branch + an unconditional branch to the destination. 1596 bool 1597 ARMConstantIslands::fixupConditionalBr(ImmBranch &Br) { 1598 MachineInstr *MI = Br.MI; 1599 MachineBasicBlock *DestBB = MI->getOperand(0).getMBB(); 1600 1601 // Add an unconditional branch to the destination and invert the branch 1602 // condition to jump over it: 1603 // blt L1 1604 // => 1605 // bge L2 1606 // b L1 1607 // L2: 1608 ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(1).getImm(); 1609 CC = ARMCC::getOppositeCondition(CC); 1610 unsigned CCReg = MI->getOperand(2).getReg(); 1611 1612 // If the branch is at the end of its MBB and that has a fall-through block, 1613 // direct the updated conditional branch to the fall-through block. Otherwise, 1614 // split the MBB before the next instruction. 1615 MachineBasicBlock *MBB = MI->getParent(); 1616 MachineInstr *BMI = &MBB->back(); 1617 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB); 1618 1619 ++NumCBrFixed; 1620 if (BMI != MI) { 1621 if (std::next(MachineBasicBlock::iterator(MI)) == std::prev(MBB->end()) && 1622 BMI->getOpcode() == Br.UncondBr) { 1623 // Last MI in the BB is an unconditional branch. Can we simply invert the 1624 // condition and swap destinations: 1625 // beq L1 1626 // b L2 1627 // => 1628 // bne L2 1629 // b L1 1630 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB(); 1631 if (isBBInRange(MI, NewDest, Br.MaxDisp)) { 1632 DEBUG(dbgs() << " Invert Bcc condition and swap its destination with " 1633 << *BMI); 1634 BMI->getOperand(0).setMBB(DestBB); 1635 MI->getOperand(0).setMBB(NewDest); 1636 MI->getOperand(1).setImm(CC); 1637 return true; 1638 } 1639 } 1640 } 1641 1642 if (NeedSplit) { 1643 splitBlockBeforeInstr(MI); 1644 // No need for the branch to the next block. We're adding an unconditional 1645 // branch to the destination. 1646 int delta = TII->getInstSizeInBytes(MBB->back()); 1647 BBInfo[MBB->getNumber()].Size -= delta; 1648 MBB->back().eraseFromParent(); 1649 // BBInfo[SplitBB].Offset is wrong temporarily, fixed below 1650 } 1651 MachineBasicBlock *NextBB = &*++MBB->getIterator(); 1652 1653 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber() 1654 << " also invert condition and change dest. to BB#" 1655 << NextBB->getNumber() << "\n"); 1656 1657 // Insert a new conditional branch and a new unconditional branch. 1658 // Also update the ImmBranch as well as adding a new entry for the new branch. 1659 BuildMI(MBB, DebugLoc(), TII->get(MI->getOpcode())) 1660 .addMBB(NextBB).addImm(CC).addReg(CCReg); 1661 Br.MI = &MBB->back(); 1662 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back()); 1663 if (isThumb) 1664 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB) 1665 .addImm(ARMCC::AL).addReg(0); 1666 else 1667 BuildMI(MBB, DebugLoc(), TII->get(Br.UncondBr)).addMBB(DestBB); 1668 BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MBB->back()); 1669 unsigned MaxDisp = getUnconditionalBrDisp(Br.UncondBr); 1670 ImmBranches.push_back(ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr)); 1671 1672 // Remove the old conditional branch. It may or may not still be in MBB. 1673 BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(*MI); 1674 MI->eraseFromParent(); 1675 adjustBBOffsetsAfter(MBB); 1676 return true; 1677 } 1678 1679 /// undoLRSpillRestore - Remove Thumb push / pop instructions that only spills 1680 /// LR / restores LR to pc. FIXME: This is done here because it's only possible 1681 /// to do this if tBfar is not used. 1682 bool ARMConstantIslands::undoLRSpillRestore() { 1683 bool MadeChange = false; 1684 for (unsigned i = 0, e = PushPopMIs.size(); i != e; ++i) { 1685 MachineInstr *MI = PushPopMIs[i]; 1686 // First two operands are predicates. 1687 if (MI->getOpcode() == ARM::tPOP_RET && 1688 MI->getOperand(2).getReg() == ARM::PC && 1689 MI->getNumExplicitOperands() == 3) { 1690 // Create the new insn and copy the predicate from the old. 1691 BuildMI(MI->getParent(), MI->getDebugLoc(), TII->get(ARM::tBX_RET)) 1692 .addOperand(MI->getOperand(0)) 1693 .addOperand(MI->getOperand(1)); 1694 MI->eraseFromParent(); 1695 MadeChange = true; 1696 } 1697 } 1698 return MadeChange; 1699 } 1700 1701 bool ARMConstantIslands::optimizeThumb2Instructions() { 1702 bool MadeChange = false; 1703 1704 // Shrink ADR and LDR from constantpool. 1705 for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) { 1706 CPUser &U = CPUsers[i]; 1707 unsigned Opcode = U.MI->getOpcode(); 1708 unsigned NewOpc = 0; 1709 unsigned Scale = 1; 1710 unsigned Bits = 0; 1711 switch (Opcode) { 1712 default: break; 1713 case ARM::t2LEApcrel: 1714 if (isARMLowRegister(U.MI->getOperand(0).getReg())) { 1715 NewOpc = ARM::tLEApcrel; 1716 Bits = 8; 1717 Scale = 4; 1718 } 1719 break; 1720 case ARM::t2LDRpci: 1721 if (isARMLowRegister(U.MI->getOperand(0).getReg())) { 1722 NewOpc = ARM::tLDRpci; 1723 Bits = 8; 1724 Scale = 4; 1725 } 1726 break; 1727 } 1728 1729 if (!NewOpc) 1730 continue; 1731 1732 unsigned UserOffset = getUserOffset(U); 1733 unsigned MaxOffs = ((1 << Bits) - 1) * Scale; 1734 1735 // Be conservative with inline asm. 1736 if (!U.KnownAlignment) 1737 MaxOffs -= 2; 1738 1739 // FIXME: Check if offset is multiple of scale if scale is not 4. 1740 if (isCPEntryInRange(U.MI, UserOffset, U.CPEMI, MaxOffs, false, true)) { 1741 DEBUG(dbgs() << "Shrink: " << *U.MI); 1742 U.MI->setDesc(TII->get(NewOpc)); 1743 MachineBasicBlock *MBB = U.MI->getParent(); 1744 BBInfo[MBB->getNumber()].Size -= 2; 1745 adjustBBOffsetsAfter(MBB); 1746 ++NumT2CPShrunk; 1747 MadeChange = true; 1748 } 1749 } 1750 1751 return MadeChange; 1752 } 1753 1754 bool ARMConstantIslands::optimizeThumb2Branches() { 1755 bool MadeChange = false; 1756 1757 // The order in which branches appear in ImmBranches is approximately their 1758 // order within the function body. By visiting later branches first, we reduce 1759 // the distance between earlier forward branches and their targets, making it 1760 // more likely that the cbn?z optimization, which can only apply to forward 1761 // branches, will succeed. 1762 for (unsigned i = ImmBranches.size(); i != 0; --i) { 1763 ImmBranch &Br = ImmBranches[i-1]; 1764 unsigned Opcode = Br.MI->getOpcode(); 1765 unsigned NewOpc = 0; 1766 unsigned Scale = 1; 1767 unsigned Bits = 0; 1768 switch (Opcode) { 1769 default: break; 1770 case ARM::t2B: 1771 NewOpc = ARM::tB; 1772 Bits = 11; 1773 Scale = 2; 1774 break; 1775 case ARM::t2Bcc: { 1776 NewOpc = ARM::tBcc; 1777 Bits = 8; 1778 Scale = 2; 1779 break; 1780 } 1781 } 1782 if (NewOpc) { 1783 unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; 1784 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 1785 if (isBBInRange(Br.MI, DestBB, MaxOffs)) { 1786 DEBUG(dbgs() << "Shrink branch: " << *Br.MI); 1787 Br.MI->setDesc(TII->get(NewOpc)); 1788 MachineBasicBlock *MBB = Br.MI->getParent(); 1789 BBInfo[MBB->getNumber()].Size -= 2; 1790 adjustBBOffsetsAfter(MBB); 1791 ++NumT2BrShrunk; 1792 MadeChange = true; 1793 } 1794 } 1795 1796 Opcode = Br.MI->getOpcode(); 1797 if (Opcode != ARM::tBcc) 1798 continue; 1799 1800 // If the conditional branch doesn't kill CPSR, then CPSR can be liveout 1801 // so this transformation is not safe. 1802 if (!Br.MI->killsRegister(ARM::CPSR)) 1803 continue; 1804 1805 NewOpc = 0; 1806 unsigned PredReg = 0; 1807 ARMCC::CondCodes Pred = getInstrPredicate(*Br.MI, PredReg); 1808 if (Pred == ARMCC::EQ) 1809 NewOpc = ARM::tCBZ; 1810 else if (Pred == ARMCC::NE) 1811 NewOpc = ARM::tCBNZ; 1812 if (!NewOpc) 1813 continue; 1814 MachineBasicBlock *DestBB = Br.MI->getOperand(0).getMBB(); 1815 // Check if the distance is within 126. Subtract starting offset by 2 1816 // because the cmp will be eliminated. 1817 unsigned BrOffset = getOffsetOf(Br.MI) + 4 - 2; 1818 unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset; 1819 if (BrOffset < DestOffset && (DestOffset - BrOffset) <= 126) { 1820 MachineBasicBlock::iterator CmpMI = Br.MI; 1821 if (CmpMI != Br.MI->getParent()->begin()) { 1822 --CmpMI; 1823 if (CmpMI->getOpcode() == ARM::tCMPi8) { 1824 unsigned Reg = CmpMI->getOperand(0).getReg(); 1825 Pred = getInstrPredicate(*CmpMI, PredReg); 1826 if (Pred == ARMCC::AL && 1827 CmpMI->getOperand(1).getImm() == 0 && 1828 isARMLowRegister(Reg)) { 1829 MachineBasicBlock *MBB = Br.MI->getParent(); 1830 DEBUG(dbgs() << "Fold: " << *CmpMI << " and: " << *Br.MI); 1831 MachineInstr *NewBR = 1832 BuildMI(*MBB, CmpMI, Br.MI->getDebugLoc(), TII->get(NewOpc)) 1833 .addReg(Reg).addMBB(DestBB,Br.MI->getOperand(0).getTargetFlags()); 1834 CmpMI->eraseFromParent(); 1835 Br.MI->eraseFromParent(); 1836 Br.MI = NewBR; 1837 BBInfo[MBB->getNumber()].Size -= 2; 1838 adjustBBOffsetsAfter(MBB); 1839 ++NumCBZ; 1840 MadeChange = true; 1841 } 1842 } 1843 } 1844 } 1845 } 1846 1847 return MadeChange; 1848 } 1849 1850 static bool isSimpleIndexCalc(MachineInstr &I, unsigned EntryReg, 1851 unsigned BaseReg) { 1852 if (I.getOpcode() != ARM::t2ADDrs) 1853 return false; 1854 1855 if (I.getOperand(0).getReg() != EntryReg) 1856 return false; 1857 1858 if (I.getOperand(1).getReg() != BaseReg) 1859 return false; 1860 1861 // FIXME: what about CC and IdxReg? 1862 return true; 1863 } 1864 1865 /// \brief While trying to form a TBB/TBH instruction, we may (if the table 1866 /// doesn't immediately follow the BR_JT) need access to the start of the 1867 /// jump-table. We know one instruction that produces such a register; this 1868 /// function works out whether that definition can be preserved to the BR_JT, 1869 /// possibly by removing an intervening addition (which is usually needed to 1870 /// calculate the actual entry to jump to). 1871 bool ARMConstantIslands::preserveBaseRegister(MachineInstr *JumpMI, 1872 MachineInstr *LEAMI, 1873 unsigned &DeadSize, 1874 bool &CanDeleteLEA, 1875 bool &BaseRegKill) { 1876 if (JumpMI->getParent() != LEAMI->getParent()) 1877 return false; 1878 1879 // Now we hope that we have at least these instructions in the basic block: 1880 // BaseReg = t2LEA ... 1881 // [...] 1882 // EntryReg = t2ADDrs BaseReg, ... 1883 // [...] 1884 // t2BR_JT EntryReg 1885 // 1886 // We have to be very conservative about what we recognise here though. The 1887 // main perturbing factors to watch out for are: 1888 // + Spills at any point in the chain: not direct problems but we would 1889 // expect a blocking Def of the spilled register so in practice what we 1890 // can do is limited. 1891 // + EntryReg == BaseReg: this is the one situation we should allow a Def 1892 // of BaseReg, but only if the t2ADDrs can be removed. 1893 // + Some instruction other than t2ADDrs computing the entry. Not seen in 1894 // the wild, but we should be careful. 1895 unsigned EntryReg = JumpMI->getOperand(0).getReg(); 1896 unsigned BaseReg = LEAMI->getOperand(0).getReg(); 1897 1898 CanDeleteLEA = true; 1899 BaseRegKill = false; 1900 MachineInstr *RemovableAdd = nullptr; 1901 MachineBasicBlock::iterator I(LEAMI); 1902 for (++I; &*I != JumpMI; ++I) { 1903 if (isSimpleIndexCalc(*I, EntryReg, BaseReg)) { 1904 RemovableAdd = &*I; 1905 break; 1906 } 1907 1908 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) { 1909 const MachineOperand &MO = I->getOperand(K); 1910 if (!MO.isReg() || !MO.getReg()) 1911 continue; 1912 if (MO.isDef() && MO.getReg() == BaseReg) 1913 return false; 1914 if (MO.isUse() && MO.getReg() == BaseReg) { 1915 BaseRegKill = BaseRegKill || MO.isKill(); 1916 CanDeleteLEA = false; 1917 } 1918 } 1919 } 1920 1921 if (!RemovableAdd) 1922 return true; 1923 1924 // Check the add really is removable, and that nothing else in the block 1925 // clobbers BaseReg. 1926 for (++I; &*I != JumpMI; ++I) { 1927 for (unsigned K = 0, E = I->getNumOperands(); K != E; ++K) { 1928 const MachineOperand &MO = I->getOperand(K); 1929 if (!MO.isReg() || !MO.getReg()) 1930 continue; 1931 if (MO.isDef() && MO.getReg() == BaseReg) 1932 return false; 1933 if (MO.isUse() && MO.getReg() == EntryReg) 1934 RemovableAdd = nullptr; 1935 } 1936 } 1937 1938 if (RemovableAdd) { 1939 RemovableAdd->eraseFromParent(); 1940 DeadSize += 4; 1941 } else if (BaseReg == EntryReg) { 1942 // The add wasn't removable, but clobbered the base for the TBB. So we can't 1943 // preserve it. 1944 return false; 1945 } 1946 1947 // We reached the end of the block without seeing another definition of 1948 // BaseReg (except, possibly the t2ADDrs, which was removed). BaseReg can be 1949 // used in the TBB/TBH if necessary. 1950 return true; 1951 } 1952 1953 /// \brief Returns whether CPEMI is the first instruction in the block 1954 /// immediately following JTMI (assumed to be a TBB or TBH terminator). If so, 1955 /// we can switch the first register to PC and usually remove the address 1956 /// calculation that preceded it. 1957 static bool jumpTableFollowsTB(MachineInstr *JTMI, MachineInstr *CPEMI) { 1958 MachineFunction::iterator MBB = JTMI->getParent()->getIterator(); 1959 MachineFunction *MF = MBB->getParent(); 1960 ++MBB; 1961 1962 return MBB != MF->end() && MBB->begin() != MBB->end() && 1963 &*MBB->begin() == CPEMI; 1964 } 1965 1966 /// optimizeThumb2JumpTables - Use tbb / tbh instructions to generate smaller 1967 /// jumptables when it's possible. 1968 bool ARMConstantIslands::optimizeThumb2JumpTables() { 1969 bool MadeChange = false; 1970 1971 // FIXME: After the tables are shrunk, can we get rid some of the 1972 // constantpool tables? 1973 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1974 if (!MJTI) return false; 1975 1976 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1977 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) { 1978 MachineInstr *MI = T2JumpTables[i]; 1979 const MCInstrDesc &MCID = MI->getDesc(); 1980 unsigned NumOps = MCID.getNumOperands(); 1981 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1); 1982 MachineOperand JTOP = MI->getOperand(JTOpIdx); 1983 unsigned JTI = JTOP.getIndex(); 1984 assert(JTI < JT.size()); 1985 1986 bool ByteOk = true; 1987 bool HalfWordOk = true; 1988 unsigned JTOffset = getOffsetOf(MI) + 4; 1989 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1990 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) { 1991 MachineBasicBlock *MBB = JTBBs[j]; 1992 unsigned DstOffset = BBInfo[MBB->getNumber()].Offset; 1993 // Negative offset is not ok. FIXME: We should change BB layout to make 1994 // sure all the branches are forward. 1995 if (ByteOk && (DstOffset - JTOffset) > ((1<<8)-1)*2) 1996 ByteOk = false; 1997 unsigned TBHLimit = ((1<<16)-1)*2; 1998 if (HalfWordOk && (DstOffset - JTOffset) > TBHLimit) 1999 HalfWordOk = false; 2000 if (!ByteOk && !HalfWordOk) 2001 break; 2002 } 2003 2004 if (!ByteOk && !HalfWordOk) 2005 continue; 2006 2007 MachineBasicBlock *MBB = MI->getParent(); 2008 if (!MI->getOperand(0).isKill()) // FIXME: needed now? 2009 continue; 2010 unsigned IdxReg = MI->getOperand(1).getReg(); 2011 bool IdxRegKill = MI->getOperand(1).isKill(); 2012 2013 CPUser &User = CPUsers[JumpTableUserIndices[JTI]]; 2014 unsigned DeadSize = 0; 2015 bool CanDeleteLEA = false; 2016 bool BaseRegKill = false; 2017 bool PreservedBaseReg = 2018 preserveBaseRegister(MI, User.MI, DeadSize, CanDeleteLEA, BaseRegKill); 2019 2020 if (!jumpTableFollowsTB(MI, User.CPEMI) && !PreservedBaseReg) 2021 continue; 2022 2023 DEBUG(dbgs() << "Shrink JT: " << *MI); 2024 MachineInstr *CPEMI = User.CPEMI; 2025 unsigned Opc = ByteOk ? ARM::t2TBB_JT : ARM::t2TBH_JT; 2026 MachineBasicBlock::iterator MI_JT = MI; 2027 MachineInstr *NewJTMI = 2028 BuildMI(*MBB, MI_JT, MI->getDebugLoc(), TII->get(Opc)) 2029 .addReg(User.MI->getOperand(0).getReg(), 2030 getKillRegState(BaseRegKill)) 2031 .addReg(IdxReg, getKillRegState(IdxRegKill)) 2032 .addJumpTableIndex(JTI, JTOP.getTargetFlags()) 2033 .addImm(CPEMI->getOperand(0).getImm()); 2034 DEBUG(dbgs() << "BB#" << MBB->getNumber() << ": " << *NewJTMI); 2035 2036 unsigned JTOpc = ByteOk ? ARM::JUMPTABLE_TBB : ARM::JUMPTABLE_TBH; 2037 CPEMI->setDesc(TII->get(JTOpc)); 2038 2039 if (jumpTableFollowsTB(MI, User.CPEMI)) { 2040 NewJTMI->getOperand(0).setReg(ARM::PC); 2041 NewJTMI->getOperand(0).setIsKill(false); 2042 2043 if (CanDeleteLEA) { 2044 User.MI->eraseFromParent(); 2045 DeadSize += 4; 2046 2047 // The LEA was eliminated, the TBB instruction becomes the only new user 2048 // of the jump table. 2049 User.MI = NewJTMI; 2050 User.MaxDisp = 4; 2051 User.NegOk = false; 2052 User.IsSoImm = false; 2053 User.KnownAlignment = false; 2054 } else { 2055 // The LEA couldn't be eliminated, so we must add another CPUser to 2056 // record the TBB or TBH use. 2057 int CPEntryIdx = JumpTableEntryIndices[JTI]; 2058 auto &CPEs = CPEntries[CPEntryIdx]; 2059 auto Entry = std::find_if(CPEs.begin(), CPEs.end(), [&](CPEntry &E) { 2060 return E.CPEMI == User.CPEMI; 2061 }); 2062 ++Entry->RefCount; 2063 CPUsers.emplace_back(CPUser(NewJTMI, User.CPEMI, 4, false, false)); 2064 } 2065 } 2066 2067 unsigned NewSize = TII->getInstSizeInBytes(*NewJTMI); 2068 unsigned OrigSize = TII->getInstSizeInBytes(*MI); 2069 MI->eraseFromParent(); 2070 2071 int Delta = OrigSize - NewSize + DeadSize; 2072 BBInfo[MBB->getNumber()].Size -= Delta; 2073 adjustBBOffsetsAfter(MBB); 2074 2075 ++NumTBs; 2076 MadeChange = true; 2077 } 2078 2079 return MadeChange; 2080 } 2081 2082 /// reorderThumb2JumpTables - Adjust the function's block layout to ensure that 2083 /// jump tables always branch forwards, since that's what tbb and tbh need. 2084 bool ARMConstantIslands::reorderThumb2JumpTables() { 2085 bool MadeChange = false; 2086 2087 MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 2088 if (!MJTI) return false; 2089 2090 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 2091 for (unsigned i = 0, e = T2JumpTables.size(); i != e; ++i) { 2092 MachineInstr *MI = T2JumpTables[i]; 2093 const MCInstrDesc &MCID = MI->getDesc(); 2094 unsigned NumOps = MCID.getNumOperands(); 2095 unsigned JTOpIdx = NumOps - (MI->isPredicable() ? 2 : 1); 2096 MachineOperand JTOP = MI->getOperand(JTOpIdx); 2097 unsigned JTI = JTOP.getIndex(); 2098 assert(JTI < JT.size()); 2099 2100 // We prefer if target blocks for the jump table come after the jump 2101 // instruction so we can use TB[BH]. Loop through the target blocks 2102 // and try to adjust them such that that's true. 2103 int JTNumber = MI->getParent()->getNumber(); 2104 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 2105 for (unsigned j = 0, ee = JTBBs.size(); j != ee; ++j) { 2106 MachineBasicBlock *MBB = JTBBs[j]; 2107 int DTNumber = MBB->getNumber(); 2108 2109 if (DTNumber < JTNumber) { 2110 // The destination precedes the switch. Try to move the block forward 2111 // so we have a positive offset. 2112 MachineBasicBlock *NewBB = 2113 adjustJTTargetBlockForward(MBB, MI->getParent()); 2114 if (NewBB) 2115 MJTI->ReplaceMBBInJumpTable(JTI, JTBBs[j], NewBB); 2116 MadeChange = true; 2117 } 2118 } 2119 } 2120 2121 return MadeChange; 2122 } 2123 2124 MachineBasicBlock *ARMConstantIslands:: 2125 adjustJTTargetBlockForward(MachineBasicBlock *BB, MachineBasicBlock *JTBB) { 2126 // If the destination block is terminated by an unconditional branch, 2127 // try to move it; otherwise, create a new block following the jump 2128 // table that branches back to the actual target. This is a very simple 2129 // heuristic. FIXME: We can definitely improve it. 2130 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 2131 SmallVector<MachineOperand, 4> Cond; 2132 SmallVector<MachineOperand, 4> CondPrior; 2133 MachineFunction::iterator BBi = BB->getIterator(); 2134 MachineFunction::iterator OldPrior = std::prev(BBi); 2135 2136 // If the block terminator isn't analyzable, don't try to move the block 2137 bool B = TII->analyzeBranch(*BB, TBB, FBB, Cond); 2138 2139 // If the block ends in an unconditional branch, move it. The prior block 2140 // has to have an analyzable terminator for us to move this one. Be paranoid 2141 // and make sure we're not trying to move the entry block of the function. 2142 if (!B && Cond.empty() && BB != &MF->front() && 2143 !TII->analyzeBranch(*OldPrior, TBB, FBB, CondPrior)) { 2144 BB->moveAfter(JTBB); 2145 OldPrior->updateTerminator(); 2146 BB->updateTerminator(); 2147 // Update numbering to account for the block being moved. 2148 MF->RenumberBlocks(); 2149 ++NumJTMoved; 2150 return nullptr; 2151 } 2152 2153 // Create a new MBB for the code after the jump BB. 2154 MachineBasicBlock *NewBB = 2155 MF->CreateMachineBasicBlock(JTBB->getBasicBlock()); 2156 MachineFunction::iterator MBBI = ++JTBB->getIterator(); 2157 MF->insert(MBBI, NewBB); 2158 2159 // Add an unconditional branch from NewBB to BB. 2160 // There doesn't seem to be meaningful DebugInfo available; this doesn't 2161 // correspond directly to anything in the source. 2162 assert (isThumb2 && "Adjusting for TB[BH] but not in Thumb2?"); 2163 BuildMI(NewBB, DebugLoc(), TII->get(ARM::t2B)).addMBB(BB) 2164 .addImm(ARMCC::AL).addReg(0); 2165 2166 // Update internal data structures to account for the newly inserted MBB. 2167 MF->RenumberBlocks(NewBB); 2168 2169 // Update the CFG. 2170 NewBB->addSuccessor(BB); 2171 JTBB->replaceSuccessor(BB, NewBB); 2172 2173 ++NumJTInserted; 2174 return NewBB; 2175 } 2176