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 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;
162 /// Flags indicating whether loads or stores with no underlying objects have
164 bool SeenNoObjLoad, SeenNoObjStore;
167 class Filler : public MachineFunctionPass {
169 Filler(TargetMachine &tm)
170 : MachineFunctionPass(ID), TM(tm) { }
172 const char *getPassName() const override {
173 return "Mips Delay Slot Filler";
176 bool runOnMachineFunction(MachineFunction &F) override {
177 bool Changed = false;
178 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
180 Changed |= runOnMachineBasicBlock(*FI);
182 // This pass invalidates liveness information when it reorders
183 // instructions to fill delay slot. Without this, -verify-machineinstrs
186 F.getRegInfo().invalidateLiveness();
191 void getAnalysisUsage(AnalysisUsage &AU) const override {
192 AU.addRequired<MachineBranchProbabilityInfo>();
193 MachineFunctionPass::getAnalysisUsage(AU);
197 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
199 Iter replaceWithCompactBranch(MachineBasicBlock &MBB,
200 Iter Branch, DebugLoc DL);
202 /// This function checks if it is valid to move Candidate to the delay slot
203 /// and returns true if it isn't. It also updates memory and register
204 /// dependence information.
205 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
206 InspectMemInstr &IM) const;
208 /// This function searches range [Begin, End) for an instruction that can be
209 /// moved to the delay slot. Returns true on success.
210 template<typename IterTy>
211 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
212 RegDefsUses &RegDU, InspectMemInstr &IM,
213 IterTy &Filler, Iter Slot) const;
215 /// This function searches in the backward direction for an instruction that
216 /// can be moved to the delay slot. Returns true on success.
217 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
219 /// This function searches MBB in the forward direction for an instruction
220 /// that can be moved to the delay slot. Returns true on success.
221 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
223 /// This function searches one of MBB's successor blocks for an instruction
224 /// that can be moved to the delay slot and inserts clones of the
225 /// instruction into the successor's predecessor blocks.
226 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
228 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
229 /// successor block that is not a landing pad.
230 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
232 /// This function analyzes MBB and returns an instruction with an unoccupied
233 /// slot that branches to Dst.
234 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
235 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
237 /// Examine Pred and see if it is possible to insert an instruction into
238 /// one of its branches delay slot or its end.
239 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
240 RegDefsUses &RegDU, bool &HasMultipleSuccs,
241 BB2BrMap &BrMap) const;
243 bool terminateSearch(const MachineInstr &Candidate) const;
250 } // end of anonymous namespace
252 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
253 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
256 /// This function inserts clones of Filler into predecessor blocks.
257 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
258 MachineFunction *MF = Filler->getParent()->getParent();
260 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
262 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
265 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
270 /// This function adds registers Filler defines to MBB's live-in register list.
271 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
272 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
273 const MachineOperand &MO = Filler->getOperand(I);
276 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
280 const MachineFunction &MF = *MBB.getParent();
281 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
282 "Shouldn't move an instruction with unallocatable registers across "
283 "basic block boundaries.");
286 if (!MBB.isLiveIn(R))
291 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
292 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
294 void RegDefsUses::init(const MachineInstr &MI) {
295 // Add all register operands which are explicit and non-variadic.
296 update(MI, 0, MI.getDesc().getNumOperands());
298 // If MI is a call, add RA to Defs to prevent users of RA from going into
303 // Add all implicit register operands of branch instructions except
306 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
307 Defs.reset(Mips::AT);
311 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
314 // If MI is a call, add all caller-saved registers to Defs.
315 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
317 CallerSavedRegs.reset(Mips::ZERO);
318 CallerSavedRegs.reset(Mips::ZERO_64);
320 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
321 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
322 CallerSavedRegs.reset(*AI);
324 Defs |= CallerSavedRegs;
327 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
328 BitVector AllocSet = TRI.getAllocatableSet(MF);
330 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
331 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
334 AllocSet.set(Mips::ZERO);
335 AllocSet.set(Mips::ZERO_64);
337 Defs |= AllocSet.flip();
340 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
341 const MachineBasicBlock &SuccBB) {
342 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
343 SE = MBB.succ_end(); SI != SE; ++SI)
345 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
346 LE = (*SI)->livein_end(); LI != LE; ++LI)
350 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
351 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
352 bool HasHazard = false;
354 for (unsigned I = Begin; I != End; ++I) {
355 const MachineOperand &MO = MI.getOperand(I);
357 if (MO.isReg() && MO.getReg())
358 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
367 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
368 unsigned Reg, bool IsDef) const {
371 // check whether Reg has already been defined or used.
372 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
376 // check whether Reg has already been defined.
377 return isRegInSet(Defs, Reg);
380 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
381 // Check Reg and all aliased Registers.
382 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
383 if (RegSet.test(*AI))
388 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
389 if (!MI.mayStore() && !MI.mayLoad())
395 OrigSeenLoad = SeenLoad;
396 OrigSeenStore = SeenStore;
397 SeenLoad |= MI.mayLoad();
398 SeenStore |= MI.mayStore();
400 // If MI is an ordered or volatile memory reference, disallow moving
401 // subsequent loads and stores to delay slot.
402 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
403 ForbidMemInstr = true;
407 return hasHazard_(MI);
410 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
414 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
417 if (const PseudoSourceValue *PSV =
418 (*MI.memoperands_begin())->getPseudoValue()) {
419 if (isa<FixedStackPseudoSourceValue>(PSV))
421 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
427 MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
428 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
429 SeenNoObjStore(false) {}
431 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
432 bool HasHazard = false;
433 SmallVector<ValueType, 4> Objs;
435 // Check underlying object list.
436 if (getUnderlyingObjects(MI, Objs)) {
437 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
438 I != Objs.end(); ++I)
439 HasHazard |= updateDefsUses(*I, MI.mayStore());
444 // No underlying objects found.
445 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
446 HasHazard |= MI.mayLoad() || OrigSeenStore;
448 SeenNoObjLoad |= MI.mayLoad();
449 SeenNoObjStore |= MI.mayStore();
454 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
456 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
460 return Defs.count(V) || SeenNoObjStore;
464 getUnderlyingObjects(const MachineInstr &MI,
465 SmallVectorImpl<ValueType> &Objects) const {
466 if (!MI.hasOneMemOperand() ||
467 (!(*MI.memoperands_begin())->getValue() &&
468 !(*MI.memoperands_begin())->getPseudoValue()))
471 if (const PseudoSourceValue *PSV =
472 (*MI.memoperands_begin())->getPseudoValue()) {
473 if (!PSV->isAliased(MFI))
475 Objects.push_back(PSV);
479 const Value *V = (*MI.memoperands_begin())->getValue();
481 SmallVector<Value *, 4> Objs;
482 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
484 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
486 if (!isIdentifiedObject(V))
489 Objects.push_back(*I);
495 // Replace Branch with the compact branch instruction.
496 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB,
497 Iter Branch, DebugLoc DL) {
498 const MipsInstrInfo *TII =
499 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
502 (((unsigned) Branch->getOpcode()) == Mips::BEQ) ? Mips::BEQZC_MM
505 const MCInstrDesc &NewDesc = TII->get(NewOpcode);
506 MachineInstrBuilder MIB = BuildMI(MBB, Branch, DL, NewDesc);
508 MIB.addReg(Branch->getOperand(0).getReg());
509 MIB.addMBB(Branch->getOperand(2).getMBB());
511 Iter tmpIter = Branch;
512 Branch = std::prev(Branch);
518 // For given opcode returns opcode of corresponding instruction with short
520 static int getEquivalentCallShort(int Opcode) {
523 return Mips::BGEZALS_MM;
525 return Mips::BLTZALS_MM;
527 return Mips::JALS_MM;
529 return Mips::JALRS_MM;
530 case Mips::JALR16_MM:
531 return Mips::JALRS16_MM;
533 llvm_unreachable("Unexpected call instruction for microMIPS.");
537 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
538 /// We assume there is only one delay slot per delayed instruction.
539 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
540 bool Changed = false;
541 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
542 bool InMicroMipsMode = STI.inMicroMipsMode();
543 const MipsInstrInfo *TII = STI.getInstrInfo();
545 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
546 if (!hasUnoccupiedSlot(&*I))
552 // Delay slot filling is disabled at -O0.
553 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
556 if (searchBackward(MBB, I)) {
558 } else if (I->isTerminator()) {
559 if (searchSuccBBs(MBB, I)) {
562 } else if (searchForward(MBB, I)) {
567 // Get instruction with delay slot.
568 MachineBasicBlock::instr_iterator DSI(I);
570 if (InMicroMipsMode && TII->GetInstSizeInBytes(std::next(DSI)) == 2 &&
572 // If instruction in delay slot is 16b change opcode to
573 // corresponding instruction with short delay slot.
574 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
581 // If instruction is BEQ or BNE with one ZERO register, then instead of
582 // adding NOP replace this instruction with the corresponding compact
583 // branch instruction, i.e. BEQZC or BNEZC.
584 unsigned Opcode = I->getOpcode();
585 if (InMicroMipsMode &&
586 (Opcode == Mips::BEQ || Opcode == Mips::BNE) &&
587 ((unsigned) I->getOperand(1).getReg()) == Mips::ZERO) {
589 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
592 // Bundle the NOP to the instruction with the delay slot.
593 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
594 MIBundleBuilder(MBB, I, std::next(I, 2));
601 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
602 /// slots in Mips MachineFunctions
603 FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
604 return new Filler(tm);
607 template<typename IterTy>
608 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
609 RegDefsUses &RegDU, InspectMemInstr& IM,
610 IterTy &Filler, Iter Slot) const {
611 for (IterTy I = Begin; I != End; ++I) {
613 if (I->isDebugValue())
616 if (terminateSearch(*I))
619 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
620 "Cannot put calls, returns or branches in delay slot.");
622 if (delayHasHazard(*I, RegDU, IM))
625 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
626 if (STI.isTargetNaCl()) {
627 // In NaCl, instructions that must be masked are forbidden in delay slots.
628 // We only check for loads, stores and SP changes. Calls, returns and
629 // branches are not checked because non-NaCl targets never put them in
632 if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx) &&
633 baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg())) ||
634 I->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
638 bool InMicroMipsMode = STI.inMicroMipsMode();
639 const MipsInstrInfo *TII = STI.getInstrInfo();
640 unsigned Opcode = (*Slot).getOpcode();
641 if (InMicroMipsMode && TII->GetInstSizeInBytes(&(*I)) == 2 &&
642 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
643 Opcode == Mips::PseudoReturn))
653 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
654 if (DisableBackwardSearch)
657 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
658 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
663 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler,
667 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
668 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
673 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
674 // Can handle only calls.
675 if (DisableForwardSearch || !Slot->isCall())
678 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
682 RegDU.setCallerSaved(*Slot);
684 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler, Slot))
687 MBB.splice(std::next(Slot), &MBB, Filler);
688 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
693 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
694 if (DisableSuccBBSearch)
697 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
702 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
703 bool HasMultipleSuccs = false;
705 std::unique_ptr<InspectMemInstr> IM;
708 // Iterate over SuccBB's predecessor list.
709 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
710 PE = SuccBB->pred_end(); PI != PE; ++PI)
711 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
714 // Do not allow moving instructions which have unallocatable register operands
715 // across basic block boundaries.
716 RegDU.setUnallocatableRegs(*MBB.getParent());
718 // Only allow moving loads from stack or constants if any of the SuccBB's
719 // predecessors have multiple successors.
720 if (HasMultipleSuccs) {
721 IM.reset(new LoadFromStackOrConst());
723 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
724 IM.reset(new MemDefsUses(MFI));
727 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler,
731 insertDelayFiller(Filler, BrMap);
732 addLiveInRegs(Filler, *SuccBB);
733 Filler->eraseFromParent();
738 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
742 // Select the successor with the larget edge weight.
743 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
744 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
745 [&](const MachineBasicBlock *Dst0,
746 const MachineBasicBlock *Dst1) {
747 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
749 return S->isLandingPad() ? nullptr : S;
752 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
753 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
754 const MipsInstrInfo *TII =
755 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
756 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
757 SmallVector<MachineInstr*, 2> BranchInstrs;
758 SmallVector<MachineOperand, 2> Cond;
760 MipsInstrInfo::BranchType R =
761 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
763 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
764 return std::make_pair(R, nullptr);
766 if (R != MipsInstrInfo::BT_CondUncond) {
767 if (!hasUnoccupiedSlot(BranchInstrs[0]))
768 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
770 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
772 return std::make_pair(R, BranchInstrs[0]);
775 assert((TrueBB == &Dst) || (FalseBB == &Dst));
777 // Examine the conditional branch. See if its slot is occupied.
778 if (hasUnoccupiedSlot(BranchInstrs[0]))
779 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
781 // If that fails, try the unconditional branch.
782 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
783 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
785 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
788 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
789 RegDefsUses &RegDU, bool &HasMultipleSuccs,
790 BB2BrMap &BrMap) const {
791 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
792 getBranch(Pred, Succ);
794 // Return if either getBranch wasn't able to analyze the branches or there
795 // were no branches with unoccupied slots.
796 if (P.first == MipsInstrInfo::BT_None)
799 if ((P.first != MipsInstrInfo::BT_Uncond) &&
800 (P.first != MipsInstrInfo::BT_NoBranch)) {
801 HasMultipleSuccs = true;
802 RegDU.addLiveOut(Pred, Succ);
805 BrMap[&Pred] = P.second;
809 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
810 InspectMemInstr &IM) const {
811 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
813 HasHazard |= IM.hasHazard(Candidate);
814 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
819 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
820 return (Candidate.isTerminator() || Candidate.isCall() ||
821 Candidate.isPosition() || Candidate.isInlineAsm() ||
822 Candidate.hasUnmodeledSideEffects());