| 1 | //===- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler -------------------===// |
| 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 | // Simple pass to fill delay slots with useful instructions. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "Mips.h" |
| 14 | #include "MipsInstrInfo.h" |
| 15 | #include "MipsSubtarget.h" |
| 16 | #include "llvm/ADT/BitVector.h" |
| 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/PointerUnion.h" |
| 19 | #include "llvm/ADT/STLExtras.h" |
| 20 | #include "llvm/ADT/SmallPtrSet.h" |
| 21 | #include "llvm/ADT/SmallVector.h" |
| 22 | #include "llvm/ADT/Statistic.h" |
| 23 | #include "llvm/ADT/StringRef.h" |
| 24 | #include "llvm/Analysis/AliasAnalysis.h" |
| 25 | #include "llvm/Analysis/ValueTracking.h" |
| 26 | #include "llvm/CodeGen/MachineBasicBlock.h" |
| 27 | #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" |
| 28 | #include "llvm/CodeGen/MachineFunction.h" |
| 29 | #include "llvm/CodeGen/MachineFunctionPass.h" |
| 30 | #include "llvm/CodeGen/MachineInstr.h" |
| 31 | #include "llvm/CodeGen/MachineInstrBuilder.h" |
| 32 | #include "llvm/CodeGen/MachineOperand.h" |
| 33 | #include "llvm/CodeGen/MachineRegisterInfo.h" |
| 34 | #include "llvm/CodeGen/PseudoSourceValue.h" |
| 35 | #include "llvm/CodeGen/TargetRegisterInfo.h" |
| 36 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
| 37 | #include "llvm/MC/MCInstrDesc.h" |
| 38 | #include "llvm/MC/MCRegisterInfo.h" |
| 39 | #include "llvm/Support/Casting.h" |
| 40 | #include "llvm/Support/CodeGen.h" |
| 41 | #include "llvm/Support/CommandLine.h" |
| 42 | #include "llvm/Support/ErrorHandling.h" |
| 43 | #include "llvm/Support/raw_ostream.h" |
| 44 | #include "llvm/Target/TargetMachine.h" |
| 45 | #include <cassert> |
| 46 | #include <iterator> |
| 47 | #include <memory> |
| 48 | #include <utility> |
| 49 | |
| 50 | using namespace llvm; |
| 51 | |
| 52 | #define DEBUG_TYPE "mips-delay-slot-filler" |
| 53 | |
| 54 | STATISTIC(FilledSlots, "Number of delay slots filled" ); |
| 55 | STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that" |
| 56 | " are not NOP." ); |
| 57 | STATISTIC(R5900ShortLoopNops, "Number of delay slots left as NOP for R5900 " |
| 58 | "short loop fix" ); |
| 59 | |
| 60 | static cl::opt<bool> DisableDelaySlotFiller( |
| 61 | "disable-mips-delay-filler" , |
| 62 | cl::init(Val: false), |
| 63 | cl::desc("Fill all delay slots with NOPs." ), |
| 64 | cl::Hidden); |
| 65 | |
| 66 | static cl::opt<bool> DisableForwardSearch( |
| 67 | "disable-mips-df-forward-search" , |
| 68 | cl::init(Val: true), |
| 69 | cl::desc("Disallow MIPS delay filler to search forward." ), |
| 70 | cl::Hidden); |
| 71 | |
| 72 | static cl::opt<bool> DisableSuccBBSearch( |
| 73 | "disable-mips-df-succbb-search" , |
| 74 | cl::init(Val: true), |
| 75 | cl::desc("Disallow MIPS delay filler to search successor basic blocks." ), |
| 76 | cl::Hidden); |
| 77 | |
| 78 | static cl::opt<bool> DisableBackwardSearch( |
| 79 | "disable-mips-df-backward-search" , |
| 80 | cl::init(Val: false), |
| 81 | cl::desc("Disallow MIPS delay filler to search backward." ), |
| 82 | cl::Hidden); |
| 83 | |
| 84 | extern cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy; |
| 85 | |
| 86 | namespace { |
| 87 | |
| 88 | using Iter = MachineBasicBlock::iterator; |
| 89 | using ReverseIter = MachineBasicBlock::reverse_iterator; |
| 90 | using BB2BrMap = SmallDenseMap<MachineBasicBlock *, MachineInstr *, 2>; |
| 91 | |
| 92 | // Holds information about one branch instruction |
| 93 | // This is used by the MIPS1 target to easily find all paths of a branch to |
| 94 | // then check the first instruction for possible load delay hazards |
| 95 | class BranchInformation { |
| 96 | private: |
| 97 | // The pointer to the actual branch instruction |
| 98 | const MachineInstr *BranchInstr = nullptr; |
| 99 | // The pointer to the instruction after the branch (= the `else` case) |
| 100 | const MachineInstr *ElseBranchInstr = nullptr; |
| 101 | |
| 102 | // Check if `Adr` is a pseudo instruction and if so, then treat it as non |
| 103 | // existing |
| 104 | static const MachineInstr *filterPseudoInstr(const MachineInstr *Adr) { |
| 105 | if (Adr && !Adr->isPseudo()) { |
| 106 | return Adr; |
| 107 | } |
| 108 | return nullptr; |
| 109 | } |
| 110 | |
| 111 | public: |
| 112 | // Creates a new `BranchInformation` from the branch candidate `CurrentSlot` |
| 113 | // together with the end (`MBBEnd`) of the current MBB and the first |
| 114 | // instruction of the next MBB `NextMBBInstr` |
| 115 | BranchInformation(MachineInstrBundleIterator<MachineInstr> CurrentSlot, |
| 116 | MachineInstrBundleIterator<MachineInstr> MBBEnd, |
| 117 | const MachineInstr *NextMBBInstr) |
| 118 | : BranchInstr( |
| 119 | CurrentSlot->isBranch() |
| 120 | ? BranchInformation::filterPseudoInstr(Adr: &(*CurrentSlot)) |
| 121 | : nullptr), |
| 122 | ElseBranchInstr( |
| 123 | (++CurrentSlot) == MBBEnd |
| 124 | ? BranchInformation::filterPseudoInstr(Adr: NextMBBInstr) |
| 125 | : BranchInformation::filterPseudoInstr(Adr: &(*CurrentSlot))) {} |
| 126 | |
| 127 | // Checks if we have a branch |
| 128 | constexpr bool hasBranchInstr() const { return this->BranchInstr; } |
| 129 | |
| 130 | // Checks if we have an else branch |
| 131 | constexpr bool hasBranchElseInstr() const { return this->ElseBranchInstr; } |
| 132 | |
| 133 | // Checks if we have an indirect branch |
| 134 | constexpr bool isIndirectBranch() const { |
| 135 | if (this->BranchInstr) { |
| 136 | return this->BranchInstr->isIndirectBranch(); |
| 137 | } |
| 138 | return false; |
| 139 | } |
| 140 | |
| 141 | // Checks if we have an unconditional branch |
| 142 | constexpr bool isUnconditionalBranch() const { |
| 143 | if (this->BranchInstr) { |
| 144 | return this->BranchInstr->isUnconditionalBranch(); |
| 145 | } |
| 146 | return false; |
| 147 | } |
| 148 | |
| 149 | // Accesses the branch instruction |
| 150 | const MachineInstr *getBranchInstr() const { return this->BranchInstr; } |
| 151 | |
| 152 | // Accesses the instruction after the branch |
| 153 | const MachineInstr *getBranchElseInstr() const { |
| 154 | return this->ElseBranchInstr; |
| 155 | } |
| 156 | |
| 157 | // Gets the target of the branch |
| 158 | const MachineBasicBlock *getBranchTarget() const { |
| 159 | if (this->isIndirectBranch() || !this->hasBranchInstr()) { |
| 160 | // Indirect branch has no known target |
| 161 | return nullptr; |
| 162 | } |
| 163 | |
| 164 | for (const MachineOperand &MO : this->BranchInstr->operands()) { |
| 165 | if (MO.isMBB()) { |
| 166 | return MO.getMBB(); |
| 167 | } |
| 168 | } |
| 169 | return nullptr; |
| 170 | } |
| 171 | }; |
| 172 | |
| 173 | class RegDefsUses { |
| 174 | public: |
| 175 | RegDefsUses(const TargetRegisterInfo &TRI); |
| 176 | |
| 177 | void init(const MachineInstr &MI); |
| 178 | |
| 179 | /// This function sets all caller-saved registers in Defs. |
| 180 | void setCallerSaved(const MachineInstr &MI); |
| 181 | |
| 182 | /// This function sets all unallocatable registers in Defs. |
| 183 | void setUnallocatableRegs(const MachineFunction &MF); |
| 184 | |
| 185 | /// Set bits in Uses corresponding to MBB's live-out registers except for |
| 186 | /// the registers that are live-in to SuccBB. |
| 187 | void addLiveOut(const MachineBasicBlock &MBB, |
| 188 | const MachineBasicBlock &SuccBB); |
| 189 | |
| 190 | bool update(const MachineInstr &MI, unsigned Begin, unsigned End); |
| 191 | |
| 192 | private: |
| 193 | bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg, |
| 194 | bool IsDef) const; |
| 195 | |
| 196 | /// Returns true if Reg or its alias is in RegSet. |
| 197 | bool isRegInSet(const BitVector &RegSet, unsigned Reg) const; |
| 198 | |
| 199 | const TargetRegisterInfo &TRI; |
| 200 | BitVector Defs, Uses; |
| 201 | }; |
| 202 | |
| 203 | /// Base class for inspecting loads and stores. |
| 204 | class InspectMemInstr { |
| 205 | public: |
| 206 | InspectMemInstr(bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {} |
| 207 | virtual ~InspectMemInstr() = default; |
| 208 | |
| 209 | /// Return true if MI cannot be moved to delay slot. |
| 210 | bool hasHazard(const MachineInstr &MI); |
| 211 | |
| 212 | protected: |
| 213 | /// Flags indicating whether loads or stores have been seen. |
| 214 | bool OrigSeenLoad = false; |
| 215 | bool OrigSeenStore = false; |
| 216 | bool SeenLoad = false; |
| 217 | bool SeenStore = false; |
| 218 | |
| 219 | /// Memory instructions are not allowed to move to delay slot if this flag |
| 220 | /// is true. |
| 221 | bool ForbidMemInstr; |
| 222 | |
| 223 | private: |
| 224 | virtual bool hasHazard_(const MachineInstr &MI) = 0; |
| 225 | }; |
| 226 | |
| 227 | /// This subclass rejects any memory instructions. |
| 228 | class NoMemInstr : public InspectMemInstr { |
| 229 | public: |
| 230 | NoMemInstr() : InspectMemInstr(true) {} |
| 231 | |
| 232 | private: |
| 233 | bool hasHazard_(const MachineInstr &MI) override { return true; } |
| 234 | }; |
| 235 | |
| 236 | /// This subclass accepts loads from stacks and constant loads. |
| 237 | class LoadFromStackOrConst : public InspectMemInstr { |
| 238 | public: |
| 239 | LoadFromStackOrConst() : InspectMemInstr(false) {} |
| 240 | |
| 241 | private: |
| 242 | bool hasHazard_(const MachineInstr &MI) override; |
| 243 | }; |
| 244 | |
| 245 | /// This subclass uses memory dependence information to determine whether a |
| 246 | /// memory instruction can be moved to a delay slot. |
| 247 | class MemDefsUses : public InspectMemInstr { |
| 248 | public: |
| 249 | explicit MemDefsUses(const MachineFrameInfo *MFI); |
| 250 | |
| 251 | private: |
| 252 | using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>; |
| 253 | |
| 254 | bool hasHazard_(const MachineInstr &MI) override; |
| 255 | |
| 256 | /// Update Defs and Uses. Return true if there exist dependences that |
| 257 | /// disqualify the delay slot candidate between V and values in Uses and |
| 258 | /// Defs. |
| 259 | bool updateDefsUses(ValueType V, bool MayStore); |
| 260 | |
| 261 | /// Get the list of underlying objects of MI's memory operand. |
| 262 | bool getUnderlyingObjects(const MachineInstr &MI, |
| 263 | SmallVectorImpl<ValueType> &Objects) const; |
| 264 | |
| 265 | const MachineFrameInfo *MFI; |
| 266 | SmallPtrSet<ValueType, 4> Uses, Defs; |
| 267 | |
| 268 | /// Flags indicating whether loads or stores with no underlying objects have |
| 269 | /// been seen. |
| 270 | bool SeenNoObjLoad = false; |
| 271 | bool SeenNoObjStore = false; |
| 272 | }; |
| 273 | |
| 274 | class MipsDelaySlotFiller : public MachineFunctionPass { |
| 275 | public: |
| 276 | MipsDelaySlotFiller() : MachineFunctionPass(ID) {} |
| 277 | |
| 278 | StringRef getPassName() const override { return "Mips Delay Slot Filler" ; } |
| 279 | |
| 280 | bool runOnMachineFunction(MachineFunction &F) override { |
| 281 | TM = &F.getTarget(); |
| 282 | bool Changed = false; |
| 283 | for (auto MBB = F.begin(); MBB != F.end();) { |
| 284 | auto curMBB = MBB; |
| 285 | MBB++; |
| 286 | |
| 287 | Changed |= runOnMachineBasicBlock( |
| 288 | MBB&: *curMBB, FirstNextMBBInstr: (MBB != F.end() && !(*MBB).empty()) ? &(*MBB).instr_front() |
| 289 | : nullptr); |
| 290 | } |
| 291 | |
| 292 | // This pass invalidates liveness information when it reorders |
| 293 | // instructions to fill delay slot. Without this, -verify-machineinstrs |
| 294 | // will fail. |
| 295 | if (Changed) |
| 296 | F.getRegInfo().invalidateLiveness(); |
| 297 | |
| 298 | return Changed; |
| 299 | } |
| 300 | |
| 301 | MachineFunctionProperties getRequiredProperties() const override { |
| 302 | return MachineFunctionProperties().setNoVRegs(); |
| 303 | } |
| 304 | |
| 305 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 306 | AU.addRequired<MachineBranchProbabilityInfoWrapperPass>(); |
| 307 | MachineFunctionPass::getAnalysisUsage(AU); |
| 308 | } |
| 309 | |
| 310 | static char ID; |
| 311 | |
| 312 | private: |
| 313 | bool runOnMachineBasicBlock(MachineBasicBlock &MBB, |
| 314 | MachineInstr *FirstNextMBBInstr); |
| 315 | |
| 316 | Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch, |
| 317 | const DebugLoc &DL); |
| 318 | |
| 319 | /// This function checks if it is valid to move Candidate to the delay slot |
| 320 | /// and returns true if it isn't. It also updates memory and register |
| 321 | /// dependence information. |
| 322 | bool delayHasHazard(const MipsSubtarget &STI, const MachineInstr &Candidate, |
| 323 | const BranchInformation &BranchInfo, RegDefsUses &RegDU, |
| 324 | InspectMemInstr &IM) const; |
| 325 | |
| 326 | /// This function searches range [Begin, End) for an instruction that can be |
| 327 | /// moved to the delay slot. Returns true on success. |
| 328 | template <typename IterTy> |
| 329 | bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End, |
| 330 | const BranchInformation &BranchInfo, RegDefsUses &RegDU, |
| 331 | InspectMemInstr &IM, Iter Slot, IterTy &Filler) const; |
| 332 | |
| 333 | /// This function searches in the backward direction for an instruction that |
| 334 | /// can be moved to the delay slot. Returns true on success. |
| 335 | bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot, |
| 336 | const BranchInformation &BranchInfo) const; |
| 337 | |
| 338 | /// This function searches MBB in the forward direction for an instruction |
| 339 | /// that can be moved to the delay slot. Returns true on success. |
| 340 | bool searchForward(MachineBasicBlock &MBB, Iter Slot, |
| 341 | const BranchInformation &BranchInfo) const; |
| 342 | |
| 343 | /// This function searches one of MBB's successor blocks for an instruction |
| 344 | /// that can be moved to the delay slot and inserts clones of the |
| 345 | /// instruction into the successor's predecessor blocks. |
| 346 | bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot, |
| 347 | const BranchInformation &BranchInfo) const; |
| 348 | |
| 349 | /// Pick a successor block of MBB. Return NULL if MBB doesn't have a |
| 350 | /// successor block that is not a landing pad. |
| 351 | MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const; |
| 352 | |
| 353 | /// This function analyzes MBB and returns an instruction with an unoccupied |
| 354 | /// slot that branches to Dst. |
| 355 | std::pair<MipsInstrInfo::BranchType, MachineInstr *> |
| 356 | getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const; |
| 357 | |
| 358 | /// Examine Pred and see if it is possible to insert an instruction into |
| 359 | /// one of its branches delay slot or its end. |
| 360 | bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ, |
| 361 | RegDefsUses &RegDU, bool &HasMultipleSuccs, |
| 362 | BB2BrMap &BrMap) const; |
| 363 | |
| 364 | bool terminateSearch(const MachineInstr &Candidate) const; |
| 365 | |
| 366 | const TargetMachine *TM = nullptr; |
| 367 | }; |
| 368 | |
| 369 | } // end anonymous namespace |
| 370 | |
| 371 | char MipsDelaySlotFiller::ID = 0; |
| 372 | |
| 373 | static bool hasUnoccupiedSlot(const MachineInstr *MI) { |
| 374 | return MI->hasDelaySlot() && !MI->isBundledWithSucc(); |
| 375 | } |
| 376 | |
| 377 | /// Check if a branch is a short backward loop that triggers the R5900 erratum. |
| 378 | /// Quote from binutils-gdb/gas/config/tc-mips.c: |
| 379 | /// |
| 380 | /// On the R5900 short loops need to be fixed by inserting a NOP in the |
| 381 | /// branch delay slot. |
| 382 | /// |
| 383 | /// The short loop bug under certain conditions causes loops to execute |
| 384 | /// only once or twice. We must ensure that the assembler never |
| 385 | /// generates loops that satisfy all of the following conditions: |
| 386 | /// |
| 387 | /// - a loop consists of less than or equal to six instructions |
| 388 | /// (including the branch delay slot); |
| 389 | /// - a loop contains only one conditional branch instruction at the end |
| 390 | /// of the loop; |
| 391 | /// - a loop does not contain any other branch or jump instructions; |
| 392 | /// - a branch delay slot of the loop is not NOP (EE 2.9 or later). |
| 393 | /// |
| 394 | /// We need to do this because of a hardware bug in the R5900 chip. |
| 395 | static bool isR5900ShortLoopBranch(const MachineInstr *MI, |
| 396 | const MachineBasicBlock &MBB) { |
| 397 | // Must be a conditional branch (not jump or indirect branch) |
| 398 | if (!MI->isBranch() || MI->isIndirectBranch()) |
| 399 | return false; |
| 400 | |
| 401 | // Check if this is a conditional branch by looking for an MBB operand |
| 402 | const MachineBasicBlock *TargetMBB = nullptr; |
| 403 | for (const MachineOperand &MO : MI->operands()) { |
| 404 | if (MO.isMBB()) { |
| 405 | TargetMBB = MO.getMBB(); |
| 406 | break; |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | // Must have a target and must target the same basic block (backward branch) |
| 411 | if (!TargetMBB || TargetMBB != &MBB) |
| 412 | return false; |
| 413 | |
| 414 | // Count instructions from the beginning of the block to the branch |
| 415 | // A short loop is 6 instructions or fewer (including branch + delay slot) |
| 416 | // The delay slot adds 1 more, so we check if instructions before branch <= 5 |
| 417 | unsigned InstrCount = 0; |
| 418 | bool HasOtherBranch = false; |
| 419 | |
| 420 | for (const MachineInstr &Instr : MBB) { |
| 421 | if (&Instr == MI) |
| 422 | break; |
| 423 | |
| 424 | // Skip debug and pseudo instructions |
| 425 | if (Instr.isDebugInstr() || Instr.isTransient()) |
| 426 | continue; |
| 427 | |
| 428 | ++InstrCount; |
| 429 | |
| 430 | // If there's another branch in the loop, the erratum doesn't apply |
| 431 | if (Instr.isBranch() || Instr.isCall()) { |
| 432 | HasOtherBranch = true; |
| 433 | break; |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | // If there's another branch/call in the loop, erratum doesn't apply |
| 438 | if (HasOtherBranch) |
| 439 | return false; |
| 440 | |
| 441 | // Add 1 for the branch itself, +1 for delay slot = InstrCount + 2 |
| 442 | // Erratum triggers when total <= 6, so InstrCount + 2 <= 6 => InstrCount <= 4 |
| 443 | // But we're conservative: if InstrCount <= 5 (total <= 7), skip filling |
| 444 | // to match the exact condition from r5900check: offset -5 to -1 (2-6 instrs) |
| 445 | return InstrCount <= 5; |
| 446 | } |
| 447 | |
| 448 | INITIALIZE_PASS(MipsDelaySlotFiller, DEBUG_TYPE, |
| 449 | "Fill delay slot for MIPS" , false, false) |
| 450 | |
| 451 | /// This function inserts clones of Filler into predecessor blocks. |
| 452 | static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) { |
| 453 | MachineFunction *MF = Filler->getParent()->getParent(); |
| 454 | |
| 455 | for (const auto &I : BrMap) { |
| 456 | if (I.second) { |
| 457 | MIBundleBuilder(I.second).append(MI: MF->CloneMachineInstr(Orig: &*Filler)); |
| 458 | ++UsefulSlots; |
| 459 | } else { |
| 460 | I.first->push_back(MI: MF->CloneMachineInstr(Orig: &*Filler)); |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | /// This function adds registers Filler defines to MBB's live-in register list. |
| 466 | static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) { |
| 467 | for (const MachineOperand &MO : Filler->operands()) { |
| 468 | unsigned R; |
| 469 | |
| 470 | if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg())) |
| 471 | continue; |
| 472 | |
| 473 | #ifndef NDEBUG |
| 474 | const MachineFunction &MF = *MBB.getParent(); |
| 475 | assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) && |
| 476 | "Shouldn't move an instruction with unallocatable registers across " |
| 477 | "basic block boundaries." ); |
| 478 | #endif |
| 479 | |
| 480 | if (!MBB.isLiveIn(Reg: R)) |
| 481 | MBB.addLiveIn(PhysReg: R); |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI) |
| 486 | : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {} |
| 487 | |
| 488 | void RegDefsUses::init(const MachineInstr &MI) { |
| 489 | // Add all register operands which are explicit and non-variadic. |
| 490 | update(MI, Begin: 0, End: MI.getDesc().getNumOperands()); |
| 491 | |
| 492 | // If MI is a call, add RA to Defs to prevent users of RA from going into |
| 493 | // delay slot. |
| 494 | if (MI.isCall()) |
| 495 | Defs.set(Mips::RA); |
| 496 | |
| 497 | // Add all implicit register operands of branch instructions except |
| 498 | // register AT. |
| 499 | if (MI.isBranch()) { |
| 500 | update(MI, Begin: MI.getDesc().getNumOperands(), End: MI.getNumOperands()); |
| 501 | Defs.reset(Idx: Mips::AT); |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | void RegDefsUses::setCallerSaved(const MachineInstr &MI) { |
| 506 | assert(MI.isCall()); |
| 507 | |
| 508 | // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into |
| 509 | // the delay slot. The reason is that RA/RA_64 must not be changed |
| 510 | // in the delay slot so that the callee can return to the caller. |
| 511 | if (MI.definesRegister(Reg: Mips::RA, /*TRI=*/nullptr) || |
| 512 | MI.definesRegister(Reg: Mips::RA_64, /*TRI=*/nullptr)) { |
| 513 | Defs.set(Mips::RA); |
| 514 | Defs.set(Mips::RA_64); |
| 515 | } |
| 516 | |
| 517 | // If MI is a call, add all caller-saved registers to Defs. |
| 518 | BitVector CallerSavedRegs(TRI.getNumRegs(), true); |
| 519 | |
| 520 | CallerSavedRegs.reset(Idx: Mips::ZERO); |
| 521 | CallerSavedRegs.reset(Idx: Mips::ZERO_64); |
| 522 | |
| 523 | for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MF: MI.getParent()->getParent()); |
| 524 | *R; ++R) |
| 525 | for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI) |
| 526 | CallerSavedRegs.reset(Idx: *AI); |
| 527 | |
| 528 | Defs |= CallerSavedRegs; |
| 529 | } |
| 530 | |
| 531 | void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) { |
| 532 | BitVector AllocSet = TRI.getAllocatableSet(MF); |
| 533 | |
| 534 | for (unsigned R : AllocSet.set_bits()) |
| 535 | for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI) |
| 536 | AllocSet.set(*AI); |
| 537 | |
| 538 | AllocSet.set(Mips::ZERO); |
| 539 | AllocSet.set(Mips::ZERO_64); |
| 540 | |
| 541 | Defs |= AllocSet.flip(); |
| 542 | } |
| 543 | |
| 544 | void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB, |
| 545 | const MachineBasicBlock &SuccBB) { |
| 546 | for (const MachineBasicBlock *S : MBB.successors()) |
| 547 | if (S != &SuccBB) |
| 548 | for (const auto &LI : S->liveins()) |
| 549 | Uses.set(LI.PhysReg.id()); |
| 550 | } |
| 551 | |
| 552 | bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) { |
| 553 | BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs()); |
| 554 | bool HasHazard = false; |
| 555 | |
| 556 | for (unsigned I = Begin; I != End; ++I) { |
| 557 | const MachineOperand &MO = MI.getOperand(i: I); |
| 558 | |
| 559 | if (MO.isReg() && MO.getReg()) { |
| 560 | if (checkRegDefsUses(NewDefs, NewUses, Reg: MO.getReg(), IsDef: MO.isDef())) { |
| 561 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found register hazard for operand " |
| 562 | << I << ": " ; |
| 563 | MO.dump()); |
| 564 | HasHazard = true; |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | Defs |= NewDefs; |
| 570 | Uses |= NewUses; |
| 571 | |
| 572 | return HasHazard; |
| 573 | } |
| 574 | |
| 575 | bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, |
| 576 | unsigned Reg, bool IsDef) const { |
| 577 | if (IsDef) { |
| 578 | NewDefs.set(Reg); |
| 579 | // check whether Reg has already been defined or used. |
| 580 | return (isRegInSet(RegSet: Defs, Reg) || isRegInSet(RegSet: Uses, Reg)); |
| 581 | } |
| 582 | |
| 583 | NewUses.set(Reg); |
| 584 | // check whether Reg has already been defined. |
| 585 | return isRegInSet(RegSet: Defs, Reg); |
| 586 | } |
| 587 | |
| 588 | bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const { |
| 589 | // Check Reg and all aliased Registers. |
| 590 | for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI) |
| 591 | if (RegSet.test(Idx: *AI)) |
| 592 | return true; |
| 593 | return false; |
| 594 | } |
| 595 | |
| 596 | bool InspectMemInstr::hasHazard(const MachineInstr &MI) { |
| 597 | if (!MI.mayStore() && !MI.mayLoad()) |
| 598 | return false; |
| 599 | |
| 600 | if (ForbidMemInstr) |
| 601 | return true; |
| 602 | |
| 603 | OrigSeenLoad = SeenLoad; |
| 604 | OrigSeenStore = SeenStore; |
| 605 | SeenLoad |= MI.mayLoad(); |
| 606 | SeenStore |= MI.mayStore(); |
| 607 | |
| 608 | // If MI is an ordered or volatile memory reference, disallow moving |
| 609 | // subsequent loads and stores to delay slot. |
| 610 | if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) { |
| 611 | ForbidMemInstr = true; |
| 612 | return true; |
| 613 | } |
| 614 | |
| 615 | return hasHazard_(MI); |
| 616 | } |
| 617 | |
| 618 | bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) { |
| 619 | if (MI.mayStore()) |
| 620 | return true; |
| 621 | |
| 622 | if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue()) |
| 623 | return true; |
| 624 | |
| 625 | if (const PseudoSourceValue *PSV = |
| 626 | (*MI.memoperands_begin())->getPseudoValue()) { |
| 627 | if (isa<FixedStackPseudoSourceValue>(Val: PSV)) |
| 628 | return false; |
| 629 | return !PSV->isConstant(nullptr) && !PSV->isStack(); |
| 630 | } |
| 631 | |
| 632 | return true; |
| 633 | } |
| 634 | |
| 635 | MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_) |
| 636 | : InspectMemInstr(false), MFI(MFI_) {} |
| 637 | |
| 638 | bool MemDefsUses::hasHazard_(const MachineInstr &MI) { |
| 639 | bool HasHazard = false; |
| 640 | |
| 641 | // Check underlying object list. |
| 642 | SmallVector<ValueType, 4> Objs; |
| 643 | if (getUnderlyingObjects(MI, Objects&: Objs)) { |
| 644 | for (ValueType VT : Objs) |
| 645 | HasHazard |= updateDefsUses(V: VT, MayStore: MI.mayStore()); |
| 646 | return HasHazard; |
| 647 | } |
| 648 | |
| 649 | // No underlying objects found. |
| 650 | HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore); |
| 651 | HasHazard |= MI.mayLoad() || OrigSeenStore; |
| 652 | |
| 653 | SeenNoObjLoad |= MI.mayLoad(); |
| 654 | SeenNoObjStore |= MI.mayStore(); |
| 655 | |
| 656 | return HasHazard; |
| 657 | } |
| 658 | |
| 659 | bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) { |
| 660 | if (MayStore) |
| 661 | return !Defs.insert(Ptr: V).second || Uses.count(Ptr: V) || SeenNoObjStore || |
| 662 | SeenNoObjLoad; |
| 663 | |
| 664 | Uses.insert(Ptr: V); |
| 665 | return Defs.count(Ptr: V) || SeenNoObjStore; |
| 666 | } |
| 667 | |
| 668 | bool MemDefsUses:: |
| 669 | getUnderlyingObjects(const MachineInstr &MI, |
| 670 | SmallVectorImpl<ValueType> &Objects) const { |
| 671 | if (!MI.hasOneMemOperand()) |
| 672 | return false; |
| 673 | |
| 674 | auto & MMO = **MI.memoperands_begin(); |
| 675 | |
| 676 | if (const PseudoSourceValue *PSV = MMO.getPseudoValue()) { |
| 677 | if (!PSV->isAliased(MFI)) |
| 678 | return false; |
| 679 | Objects.push_back(Elt: PSV); |
| 680 | return true; |
| 681 | } |
| 682 | |
| 683 | if (const Value *V = MMO.getValue()) { |
| 684 | SmallVector<const Value *, 4> Objs; |
| 685 | ::getUnderlyingObjects(V, Objects&: Objs); |
| 686 | |
| 687 | for (const Value *UValue : Objs) { |
| 688 | if (!isIdentifiedObject(V)) |
| 689 | return false; |
| 690 | |
| 691 | Objects.push_back(Elt: UValue); |
| 692 | } |
| 693 | return true; |
| 694 | } |
| 695 | |
| 696 | return false; |
| 697 | } |
| 698 | |
| 699 | // Replace Branch with the compact branch instruction. |
| 700 | Iter MipsDelaySlotFiller::replaceWithCompactBranch(MachineBasicBlock &MBB, |
| 701 | Iter Branch, |
| 702 | const DebugLoc &DL) { |
| 703 | const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>(); |
| 704 | const MipsInstrInfo *TII = STI.getInstrInfo(); |
| 705 | |
| 706 | unsigned NewOpcode = TII->getEquivalentCompactForm(I: Branch); |
| 707 | Branch = TII->genInstrWithNewOpc(NewOpc: NewOpcode, I: Branch); |
| 708 | |
| 709 | auto *ToErase = cast<MachineInstr>(Val: &*std::next(x: Branch)); |
| 710 | // Update call info for the Branch. |
| 711 | if (ToErase->shouldUpdateAdditionalCallInfo()) |
| 712 | ToErase->getMF()->moveAdditionalCallInfo(Old: ToErase, |
| 713 | New: cast<MachineInstr>(Val: &*Branch)); |
| 714 | ToErase->eraseFromParent(); |
| 715 | return Branch; |
| 716 | } |
| 717 | |
| 718 | // For given opcode returns opcode of corresponding instruction with short |
| 719 | // delay slot. |
| 720 | // For the pseudo TAILCALL*_MM instructions return the short delay slot |
| 721 | // form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range |
| 722 | // that is too short to make use of for tail calls. |
| 723 | static int getEquivalentCallShort(int Opcode) { |
| 724 | switch (Opcode) { |
| 725 | case Mips::BGEZAL: |
| 726 | return Mips::BGEZALS_MM; |
| 727 | case Mips::BLTZAL: |
| 728 | return Mips::BLTZALS_MM; |
| 729 | case Mips::JAL: |
| 730 | case Mips::JAL_MM: |
| 731 | return Mips::JALS_MM; |
| 732 | case Mips::JALR: |
| 733 | return Mips::JALRS_MM; |
| 734 | case Mips::JALR16_MM: |
| 735 | return Mips::JALRS16_MM; |
| 736 | case Mips::TAILCALL_MM: |
| 737 | llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!" ); |
| 738 | case Mips::TAILCALLREG: |
| 739 | return Mips::JR16_MM; |
| 740 | default: |
| 741 | llvm_unreachable("Unexpected call instruction for microMIPS." ); |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | /// runOnMachineBasicBlock - Fill in delay slots for the given basic block. |
| 746 | /// We assume there is only one delay slot per delayed instruction. |
| 747 | bool MipsDelaySlotFiller::runOnMachineBasicBlock( |
| 748 | MachineBasicBlock &MBB, MachineInstr *FirstNextMBBInstr) { |
| 749 | bool Changed = false; |
| 750 | const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>(); |
| 751 | bool InMicroMipsMode = STI.inMicroMipsMode(); |
| 752 | const MipsInstrInfo *TII = STI.getInstrInfo(); |
| 753 | |
| 754 | for (Iter I = MBB.begin(); I != MBB.end(); ++I) { |
| 755 | if (!hasUnoccupiedSlot(MI: &*I)) |
| 756 | continue; |
| 757 | |
| 758 | // R5900 short loop erratum fix: skip delay slot filling for short backward |
| 759 | // loops to avoid triggering a hardware bug where short loops may exit |
| 760 | // early. The fix can be controlled with -mfix-r5900 / -mno-fix-r5900. |
| 761 | bool SkipForFixR5900 = false; |
| 762 | if (STI.fixR5900() && isR5900ShortLoopBranch(MI: &*I, MBB)) { |
| 763 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": skipping delay slot fill for R5900 " |
| 764 | "short loop branch.\n" ); |
| 765 | ++R5900ShortLoopNops; |
| 766 | SkipForFixR5900 = true; |
| 767 | } |
| 768 | |
| 769 | // Delay slot filling is disabled at -O0, in microMIPS32R6, or for R5900 |
| 770 | // short loop branches. |
| 771 | if (!DisableDelaySlotFiller && |
| 772 | (TM->getOptLevel() != CodeGenOptLevel::None) && |
| 773 | !(InMicroMipsMode && STI.hasMips32r6()) && !SkipForFixR5900) { |
| 774 | |
| 775 | bool Filled = false; |
| 776 | const auto BranchInfo = |
| 777 | BranchInformation(I, MBB.end(), FirstNextMBBInstr); |
| 778 | |
| 779 | if (MipsCompactBranchPolicy.getValue() != CB_Always || |
| 780 | !TII->getEquivalentCompactForm(I)) { |
| 781 | if (searchBackward(MBB, Slot&: *I, BranchInfo)) { |
| 782 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot" |
| 783 | " in backwards search.\n" ); |
| 784 | Filled = true; |
| 785 | } else if (I->isTerminator()) { |
| 786 | if (searchSuccBBs(MBB, Slot: I, BranchInfo)) { |
| 787 | Filled = true; |
| 788 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot" |
| 789 | " in successor BB search.\n" ); |
| 790 | } |
| 791 | } else if (searchForward(MBB, Slot: I, BranchInfo)) { |
| 792 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot" |
| 793 | " in forwards search.\n" ); |
| 794 | Filled = true; |
| 795 | } |
| 796 | } |
| 797 | |
| 798 | if (Filled) { |
| 799 | // Get instruction with delay slot. |
| 800 | MachineBasicBlock::instr_iterator DSI = I.getInstrIterator(); |
| 801 | |
| 802 | if (InMicroMipsMode && TII->getInstSizeInBytes(MI: *std::next(x: DSI)) == 2 && |
| 803 | DSI->isCall()) { |
| 804 | // If instruction in delay slot is 16b change opcode to |
| 805 | // corresponding instruction with short delay slot. |
| 806 | |
| 807 | // TODO: Implement an instruction mapping table of 16bit opcodes to |
| 808 | // 32bit opcodes so that an instruction can be expanded. This would |
| 809 | // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop. |
| 810 | // TODO: Permit b16 when branching backwards to the same function |
| 811 | // if it is in range. |
| 812 | DSI->setDesc(TII->get(Opcode: getEquivalentCallShort(Opcode: DSI->getOpcode()))); |
| 813 | } |
| 814 | ++FilledSlots; |
| 815 | Changed = true; |
| 816 | continue; |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | // For microMIPS if instruction is BEQ or BNE with one ZERO register, then |
| 821 | // instead of adding NOP replace this instruction with the corresponding |
| 822 | // compact branch instruction, i.e. BEQZC or BNEZC. Additionally |
| 823 | // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can |
| 824 | // be replaced with JRC16_MM. |
| 825 | |
| 826 | // For MIPSR6 attempt to produce the corresponding compact (no delay slot) |
| 827 | // form of the CTI. For indirect jumps this will not require inserting a |
| 828 | // NOP and for branches will hopefully avoid requiring a NOP. |
| 829 | if ((InMicroMipsMode || |
| 830 | (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) && |
| 831 | TII->getEquivalentCompactForm(I)) { |
| 832 | I = replaceWithCompactBranch(MBB, Branch: I, DL: I->getDebugLoc()); |
| 833 | Changed = true; |
| 834 | continue; |
| 835 | } |
| 836 | |
| 837 | // Bundle the NOP to the instruction with the delay slot. |
| 838 | LLVM_DEBUG(dbgs() << DEBUG_TYPE << ": could not fill delay slot for " ; |
| 839 | I->dump()); |
| 840 | TII->insertNop(MBB, MI: std::next(x: I), DL: I->getDebugLoc()); |
| 841 | MIBundleBuilder(MBB, I, std::next(x: I, n: 2)); |
| 842 | ++FilledSlots; |
| 843 | Changed = true; |
| 844 | } |
| 845 | return Changed; |
| 846 | } |
| 847 | |
| 848 | template <typename IterTy> |
| 849 | bool MipsDelaySlotFiller::searchRange(MachineBasicBlock &MBB, IterTy Begin, |
| 850 | IterTy End, |
| 851 | const BranchInformation &BranchInfo, |
| 852 | RegDefsUses &RegDU, InspectMemInstr &IM, |
| 853 | Iter Slot, IterTy &Filler) const { |
| 854 | for (IterTy I = Begin; I != End;) { |
| 855 | IterTy CurrI = I; |
| 856 | ++I; |
| 857 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": checking instruction: " ; CurrI->dump()); |
| 858 | |
| 859 | if (terminateSearch(Candidate: *CurrI)) { |
| 860 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": should terminate search: " ; |
| 861 | CurrI->dump()); |
| 862 | break; |
| 863 | } |
| 864 | // Skip debug and pseudo instructions. |
| 865 | // Instruction TargetOpcode::JUMP_TABLE_DEBUG_INFO is only used to note |
| 866 | // jump table debug info. |
| 867 | if (CurrI->isDebugInstr() || CurrI->isJumpTableDebugInfo() || |
| 868 | CurrI->isMetaInstruction()) { |
| 869 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": ignoring debug instruction: " ; |
| 870 | CurrI->dump()); |
| 871 | continue; |
| 872 | } |
| 873 | |
| 874 | if (CurrI->isBundle()) { |
| 875 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": ignoring BUNDLE instruction: " ; |
| 876 | CurrI->dump()); |
| 877 | // However, we still need to update the register def-use information. |
| 878 | RegDU.update(MI: *CurrI, Begin: 0, End: CurrI->getNumOperands()); |
| 879 | continue; |
| 880 | } |
| 881 | |
| 882 | assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) && |
| 883 | "Cannot put calls, returns or branches in delay slot." ); |
| 884 | |
| 885 | if (CurrI->isKill()) { |
| 886 | CurrI->eraseFromParent(); |
| 887 | continue; |
| 888 | } |
| 889 | |
| 890 | const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>(); |
| 891 | if (delayHasHazard(STI, Candidate: *CurrI, BranchInfo, RegDU, IM)) |
| 892 | continue; |
| 893 | |
| 894 | bool InMicroMipsMode = STI.inMicroMipsMode(); |
| 895 | const MipsInstrInfo *TII = STI.getInstrInfo(); |
| 896 | unsigned Opcode = (*Slot).getOpcode(); |
| 897 | |
| 898 | // In mips1-4, should not put mflo into the delay slot for the return. |
| 899 | if ((IsMFLOMFHI(CurrI->getOpcode())) && |
| 900 | (!STI.hasMips32() && !STI.hasMips5())) |
| 901 | continue; |
| 902 | |
| 903 | // This is complicated by the tail call optimization. For non-PIC code |
| 904 | // there is only a 32bit sized unconditional branch which can be assumed |
| 905 | // to be able to reach the target. b16 only has a range of +/- 1 KB. |
| 906 | // It's entirely possible that the target function is reachable with b16 |
| 907 | // but we don't have enough information to make that decision. |
| 908 | if (InMicroMipsMode && TII->getInstSizeInBytes(MI: *CurrI) == 2 && |
| 909 | (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch || |
| 910 | Opcode == Mips::PseudoIndirectBranch_MM || |
| 911 | Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL)) |
| 912 | continue; |
| 913 | // Instructions LWP/SWP and MOVEP should not be in a delay slot as that |
| 914 | // results in unpredictable behaviour |
| 915 | if (InMicroMipsMode && (Opcode == Mips::LWP_MM || Opcode == Mips::SWP_MM || |
| 916 | Opcode == Mips::MOVEP_MM)) |
| 917 | continue; |
| 918 | |
| 919 | Filler = CurrI; |
| 920 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": found instruction for delay slot: " ; |
| 921 | CurrI->dump()); |
| 922 | |
| 923 | return true; |
| 924 | } |
| 925 | |
| 926 | return false; |
| 927 | } |
| 928 | |
| 929 | bool MipsDelaySlotFiller::searchBackward( |
| 930 | MachineBasicBlock &MBB, MachineInstr &Slot, |
| 931 | const BranchInformation &BranchInfo) const { |
| 932 | if (DisableBackwardSearch) |
| 933 | return false; |
| 934 | |
| 935 | auto *Fn = MBB.getParent(); |
| 936 | RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo()); |
| 937 | MemDefsUses MemDU(&Fn->getFrameInfo()); |
| 938 | ReverseIter Filler; |
| 939 | |
| 940 | RegDU.init(MI: Slot); |
| 941 | |
| 942 | MachineBasicBlock::iterator SlotI = Slot; |
| 943 | if (!searchRange(MBB, Begin: ++SlotI.getReverse(), End: MBB.rend(), BranchInfo, RegDU, |
| 944 | IM&: MemDU, Slot, Filler)) { |
| 945 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": could not find instruction for delay " |
| 946 | "slot using backwards search.\n" ); |
| 947 | return false; |
| 948 | } |
| 949 | |
| 950 | MBB.splice(Where: std::next(x: SlotI), Other: &MBB, From: Filler.getReverse()); |
| 951 | MIBundleBuilder(MBB, SlotI, std::next(x: SlotI, n: 2)); |
| 952 | ++UsefulSlots; |
| 953 | return true; |
| 954 | } |
| 955 | |
| 956 | bool MipsDelaySlotFiller::searchForward( |
| 957 | MachineBasicBlock &MBB, Iter Slot, |
| 958 | const BranchInformation &BranchInfo) const { |
| 959 | // Can handle only calls. |
| 960 | if (DisableForwardSearch || !Slot->isCall()) |
| 961 | return false; |
| 962 | |
| 963 | RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo()); |
| 964 | NoMemInstr NM; |
| 965 | Iter Filler; |
| 966 | |
| 967 | RegDU.setCallerSaved(*Slot); |
| 968 | |
| 969 | if (!searchRange(MBB, Begin: std::next(x: Slot), End: MBB.end(), BranchInfo, RegDU, IM&: NM, Slot, |
| 970 | Filler)) { |
| 971 | LLVM_DEBUG(dbgs() << DEBUG_TYPE ": could not find instruction for delay " |
| 972 | "slot using forwards search.\n" ); |
| 973 | return false; |
| 974 | } |
| 975 | |
| 976 | MBB.splice(Where: std::next(x: Slot), Other: &MBB, From: Filler); |
| 977 | MIBundleBuilder(MBB, Slot, std::next(x: Slot, n: 2)); |
| 978 | ++UsefulSlots; |
| 979 | return true; |
| 980 | } |
| 981 | |
| 982 | bool MipsDelaySlotFiller::searchSuccBBs( |
| 983 | MachineBasicBlock &MBB, Iter Slot, |
| 984 | const BranchInformation &BranchInfo) const { |
| 985 | if (DisableSuccBBSearch) |
| 986 | return false; |
| 987 | |
| 988 | MachineBasicBlock *SuccBB = selectSuccBB(B&: MBB); |
| 989 | |
| 990 | if (!SuccBB) |
| 991 | return false; |
| 992 | |
| 993 | RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo()); |
| 994 | bool HasMultipleSuccs = false; |
| 995 | BB2BrMap BrMap; |
| 996 | std::unique_ptr<InspectMemInstr> IM; |
| 997 | Iter Filler; |
| 998 | auto *Fn = MBB.getParent(); |
| 999 | |
| 1000 | // Iterate over SuccBB's predecessor list. |
| 1001 | for (MachineBasicBlock *Pred : SuccBB->predecessors()) |
| 1002 | if (!examinePred(Pred&: *Pred, Succ: *SuccBB, RegDU, HasMultipleSuccs, BrMap)) |
| 1003 | return false; |
| 1004 | |
| 1005 | // Do not allow moving instructions which have unallocatable register operands |
| 1006 | // across basic block boundaries. |
| 1007 | RegDU.setUnallocatableRegs(*Fn); |
| 1008 | |
| 1009 | // Only allow moving loads from stack or constants if any of the SuccBB's |
| 1010 | // predecessors have multiple successors. |
| 1011 | if (HasMultipleSuccs) { |
| 1012 | IM.reset(p: new LoadFromStackOrConst()); |
| 1013 | } else { |
| 1014 | const MachineFrameInfo &MFI = Fn->getFrameInfo(); |
| 1015 | IM.reset(p: new MemDefsUses(&MFI)); |
| 1016 | } |
| 1017 | |
| 1018 | if (!searchRange(MBB, Begin: SuccBB->begin(), End: SuccBB->end(), BranchInfo, RegDU, IM&: *IM, |
| 1019 | Slot, Filler)) |
| 1020 | return false; |
| 1021 | |
| 1022 | insertDelayFiller(Filler, BrMap); |
| 1023 | addLiveInRegs(Filler, MBB&: *SuccBB); |
| 1024 | Filler->eraseFromParent(); |
| 1025 | |
| 1026 | return true; |
| 1027 | } |
| 1028 | |
| 1029 | MachineBasicBlock * |
| 1030 | MipsDelaySlotFiller::selectSuccBB(MachineBasicBlock &B) const { |
| 1031 | if (B.succ_empty()) |
| 1032 | return nullptr; |
| 1033 | |
| 1034 | // Select the successor with the larget edge weight. |
| 1035 | auto &Prob = getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI(); |
| 1036 | MachineBasicBlock *S = |
| 1037 | *llvm::max_element(Range: B.successors(), C: [&](const MachineBasicBlock *Dst0, |
| 1038 | const MachineBasicBlock *Dst1) { |
| 1039 | return Prob.getEdgeProbability(Src: &B, Dst: Dst0) < |
| 1040 | Prob.getEdgeProbability(Src: &B, Dst: Dst1); |
| 1041 | }); |
| 1042 | return S->isEHPad() ? nullptr : S; |
| 1043 | } |
| 1044 | |
| 1045 | std::pair<MipsInstrInfo::BranchType, MachineInstr *> |
| 1046 | MipsDelaySlotFiller::getBranch(MachineBasicBlock &MBB, |
| 1047 | const MachineBasicBlock &Dst) const { |
| 1048 | const MipsInstrInfo *TII = |
| 1049 | MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo(); |
| 1050 | MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr; |
| 1051 | SmallVector<MachineInstr*, 2> BranchInstrs; |
| 1052 | SmallVector<MachineOperand, 2> Cond; |
| 1053 | |
| 1054 | MipsInstrInfo::BranchType R = |
| 1055 | TII->analyzeBranch(MBB, TBB&: TrueBB, FBB&: FalseBB, Cond, AllowModify: false, BranchInstrs); |
| 1056 | |
| 1057 | if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch)) |
| 1058 | return std::make_pair(x&: R, y: nullptr); |
| 1059 | |
| 1060 | if (R != MipsInstrInfo::BT_CondUncond) { |
| 1061 | if (!hasUnoccupiedSlot(MI: BranchInstrs[0])) |
| 1062 | return std::make_pair(x: MipsInstrInfo::BT_None, y: nullptr); |
| 1063 | |
| 1064 | assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst))); |
| 1065 | |
| 1066 | return std::make_pair(x&: R, y&: BranchInstrs[0]); |
| 1067 | } |
| 1068 | |
| 1069 | assert((TrueBB == &Dst) || (FalseBB == &Dst)); |
| 1070 | |
| 1071 | // Examine the conditional branch. See if its slot is occupied. |
| 1072 | if (hasUnoccupiedSlot(MI: BranchInstrs[0])) |
| 1073 | return std::make_pair(x: MipsInstrInfo::BT_Cond, y&: BranchInstrs[0]); |
| 1074 | |
| 1075 | // If that fails, try the unconditional branch. |
| 1076 | if (hasUnoccupiedSlot(MI: BranchInstrs[1]) && (FalseBB == &Dst)) |
| 1077 | return std::make_pair(x: MipsInstrInfo::BT_Uncond, y&: BranchInstrs[1]); |
| 1078 | |
| 1079 | return std::make_pair(x: MipsInstrInfo::BT_None, y: nullptr); |
| 1080 | } |
| 1081 | |
| 1082 | bool MipsDelaySlotFiller::examinePred(MachineBasicBlock &Pred, |
| 1083 | const MachineBasicBlock &Succ, |
| 1084 | RegDefsUses &RegDU, |
| 1085 | bool &HasMultipleSuccs, |
| 1086 | BB2BrMap &BrMap) const { |
| 1087 | std::pair<MipsInstrInfo::BranchType, MachineInstr *> P = |
| 1088 | getBranch(MBB&: Pred, Dst: Succ); |
| 1089 | |
| 1090 | // Return if either getBranch wasn't able to analyze the branches or there |
| 1091 | // were no branches with unoccupied slots. |
| 1092 | if (P.first == MipsInstrInfo::BT_None) |
| 1093 | return false; |
| 1094 | |
| 1095 | if ((P.first != MipsInstrInfo::BT_Uncond) && |
| 1096 | (P.first != MipsInstrInfo::BT_NoBranch)) { |
| 1097 | HasMultipleSuccs = true; |
| 1098 | RegDU.addLiveOut(MBB: Pred, SuccBB: Succ); |
| 1099 | } |
| 1100 | |
| 1101 | BrMap[&Pred] = P.second; |
| 1102 | return true; |
| 1103 | } |
| 1104 | |
| 1105 | /// Returns true if putting the candidate in the delay slot could let the |
| 1106 | /// branch target, or the instruction after the slot, read its result too |
| 1107 | /// early, or if those cannot be determined. |
| 1108 | static bool delayExposesHazard( |
| 1109 | const BranchInformation &BranchInfo, const MachineInstr &Candidate, |
| 1110 | function_ref<bool(const MachineInstr &, const MachineInstr &)> IsSafe) { |
| 1111 | // With no branch, or a branch whose target we cannot see, we do not know |
| 1112 | // which instruction executes next. Assume the worst. |
| 1113 | if (!BranchInfo.hasBranchInstr() || BranchInfo.isIndirectBranch()) |
| 1114 | return true; |
| 1115 | |
| 1116 | const MachineBasicBlock *TargetMBB = BranchInfo.getBranchTarget(); |
| 1117 | if (!TargetMBB || TargetMBB->empty()) |
| 1118 | return true; |
| 1119 | |
| 1120 | bool Exposed = !IsSafe(TargetMBB->instr_front(), Candidate); |
| 1121 | |
| 1122 | // A conditional branch also falls through, so the instruction after the |
| 1123 | // delay slot can be the one that reads the result. |
| 1124 | if (!BranchInfo.isUnconditionalBranch()) { |
| 1125 | if (!BranchInfo.hasBranchElseInstr()) |
| 1126 | return true; |
| 1127 | Exposed |= !IsSafe(*BranchInfo.getBranchElseInstr(), Candidate); |
| 1128 | } |
| 1129 | |
| 1130 | return Exposed; |
| 1131 | } |
| 1132 | |
| 1133 | bool MipsDelaySlotFiller::delayHasHazard(const MipsSubtarget &STI, |
| 1134 | const MachineInstr &Candidate, |
| 1135 | const BranchInformation &BranchInfo, |
| 1136 | RegDefsUses &RegDU, |
| 1137 | InspectMemInstr &IM) const { |
| 1138 | assert(!Candidate.isKill() && |
| 1139 | "KILL instructions should have been eliminated at this point." ); |
| 1140 | |
| 1141 | bool HasHazard = Candidate.isImplicitDef(); |
| 1142 | |
| 1143 | HasHazard |= IM.hasHazard(MI: Candidate); |
| 1144 | HasHazard |= RegDU.update(MI: Candidate, Begin: 0, End: Candidate.getNumOperands()); |
| 1145 | |
| 1146 | if (!HasHazard) { |
| 1147 | const MipsInstrInfo *TII = STI.getInstrInfo(); |
| 1148 | |
| 1149 | // MIPS-I has no load-use interlock: the instruction executed after a load |
| 1150 | // must not read the loaded register. |
| 1151 | if (STI.hasMips1() && !STI.hasMips2() && TII->HasLoadDelaySlot(MI: Candidate)) |
| 1152 | return delayExposesHazard( |
| 1153 | BranchInfo, Candidate, |
| 1154 | IsSafe: [TII](const MachineInstr &InShadow, const MachineInstr &Cand) { |
| 1155 | return TII->SafeInLoadDelaySlot(MIInSlot: InShadow, LoadMI: Cand); |
| 1156 | }); |
| 1157 | |
| 1158 | // MIPS-I through MIPS-III have the same problem when a value is moved |
| 1159 | // out of the floating point unit: |
| 1160 | if (!STI.hasMips32() && !STI.hasMips4() && TII->HasFPUDelaySlot(MI: Candidate)) |
| 1161 | return delayExposesHazard( |
| 1162 | BranchInfo, Candidate, |
| 1163 | IsSafe: [TII](const MachineInstr &InShadow, const MachineInstr &Cand) { |
| 1164 | return TII->SafeInFPUDelaySlot(MIInSlot: InShadow, FPUMI: Cand); |
| 1165 | }); |
| 1166 | } |
| 1167 | |
| 1168 | return HasHazard; |
| 1169 | } |
| 1170 | |
| 1171 | bool MipsDelaySlotFiller::terminateSearch(const MachineInstr &Candidate) const { |
| 1172 | return (Candidate.isTerminator() || Candidate.isCall() || |
| 1173 | Candidate.isPosition() || Candidate.isInlineAsm() || |
| 1174 | Candidate.hasUnmodeledSideEffects()); |
| 1175 | } |
| 1176 | |
| 1177 | /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay |
| 1178 | /// slots in Mips MachineFunctions |
| 1179 | FunctionPass *llvm::createMipsDelaySlotFillerPass() { |
| 1180 | return new MipsDelaySlotFiller(); |
| 1181 | } |
| 1182 | |