1 //===-- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Simple pass to fill delay slots with useful instructions.
12 //===----------------------------------------------------------------------===//
14 #include "MCTargetDesc/MipsMCNaCl.h"
16 #include "MipsInstrInfo.h"
17 #include "MipsTargetMachine.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
35 #define DEBUG_TYPE "delay-slot-filler"
37 STATISTIC(FilledSlots, "Number of delay slots filled");
38 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
41 static cl::opt<bool> DisableDelaySlotFiller(
42 "disable-mips-delay-filler",
44 cl::desc("Fill all delay slots with NOPs."),
47 static cl::opt<bool> DisableForwardSearch(
48 "disable-mips-df-forward-search",
50 cl::desc("Disallow MIPS delay filler to search forward."),
53 static cl::opt<bool> DisableSuccBBSearch(
54 "disable-mips-df-succbb-search",
56 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
59 static cl::opt<bool> DisableBackwardSearch(
60 "disable-mips-df-backward-search",
62 cl::desc("Disallow MIPS delay filler to search backward."),
66 typedef MachineBasicBlock::iterator Iter;
67 typedef MachineBasicBlock::reverse_iterator ReverseIter;
68 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
72 RegDefsUses(const TargetRegisterInfo &TRI);
73 void init(const MachineInstr &MI);
75 /// This function sets all caller-saved registers in Defs.
76 void setCallerSaved(const MachineInstr &MI);
78 /// This function sets all unallocatable registers in Defs.
79 void setUnallocatableRegs(const MachineFunction &MF);
81 /// Set bits in Uses corresponding to MBB's live-out registers except for
82 /// the registers that are live-in to SuccBB.
83 void addLiveOut(const MachineBasicBlock &MBB,
84 const MachineBasicBlock &SuccBB);
86 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
89 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
92 /// Returns true if Reg or its alias is in RegSet.
93 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
95 const TargetRegisterInfo &TRI;
99 /// Base class for inspecting loads and stores.
100 class InspectMemInstr {
102 InspectMemInstr(bool ForbidMemInstr_)
103 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
104 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
106 /// Return true if MI cannot be moved to delay slot.
107 bool hasHazard(const MachineInstr &MI);
109 virtual ~InspectMemInstr() {}
112 /// Flags indicating whether loads or stores have been seen.
113 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
115 /// Memory instructions are not allowed to move to delay slot if this flag
120 virtual bool hasHazard_(const MachineInstr &MI) = 0;
123 /// This subclass rejects any memory instructions.
124 class NoMemInstr : public InspectMemInstr {
126 NoMemInstr() : InspectMemInstr(true) {}
128 bool hasHazard_(const MachineInstr &MI) override { return true; }
131 /// This subclass accepts loads from stacks and constant loads.
132 class LoadFromStackOrConst : public InspectMemInstr {
134 LoadFromStackOrConst() : InspectMemInstr(false) {}
136 bool hasHazard_(const MachineInstr &MI) override;
139 /// This subclass uses memory dependence information to determine whether a
140 /// memory instruction can be moved to a delay slot.
141 class MemDefsUses : public InspectMemInstr {
143 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
146 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
148 bool hasHazard_(const MachineInstr &MI) override;
150 /// Update Defs and Uses. Return true if there exist dependences that
151 /// disqualify the delay slot candidate between V and values in Uses and
153 bool updateDefsUses(ValueType V, bool MayStore);
155 /// Get the list of underlying objects of MI's memory operand.
156 bool getUnderlyingObjects(const MachineInstr &MI,
157 SmallVectorImpl<ValueType> &Objects) const;
159 const MachineFrameInfo *MFI;
160 SmallPtrSet<ValueType, 4> Uses, Defs;
161 const DataLayout &DL;
163 /// Flags indicating whether loads or stores with no underlying objects have
165 bool SeenNoObjLoad, SeenNoObjStore;
168 class Filler : public MachineFunctionPass {
170 Filler(TargetMachine &tm)
171 : MachineFunctionPass(ID), TM(tm) { }
173 const char *getPassName() const override {
174 return "Mips Delay Slot Filler";
177 bool runOnMachineFunction(MachineFunction &F) override {
178 bool Changed = false;
179 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
181 Changed |= runOnMachineBasicBlock(*FI);
183 // This pass invalidates liveness information when it reorders
184 // instructions to fill delay slot. Without this, -verify-machineinstrs
187 F.getRegInfo().invalidateLiveness();
192 void getAnalysisUsage(AnalysisUsage &AU) const override {
193 AU.addRequired<MachineBranchProbabilityInfo>();
194 MachineFunctionPass::getAnalysisUsage(AU);
198 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
200 Iter replaceWithCompactBranch(MachineBasicBlock &MBB,
201 Iter Branch, DebugLoc DL);
203 Iter replaceWithCompactJump(MachineBasicBlock &MBB,
204 Iter Jump, DebugLoc DL);
206 /// This function checks if it is valid to move Candidate to the delay slot
207 /// and returns true if it isn't. It also updates memory and register
208 /// dependence information.
209 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
210 InspectMemInstr &IM) const;
212 /// This function searches range [Begin, End) for an instruction that can be
213 /// moved to the delay slot. Returns true on success.
214 template<typename IterTy>
215 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
216 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
217 IterTy &Filler) const;
219 /// This function searches in the backward direction for an instruction that
220 /// can be moved to the delay slot. Returns true on success.
221 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
223 /// This function searches MBB in the forward direction for an instruction
224 /// that can be moved to the delay slot. Returns true on success.
225 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
227 /// This function searches one of MBB's successor blocks for an instruction
228 /// that can be moved to the delay slot and inserts clones of the
229 /// instruction into the successor's predecessor blocks.
230 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
232 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
233 /// successor block that is not a landing pad.
234 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
236 /// This function analyzes MBB and returns an instruction with an unoccupied
237 /// slot that branches to Dst.
238 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
239 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
241 /// Examine Pred and see if it is possible to insert an instruction into
242 /// one of its branches delay slot or its end.
243 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
244 RegDefsUses &RegDU, bool &HasMultipleSuccs,
245 BB2BrMap &BrMap) const;
247 bool terminateSearch(const MachineInstr &Candidate) const;
254 } // end of anonymous namespace
256 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
257 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
260 /// This function inserts clones of Filler into predecessor blocks.
261 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
262 MachineFunction *MF = Filler->getParent()->getParent();
264 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
266 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
269 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
274 /// This function adds registers Filler defines to MBB's live-in register list.
275 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
276 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
277 const MachineOperand &MO = Filler->getOperand(I);
280 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
284 const MachineFunction &MF = *MBB.getParent();
285 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
286 "Shouldn't move an instruction with unallocatable registers across "
287 "basic block boundaries.");
290 if (!MBB.isLiveIn(R))
295 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
296 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
298 void RegDefsUses::init(const MachineInstr &MI) {
299 // Add all register operands which are explicit and non-variadic.
300 update(MI, 0, MI.getDesc().getNumOperands());
302 // If MI is a call, add RA to Defs to prevent users of RA from going into
307 // Add all implicit register operands of branch instructions except
310 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
311 Defs.reset(Mips::AT);
315 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
318 // If MI is a call, add all caller-saved registers to Defs.
319 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
321 CallerSavedRegs.reset(Mips::ZERO);
322 CallerSavedRegs.reset(Mips::ZERO_64);
324 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
326 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
327 CallerSavedRegs.reset(*AI);
329 Defs |= CallerSavedRegs;
332 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
333 BitVector AllocSet = TRI.getAllocatableSet(MF);
335 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
336 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
339 AllocSet.set(Mips::ZERO);
340 AllocSet.set(Mips::ZERO_64);
342 Defs |= AllocSet.flip();
345 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
346 const MachineBasicBlock &SuccBB) {
347 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
348 SE = MBB.succ_end(); SI != SE; ++SI)
350 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
351 LE = (*SI)->livein_end(); LI != LE; ++LI)
355 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
356 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
357 bool HasHazard = false;
359 for (unsigned I = Begin; I != End; ++I) {
360 const MachineOperand &MO = MI.getOperand(I);
362 if (MO.isReg() && MO.getReg())
363 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
372 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
373 unsigned Reg, bool IsDef) const {
376 // check whether Reg has already been defined or used.
377 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
381 // check whether Reg has already been defined.
382 return isRegInSet(Defs, Reg);
385 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
386 // Check Reg and all aliased Registers.
387 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
388 if (RegSet.test(*AI))
393 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
394 if (!MI.mayStore() && !MI.mayLoad())
400 OrigSeenLoad = SeenLoad;
401 OrigSeenStore = SeenStore;
402 SeenLoad |= MI.mayLoad();
403 SeenStore |= MI.mayStore();
405 // If MI is an ordered or volatile memory reference, disallow moving
406 // subsequent loads and stores to delay slot.
407 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
408 ForbidMemInstr = true;
412 return hasHazard_(MI);
415 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
419 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
422 if (const PseudoSourceValue *PSV =
423 (*MI.memoperands_begin())->getPseudoValue()) {
424 if (isa<FixedStackPseudoSourceValue>(PSV))
426 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
432 MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
433 : InspectMemInstr(false), MFI(MFI_), DL(DL), SeenNoObjLoad(false),
434 SeenNoObjStore(false) {}
436 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
437 bool HasHazard = false;
438 SmallVector<ValueType, 4> Objs;
440 // Check underlying object list.
441 if (getUnderlyingObjects(MI, Objs)) {
442 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
443 I != Objs.end(); ++I)
444 HasHazard |= updateDefsUses(*I, MI.mayStore());
449 // No underlying objects found.
450 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
451 HasHazard |= MI.mayLoad() || OrigSeenStore;
453 SeenNoObjLoad |= MI.mayLoad();
454 SeenNoObjStore |= MI.mayStore();
459 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
461 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
465 return Defs.count(V) || SeenNoObjStore;
469 getUnderlyingObjects(const MachineInstr &MI,
470 SmallVectorImpl<ValueType> &Objects) const {
471 if (!MI.hasOneMemOperand() ||
472 (!(*MI.memoperands_begin())->getValue() &&
473 !(*MI.memoperands_begin())->getPseudoValue()))
476 if (const PseudoSourceValue *PSV =
477 (*MI.memoperands_begin())->getPseudoValue()) {
478 if (!PSV->isAliased(MFI))
480 Objects.push_back(PSV);
484 const Value *V = (*MI.memoperands_begin())->getValue();
486 SmallVector<Value *, 4> Objs;
487 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
489 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
491 if (!isIdentifiedObject(V))
494 Objects.push_back(*I);
500 // Replace Branch with the compact branch instruction.
501 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB,
502 Iter Branch, DebugLoc DL) {
503 const MipsInstrInfo *TII =
504 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
507 (((unsigned) Branch->getOpcode()) == Mips::BEQ) ? Mips::BEQZC_MM
510 const MCInstrDesc &NewDesc = TII->get(NewOpcode);
511 MachineInstrBuilder MIB = BuildMI(MBB, Branch, DL, NewDesc);
513 MIB.addReg(Branch->getOperand(0).getReg());
514 MIB.addMBB(Branch->getOperand(2).getMBB());
516 Iter tmpIter = Branch;
517 Branch = std::prev(Branch);
523 // Replace Jumps with the compact jump instruction.
524 Iter Filler::replaceWithCompactJump(MachineBasicBlock &MBB,
525 Iter Jump, DebugLoc DL) {
526 const MipsInstrInfo *TII =
527 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
529 const MCInstrDesc &NewDesc = TII->get(Mips::JRC16_MM);
530 MachineInstrBuilder MIB = BuildMI(MBB, Jump, DL, NewDesc);
532 MIB.addReg(Jump->getOperand(0).getReg());
535 Jump = std::prev(Jump);
541 // For given opcode returns opcode of corresponding instruction with short
543 static int getEquivalentCallShort(int Opcode) {
546 return Mips::BGEZALS_MM;
548 return Mips::BLTZALS_MM;
550 return Mips::JALS_MM;
552 return Mips::JALRS_MM;
553 case Mips::JALR16_MM:
554 return Mips::JALRS16_MM;
556 llvm_unreachable("Unexpected call instruction for microMIPS.");
560 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
561 /// We assume there is only one delay slot per delayed instruction.
562 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
563 bool Changed = false;
564 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
565 bool InMicroMipsMode = STI.inMicroMipsMode();
566 const MipsInstrInfo *TII = STI.getInstrInfo();
568 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
569 if (!hasUnoccupiedSlot(&*I))
575 // Delay slot filling is disabled at -O0.
576 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
579 if (searchBackward(MBB, I)) {
581 } else if (I->isTerminator()) {
582 if (searchSuccBBs(MBB, I)) {
585 } else if (searchForward(MBB, I)) {
590 // Get instruction with delay slot.
591 MachineBasicBlock::instr_iterator DSI(I);
593 if (InMicroMipsMode && TII->GetInstSizeInBytes(std::next(DSI)) == 2 &&
595 // If instruction in delay slot is 16b change opcode to
596 // corresponding instruction with short delay slot.
597 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
604 // If instruction is BEQ or BNE with one ZERO register, then instead of
605 // adding NOP replace this instruction with the corresponding compact
606 // branch instruction, i.e. BEQZC or BNEZC.
607 unsigned Opcode = I->getOpcode();
608 if (InMicroMipsMode) {
612 if (((unsigned) I->getOperand(1).getReg()) == Mips::ZERO) {
613 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
618 case Mips::PseudoReturn:
619 case Mips::PseudoIndirectBranch:
620 // For microMIPS the PseudoReturn and PseudoIndirectBranch are allways
621 // expanded to JR_MM, so they can be replaced with JRC16_MM.
622 I = replaceWithCompactJump(MBB, I, I->getDebugLoc());
628 // Bundle the NOP to the instruction with the delay slot.
629 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
630 MIBundleBuilder(MBB, I, std::next(I, 2));
636 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
637 /// slots in Mips MachineFunctions
638 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
639 return new Filler(tm);
642 template<typename IterTy>
643 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
644 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
645 IterTy &Filler) const {
646 bool IsReverseIter = std::is_convertible<IterTy, ReverseIter>::value;
648 for (IterTy I = Begin; I != End;) {
653 if (CurrI->isDebugValue())
656 if (terminateSearch(*CurrI))
659 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
660 "Cannot put calls, returns or branches in delay slot.");
662 if (CurrI->isKill()) {
663 CurrI->eraseFromParent();
665 // This special case is needed for reverse iterators, because when we
666 // erase an instruction, the iterators are updated to point to the next
668 if (IsReverseIter && I != End)
673 if (delayHasHazard(*CurrI, RegDU, IM))
676 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
677 if (STI.isTargetNaCl()) {
678 // In NaCl, instructions that must be masked are forbidden in delay slots.
679 // We only check for loads, stores and SP changes. Calls, returns and
680 // branches are not checked because non-NaCl targets never put them in
683 if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
684 baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
685 CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
689 bool InMicroMipsMode = STI.inMicroMipsMode();
690 const MipsInstrInfo *TII = STI.getInstrInfo();
691 unsigned Opcode = (*Slot).getOpcode();
692 if (InMicroMipsMode && TII->GetInstSizeInBytes(&(*CurrI)) == 2 &&
693 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
694 Opcode == Mips::PseudoReturn))
704 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
705 if (DisableBackwardSearch)
708 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
709 MemDefsUses MemDU(*TM.getDataLayout(), MBB.getParent()->getFrameInfo());
714 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Slot,
718 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
719 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
724 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
725 // Can handle only calls.
726 if (DisableForwardSearch || !Slot->isCall())
729 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
733 RegDU.setCallerSaved(*Slot);
735 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
738 MBB.splice(std::next(Slot), &MBB, Filler);
739 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
744 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
745 if (DisableSuccBBSearch)
748 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
753 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
754 bool HasMultipleSuccs = false;
756 std::unique_ptr<InspectMemInstr> IM;
759 // Iterate over SuccBB's predecessor list.
760 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
761 PE = SuccBB->pred_end(); PI != PE; ++PI)
762 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
765 // Do not allow moving instructions which have unallocatable register operands
766 // across basic block boundaries.
767 RegDU.setUnallocatableRegs(*MBB.getParent());
769 // Only allow moving loads from stack or constants if any of the SuccBB's
770 // predecessors have multiple successors.
771 if (HasMultipleSuccs) {
772 IM.reset(new LoadFromStackOrConst());
774 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
775 IM.reset(new MemDefsUses(*TM.getDataLayout(), MFI));
778 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
782 insertDelayFiller(Filler, BrMap);
783 addLiveInRegs(Filler, *SuccBB);
784 Filler->eraseFromParent();
789 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
793 // Select the successor with the larget edge weight.
794 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
795 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
796 [&](const MachineBasicBlock *Dst0,
797 const MachineBasicBlock *Dst1) {
798 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
800 return S->isLandingPad() ? nullptr : S;
803 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
804 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
805 const MipsInstrInfo *TII =
806 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
807 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
808 SmallVector<MachineInstr*, 2> BranchInstrs;
809 SmallVector<MachineOperand, 2> Cond;
811 MipsInstrInfo::BranchType R =
812 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
814 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
815 return std::make_pair(R, nullptr);
817 if (R != MipsInstrInfo::BT_CondUncond) {
818 if (!hasUnoccupiedSlot(BranchInstrs[0]))
819 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
821 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
823 return std::make_pair(R, BranchInstrs[0]);
826 assert((TrueBB == &Dst) || (FalseBB == &Dst));
828 // Examine the conditional branch. See if its slot is occupied.
829 if (hasUnoccupiedSlot(BranchInstrs[0]))
830 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
832 // If that fails, try the unconditional branch.
833 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
834 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
836 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
839 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
840 RegDefsUses &RegDU, bool &HasMultipleSuccs,
841 BB2BrMap &BrMap) const {
842 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
843 getBranch(Pred, Succ);
845 // Return if either getBranch wasn't able to analyze the branches or there
846 // were no branches with unoccupied slots.
847 if (P.first == MipsInstrInfo::BT_None)
850 if ((P.first != MipsInstrInfo::BT_Uncond) &&
851 (P.first != MipsInstrInfo::BT_NoBranch)) {
852 HasMultipleSuccs = true;
853 RegDU.addLiveOut(Pred, Succ);
856 BrMap[&Pred] = P.second;
860 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
861 InspectMemInstr &IM) const {
862 assert(!Candidate.isKill() &&
863 "KILL instructions should have been eliminated at this point.");
865 bool HasHazard = Candidate.isImplicitDef();
867 HasHazard |= IM.hasHazard(Candidate);
868 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
873 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
874 return (Candidate.isTerminator() || Candidate.isCall() ||
875 Candidate.isPosition() || Candidate.isInlineAsm() ||
876 Candidate.hasUnmodeledSideEffects());