53 #define DEBUG_TYPE "delay-slot-filler"
55 STATISTIC(FilledSlots,
"Number of delay slots filled");
56 STATISTIC(UsefulSlots,
"Number of delay slots filled with instructions that"
60 "disable-mips-delay-filler",
62 cl::desc(
"Fill all delay slots with NOPs."),
66 "disable-mips-df-forward-search",
68 cl::desc(
"Disallow MIPS delay filler to search forward."),
72 "disable-mips-df-succbb-search",
74 cl::desc(
"Disallow MIPS delay filler to search successor basic blocks."),
78 "disable-mips-df-backward-search",
80 cl::desc(
"Disallow MIPS delay filler to search backward."),
96 cl::desc(
"MIPS Specific: Compact branch policy."),
134 bool isRegInSet(
const BitVector &RegSet,
unsigned Reg)
const;
141 class InspectMemInstr {
143 InspectMemInstr(
bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
144 virtual ~InspectMemInstr() =
default;
151 bool OrigSeenLoad =
false;
152 bool OrigSeenStore =
false;
153 bool SeenLoad =
false;
154 bool SeenStore =
false;
165 class NoMemInstr :
public InspectMemInstr {
167 NoMemInstr() : InspectMemInstr(
true) {}
174 class LoadFromStackOrConst :
public InspectMemInstr {
176 LoadFromStackOrConst() : InspectMemInstr(
false) {}
184 class MemDefsUses :
public InspectMemInstr {
208 bool SeenNoObjLoad =
false;
209 bool SeenNoObjStore =
false;
216 StringRef getPassName()
const override {
return "Mips Delay Slot Filler"; }
220 bool Changed =
false;
223 Changed |= runOnMachineBasicBlock(*FI);
253 bool delayHasHazard(
const MachineInstr &Candidate, RegDefsUses &RegDU,
254 InspectMemInstr &IM)
const;
258 template<
typename IterTy>
260 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
261 IterTy &Filler)
const;
282 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
288 RegDefsUses &RegDU,
bool &HasMultipleSuccs,
289 BB2BrMap &BrMap)
const;
291 bool terminateSearch(
const MachineInstr &Candidate)
const;
310 for (BB2BrMap::const_iterator
I = BrMap.begin();
I != BrMap.end(); ++
I) {
322 for (
unsigned I = 0,
E = Filler->getNumOperands();
I !=
E; ++
I) {
332 "Shouldn't move an instruction with unallocatable registers across "
333 "basic block boundaries.");
342 : TRI(TRI), Defs(TRI.getNumRegs(),
false), Uses(TRI.getNumRegs(),
false) {}
357 Defs.reset(Mips::AT);
361 void RegDefsUses::setCallerSaved(
const MachineInstr &MI) {
369 Defs.set(Mips::RA_64);
373 BitVector CallerSavedRegs(TRI.getNumRegs(),
true);
375 CallerSavedRegs.
reset(Mips::ZERO);
376 CallerSavedRegs.
reset(Mips::ZERO_64);
381 CallerSavedRegs.
reset(*AI);
383 Defs |= CallerSavedRegs;
387 BitVector AllocSet = TRI.getAllocatableSet(MF);
389 for (
unsigned R : AllocSet.
set_bits())
393 AllocSet.
set(Mips::ZERO);
394 AllocSet.
set(Mips::ZERO_64);
396 Defs |= AllocSet.
flip();
404 for (
const auto &LI : (*SI)->liveins())
405 Uses.
set(LI.PhysReg);
408 bool RegDefsUses::update(
const MachineInstr &MI,
unsigned Begin,
unsigned End) {
409 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
410 bool HasHazard =
false;
412 for (
unsigned I = Begin;
I !=
End; ++
I) {
416 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.
getReg(), MO.
isDef());
426 unsigned Reg,
bool IsDef)
const {
430 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
435 return isRegInSet(Defs, Reg);
438 bool RegDefsUses::isRegInSet(
const BitVector &RegSet,
unsigned Reg)
const {
441 if (RegSet.
test(*AI))
446 bool InspectMemInstr::hasHazard(
const MachineInstr &MI) {
453 OrigSeenLoad = SeenLoad;
454 OrigSeenStore = SeenStore;
461 ForbidMemInstr =
true;
465 return hasHazard_(MI);
468 bool LoadFromStackOrConst::hasHazard_(
const MachineInstr &MI) {
477 if (isa<FixedStackPseudoSourceValue>(PSV))
479 return !PSV->isConstant(
nullptr) && !PSV->isStack();
486 : InspectMemInstr(
false), MFI(MFI_), DL(DL) {}
489 bool HasHazard =
false;
495 I != Objs.
end(); ++
I)
496 HasHazard |= updateDefsUses(*
I, MI.
mayStore());
502 HasHazard = MI.
mayStore() && (OrigSeenLoad || OrigSeenStore);
503 HasHazard |= MI.
mayLoad() || OrigSeenStore;
513 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
517 return Defs.count(V) || SeenNoObjStore;
530 if (!PSV->isAliased(MFI))
559 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
561 std::next(Branch)->eraseFromParent();
573 return Mips::BGEZALS_MM;
575 return Mips::BLTZALS_MM;
577 return Mips::JALS_MM;
579 return Mips::JALRS_MM;
580 case Mips::JALR16_MM:
581 return Mips::JALRS16_MM;
582 case Mips::TAILCALL_MM:
584 case Mips::TAILCALLREG:
585 return Mips::JR16_MM;
594 bool Changed =
false;
618 if (searchBackward(MBB, *
I)) {
620 }
else if (
I->isTerminator()) {
621 if (searchSuccBBs(MBB,
I)) {
624 }
else if (searchForward(MBB,
I)) {
658 if ((InMicroMipsMode ||
661 I = replaceWithCompactBranch(MBB,
I,
I->getDebugLoc());
666 BuildMI(MBB, std::next(
I),
I->getDebugLoc(), TII->get(Mips::NOP));
673 template<
typename IterTy>
675 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
676 IterTy &Filler)
const {
677 for (IterTy
I = Begin;
I !=
End;) {
682 if (CurrI->isDebugValue())
685 if (terminateSearch(*CurrI))
688 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
689 "Cannot put calls, returns or branches in delay slot.");
691 if (CurrI->isKill()) {
692 CurrI->eraseFromParent();
696 if (delayHasHazard(*CurrI, RegDU, IM))
714 unsigned Opcode = (*Slot).getOpcode();
721 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
722 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
737 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
738 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
744 if (!searchRange(MBB, ++SlotI.
getReverse(), MBB.
rend(), RegDU, MemDU, Slot,
748 MBB.
splice(std::next(SlotI), &MBB, Filler.getReverse());
763 RegDU.setCallerSaved(*Slot);
765 if (!searchRange(MBB, std::next(Slot), MBB.
end(), RegDU, NM, Slot, Filler))
768 MBB.
splice(std::next(Slot), &MBB, Filler);
784 bool HasMultipleSuccs =
false;
786 std::unique_ptr<InspectMemInstr> IM;
792 PE = SuccBB->
pred_end(); PI != PE; ++PI)
793 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
798 RegDU.setUnallocatableRegs(*Fn);
802 if (HasMultipleSuccs) {
803 IM.reset(
new LoadFromStackOrConst());
806 IM.reset(
new MemDefsUses(Fn->getDataLayout(), &MFI));
809 if (!searchRange(MBB, SuccBB->
begin(), SuccBB->
end(), RegDU, *IM, Slot,
815 Filler->eraseFromParent();
825 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
829 return Prob.getEdgeProbability(&B, Dst0) <
830 Prob.getEdgeProbability(&B, Dst1);
832 return S->
isEHPad() ?
nullptr : S;
835 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
844 TII->
analyzeBranch(MBB, TrueBB, FalseBB, Cond,
false, BranchInstrs);
846 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
847 return std::make_pair(R,
nullptr);
849 if (R != MipsInstrInfo::BT_CondUncond) {
851 return std::make_pair(MipsInstrInfo::BT_None,
nullptr);
853 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
855 return std::make_pair(R, BranchInstrs[0]);
858 assert((TrueBB == &Dst) || (FalseBB == &Dst));
862 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
866 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
868 return std::make_pair(MipsInstrInfo::BT_None,
nullptr);
872 RegDefsUses &RegDU,
bool &HasMultipleSuccs,
873 BB2BrMap &BrMap)
const {
874 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
P =
875 getBranch(Pred, Succ);
879 if (P.first == MipsInstrInfo::BT_None)
882 if ((P.first != MipsInstrInfo::BT_Uncond) &&
883 (P.first != MipsInstrInfo::BT_NoBranch)) {
884 HasMultipleSuccs =
true;
885 RegDU.addLiveOut(Pred, Succ);
888 BrMap[&Pred] = P.second;
892 bool Filler::delayHasHazard(
const MachineInstr &Candidate, RegDefsUses &RegDU,
893 InspectMemInstr &IM)
const {
895 "KILL instructions should have been eliminated at this point.");
899 HasHazard |= IM.hasHazard(Candidate);
900 HasHazard |= RegDU.update(Candidate, 0, Candidate.
getNumOperands());
905 bool Filler::terminateSearch(
const MachineInstr &Candidate)
const {
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
Return the number of bytes of code the specified instruction may be.
void push_back(const T &Elt)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isEHPad() const
Returns true if the block is a landing pad.
A parsed version of the target data layout string in and methods for querying it. ...
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
typename SuperClass::const_iterator const_iterator
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
STATISTIC(NumFunctions,"Total number of functions")
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Branch Analysis.
bool isBasePlusOffsetMemoryAccess(unsigned Opcode, unsigned *AddrIdx, bool *IsStore=nullptr)
iterator_range< const_set_bits_iterator > set_bits() const
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
const MipsInstrInfo * getInstrInfo() const override
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
Optimal is the default and will produce compact branches when delay slots cannot be filled...
FunctionPass * createMipsDelaySlotFillerPass()
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions ...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
static bool hasUnoccupiedSlot(const MachineInstr *MI)
void GetUnderlyingObjects(Value *V, SmallVectorImpl< Value * > &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
static cl::opt< bool > DisableDelaySlotFiller("disable-mips-delay-filler", cl::init(false), cl::desc("Fill all delay slots with NOPs."), cl::Hidden)
AnalysisUsage & addRequired()
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Reg
All possible values of the reg field in the ModR/M byte.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
bool baseRegNeedsLoadStoreMask(unsigned Reg)
unsigned getNumOperands() const
Access to explicit operands of the instruction.
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB)
This function adds registers Filler defines to MBB's live-in register list.
static cl::opt< CompactBranchPolicy > MipsCompactBranchPolicy("mips-compact-branches", cl::Optional, cl::init(CB_Optimal), cl::desc("MIPS Specific: Compact branch policy."), cl::values(clEnumValN(CB_Never,"never","Do not use compact branches if possible."), clEnumValN(CB_Optimal,"optimal","Use compact branches where appropiate (default)."), clEnumValN(CB_Always,"always","Always use compact branches if possible.")))
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
static cl::opt< bool > DisableBackwardSearch("disable-mips-df-backward-search", cl::init(false), cl::desc("Disallow MIPS delay filler to search backward."), cl::Hidden)
static cl::opt< bool > DisableForwardSearch("disable-mips-df-forward-search", cl::init(true), cl::desc("Disallow MIPS delay filler to search forward."), cl::Hidden)
BitVector getAllocatableSet(const MachineFunction &MF, const TargetRegisterClass *RC=nullptr) const
Returns a bitset indexed by register number indicating if a register is allocatable or not...
static void getUnderlyingObjects(MachineInstr *MI, SmallVectorImpl< Value * > &Objs, const DataLayout &DL)
Return the underlying objects for the memory references of an instruction.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MachineBasicBlock * getParent() const
bool isImplicitDef() const
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Function Alias Analysis false
initializer< Ty > init(const Ty &Val)
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const MachineOperand & getOperand(unsigned i) const
'always' may in some circumstances may not be absolutely adhered to there may not be a corresponding ...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
static const unsigned End
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
FunctionPass class - This class is used to implement most global optimizations.
std::vector< MachineBasicBlock * >::const_iterator const_succ_iterator
bool inMicroMipsMode() const
std::vector< MachineBasicBlock * >::iterator pred_iterator
succ_iterator succ_begin()
static cl::opt< bool > DisableSuccBBSearch("disable-mips-df-succbb-search", cl::init(true), cl::desc("Disallow MIPS delay filler to search successor basic blocks."), cl::Hidden)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
pred_iterator pred_begin()
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
unsigned getEquivalentCompactForm(const MachineBasicBlock::iterator I) const
Determine the opcode of a non-delay slot form for a branch if one exists.
bool definesRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr fully defines the specified register.
Iterator for intrusive lists based on ilist_node.
bool isTargetNaCl() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
const MipsRegisterInfo * getRegisterInfo() const override
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
CloneMachineInstr - Create a new MachineInstr which is a copy of the 'Orig' instruction, identical in all ways except the instruction has no parent, prev, or next.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool test(unsigned Idx) const
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
Special value supplied for machine level alias analysis.
static int getEquivalentCallShort(int Opcode)
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
llvm_unreachable("Unknown RegBank!")
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap)
This function inserts clones of Filler into predecessor blocks.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool isCall(QueryType Type=AnyInBundle) const
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
The policy 'never' may in some circumstances or for some ISAs not be absolutely adhered to...
bool isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
Instructions::iterator instr_iterator
unsigned getReg() const
getReg - Returns the register number.
MIBundleBuilder & append(MachineInstr *MI)
Insert MI into MBB by appending it to the instructions in the bundle.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Primary interface to the complete machine description for the target machine.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
Properties which a MachineFunction may have at a given point in time.
Helper class for constructing bundles of MachineInstrs.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.