| 1 | //===- MipsConstantIslandPass.cpp - Emit Pc Relative loads ----------------===// |
| 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 pass is used to make Pc relative loads of constants. |
| 10 | // For now, only Mips16 will use this. |
| 11 | // |
| 12 | // Loading constants inline is expensive on Mips16 and it's in general better |
| 13 | // to place the constant nearby in code space and then it can be loaded with a |
| 14 | // simple 16 bit load instruction. |
| 15 | // |
| 16 | // The constants can be not just numbers but addresses of functions and labels. |
| 17 | // This can be particularly helpful in static relocation mode for embedded |
| 18 | // non-linux targets. |
| 19 | // |
| 20 | //===----------------------------------------------------------------------===// |
| 21 | |
| 22 | #include "Mips.h" |
| 23 | #include "Mips16InstrInfo.h" |
| 24 | #include "MipsMachineFunction.h" |
| 25 | #include "MipsSubtarget.h" |
| 26 | #include "llvm/ADT/STLExtras.h" |
| 27 | #include "llvm/ADT/SmallVector.h" |
| 28 | #include "llvm/ADT/Statistic.h" |
| 29 | #include "llvm/ADT/StringRef.h" |
| 30 | #include "llvm/CodeGen/MachineBasicBlock.h" |
| 31 | #include "llvm/CodeGen/MachineConstantPool.h" |
| 32 | #include "llvm/CodeGen/MachineFunction.h" |
| 33 | #include "llvm/CodeGen/MachineFunctionAnalysisManager.h" |
| 34 | #include "llvm/CodeGen/MachineFunctionPass.h" |
| 35 | #include "llvm/CodeGen/MachineInstr.h" |
| 36 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 37 | #include "llvm/CodeGen/MachineOperand.h" |
| 38 | #include "llvm/CodeGen/MachinePassManager.h" |
| 39 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
| 40 | #include "llvm/Config/llvm-config.h" |
| 41 | #include "llvm/IR/Analysis.h" |
| 42 | #include "llvm/IR/Constants.h" |
| 43 | #include "llvm/IR/DataLayout.h" |
| 44 | #include "llvm/IR/DebugLoc.h" |
| 45 | #include "llvm/IR/Function.h" |
| 46 | #include "llvm/IR/Type.h" |
| 47 | #include "llvm/Support/Compiler.h" |
| 48 | #include "llvm/Support/Debug.h" |
| 49 | #include "llvm/Support/ErrorHandling.h" |
| 50 | #include "llvm/Support/Format.h" |
| 51 | #include "llvm/Support/raw_ostream.h" |
| 52 | #include <cassert> |
| 53 | #include <cstdint> |
| 54 | #include <iterator> |
| 55 | #include <vector> |
| 56 | |
| 57 | using namespace llvm; |
| 58 | |
| 59 | #define DEBUG_TYPE "mips-constant-islands" |
| 60 | |
| 61 | STATISTIC(NumCPEs, "Number of constpool entries" ); |
| 62 | STATISTIC(NumSplit, "Number of uncond branches inserted" ); |
| 63 | STATISTIC(NumCBrFixed, "Number of cond branches fixed" ); |
| 64 | STATISTIC(NumUBrFixed, "Number of uncond branches fixed" ); |
| 65 | |
| 66 | static unsigned int branchTargetOperand(MachineInstr *MI) { |
| 67 | switch (MI->getOpcode()) { |
| 68 | case Mips::Bimm16: |
| 69 | case Mips::BimmX16: |
| 70 | case Mips::Bteqz16: |
| 71 | case Mips::BteqzX16: |
| 72 | case Mips::Btnez16: |
| 73 | case Mips::BtnezX16: |
| 74 | case Mips::JalB16: |
| 75 | return 0; |
| 76 | case Mips::BeqzRxImm16: |
| 77 | case Mips::BeqzRxImmX16: |
| 78 | case Mips::BnezRxImm16: |
| 79 | case Mips::BnezRxImmX16: |
| 80 | return 1; |
| 81 | } |
| 82 | llvm_unreachable("Unknown branch type" ); |
| 83 | } |
| 84 | |
| 85 | static unsigned int longformBranchOpcode(unsigned int Opcode) { |
| 86 | switch (Opcode) { |
| 87 | case Mips::Bimm16: |
| 88 | case Mips::BimmX16: |
| 89 | return Mips::BimmX16; |
| 90 | case Mips::Bteqz16: |
| 91 | case Mips::BteqzX16: |
| 92 | return Mips::BteqzX16; |
| 93 | case Mips::Btnez16: |
| 94 | case Mips::BtnezX16: |
| 95 | return Mips::BtnezX16; |
| 96 | case Mips::JalB16: |
| 97 | return Mips::JalB16; |
| 98 | case Mips::BeqzRxImm16: |
| 99 | case Mips::BeqzRxImmX16: |
| 100 | return Mips::BeqzRxImmX16; |
| 101 | case Mips::BnezRxImm16: |
| 102 | case Mips::BnezRxImmX16: |
| 103 | return Mips::BnezRxImmX16; |
| 104 | } |
| 105 | llvm_unreachable("Unknown branch type" ); |
| 106 | } |
| 107 | |
| 108 | // FIXME: need to go through this whole constant islands port and check |
| 109 | // the math for branch ranges and clean this up and make some functions |
| 110 | // to calculate things that are done many times identically. |
| 111 | // Need to refactor some of the code to call this routine. |
| 112 | static unsigned int branchMaxOffsets(unsigned int Opcode) { |
| 113 | unsigned Bits, Scale; |
| 114 | switch (Opcode) { |
| 115 | case Mips::Bimm16: |
| 116 | Bits = 11; |
| 117 | Scale = 2; |
| 118 | break; |
| 119 | case Mips::BimmX16: |
| 120 | Bits = 16; |
| 121 | Scale = 2; |
| 122 | break; |
| 123 | case Mips::BeqzRxImm16: |
| 124 | Bits = 8; |
| 125 | Scale = 2; |
| 126 | break; |
| 127 | case Mips::BeqzRxImmX16: |
| 128 | Bits = 16; |
| 129 | Scale = 2; |
| 130 | break; |
| 131 | case Mips::BnezRxImm16: |
| 132 | Bits = 8; |
| 133 | Scale = 2; |
| 134 | break; |
| 135 | case Mips::BnezRxImmX16: |
| 136 | Bits = 16; |
| 137 | Scale = 2; |
| 138 | break; |
| 139 | case Mips::Bteqz16: |
| 140 | Bits = 8; |
| 141 | Scale = 2; |
| 142 | break; |
| 143 | case Mips::BteqzX16: |
| 144 | Bits = 16; |
| 145 | Scale = 2; |
| 146 | break; |
| 147 | case Mips::Btnez16: |
| 148 | Bits = 8; |
| 149 | Scale = 2; |
| 150 | break; |
| 151 | case Mips::BtnezX16: |
| 152 | Bits = 16; |
| 153 | Scale = 2; |
| 154 | break; |
| 155 | default: |
| 156 | llvm_unreachable("Unknown branch type" ); |
| 157 | } |
| 158 | unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; |
| 159 | return MaxOffs; |
| 160 | } |
| 161 | |
| 162 | namespace { |
| 163 | |
| 164 | using Iter = MachineBasicBlock::iterator; |
| 165 | using ReverseIter = MachineBasicBlock::reverse_iterator; |
| 166 | |
| 167 | /// MipsConstantIslands - Due to limited PC-relative displacements, Mips |
| 168 | /// requires constant pool entries to be scattered among the instructions |
| 169 | /// inside a function. To do this, it completely ignores the normal LLVM |
| 170 | /// constant pool; instead, it places constants wherever it feels like with |
| 171 | /// special instructions. |
| 172 | /// |
| 173 | /// The terminology used in this pass includes: |
| 174 | /// Islands - Clumps of constants placed in the function. |
| 175 | /// Water - Potential places where an island could be formed. |
| 176 | /// CPE - A constant pool entry that has been placed somewhere, which |
| 177 | /// tracks a list of users. |
| 178 | |
| 179 | class MipsConstantIslandLegacy : public MachineFunctionPass { |
| 180 | public: |
| 181 | static char ID; |
| 182 | |
| 183 | MipsConstantIslandLegacy() : MachineFunctionPass(ID) {} |
| 184 | |
| 185 | StringRef getPassName() const override { return "Mips Constant Islands" ; } |
| 186 | |
| 187 | bool runOnMachineFunction(MachineFunction &F) override; |
| 188 | |
| 189 | MachineFunctionProperties getRequiredProperties() const override { |
| 190 | return MachineFunctionProperties().setNoVRegs(); |
| 191 | } |
| 192 | }; |
| 193 | |
| 194 | class MipsConstantIslandImpl { |
| 195 | /// BasicBlockInfo - Information about the offset and size of a single |
| 196 | /// basic block. |
| 197 | struct BasicBlockInfo { |
| 198 | /// Offset - Distance from the beginning of the function to the beginning |
| 199 | /// of this basic block. |
| 200 | /// |
| 201 | /// Offsets are computed assuming worst case padding before an aligned |
| 202 | /// block. This means that subtracting basic block offsets always gives a |
| 203 | /// conservative estimate of the real distance which may be smaller. |
| 204 | /// |
| 205 | /// Because worst case padding is used, the computed offset of an aligned |
| 206 | /// block may not actually be aligned. |
| 207 | unsigned Offset = 0; |
| 208 | |
| 209 | /// Size - Size of the basic block in bytes. If the block contains |
| 210 | /// inline assembly, this is a worst case estimate. |
| 211 | /// |
| 212 | /// The size does not include any alignment padding whether from the |
| 213 | /// beginning of the block, or from an aligned jump table at the end. |
| 214 | unsigned Size = 0; |
| 215 | |
| 216 | BasicBlockInfo() = default; |
| 217 | |
| 218 | unsigned postOffset() const { return Offset + Size; } |
| 219 | }; |
| 220 | |
| 221 | std::vector<BasicBlockInfo> BBInfo; |
| 222 | |
| 223 | /// WaterList - A sorted list of basic blocks where islands could be placed |
| 224 | /// (i.e. blocks that don't fall through to the following block, due |
| 225 | /// to a return, unreachable, or unconditional branch). |
| 226 | std::vector<MachineBasicBlock*> WaterList; |
| 227 | |
| 228 | /// NewWaterList - The subset of WaterList that was created since the |
| 229 | /// previous iteration by inserting unconditional branches. |
| 230 | SmallPtrSet<MachineBasicBlock *, 4> NewWaterList; |
| 231 | |
| 232 | using water_iterator = std::vector<MachineBasicBlock *>::iterator; |
| 233 | |
| 234 | /// CPUser - One user of a constant pool, keeping the machine instruction |
| 235 | /// pointer, the constant pool being referenced, and the max displacement |
| 236 | /// allowed from the instruction to the CP. The HighWaterMark records the |
| 237 | /// highest basic block where a new CPEntry can be placed. To ensure this |
| 238 | /// pass terminates, the CP entries are initially placed at the end of the |
| 239 | /// function and then move monotonically to lower addresses. The |
| 240 | /// exception to this rule is when the current CP entry for a particular |
| 241 | /// CPUser is out of range, but there is another CP entry for the same |
| 242 | /// constant value in range. We want to use the existing in-range CP |
| 243 | /// entry, but if it later moves out of range, the search for new water |
| 244 | /// should resume where it left off. The HighWaterMark is used to record |
| 245 | /// that point. |
| 246 | struct CPUser { |
| 247 | MachineInstr *MI; |
| 248 | MachineInstr *CPEMI; |
| 249 | MachineBasicBlock *HighWaterMark; |
| 250 | |
| 251 | private: |
| 252 | unsigned MaxDisp; |
| 253 | unsigned LongFormMaxDisp; // mips16 has 16/32 bit instructions |
| 254 | // with different displacements |
| 255 | unsigned LongFormOpcode; |
| 256 | |
| 257 | public: |
| 258 | bool NegOk; |
| 259 | |
| 260 | CPUser(MachineInstr *mi, MachineInstr *cpemi, unsigned maxdisp, |
| 261 | bool neg, |
| 262 | unsigned longformmaxdisp, unsigned longformopcode) |
| 263 | : MI(mi), CPEMI(cpemi), MaxDisp(maxdisp), |
| 264 | LongFormMaxDisp(longformmaxdisp), LongFormOpcode(longformopcode), |
| 265 | NegOk(neg){ |
| 266 | HighWaterMark = CPEMI->getParent(); |
| 267 | } |
| 268 | |
| 269 | /// getMaxDisp - Returns the maximum displacement supported by MI. |
| 270 | unsigned getMaxDisp() const { return MaxDisp; } |
| 271 | |
| 272 | void setMaxDisp(unsigned val) { |
| 273 | MaxDisp = val; |
| 274 | } |
| 275 | |
| 276 | unsigned getLongFormMaxDisp() const { |
| 277 | return LongFormMaxDisp; |
| 278 | } |
| 279 | |
| 280 | unsigned getLongFormOpcode() const { |
| 281 | return LongFormOpcode; |
| 282 | } |
| 283 | }; |
| 284 | |
| 285 | /// CPUsers - Keep track of all of the machine instructions that use various |
| 286 | /// constant pools and their max displacement. |
| 287 | std::vector<CPUser> CPUsers; |
| 288 | |
| 289 | /// CPEntry - One per constant pool entry, keeping the machine instruction |
| 290 | /// pointer, the constpool index, and the number of CPUser's which |
| 291 | /// reference this entry. |
| 292 | struct CPEntry { |
| 293 | MachineInstr *CPEMI; |
| 294 | unsigned CPI; |
| 295 | unsigned RefCount; |
| 296 | |
| 297 | CPEntry(MachineInstr *cpemi, unsigned cpi, unsigned rc = 0) |
| 298 | : CPEMI(cpemi), CPI(cpi), RefCount(rc) {} |
| 299 | }; |
| 300 | |
| 301 | /// CPEntries - Keep track of all of the constant pool entry machine |
| 302 | /// instructions. For each original constpool index (i.e. those that |
| 303 | /// existed upon entry to this pass), it keeps a vector of entries. |
| 304 | /// Original elements are cloned as we go along; the clones are |
| 305 | /// put in the vector of the original element, but have distinct CPIs. |
| 306 | std::vector<std::vector<CPEntry>> CPEntries; |
| 307 | |
| 308 | /// ImmBranch - One per immediate branch, keeping the machine instruction |
| 309 | /// pointer, conditional or unconditional, the max displacement, |
| 310 | /// and (if isCond is true) the corresponding unconditional branch |
| 311 | /// opcode. |
| 312 | struct ImmBranch { |
| 313 | MachineInstr *MI; |
| 314 | unsigned MaxDisp : 31; |
| 315 | LLVM_PREFERRED_TYPE(bool) |
| 316 | unsigned isCond : 1; |
| 317 | int UncondBr; |
| 318 | |
| 319 | ImmBranch(MachineInstr *mi, unsigned maxdisp, bool cond, int ubr) |
| 320 | : MI(mi), MaxDisp(maxdisp), isCond(cond), UncondBr(ubr) {} |
| 321 | }; |
| 322 | |
| 323 | /// ImmBranches - Keep track of all the immediate branch instructions. |
| 324 | /// |
| 325 | std::vector<ImmBranch> ImmBranches; |
| 326 | |
| 327 | /// HasFarJump - True if any far jump instruction has been emitted during |
| 328 | /// the branch fix up pass. |
| 329 | bool HasFarJump; |
| 330 | |
| 331 | const MipsSubtarget *STI = nullptr; |
| 332 | const Mips16InstrInfo *TII; |
| 333 | MipsFunctionInfo *MFI; |
| 334 | MachineFunction *MF = nullptr; |
| 335 | MachineConstantPool *MCP = nullptr; |
| 336 | |
| 337 | unsigned PICLabelUId; |
| 338 | bool PrescannedForConstants = false; |
| 339 | |
| 340 | void initPICLabelUId(unsigned UId) { PICLabelUId = UId; } |
| 341 | |
| 342 | unsigned createPICLabelUId() { return PICLabelUId++; } |
| 343 | |
| 344 | void doInitialPlacement(std::vector<MachineInstr*> &CPEMIs); |
| 345 | CPEntry *findConstPoolEntry(unsigned CPI, const MachineInstr *CPEMI); |
| 346 | Align getCPEAlign(const MachineInstr &CPEMI); |
| 347 | unsigned getMaxDisp(const CPUser &U) const { |
| 348 | int SmallOffset = STI->getCLOpts().constant_islands_small_offset; |
| 349 | return SmallOffset ? SmallOffset : U.getMaxDisp(); |
| 350 | } |
| 351 | void initializeFunctionInfo(const std::vector<MachineInstr*> &CPEMIs); |
| 352 | unsigned getOffsetOf(MachineInstr *MI) const; |
| 353 | unsigned getUserOffset(CPUser&) const; |
| 354 | void dumpBBs(); |
| 355 | |
| 356 | bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, |
| 357 | unsigned Disp, bool NegativeOK); |
| 358 | bool isOffsetInRange(unsigned UserOffset, unsigned TrialOffset, |
| 359 | const CPUser &U); |
| 360 | |
| 361 | void computeBlockSize(MachineBasicBlock *MBB); |
| 362 | MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI); |
| 363 | void updateForInsertedWaterBlock(MachineBasicBlock *NewBB); |
| 364 | void adjustBBOffsetsAfter(MachineBasicBlock *BB); |
| 365 | bool decrementCPEReferenceCount(unsigned CPI, MachineInstr* CPEMI); |
| 366 | int findInRangeCPEntry(CPUser& U, unsigned UserOffset); |
| 367 | int findLongFormInRangeCPEntry(CPUser& U, unsigned UserOffset); |
| 368 | bool findAvailableWater(CPUser&U, unsigned UserOffset, |
| 369 | water_iterator &WaterIter); |
| 370 | void createNewWater(unsigned CPUserIndex, unsigned UserOffset, |
| 371 | MachineBasicBlock *&NewMBB); |
| 372 | bool handleConstantPoolUser(unsigned CPUserIndex); |
| 373 | void removeDeadCPEMI(MachineInstr *CPEMI); |
| 374 | bool removeUnusedCPEntries(); |
| 375 | bool isCPEntryInRange(MachineInstr *MI, unsigned UserOffset, |
| 376 | MachineInstr *CPEMI, unsigned Disp, bool NegOk, |
| 377 | bool DoDump = false); |
| 378 | bool isWaterInRange(unsigned UserOffset, MachineBasicBlock *Water, |
| 379 | CPUser &U, unsigned &Growth); |
| 380 | bool isBBInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp); |
| 381 | bool fixupImmediateBr(ImmBranch &Br); |
| 382 | bool fixupConditionalBr(ImmBranch &Br); |
| 383 | bool fixupUnconditionalBr(ImmBranch &Br); |
| 384 | |
| 385 | void prescanForConstants(); |
| 386 | |
| 387 | public: |
| 388 | bool runOnMachineFunction(MachineFunction &MF); |
| 389 | }; |
| 390 | |
| 391 | } // end anonymous namespace |
| 392 | |
| 393 | char MipsConstantIslandLegacy::ID = 0; |
| 394 | |
| 395 | bool MipsConstantIslandImpl::isOffsetInRange(unsigned UserOffset, |
| 396 | unsigned TrialOffset, |
| 397 | const CPUser &U) { |
| 398 | return isOffsetInRange(UserOffset, TrialOffset, Disp: getMaxDisp(U), NegativeOK: U.NegOk); |
| 399 | } |
| 400 | |
| 401 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 402 | /// print block size and offset information - debugging |
| 403 | LLVM_DUMP_METHOD void MipsConstantIslandImpl::dumpBBs() { |
| 404 | for (unsigned J = 0, E = BBInfo.size(); J !=E; ++J) { |
| 405 | const BasicBlockInfo &BBI = BBInfo[J]; |
| 406 | dbgs() << format("%08x %bb.%u\t" , BBI.Offset, J) |
| 407 | << format(" size=%#x\n" , BBInfo[J].Size); |
| 408 | } |
| 409 | } |
| 410 | #endif |
| 411 | |
| 412 | bool MipsConstantIslandImpl::runOnMachineFunction(MachineFunction &mf) { |
| 413 | // The intention is for this to be a mips16 only pass for now |
| 414 | // FIXME: |
| 415 | MF = &mf; |
| 416 | MCP = mf.getConstantPool(); |
| 417 | STI = &mf.getSubtarget<MipsSubtarget>(); |
| 418 | LLVM_DEBUG(dbgs() << "constant island machine function " |
| 419 | << "\n" ); |
| 420 | if (!STI->inMips16Mode() || !STI->useConstantIslands()) { |
| 421 | return false; |
| 422 | } |
| 423 | TII = (const Mips16InstrInfo *)STI->getInstrInfo(); |
| 424 | MFI = MF->getInfo<MipsFunctionInfo>(); |
| 425 | LLVM_DEBUG(dbgs() << "constant island processing " |
| 426 | << "\n" ); |
| 427 | // |
| 428 | // will need to make predermination if there is any constants we need to |
| 429 | // put in constant islands. TBD. |
| 430 | // |
| 431 | if (!PrescannedForConstants) prescanForConstants(); |
| 432 | |
| 433 | HasFarJump = false; |
| 434 | // This pass invalidates liveness information when it splits basic blocks. |
| 435 | MF->getRegInfo().invalidateLiveness(); |
| 436 | |
| 437 | // Renumber all of the machine basic blocks in the function, guaranteeing that |
| 438 | // the numbers agree with the position of the block in the function. |
| 439 | MF->RenumberBlocks(); |
| 440 | |
| 441 | bool MadeChange = false; |
| 442 | |
| 443 | // Perform the initial placement of the constant pool entries. To start with, |
| 444 | // we put them all at the end of the function. |
| 445 | std::vector<MachineInstr*> CPEMIs; |
| 446 | if (!MCP->isEmpty()) |
| 447 | doInitialPlacement(CPEMIs); |
| 448 | |
| 449 | /// The next UID to take is the first unused one. |
| 450 | initPICLabelUId(UId: CPEMIs.size()); |
| 451 | |
| 452 | // Do the initial scan of the function, building up information about the |
| 453 | // sizes of each block, the location of all the water, and finding all of the |
| 454 | // constant pool users. |
| 455 | initializeFunctionInfo(CPEMIs); |
| 456 | CPEMIs.clear(); |
| 457 | LLVM_DEBUG(dumpBBs()); |
| 458 | |
| 459 | /// Remove dead constant pool entries. |
| 460 | MadeChange |= removeUnusedCPEntries(); |
| 461 | |
| 462 | // Iteratively place constant pool entries and fix up branches until there |
| 463 | // is no change. |
| 464 | unsigned NoCPIters = 0, NoBRIters = 0; |
| 465 | (void)NoBRIters; |
| 466 | while (true) { |
| 467 | LLVM_DEBUG(dbgs() << "Beginning CP iteration #" << NoCPIters << '\n'); |
| 468 | bool CPChange = false; |
| 469 | for (unsigned i = 0, e = CPUsers.size(); i != e; ++i) |
| 470 | CPChange |= handleConstantPoolUser(CPUserIndex: i); |
| 471 | if (CPChange && ++NoCPIters > 30) |
| 472 | report_fatal_error(reason: "Constant Island pass failed to converge!" ); |
| 473 | LLVM_DEBUG(dumpBBs()); |
| 474 | |
| 475 | // Clear NewWaterList now. If we split a block for branches, it should |
| 476 | // appear as "new water" for the next iteration of constant pool placement. |
| 477 | NewWaterList.clear(); |
| 478 | |
| 479 | LLVM_DEBUG(dbgs() << "Beginning BR iteration #" << NoBRIters << '\n'); |
| 480 | bool BRChange = false; |
| 481 | for (unsigned i = 0, e = ImmBranches.size(); i != e; ++i) |
| 482 | BRChange |= fixupImmediateBr(Br&: ImmBranches[i]); |
| 483 | if (BRChange && ++NoBRIters > 30) |
| 484 | report_fatal_error(reason: "Branch Fix Up pass failed to converge!" ); |
| 485 | LLVM_DEBUG(dumpBBs()); |
| 486 | if (!CPChange && !BRChange) |
| 487 | break; |
| 488 | MadeChange = true; |
| 489 | } |
| 490 | |
| 491 | LLVM_DEBUG(dbgs() << '\n'; dumpBBs()); |
| 492 | |
| 493 | BBInfo.clear(); |
| 494 | WaterList.clear(); |
| 495 | CPUsers.clear(); |
| 496 | CPEntries.clear(); |
| 497 | ImmBranches.clear(); |
| 498 | return MadeChange; |
| 499 | } |
| 500 | |
| 501 | /// doInitialPlacement - Perform the initial placement of the constant pool |
| 502 | /// entries. To start with, we put them all at the end of the function. |
| 503 | void MipsConstantIslandImpl::doInitialPlacement( |
| 504 | std::vector<MachineInstr *> &CPEMIs) { |
| 505 | // Create the basic block to hold the CPE's. |
| 506 | MachineBasicBlock *BB = MF->CreateMachineBasicBlock(); |
| 507 | MF->push_back(MBB: BB); |
| 508 | |
| 509 | // MachineConstantPool measures alignment in bytes. We measure in log2(bytes). |
| 510 | const Align MaxAlign = MCP->getConstantPoolAlign(); |
| 511 | |
| 512 | // Mark the basic block as required by the const-pool. |
| 513 | // If -mips-align-constant-islands isn't set, use 4-byte alignment for |
| 514 | // everything. |
| 515 | BB->setAlignment(STI->getCLOpts().align_constant_islands ? MaxAlign |
| 516 | : Align(4)); |
| 517 | |
| 518 | // The function needs to be as aligned as the basic blocks. The linker may |
| 519 | // move functions around based on their alignment. |
| 520 | MF->ensureAlignment(A: BB->getAlignment()); |
| 521 | |
| 522 | // Order the entries in BB by descending alignment. That ensures correct |
| 523 | // alignment of all entries as long as BB is sufficiently aligned. Keep |
| 524 | // track of the insertion point for each alignment. We are going to bucket |
| 525 | // sort the entries as they are created. |
| 526 | SmallVector<MachineBasicBlock::iterator, 8> InsPoint(Log2(A: MaxAlign) + 1, |
| 527 | BB->end()); |
| 528 | |
| 529 | // Add all of the constants from the constant pool to the end block, use an |
| 530 | // identity mapping of CPI's to CPE's. |
| 531 | const std::vector<MachineConstantPoolEntry> &CPs = MCP->getConstants(); |
| 532 | |
| 533 | const DataLayout &TD = MF->getDataLayout(); |
| 534 | for (unsigned i = 0, e = CPs.size(); i != e; ++i) { |
| 535 | unsigned Size = CPs[i].getSizeInBytes(DL: TD); |
| 536 | assert(Size >= 4 && "Too small constant pool entry" ); |
| 537 | Align Alignment = CPs[i].getAlign(); |
| 538 | // Verify that all constant pool entries are a multiple of their alignment. |
| 539 | // If not, we would have to pad them out so that instructions stay aligned. |
| 540 | assert(isAligned(Alignment, Size) && "CP Entry not multiple of 4 bytes!" ); |
| 541 | |
| 542 | // Insert CONSTPOOL_ENTRY before entries with a smaller alignment. |
| 543 | unsigned LogAlign = Log2(A: Alignment); |
| 544 | MachineBasicBlock::iterator InsAt = InsPoint[LogAlign]; |
| 545 | |
| 546 | MachineInstr *CPEMI = |
| 547 | BuildMI(BB&: *BB, I: InsAt, MIMD: DebugLoc(), MCID: TII->get(Opcode: Mips::CONSTPOOL_ENTRY)) |
| 548 | .addImm(Val: i).addConstantPoolIndex(Idx: i).addImm(Val: Size); |
| 549 | |
| 550 | CPEMIs.push_back(x: CPEMI); |
| 551 | |
| 552 | // Ensure that future entries with higher alignment get inserted before |
| 553 | // CPEMI. This is bucket sort with iterators. |
| 554 | for (unsigned a = LogAlign + 1; a <= Log2(A: MaxAlign); ++a) |
| 555 | if (InsPoint[a] == InsAt) |
| 556 | InsPoint[a] = CPEMI; |
| 557 | // Add a new CPEntry, but no corresponding CPUser yet. |
| 558 | CPEntries.emplace_back(args: 1, args: CPEntry(CPEMI, i)); |
| 559 | ++NumCPEs; |
| 560 | LLVM_DEBUG(dbgs() << "Moved CPI#" << i << " to end of function, size = " |
| 561 | << Size << ", align = " << Alignment.value() << '\n'); |
| 562 | } |
| 563 | LLVM_DEBUG(BB->dump()); |
| 564 | } |
| 565 | |
| 566 | /// BBHasFallthrough - Return true if the specified basic block can fallthrough |
| 567 | /// into the block immediately after it. |
| 568 | static bool BBHasFallthrough(MachineBasicBlock *MBB) { |
| 569 | // Get the next machine basic block in the function. |
| 570 | MachineFunction::iterator MBBI = MBB->getIterator(); |
| 571 | // Can't fall off end of function. |
| 572 | if (std::next(x: MBBI) == MBB->getParent()->end()) |
| 573 | return false; |
| 574 | |
| 575 | MachineBasicBlock *NextBB = &*std::next(x: MBBI); |
| 576 | return llvm::is_contained(Range: MBB->successors(), Element: NextBB); |
| 577 | } |
| 578 | |
| 579 | /// findConstPoolEntry - Given the constpool index and CONSTPOOL_ENTRY MI, |
| 580 | /// look up the corresponding CPEntry. |
| 581 | MipsConstantIslandImpl::CPEntry * |
| 582 | MipsConstantIslandImpl::findConstPoolEntry(unsigned CPI, |
| 583 | const MachineInstr *CPEMI) { |
| 584 | std::vector<CPEntry> &CPEs = CPEntries[CPI]; |
| 585 | // Number of entries per constpool index should be small, just do a |
| 586 | // linear search. |
| 587 | for (CPEntry &CPE : CPEs) { |
| 588 | if (CPE.CPEMI == CPEMI) |
| 589 | return &CPE; |
| 590 | } |
| 591 | return nullptr; |
| 592 | } |
| 593 | |
| 594 | /// getCPEAlign - Returns the required alignment of the constant pool entry |
| 595 | /// represented by CPEMI. Alignment is measured in log2(bytes) units. |
| 596 | Align MipsConstantIslandImpl::getCPEAlign(const MachineInstr &CPEMI) { |
| 597 | assert(CPEMI.getOpcode() == Mips::CONSTPOOL_ENTRY); |
| 598 | |
| 599 | // Everything is 4-byte aligned unless -mips-align-constant-islands is set. |
| 600 | if (!STI->getCLOpts().align_constant_islands) |
| 601 | return Align(4); |
| 602 | |
| 603 | unsigned CPI = CPEMI.getOperand(i: 1).getIndex(); |
| 604 | assert(CPI < MCP->getConstants().size() && "Invalid constant pool index." ); |
| 605 | return MCP->getConstants()[CPI].getAlign(); |
| 606 | } |
| 607 | |
| 608 | /// initializeFunctionInfo - Do the initial scan of the function, building up |
| 609 | /// information about the sizes of each block, the location of all the water, |
| 610 | /// and finding all of the constant pool users. |
| 611 | void MipsConstantIslandImpl::initializeFunctionInfo( |
| 612 | const std::vector<MachineInstr *> &CPEMIs) { |
| 613 | BBInfo.clear(); |
| 614 | BBInfo.resize(new_size: MF->getNumBlockIDs()); |
| 615 | |
| 616 | // First thing, compute the size of all basic blocks, and see if the function |
| 617 | // has any inline assembly in it. If so, we have to be conservative about |
| 618 | // alignment assumptions, as we don't know for sure the size of any |
| 619 | // instructions in the inline assembly. |
| 620 | for (MachineBasicBlock &MBB : *MF) |
| 621 | computeBlockSize(MBB: &MBB); |
| 622 | |
| 623 | // Compute block offsets. |
| 624 | adjustBBOffsetsAfter(BB: &MF->front()); |
| 625 | |
| 626 | // Now go back through the instructions and build up our data structures. |
| 627 | for (MachineBasicBlock &MBB : *MF) { |
| 628 | // If this block doesn't fall through into the next MBB, then this is |
| 629 | // 'water' that a constant pool island could be placed. |
| 630 | if (!BBHasFallthrough(MBB: &MBB)) |
| 631 | WaterList.push_back(x: &MBB); |
| 632 | for (MachineInstr &MI : MBB) { |
| 633 | if (MI.isDebugInstr()) |
| 634 | continue; |
| 635 | |
| 636 | int Opc = MI.getOpcode(); |
| 637 | if (MI.isBranch()) { |
| 638 | bool isCond = false; |
| 639 | unsigned Bits = 0; |
| 640 | unsigned Scale = 1; |
| 641 | int UOpc = Opc; |
| 642 | switch (Opc) { |
| 643 | default: |
| 644 | continue; // Ignore other branches for now |
| 645 | case Mips::Bimm16: |
| 646 | Bits = 11; |
| 647 | Scale = 2; |
| 648 | isCond = false; |
| 649 | break; |
| 650 | case Mips::BimmX16: |
| 651 | Bits = 16; |
| 652 | Scale = 2; |
| 653 | isCond = false; |
| 654 | break; |
| 655 | case Mips::BeqzRxImm16: |
| 656 | UOpc=Mips::Bimm16; |
| 657 | Bits = 8; |
| 658 | Scale = 2; |
| 659 | isCond = true; |
| 660 | break; |
| 661 | case Mips::BeqzRxImmX16: |
| 662 | UOpc=Mips::Bimm16; |
| 663 | Bits = 16; |
| 664 | Scale = 2; |
| 665 | isCond = true; |
| 666 | break; |
| 667 | case Mips::BnezRxImm16: |
| 668 | UOpc=Mips::Bimm16; |
| 669 | Bits = 8; |
| 670 | Scale = 2; |
| 671 | isCond = true; |
| 672 | break; |
| 673 | case Mips::BnezRxImmX16: |
| 674 | UOpc=Mips::Bimm16; |
| 675 | Bits = 16; |
| 676 | Scale = 2; |
| 677 | isCond = true; |
| 678 | break; |
| 679 | case Mips::Bteqz16: |
| 680 | UOpc=Mips::Bimm16; |
| 681 | Bits = 8; |
| 682 | Scale = 2; |
| 683 | isCond = true; |
| 684 | break; |
| 685 | case Mips::BteqzX16: |
| 686 | UOpc=Mips::Bimm16; |
| 687 | Bits = 16; |
| 688 | Scale = 2; |
| 689 | isCond = true; |
| 690 | break; |
| 691 | case Mips::Btnez16: |
| 692 | UOpc=Mips::Bimm16; |
| 693 | Bits = 8; |
| 694 | Scale = 2; |
| 695 | isCond = true; |
| 696 | break; |
| 697 | case Mips::BtnezX16: |
| 698 | UOpc=Mips::Bimm16; |
| 699 | Bits = 16; |
| 700 | Scale = 2; |
| 701 | isCond = true; |
| 702 | break; |
| 703 | } |
| 704 | // Record this immediate branch. |
| 705 | unsigned MaxOffs = ((1 << (Bits-1))-1) * Scale; |
| 706 | ImmBranches.push_back(x: ImmBranch(&MI, MaxOffs, isCond, UOpc)); |
| 707 | } |
| 708 | |
| 709 | if (Opc == Mips::CONSTPOOL_ENTRY) |
| 710 | continue; |
| 711 | |
| 712 | // Scan the instructions for constant pool operands. |
| 713 | for (const MachineOperand &MO : MI.operands()) |
| 714 | if (MO.isCPI()) { |
| 715 | // We found one. The addressing mode tells us the max displacement |
| 716 | // from the PC that this instruction permits. |
| 717 | |
| 718 | // Basic size info comes from the TSFlags field. |
| 719 | unsigned Bits = 0; |
| 720 | unsigned Scale = 1; |
| 721 | bool NegOk = false; |
| 722 | unsigned LongFormBits = 0; |
| 723 | unsigned LongFormScale = 0; |
| 724 | unsigned LongFormOpcode = 0; |
| 725 | switch (Opc) { |
| 726 | default: |
| 727 | llvm_unreachable("Unknown addressing mode for CP reference!" ); |
| 728 | case Mips::LwRxPcTcp16: |
| 729 | Bits = 8; |
| 730 | Scale = 4; |
| 731 | LongFormOpcode = Mips::LwRxPcTcpX16; |
| 732 | LongFormBits = 14; |
| 733 | LongFormScale = 1; |
| 734 | break; |
| 735 | case Mips::LwRxPcTcpX16: |
| 736 | Bits = 14; |
| 737 | Scale = 1; |
| 738 | NegOk = true; |
| 739 | break; |
| 740 | } |
| 741 | // Remember that this is a user of a CP entry. |
| 742 | unsigned CPI = MO.getIndex(); |
| 743 | MachineInstr *CPEMI = CPEMIs[CPI]; |
| 744 | unsigned MaxOffs = ((1 << Bits)-1) * Scale; |
| 745 | unsigned LongFormMaxOffs = ((1 << LongFormBits)-1) * LongFormScale; |
| 746 | CPUsers.push_back(x: CPUser(&MI, CPEMI, MaxOffs, NegOk, LongFormMaxOffs, |
| 747 | LongFormOpcode)); |
| 748 | |
| 749 | // Increment corresponding CPEntry reference count. |
| 750 | CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); |
| 751 | assert(CPE && "Cannot find a corresponding CPEntry!" ); |
| 752 | CPE->RefCount++; |
| 753 | |
| 754 | // Instructions can only use one CP entry, don't bother scanning the |
| 755 | // rest of the operands. |
| 756 | break; |
| 757 | } |
| 758 | } |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /// computeBlockSize - Compute the size and some alignment information for MBB. |
| 763 | /// This function updates BBInfo directly. |
| 764 | void MipsConstantIslandImpl::computeBlockSize(MachineBasicBlock *MBB) { |
| 765 | BasicBlockInfo &BBI = BBInfo[MBB->getNumber()]; |
| 766 | BBI.Size = 0; |
| 767 | |
| 768 | for (const MachineInstr &MI : *MBB) |
| 769 | BBI.Size += TII->getInstSizeInBytes(MI); |
| 770 | } |
| 771 | |
| 772 | /// getOffsetOf - Return the current offset of the specified machine instruction |
| 773 | /// from the start of the function. This offset changes as stuff is moved |
| 774 | /// around inside the function. |
| 775 | unsigned MipsConstantIslandImpl::getOffsetOf(MachineInstr *MI) const { |
| 776 | MachineBasicBlock *MBB = MI->getParent(); |
| 777 | |
| 778 | // The offset is composed of two things: the sum of the sizes of all MBB's |
| 779 | // before this instruction's block, and the offset from the start of the block |
| 780 | // it is in. |
| 781 | unsigned Offset = BBInfo[MBB->getNumber()].Offset; |
| 782 | |
| 783 | // Sum instructions before MI in MBB. |
| 784 | for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) { |
| 785 | assert(I != MBB->end() && "Didn't find MI in its own basic block?" ); |
| 786 | Offset += TII->getInstSizeInBytes(MI: *I); |
| 787 | } |
| 788 | return Offset; |
| 789 | } |
| 790 | |
| 791 | /// CompareMBBNumbers - Little predicate function to sort the WaterList by MBB |
| 792 | /// ID. |
| 793 | static bool CompareMBBNumbers(const MachineBasicBlock *LHS, |
| 794 | const MachineBasicBlock *RHS) { |
| 795 | return LHS->getNumber() < RHS->getNumber(); |
| 796 | } |
| 797 | |
| 798 | /// updateForInsertedWaterBlock - When a block is newly inserted into the |
| 799 | /// machine function, it upsets all of the block numbers. Renumber the blocks |
| 800 | /// and update the arrays that parallel this numbering. |
| 801 | void MipsConstantIslandImpl::updateForInsertedWaterBlock( |
| 802 | MachineBasicBlock *NewBB) { |
| 803 | // Renumber the MBB's to keep them consecutive. |
| 804 | NewBB->getParent()->RenumberBlocks(MBBFrom: NewBB); |
| 805 | |
| 806 | // Insert an entry into BBInfo to align it properly with the (newly |
| 807 | // renumbered) block numbers. |
| 808 | BBInfo.insert(position: BBInfo.begin() + NewBB->getNumber(), x: BasicBlockInfo()); |
| 809 | |
| 810 | // Next, update WaterList. Specifically, we need to add NewMBB as having |
| 811 | // available water after it. |
| 812 | water_iterator IP = llvm::lower_bound(Range&: WaterList, Value&: NewBB, C: CompareMBBNumbers); |
| 813 | WaterList.insert(position: IP, x: NewBB); |
| 814 | } |
| 815 | |
| 816 | unsigned MipsConstantIslandImpl::getUserOffset(CPUser &U) const { |
| 817 | return getOffsetOf(MI: U.MI); |
| 818 | } |
| 819 | |
| 820 | /// Split the basic block containing MI into two blocks, which are joined by |
| 821 | /// an unconditional branch. Update data structures and renumber blocks to |
| 822 | /// account for this change and returns the newly created block. |
| 823 | MachineBasicBlock * |
| 824 | MipsConstantIslandImpl::splitBlockBeforeInstr(MachineInstr &MI) { |
| 825 | MachineBasicBlock *OrigBB = MI.getParent(); |
| 826 | |
| 827 | // Create a new MBB for the code after the OrigBB. |
| 828 | MachineBasicBlock *NewBB = |
| 829 | MF->CreateMachineBasicBlock(BB: OrigBB->getBasicBlock()); |
| 830 | MachineFunction::iterator MBBI = ++OrigBB->getIterator(); |
| 831 | MF->insert(MBBI, MBB: NewBB); |
| 832 | |
| 833 | // Splice the instructions starting with MI over to NewBB. |
| 834 | NewBB->splice(Where: NewBB->end(), Other: OrigBB, From: MI, To: OrigBB->end()); |
| 835 | |
| 836 | // Add an unconditional branch from OrigBB to NewBB. |
| 837 | // Note the new unconditional branch is not being recorded. |
| 838 | // There doesn't seem to be meaningful DebugInfo available; this doesn't |
| 839 | // correspond to anything in the source. |
| 840 | BuildMI(BB: OrigBB, MIMD: DebugLoc(), MCID: TII->get(Opcode: Mips::Bimm16)).addMBB(MBB: NewBB); |
| 841 | ++NumSplit; |
| 842 | |
| 843 | // Update the CFG. All succs of OrigBB are now succs of NewBB. |
| 844 | NewBB->transferSuccessors(FromMBB: OrigBB); |
| 845 | |
| 846 | // OrigBB branches to NewBB. |
| 847 | OrigBB->addSuccessor(Succ: NewBB); |
| 848 | |
| 849 | // Update internal data structures to account for the newly inserted MBB. |
| 850 | // This is almost the same as updateForInsertedWaterBlock, except that |
| 851 | // the Water goes after OrigBB, not NewBB. |
| 852 | MF->RenumberBlocks(MBBFrom: NewBB); |
| 853 | |
| 854 | // Insert an entry into BBInfo to align it properly with the (newly |
| 855 | // renumbered) block numbers. |
| 856 | BBInfo.insert(position: BBInfo.begin() + NewBB->getNumber(), x: BasicBlockInfo()); |
| 857 | |
| 858 | // Next, update WaterList. Specifically, we need to add OrigMBB as having |
| 859 | // available water after it (but not if it's already there, which happens |
| 860 | // when splitting before a conditional branch that is followed by an |
| 861 | // unconditional branch - in that case we want to insert NewBB). |
| 862 | water_iterator IP = llvm::lower_bound(Range&: WaterList, Value&: OrigBB, C: CompareMBBNumbers); |
| 863 | MachineBasicBlock* WaterBB = *IP; |
| 864 | if (WaterBB == OrigBB) |
| 865 | WaterList.insert(position: std::next(x: IP), x: NewBB); |
| 866 | else |
| 867 | WaterList.insert(position: IP, x: OrigBB); |
| 868 | NewWaterList.insert(Ptr: OrigBB); |
| 869 | |
| 870 | // Figure out how large the OrigBB is. As the first half of the original |
| 871 | // block, it cannot contain a tablejump. The size includes |
| 872 | // the new jump we added. (It should be possible to do this without |
| 873 | // recounting everything, but it's very confusing, and this is rarely |
| 874 | // executed.) |
| 875 | computeBlockSize(MBB: OrigBB); |
| 876 | |
| 877 | // Figure out how large the NewMBB is. As the second half of the original |
| 878 | // block, it may contain a tablejump. |
| 879 | computeBlockSize(MBB: NewBB); |
| 880 | |
| 881 | // All BBOffsets following these blocks must be modified. |
| 882 | adjustBBOffsetsAfter(BB: OrigBB); |
| 883 | |
| 884 | return NewBB; |
| 885 | } |
| 886 | |
| 887 | /// isOffsetInRange - Checks whether UserOffset (the location of a constant pool |
| 888 | /// reference) is within MaxDisp of TrialOffset (a proposed location of a |
| 889 | /// constant pool entry). |
| 890 | bool MipsConstantIslandImpl::isOffsetInRange(unsigned UserOffset, |
| 891 | unsigned TrialOffset, |
| 892 | unsigned MaxDisp, |
| 893 | bool NegativeOK) { |
| 894 | if (UserOffset <= TrialOffset) { |
| 895 | // User before the Trial. |
| 896 | if (TrialOffset - UserOffset <= MaxDisp) |
| 897 | return true; |
| 898 | } else if (NegativeOK) { |
| 899 | if (UserOffset - TrialOffset <= MaxDisp) |
| 900 | return true; |
| 901 | } |
| 902 | return false; |
| 903 | } |
| 904 | |
| 905 | /// isWaterInRange - Returns true if a CPE placed after the specified |
| 906 | /// Water (a basic block) will be in range for the specific MI. |
| 907 | /// |
| 908 | /// Compute how much the function will grow by inserting a CPE after Water. |
| 909 | bool MipsConstantIslandImpl::isWaterInRange(unsigned UserOffset, |
| 910 | MachineBasicBlock *Water, CPUser &U, |
| 911 | unsigned &Growth) { |
| 912 | unsigned CPEOffset = BBInfo[Water->getNumber()].postOffset(); |
| 913 | unsigned NextBlockOffset; |
| 914 | Align NextBlockAlignment; |
| 915 | MachineFunction::const_iterator NextBlock = ++Water->getIterator(); |
| 916 | if (NextBlock == MF->end()) { |
| 917 | NextBlockOffset = BBInfo[Water->getNumber()].postOffset(); |
| 918 | NextBlockAlignment = Align(1); |
| 919 | } else { |
| 920 | NextBlockOffset = BBInfo[NextBlock->getNumber()].Offset; |
| 921 | NextBlockAlignment = NextBlock->getAlignment(); |
| 922 | } |
| 923 | unsigned Size = U.CPEMI->getOperand(i: 2).getImm(); |
| 924 | unsigned CPEEnd = CPEOffset + Size; |
| 925 | |
| 926 | // The CPE may be able to hide in the alignment padding before the next |
| 927 | // block. It may also cause more padding to be required if it is more aligned |
| 928 | // that the next block. |
| 929 | if (CPEEnd > NextBlockOffset) { |
| 930 | Growth = CPEEnd - NextBlockOffset; |
| 931 | // Compute the padding that would go at the end of the CPE to align the next |
| 932 | // block. |
| 933 | Growth += offsetToAlignment(Value: CPEEnd, Alignment: NextBlockAlignment); |
| 934 | |
| 935 | // If the CPE is to be inserted before the instruction, that will raise |
| 936 | // the offset of the instruction. Also account for unknown alignment padding |
| 937 | // in blocks between CPE and the user. |
| 938 | if (CPEOffset < UserOffset) |
| 939 | UserOffset += Growth; |
| 940 | } else |
| 941 | // CPE fits in existing padding. |
| 942 | Growth = 0; |
| 943 | |
| 944 | return isOffsetInRange(UserOffset, TrialOffset: CPEOffset, U); |
| 945 | } |
| 946 | |
| 947 | /// isCPEntryInRange - Returns true if the distance between specific MI and |
| 948 | /// specific ConstPool entry instruction can fit in MI's displacement field. |
| 949 | bool MipsConstantIslandImpl::isCPEntryInRange(MachineInstr *MI, |
| 950 | unsigned UserOffset, |
| 951 | MachineInstr *CPEMI, |
| 952 | unsigned MaxDisp, bool NegOk, |
| 953 | bool DoDump) { |
| 954 | unsigned CPEOffset = getOffsetOf(MI: CPEMI); |
| 955 | |
| 956 | if (DoDump) { |
| 957 | LLVM_DEBUG({ |
| 958 | unsigned Block = MI->getParent()->getNumber(); |
| 959 | const BasicBlockInfo &BBI = BBInfo[Block]; |
| 960 | dbgs() << "User of CPE#" << CPEMI->getOperand(0).getImm() |
| 961 | << " max delta=" << MaxDisp |
| 962 | << format(" insn address=%#x" , UserOffset) << " in " |
| 963 | << printMBBReference(*MI->getParent()) << ": " |
| 964 | << format("%#x-%x\t" , BBI.Offset, BBI.postOffset()) << *MI |
| 965 | << format("CPE address=%#x offset=%+d: " , CPEOffset, |
| 966 | int(CPEOffset - UserOffset)); |
| 967 | }); |
| 968 | } |
| 969 | |
| 970 | return isOffsetInRange(UserOffset, TrialOffset: CPEOffset, MaxDisp, NegativeOK: NegOk); |
| 971 | } |
| 972 | |
| 973 | #ifndef NDEBUG |
| 974 | /// BBIsJumpedOver - Return true of the specified basic block's only predecessor |
| 975 | /// unconditionally branches to its only successor. |
| 976 | static bool BBIsJumpedOver(MachineBasicBlock *MBB) { |
| 977 | if (MBB->pred_size() != 1 || MBB->succ_size() != 1) |
| 978 | return false; |
| 979 | MachineBasicBlock *Succ = *MBB->succ_begin(); |
| 980 | MachineBasicBlock *Pred = *MBB->pred_begin(); |
| 981 | MachineInstr *PredMI = &Pred->back(); |
| 982 | if (PredMI->getOpcode() == Mips::Bimm16) |
| 983 | return PredMI->getOperand(0).getMBB() == Succ; |
| 984 | return false; |
| 985 | } |
| 986 | #endif |
| 987 | |
| 988 | void MipsConstantIslandImpl::adjustBBOffsetsAfter(MachineBasicBlock *BB) { |
| 989 | unsigned BBNum = BB->getNumber(); |
| 990 | for(unsigned i = BBNum + 1, e = MF->getNumBlockIDs(); i < e; ++i) { |
| 991 | // Get the offset and known bits at the end of the layout predecessor. |
| 992 | // Include the alignment of the current block. |
| 993 | unsigned Offset = BBInfo[i - 1].Offset + BBInfo[i - 1].Size; |
| 994 | BBInfo[i].Offset = Offset; |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | /// decrementCPEReferenceCount - find the constant pool entry with index CPI |
| 999 | /// and instruction CPEMI, and decrement its refcount. If the refcount |
| 1000 | /// becomes 0 remove the entry and instruction. Returns true if we removed |
| 1001 | /// the entry, false if we didn't. |
| 1002 | bool MipsConstantIslandImpl::decrementCPEReferenceCount(unsigned CPI, |
| 1003 | MachineInstr *CPEMI) { |
| 1004 | // Find the old entry. Eliminate it if it is no longer used. |
| 1005 | CPEntry *CPE = findConstPoolEntry(CPI, CPEMI); |
| 1006 | assert(CPE && "Unexpected!" ); |
| 1007 | if (--CPE->RefCount == 0) { |
| 1008 | removeDeadCPEMI(CPEMI); |
| 1009 | CPE->CPEMI = nullptr; |
| 1010 | --NumCPEs; |
| 1011 | return true; |
| 1012 | } |
| 1013 | return false; |
| 1014 | } |
| 1015 | |
| 1016 | /// LookForCPEntryInRange - see if the currently referenced CPE is in range; |
| 1017 | /// if not, see if an in-range clone of the CPE is in range, and if so, |
| 1018 | /// change the data structures so the user references the clone. Returns: |
| 1019 | /// 0 = no existing entry found |
| 1020 | /// 1 = entry found, and there were no code insertions or deletions |
| 1021 | /// 2 = entry found, and there were code insertions or deletions |
| 1022 | int MipsConstantIslandImpl::findInRangeCPEntry(CPUser &U, unsigned UserOffset) { |
| 1023 | MachineInstr *UserMI = U.MI; |
| 1024 | MachineInstr *CPEMI = U.CPEMI; |
| 1025 | |
| 1026 | // Check to see if the CPE is already in-range. |
| 1027 | if (isCPEntryInRange(MI: UserMI, UserOffset, CPEMI, MaxDisp: getMaxDisp(U), NegOk: U.NegOk, |
| 1028 | DoDump: true)) { |
| 1029 | LLVM_DEBUG(dbgs() << "In range\n" ); |
| 1030 | return 1; |
| 1031 | } |
| 1032 | |
| 1033 | // No. Look for previously created clones of the CPE that are in range. |
| 1034 | unsigned CPI = CPEMI->getOperand(i: 1).getIndex(); |
| 1035 | std::vector<CPEntry> &CPEs = CPEntries[CPI]; |
| 1036 | for (CPEntry &CPE : CPEs) { |
| 1037 | // We already tried this one |
| 1038 | if (CPE.CPEMI == CPEMI) |
| 1039 | continue; |
| 1040 | // Removing CPEs can leave empty entries, skip |
| 1041 | if (CPE.CPEMI == nullptr) |
| 1042 | continue; |
| 1043 | if (isCPEntryInRange(MI: UserMI, UserOffset, CPEMI: CPE.CPEMI, MaxDisp: getMaxDisp(U), |
| 1044 | NegOk: U.NegOk)) { |
| 1045 | LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI |
| 1046 | << "\n" ); |
| 1047 | // Point the CPUser node to the replacement |
| 1048 | U.CPEMI = CPE.CPEMI; |
| 1049 | // Change the CPI in the instruction operand to refer to the clone. |
| 1050 | for (MachineOperand &MO : UserMI->operands()) |
| 1051 | if (MO.isCPI()) { |
| 1052 | MO.setIndex(CPE.CPI); |
| 1053 | break; |
| 1054 | } |
| 1055 | // Adjust the refcount of the clone... |
| 1056 | CPE.RefCount++; |
| 1057 | // ...and the original. If we didn't remove the old entry, none of the |
| 1058 | // addresses changed, so we don't need another pass. |
| 1059 | return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1; |
| 1060 | } |
| 1061 | } |
| 1062 | return 0; |
| 1063 | } |
| 1064 | |
| 1065 | /// LookForCPEntryInRange - see if the currently referenced CPE is in range; |
| 1066 | /// This version checks if the longer form of the instruction can be used to |
| 1067 | /// to satisfy things. |
| 1068 | /// if not, see if an in-range clone of the CPE is in range, and if so, |
| 1069 | /// change the data structures so the user references the clone. Returns: |
| 1070 | /// 0 = no existing entry found |
| 1071 | /// 1 = entry found, and there were no code insertions or deletions |
| 1072 | /// 2 = entry found, and there were code insertions or deletions |
| 1073 | int MipsConstantIslandImpl::findLongFormInRangeCPEntry(CPUser &U, |
| 1074 | unsigned UserOffset) { |
| 1075 | MachineInstr *UserMI = U.MI; |
| 1076 | MachineInstr *CPEMI = U.CPEMI; |
| 1077 | |
| 1078 | // Check to see if the CPE is already in-range. |
| 1079 | if (isCPEntryInRange(MI: UserMI, UserOffset, CPEMI, |
| 1080 | MaxDisp: U.getLongFormMaxDisp(), NegOk: U.NegOk, |
| 1081 | DoDump: true)) { |
| 1082 | LLVM_DEBUG(dbgs() << "In range\n" ); |
| 1083 | UserMI->setDesc(TII->get(Opcode: U.getLongFormOpcode())); |
| 1084 | U.setMaxDisp(U.getLongFormMaxDisp()); |
| 1085 | return 2; // instruction is longer length now |
| 1086 | } |
| 1087 | |
| 1088 | // No. Look for previously created clones of the CPE that are in range. |
| 1089 | unsigned CPI = CPEMI->getOperand(i: 1).getIndex(); |
| 1090 | std::vector<CPEntry> &CPEs = CPEntries[CPI]; |
| 1091 | for (CPEntry &CPE : CPEs) { |
| 1092 | // We already tried this one |
| 1093 | if (CPE.CPEMI == CPEMI) |
| 1094 | continue; |
| 1095 | // Removing CPEs can leave empty entries, skip |
| 1096 | if (CPE.CPEMI == nullptr) |
| 1097 | continue; |
| 1098 | if (isCPEntryInRange(MI: UserMI, UserOffset, CPEMI: CPE.CPEMI, MaxDisp: U.getLongFormMaxDisp(), |
| 1099 | NegOk: U.NegOk)) { |
| 1100 | LLVM_DEBUG(dbgs() << "Replacing CPE#" << CPI << " with CPE#" << CPE.CPI |
| 1101 | << "\n" ); |
| 1102 | // Point the CPUser node to the replacement |
| 1103 | U.CPEMI = CPE.CPEMI; |
| 1104 | // Change the CPI in the instruction operand to refer to the clone. |
| 1105 | for (MachineOperand &MO : UserMI->operands()) |
| 1106 | if (MO.isCPI()) { |
| 1107 | MO.setIndex(CPE.CPI); |
| 1108 | break; |
| 1109 | } |
| 1110 | // Adjust the refcount of the clone... |
| 1111 | CPE.RefCount++; |
| 1112 | // ...and the original. If we didn't remove the old entry, none of the |
| 1113 | // addresses changed, so we don't need another pass. |
| 1114 | return decrementCPEReferenceCount(CPI, CPEMI) ? 2 : 1; |
| 1115 | } |
| 1116 | } |
| 1117 | return 0; |
| 1118 | } |
| 1119 | |
| 1120 | /// getUnconditionalBrDisp - Returns the maximum displacement that can fit in |
| 1121 | /// the specific unconditional branch instruction. |
| 1122 | static inline unsigned getUnconditionalBrDisp(int Opc) { |
| 1123 | switch (Opc) { |
| 1124 | case Mips::Bimm16: |
| 1125 | return ((1<<10)-1)*2; |
| 1126 | case Mips::BimmX16: |
| 1127 | return ((1<<16)-1)*2; |
| 1128 | default: |
| 1129 | break; |
| 1130 | } |
| 1131 | return ((1<<16)-1)*2; |
| 1132 | } |
| 1133 | |
| 1134 | /// findAvailableWater - Look for an existing entry in the WaterList in which |
| 1135 | /// we can place the CPE referenced from U so it's within range of U's MI. |
| 1136 | /// Returns true if found, false if not. If it returns true, WaterIter |
| 1137 | /// is set to the WaterList entry. |
| 1138 | /// To ensure that this pass |
| 1139 | /// terminates, the CPE location for a particular CPUser is only allowed to |
| 1140 | /// move to a lower address, so search backward from the end of the list and |
| 1141 | /// prefer the first water that is in range. |
| 1142 | bool MipsConstantIslandImpl::findAvailableWater(CPUser &U, unsigned UserOffset, |
| 1143 | water_iterator &WaterIter) { |
| 1144 | if (WaterList.empty()) |
| 1145 | return false; |
| 1146 | |
| 1147 | unsigned BestGrowth = ~0u; |
| 1148 | for (water_iterator IP = std::prev(x: WaterList.end()), B = WaterList.begin();; |
| 1149 | --IP) { |
| 1150 | MachineBasicBlock* WaterBB = *IP; |
| 1151 | // Check if water is in range and is either at a lower address than the |
| 1152 | // current "high water mark" or a new water block that was created since |
| 1153 | // the previous iteration by inserting an unconditional branch. In the |
| 1154 | // latter case, we want to allow resetting the high water mark back to |
| 1155 | // this new water since we haven't seen it before. Inserting branches |
| 1156 | // should be relatively uncommon and when it does happen, we want to be |
| 1157 | // sure to take advantage of it for all the CPEs near that block, so that |
| 1158 | // we don't insert more branches than necessary. |
| 1159 | unsigned Growth; |
| 1160 | if (isWaterInRange(UserOffset, Water: WaterBB, U, Growth) && |
| 1161 | (WaterBB->getNumber() < U.HighWaterMark->getNumber() || |
| 1162 | NewWaterList.count(Ptr: WaterBB)) && Growth < BestGrowth) { |
| 1163 | // This is the least amount of required padding seen so far. |
| 1164 | BestGrowth = Growth; |
| 1165 | WaterIter = IP; |
| 1166 | LLVM_DEBUG(dbgs() << "Found water after " << printMBBReference(*WaterBB) |
| 1167 | << " Growth=" << Growth << '\n'); |
| 1168 | |
| 1169 | // Keep looking unless it is perfect. |
| 1170 | if (BestGrowth == 0) |
| 1171 | return true; |
| 1172 | } |
| 1173 | if (IP == B) |
| 1174 | break; |
| 1175 | } |
| 1176 | return BestGrowth != ~0u; |
| 1177 | } |
| 1178 | |
| 1179 | /// createNewWater - No existing WaterList entry will work for |
| 1180 | /// CPUsers[CPUserIndex], so create a place to put the CPE. The end of the |
| 1181 | /// block is used if in range, and the conditional branch munged so control |
| 1182 | /// flow is correct. Otherwise the block is split to create a hole with an |
| 1183 | /// unconditional branch around it. In either case NewMBB is set to a |
| 1184 | /// block following which the new island can be inserted (the WaterList |
| 1185 | /// is not adjusted). |
| 1186 | void MipsConstantIslandImpl::createNewWater(unsigned CPUserIndex, |
| 1187 | unsigned UserOffset, |
| 1188 | MachineBasicBlock *&NewMBB) { |
| 1189 | CPUser &U = CPUsers[CPUserIndex]; |
| 1190 | MachineInstr *UserMI = U.MI; |
| 1191 | MachineInstr *CPEMI = U.CPEMI; |
| 1192 | MachineBasicBlock *UserMBB = UserMI->getParent(); |
| 1193 | const BasicBlockInfo &UserBBI = BBInfo[UserMBB->getNumber()]; |
| 1194 | |
| 1195 | // If the block does not end in an unconditional branch already, and if the |
| 1196 | // end of the block is within range, make new water there. |
| 1197 | if (BBHasFallthrough(MBB: UserMBB)) { |
| 1198 | // Size of branch to insert. |
| 1199 | unsigned Delta = 2; |
| 1200 | // Compute the offset where the CPE will begin. |
| 1201 | unsigned CPEOffset = UserBBI.postOffset() + Delta; |
| 1202 | |
| 1203 | if (isOffsetInRange(UserOffset, TrialOffset: CPEOffset, U)) { |
| 1204 | LLVM_DEBUG(dbgs() << "Split at end of " << printMBBReference(*UserMBB) |
| 1205 | << format(", expected CPE offset %#x\n" , CPEOffset)); |
| 1206 | NewMBB = &*++UserMBB->getIterator(); |
| 1207 | // Add an unconditional branch from UserMBB to fallthrough block. Record |
| 1208 | // it for branch lengthening; this new branch will not get out of range, |
| 1209 | // but if the preceding conditional branch is out of range, the targets |
| 1210 | // will be exchanged, and the altered branch may be out of range, so the |
| 1211 | // machinery has to know about it. |
| 1212 | int UncondBr = Mips::Bimm16; |
| 1213 | BuildMI(BB: UserMBB, MIMD: DebugLoc(), MCID: TII->get(Opcode: UncondBr)).addMBB(MBB: NewMBB); |
| 1214 | unsigned MaxDisp = getUnconditionalBrDisp(Opc: UncondBr); |
| 1215 | ImmBranches.push_back(x: ImmBranch(&UserMBB->back(), |
| 1216 | MaxDisp, false, UncondBr)); |
| 1217 | BBInfo[UserMBB->getNumber()].Size += Delta; |
| 1218 | adjustBBOffsetsAfter(BB: UserMBB); |
| 1219 | return; |
| 1220 | } |
| 1221 | } |
| 1222 | |
| 1223 | // What a big block. Find a place within the block to split it. |
| 1224 | |
| 1225 | // Try to split the block so it's fully aligned. Compute the latest split |
| 1226 | // point where we can add a 4-byte branch instruction, and then align to |
| 1227 | // Align which is the largest possible alignment in the function. |
| 1228 | const Align Align = MF->getAlignment(); |
| 1229 | unsigned BaseInsertOffset = UserOffset + getMaxDisp(U); |
| 1230 | LLVM_DEBUG(dbgs() << format("Split in middle of big block before %#x" , |
| 1231 | BaseInsertOffset)); |
| 1232 | |
| 1233 | // The 4 in the following is for the unconditional branch we'll be inserting |
| 1234 | // Alignment of the island is handled |
| 1235 | // inside isOffsetInRange. |
| 1236 | BaseInsertOffset -= 4; |
| 1237 | |
| 1238 | LLVM_DEBUG(dbgs() << format(", adjusted to %#x" , BaseInsertOffset) |
| 1239 | << " la=" << Log2(Align) << '\n'); |
| 1240 | |
| 1241 | // This could point off the end of the block if we've already got constant |
| 1242 | // pool entries following this block; only the last one is in the water list. |
| 1243 | // Back past any possible branches (allow for a conditional and a maximally |
| 1244 | // long unconditional). |
| 1245 | if (BaseInsertOffset + 8 >= UserBBI.postOffset()) { |
| 1246 | BaseInsertOffset = UserBBI.postOffset() - 8; |
| 1247 | LLVM_DEBUG(dbgs() << format("Move inside block: %#x\n" , BaseInsertOffset)); |
| 1248 | } |
| 1249 | unsigned EndInsertOffset = BaseInsertOffset + 4 + |
| 1250 | CPEMI->getOperand(i: 2).getImm(); |
| 1251 | MachineBasicBlock::iterator MI = UserMI; |
| 1252 | ++MI; |
| 1253 | unsigned CPUIndex = CPUserIndex+1; |
| 1254 | unsigned NumCPUsers = CPUsers.size(); |
| 1255 | //MachineInstr *LastIT = 0; |
| 1256 | for (unsigned Offset = UserOffset + TII->getInstSizeInBytes(MI: *UserMI); |
| 1257 | Offset < BaseInsertOffset; |
| 1258 | Offset += TII->getInstSizeInBytes(MI: *MI), MI = std::next(x: MI)) { |
| 1259 | assert(MI != UserMBB->end() && "Fell off end of block" ); |
| 1260 | if (CPUIndex < NumCPUsers && CPUsers[CPUIndex].MI == MI) { |
| 1261 | CPUser &U = CPUsers[CPUIndex]; |
| 1262 | if (!isOffsetInRange(UserOffset: Offset, TrialOffset: EndInsertOffset, U)) { |
| 1263 | // Shift intertion point by one unit of alignment so it is within reach. |
| 1264 | BaseInsertOffset -= Align.value(); |
| 1265 | EndInsertOffset -= Align.value(); |
| 1266 | } |
| 1267 | // This is overly conservative, as we don't account for CPEMIs being |
| 1268 | // reused within the block, but it doesn't matter much. Also assume CPEs |
| 1269 | // are added in order with alignment padding. We may eventually be able |
| 1270 | // to pack the aligned CPEs better. |
| 1271 | EndInsertOffset += U.CPEMI->getOperand(i: 2).getImm(); |
| 1272 | CPUIndex++; |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | NewMBB = splitBlockBeforeInstr(MI&: *--MI); |
| 1277 | } |
| 1278 | |
| 1279 | /// handleConstantPoolUser - Analyze the specified user, checking to see if it |
| 1280 | /// is out-of-range. If so, pick up the constant pool value and move it some |
| 1281 | /// place in-range. Return true if we changed any addresses (thus must run |
| 1282 | /// another pass of branch lengthening), false otherwise. |
| 1283 | bool MipsConstantIslandImpl::handleConstantPoolUser(unsigned CPUserIndex) { |
| 1284 | CPUser &U = CPUsers[CPUserIndex]; |
| 1285 | MachineInstr *UserMI = U.MI; |
| 1286 | MachineInstr *CPEMI = U.CPEMI; |
| 1287 | unsigned CPI = CPEMI->getOperand(i: 1).getIndex(); |
| 1288 | unsigned Size = CPEMI->getOperand(i: 2).getImm(); |
| 1289 | // Compute this only once, it's expensive. |
| 1290 | unsigned UserOffset = getUserOffset(U); |
| 1291 | |
| 1292 | // See if the current entry is within range, or there is a clone of it |
| 1293 | // in range. |
| 1294 | int result = findInRangeCPEntry(U, UserOffset); |
| 1295 | if (result==1) return false; |
| 1296 | else if (result==2) return true; |
| 1297 | |
| 1298 | // Look for water where we can place this CPE. |
| 1299 | MachineBasicBlock *NewIsland = MF->CreateMachineBasicBlock(); |
| 1300 | MachineBasicBlock *NewMBB; |
| 1301 | water_iterator IP; |
| 1302 | if (findAvailableWater(U, UserOffset, WaterIter&: IP)) { |
| 1303 | LLVM_DEBUG(dbgs() << "Found water in range\n" ); |
| 1304 | MachineBasicBlock *WaterBB = *IP; |
| 1305 | |
| 1306 | // If the original WaterList entry was "new water" on this iteration, |
| 1307 | // propagate that to the new island. This is just keeping NewWaterList |
| 1308 | // updated to match the WaterList, which will be updated below. |
| 1309 | if (NewWaterList.erase(Ptr: WaterBB)) |
| 1310 | NewWaterList.insert(Ptr: NewIsland); |
| 1311 | |
| 1312 | // The new CPE goes before the following block (NewMBB). |
| 1313 | NewMBB = &*++WaterBB->getIterator(); |
| 1314 | } else { |
| 1315 | // No water found. |
| 1316 | // we first see if a longer form of the instruction could have reached |
| 1317 | // the constant. in that case we won't bother to split |
| 1318 | if (!STI->getCLOpts().constant_islands_no_load_relaxation) { |
| 1319 | result = findLongFormInRangeCPEntry(U, UserOffset); |
| 1320 | if (result != 0) return true; |
| 1321 | } |
| 1322 | LLVM_DEBUG(dbgs() << "No water found\n" ); |
| 1323 | createNewWater(CPUserIndex, UserOffset, NewMBB); |
| 1324 | |
| 1325 | // splitBlockBeforeInstr adds to WaterList, which is important when it is |
| 1326 | // called while handling branches so that the water will be seen on the |
| 1327 | // next iteration for constant pools, but in this context, we don't want |
| 1328 | // it. Check for this so it will be removed from the WaterList. |
| 1329 | // Also remove any entry from NewWaterList. |
| 1330 | MachineBasicBlock *WaterBB = &*--NewMBB->getIterator(); |
| 1331 | IP = llvm::find(Range&: WaterList, Val: WaterBB); |
| 1332 | if (IP != WaterList.end()) |
| 1333 | NewWaterList.erase(Ptr: WaterBB); |
| 1334 | |
| 1335 | // We are adding new water. Update NewWaterList. |
| 1336 | NewWaterList.insert(Ptr: NewIsland); |
| 1337 | } |
| 1338 | |
| 1339 | // Remove the original WaterList entry; we want subsequent insertions in |
| 1340 | // this vicinity to go after the one we're about to insert. This |
| 1341 | // considerably reduces the number of times we have to move the same CPE |
| 1342 | // more than once and is also important to ensure the algorithm terminates. |
| 1343 | if (IP != WaterList.end()) |
| 1344 | WaterList.erase(position: IP); |
| 1345 | |
| 1346 | // Okay, we know we can put an island before NewMBB now, do it! |
| 1347 | MF->insert(MBBI: NewMBB->getIterator(), MBB: NewIsland); |
| 1348 | |
| 1349 | // Update internal data structures to account for the newly inserted MBB. |
| 1350 | updateForInsertedWaterBlock(NewBB: NewIsland); |
| 1351 | |
| 1352 | // Decrement the old entry, and remove it if refcount becomes 0. |
| 1353 | decrementCPEReferenceCount(CPI, CPEMI); |
| 1354 | |
| 1355 | // No existing clone of this CPE is within range. |
| 1356 | // We will be generating a new clone. Get a UID for it. |
| 1357 | unsigned ID = createPICLabelUId(); |
| 1358 | |
| 1359 | // Now that we have an island to add the CPE to, clone the original CPE and |
| 1360 | // add it to the island. |
| 1361 | U.HighWaterMark = NewIsland; |
| 1362 | U.CPEMI = BuildMI(BB: NewIsland, MIMD: DebugLoc(), MCID: TII->get(Opcode: Mips::CONSTPOOL_ENTRY)) |
| 1363 | .addImm(Val: ID).addConstantPoolIndex(Idx: CPI).addImm(Val: Size); |
| 1364 | CPEntries[CPI].push_back(x: CPEntry(U.CPEMI, ID, 1)); |
| 1365 | ++NumCPEs; |
| 1366 | |
| 1367 | // Mark the basic block as aligned as required by the const-pool entry. |
| 1368 | NewIsland->setAlignment(getCPEAlign(CPEMI: *U.CPEMI)); |
| 1369 | |
| 1370 | // Increase the size of the island block to account for the new entry. |
| 1371 | BBInfo[NewIsland->getNumber()].Size += Size; |
| 1372 | adjustBBOffsetsAfter(BB: &*--NewIsland->getIterator()); |
| 1373 | |
| 1374 | // Finally, change the CPI in the instruction operand to be ID. |
| 1375 | for (MachineOperand &MO : UserMI->operands()) |
| 1376 | if (MO.isCPI()) { |
| 1377 | MO.setIndex(ID); |
| 1378 | break; |
| 1379 | } |
| 1380 | |
| 1381 | LLVM_DEBUG( |
| 1382 | dbgs() << " Moved CPE to #" << ID << " CPI=" << CPI |
| 1383 | << format(" offset=%#x\n" , BBInfo[NewIsland->getNumber()].Offset)); |
| 1384 | |
| 1385 | return true; |
| 1386 | } |
| 1387 | |
| 1388 | /// removeDeadCPEMI - Remove a dead constant pool entry instruction. Update |
| 1389 | /// sizes and offsets of impacted basic blocks. |
| 1390 | void MipsConstantIslandImpl::removeDeadCPEMI(MachineInstr *CPEMI) { |
| 1391 | MachineBasicBlock *CPEBB = CPEMI->getParent(); |
| 1392 | unsigned Size = CPEMI->getOperand(i: 2).getImm(); |
| 1393 | CPEMI->eraseFromParent(); |
| 1394 | BBInfo[CPEBB->getNumber()].Size -= Size; |
| 1395 | // All succeeding offsets have the current size value added in, fix this. |
| 1396 | if (CPEBB->empty()) { |
| 1397 | BBInfo[CPEBB->getNumber()].Size = 0; |
| 1398 | |
| 1399 | // This block no longer needs to be aligned. |
| 1400 | CPEBB->setAlignment(Align(1)); |
| 1401 | } else { |
| 1402 | // Entries are sorted by descending alignment, so realign from the front. |
| 1403 | CPEBB->setAlignment(getCPEAlign(CPEMI: *CPEBB->begin())); |
| 1404 | } |
| 1405 | |
| 1406 | adjustBBOffsetsAfter(BB: CPEBB); |
| 1407 | // An island has only one predecessor BB and one successor BB. Check if |
| 1408 | // this BB's predecessor jumps directly to this BB's successor. This |
| 1409 | // shouldn't happen currently. |
| 1410 | assert(!BBIsJumpedOver(CPEBB) && "How did this happen?" ); |
| 1411 | // FIXME: remove the empty blocks after all the work is done? |
| 1412 | } |
| 1413 | |
| 1414 | /// removeUnusedCPEntries - Remove constant pool entries whose refcounts |
| 1415 | /// are zero. |
| 1416 | bool MipsConstantIslandImpl::removeUnusedCPEntries() { |
| 1417 | unsigned MadeChange = false; |
| 1418 | for (std::vector<CPEntry> &CPEs : CPEntries) { |
| 1419 | for (CPEntry &CPE : CPEs) { |
| 1420 | if (CPE.RefCount == 0 && CPE.CPEMI) { |
| 1421 | removeDeadCPEMI(CPEMI: CPE.CPEMI); |
| 1422 | CPE.CPEMI = nullptr; |
| 1423 | MadeChange = true; |
| 1424 | } |
| 1425 | } |
| 1426 | } |
| 1427 | return MadeChange; |
| 1428 | } |
| 1429 | |
| 1430 | /// isBBInRange - Returns true if the distance between specific MI and |
| 1431 | /// specific BB can fit in MI's displacement field. |
| 1432 | bool MipsConstantIslandImpl::isBBInRange(MachineInstr *MI, |
| 1433 | MachineBasicBlock *DestBB, |
| 1434 | unsigned MaxDisp) { |
| 1435 | unsigned PCAdj = 4; |
| 1436 | unsigned BrOffset = getOffsetOf(MI) + PCAdj; |
| 1437 | unsigned DestOffset = BBInfo[DestBB->getNumber()].Offset; |
| 1438 | |
| 1439 | LLVM_DEBUG(dbgs() << "Branch of destination " << printMBBReference(*DestBB) |
| 1440 | << " from " << printMBBReference(*MI->getParent()) |
| 1441 | << " max delta=" << MaxDisp << " from " << getOffsetOf(MI) |
| 1442 | << " to " << DestOffset << " offset " |
| 1443 | << int(DestOffset - BrOffset) << "\t" << *MI); |
| 1444 | |
| 1445 | if (BrOffset <= DestOffset) { |
| 1446 | // Branch before the Dest. |
| 1447 | if (DestOffset-BrOffset <= MaxDisp) |
| 1448 | return true; |
| 1449 | } else { |
| 1450 | if (BrOffset-DestOffset <= MaxDisp) |
| 1451 | return true; |
| 1452 | } |
| 1453 | return false; |
| 1454 | } |
| 1455 | |
| 1456 | /// fixupImmediateBr - Fix up an immediate branch whose destination is too far |
| 1457 | /// away to fit in its displacement field. |
| 1458 | bool MipsConstantIslandImpl::fixupImmediateBr(ImmBranch &Br) { |
| 1459 | MachineInstr *MI = Br.MI; |
| 1460 | unsigned TargetOperand = branchTargetOperand(MI); |
| 1461 | MachineBasicBlock *DestBB = MI->getOperand(i: TargetOperand).getMBB(); |
| 1462 | |
| 1463 | // Check to see if the DestBB is already in-range. |
| 1464 | if (isBBInRange(MI, DestBB, MaxDisp: Br.MaxDisp)) |
| 1465 | return false; |
| 1466 | |
| 1467 | if (!Br.isCond) |
| 1468 | return fixupUnconditionalBr(Br); |
| 1469 | return fixupConditionalBr(Br); |
| 1470 | } |
| 1471 | |
| 1472 | /// fixupUnconditionalBr - Fix up an unconditional branch whose destination is |
| 1473 | /// too far away to fit in its displacement field. If the LR register has been |
| 1474 | /// spilled in the epilogue, then we can use BL to implement a far jump. |
| 1475 | /// Otherwise, add an intermediate branch instruction to a branch. |
| 1476 | bool MipsConstantIslandImpl::fixupUnconditionalBr(ImmBranch &Br) { |
| 1477 | MachineInstr *MI = Br.MI; |
| 1478 | MachineBasicBlock *MBB = MI->getParent(); |
| 1479 | MachineBasicBlock *DestBB = MI->getOperand(i: 0).getMBB(); |
| 1480 | // Use BL to implement far jump. |
| 1481 | unsigned BimmX16MaxDisp = ((1 << 16)-1) * 2; |
| 1482 | if (isBBInRange(MI, DestBB, MaxDisp: BimmX16MaxDisp)) { |
| 1483 | Br.MaxDisp = BimmX16MaxDisp; |
| 1484 | MI->setDesc(TII->get(Opcode: Mips::BimmX16)); |
| 1485 | } |
| 1486 | else { |
| 1487 | // need to give the math a more careful look here |
| 1488 | // this is really a segment address and not |
| 1489 | // a PC relative address. FIXME. But I think that |
| 1490 | // just reducing the bits by 1 as I've done is correct. |
| 1491 | // The basic block we are branching too much be longword aligned. |
| 1492 | // we know that RA is saved because we always save it right now. |
| 1493 | // this requirement will be relaxed later but we also have an alternate |
| 1494 | // way to implement this that I will implement that does not need jal. |
| 1495 | // We should have a way to back out this alignment restriction |
| 1496 | // if we "can" later. but it is not harmful. |
| 1497 | // |
| 1498 | DestBB->setAlignment(Align(4)); |
| 1499 | Br.MaxDisp = ((1<<24)-1) * 2; |
| 1500 | MI->setDesc(TII->get(Opcode: Mips::JalB16)); |
| 1501 | } |
| 1502 | BBInfo[MBB->getNumber()].Size += 2; |
| 1503 | adjustBBOffsetsAfter(BB: MBB); |
| 1504 | HasFarJump = true; |
| 1505 | ++NumUBrFixed; |
| 1506 | |
| 1507 | LLVM_DEBUG(dbgs() << " Changed B to long jump " << *MI); |
| 1508 | |
| 1509 | return true; |
| 1510 | } |
| 1511 | |
| 1512 | /// fixupConditionalBr - Fix up a conditional branch whose destination is too |
| 1513 | /// far away to fit in its displacement field. It is converted to an inverse |
| 1514 | /// conditional branch + an unconditional branch to the destination. |
| 1515 | bool MipsConstantIslandImpl::fixupConditionalBr(ImmBranch &Br) { |
| 1516 | MachineInstr *MI = Br.MI; |
| 1517 | unsigned TargetOperand = branchTargetOperand(MI); |
| 1518 | MachineBasicBlock *DestBB = MI->getOperand(i: TargetOperand).getMBB(); |
| 1519 | unsigned Opcode = MI->getOpcode(); |
| 1520 | unsigned LongFormOpcode = longformBranchOpcode(Opcode); |
| 1521 | unsigned LongFormMaxOff = branchMaxOffsets(Opcode: LongFormOpcode); |
| 1522 | |
| 1523 | // Check to see if the DestBB is already in-range. |
| 1524 | if (isBBInRange(MI, DestBB, MaxDisp: LongFormMaxOff)) { |
| 1525 | Br.MaxDisp = LongFormMaxOff; |
| 1526 | MI->setDesc(TII->get(Opcode: LongFormOpcode)); |
| 1527 | return true; |
| 1528 | } |
| 1529 | |
| 1530 | // Add an unconditional branch to the destination and invert the branch |
| 1531 | // condition to jump over it: |
| 1532 | // bteqz L1 |
| 1533 | // => |
| 1534 | // bnez L2 |
| 1535 | // b L1 |
| 1536 | // L2: |
| 1537 | |
| 1538 | // If the branch is at the end of its MBB and that has a fall-through block, |
| 1539 | // direct the updated conditional branch to the fall-through block. Otherwise, |
| 1540 | // split the MBB before the next instruction. |
| 1541 | MachineBasicBlock *MBB = MI->getParent(); |
| 1542 | MachineInstr *BMI = &MBB->back(); |
| 1543 | bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB); |
| 1544 | unsigned OppositeBranchOpcode = TII->getOppositeBranchOpc(Opc: Opcode); |
| 1545 | |
| 1546 | ++NumCBrFixed; |
| 1547 | if (BMI != MI) { |
| 1548 | if (std::next(x: MachineBasicBlock::iterator(MI)) == std::prev(x: MBB->end()) && |
| 1549 | BMI->isUnconditionalBranch()) { |
| 1550 | // Last MI in the BB is an unconditional branch. Can we simply invert the |
| 1551 | // condition and swap destinations: |
| 1552 | // beqz L1 |
| 1553 | // b L2 |
| 1554 | // => |
| 1555 | // bnez L2 |
| 1556 | // b L1 |
| 1557 | unsigned BMITargetOperand = branchTargetOperand(MI: BMI); |
| 1558 | MachineBasicBlock *NewDest = |
| 1559 | BMI->getOperand(i: BMITargetOperand).getMBB(); |
| 1560 | if (isBBInRange(MI, DestBB: NewDest, MaxDisp: Br.MaxDisp)) { |
| 1561 | LLVM_DEBUG( |
| 1562 | dbgs() << " Invert Bcc condition and swap its destination with " |
| 1563 | << *BMI); |
| 1564 | MI->setDesc(TII->get(Opcode: OppositeBranchOpcode)); |
| 1565 | BMI->getOperand(i: BMITargetOperand).setMBB(DestBB); |
| 1566 | MI->getOperand(i: TargetOperand).setMBB(NewDest); |
| 1567 | return true; |
| 1568 | } |
| 1569 | } |
| 1570 | } |
| 1571 | |
| 1572 | if (NeedSplit) { |
| 1573 | splitBlockBeforeInstr(MI&: *MI); |
| 1574 | // No need for the branch to the next block. We're adding an unconditional |
| 1575 | // branch to the destination. |
| 1576 | int delta = TII->getInstSizeInBytes(MI: MBB->back()); |
| 1577 | BBInfo[MBB->getNumber()].Size -= delta; |
| 1578 | MBB->back().eraseFromParent(); |
| 1579 | // BBInfo[SplitBB].Offset is wrong temporarily, fixed below |
| 1580 | } |
| 1581 | MachineBasicBlock *NextBB = &*++MBB->getIterator(); |
| 1582 | |
| 1583 | LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*DestBB) |
| 1584 | << " also invert condition and change dest. to " |
| 1585 | << printMBBReference(*NextBB) << "\n" ); |
| 1586 | |
| 1587 | // Insert a new conditional branch and a new unconditional branch. |
| 1588 | // Also update the ImmBranch as well as adding a new entry for the new branch. |
| 1589 | if (MI->getNumExplicitOperands() == 2) { |
| 1590 | BuildMI(BB: MBB, MIMD: DebugLoc(), MCID: TII->get(Opcode: OppositeBranchOpcode)) |
| 1591 | .addReg(RegNo: MI->getOperand(i: 0).getReg()) |
| 1592 | .addMBB(MBB: NextBB); |
| 1593 | } else { |
| 1594 | BuildMI(BB: MBB, MIMD: DebugLoc(), MCID: TII->get(Opcode: OppositeBranchOpcode)) |
| 1595 | .addMBB(MBB: NextBB); |
| 1596 | } |
| 1597 | Br.MI = &MBB->back(); |
| 1598 | BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MI: MBB->back()); |
| 1599 | BuildMI(BB: MBB, MIMD: DebugLoc(), MCID: TII->get(Opcode: Br.UncondBr)).addMBB(MBB: DestBB); |
| 1600 | BBInfo[MBB->getNumber()].Size += TII->getInstSizeInBytes(MI: MBB->back()); |
| 1601 | unsigned MaxDisp = getUnconditionalBrDisp(Opc: Br.UncondBr); |
| 1602 | ImmBranches.push_back(x: ImmBranch(&MBB->back(), MaxDisp, false, Br.UncondBr)); |
| 1603 | |
| 1604 | // Remove the old conditional branch. It may or may not still be in MBB. |
| 1605 | BBInfo[MI->getParent()->getNumber()].Size -= TII->getInstSizeInBytes(MI: *MI); |
| 1606 | MI->eraseFromParent(); |
| 1607 | adjustBBOffsetsAfter(BB: MBB); |
| 1608 | return true; |
| 1609 | } |
| 1610 | |
| 1611 | void MipsConstantIslandImpl::prescanForConstants() { |
| 1612 | for (MachineBasicBlock &B : *MF) { |
| 1613 | for (MachineInstr &MI : B) { |
| 1614 | switch (MI.getDesc().getOpcode()) { |
| 1615 | case Mips::LwConstant32: { |
| 1616 | PrescannedForConstants = true; |
| 1617 | LLVM_DEBUG(dbgs() << "constant island constant " << MI << "\n" ); |
| 1618 | LLVM_DEBUG(dbgs() << "num operands " << MI.getNumOperands() << "\n" ); |
| 1619 | MachineOperand &Literal = MI.getOperand(i: 1); |
| 1620 | if (Literal.isImm()) { |
| 1621 | int64_t V = Literal.getImm(); |
| 1622 | LLVM_DEBUG(dbgs() << "literal " << V << "\n" ); |
| 1623 | Type *Int32Ty = Type::getInt32Ty(C&: MF->getFunction().getContext()); |
| 1624 | const Constant *C = ConstantInt::getSigned(Ty: Int32Ty, V); |
| 1625 | unsigned index = MCP->getConstantPoolIndex(C, Alignment: Align(4)); |
| 1626 | MI.getOperand(i: 2).ChangeToImmediate(ImmVal: index); |
| 1627 | LLVM_DEBUG(dbgs() << "constant island constant " << MI << "\n" ); |
| 1628 | MI.setDesc(TII->get(Opcode: Mips::LwRxPcTcp16)); |
| 1629 | MI.removeOperand(OpNo: 1); |
| 1630 | MI.removeOperand(OpNo: 1); |
| 1631 | MI.addOperand(Op: MachineOperand::CreateCPI(Idx: index, Offset: 0)); |
| 1632 | } |
| 1633 | break; |
| 1634 | } |
| 1635 | default: |
| 1636 | break; |
| 1637 | } |
| 1638 | } |
| 1639 | } |
| 1640 | } |
| 1641 | |
| 1642 | /// Returns a pass that converts branches to long branches. |
| 1643 | FunctionPass *llvm::createMipsConstantIslandLegacyPass() { |
| 1644 | return new MipsConstantIslandLegacy(); |
| 1645 | } |
| 1646 | |
| 1647 | bool MipsConstantIslandLegacy::runOnMachineFunction(MachineFunction &MF) { |
| 1648 | MipsConstantIslandImpl Impl; |
| 1649 | return Impl.runOnMachineFunction(mf&: MF); |
| 1650 | } |
| 1651 | |
| 1652 | PreservedAnalyses |
| 1653 | MipsConstantIslandPass::run(MachineFunction &MF, |
| 1654 | MachineFunctionAnalysisManager &MFAM) { |
| 1655 | MipsConstantIslandImpl Impl; |
| 1656 | return Impl.runOnMachineFunction(mf&: MF) |
| 1657 | ? getMachineFunctionPassPreservedAnalyses() |
| 1658 | : PreservedAnalyses::all(); |
| 1659 | } |
| 1660 | |