LLVM  5.0.0
MipsDelaySlotFiller.cpp
Go to the documentation of this file.
1 //===-- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Simple pass to fill delay slots with useful instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "Mips.h"
16 #include "MipsInstrInfo.h"
17 #include "MipsSubtarget.h"
18 #include "MipsTargetMachine.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/PointerUnion.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringRef.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"
45 #include <algorithm>
46 #include <cassert>
47 #include <iterator>
48 #include <memory>
49 #include <utility>
50 
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "delay-slot-filler"
54 
55 STATISTIC(FilledSlots, "Number of delay slots filled");
56 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
57  " are not NOP.");
58 
60  "disable-mips-delay-filler",
61  cl::init(false),
62  cl::desc("Fill all delay slots with NOPs."),
63  cl::Hidden);
64 
66  "disable-mips-df-forward-search",
67  cl::init(true),
68  cl::desc("Disallow MIPS delay filler to search forward."),
69  cl::Hidden);
70 
72  "disable-mips-df-succbb-search",
73  cl::init(true),
74  cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
75  cl::Hidden);
76 
78  "disable-mips-df-backward-search",
79  cl::init(false),
80  cl::desc("Disallow MIPS delay filler to search backward."),
81  cl::Hidden);
82 
84  CB_Never, ///< The policy 'never' may in some circumstances or for some
85  ///< ISAs not be absolutely adhered to.
86  CB_Optimal, ///< Optimal is the default and will produce compact branches
87  ///< when delay slots cannot be filled.
88  CB_Always ///< 'always' may in some circumstances may not be
89  ///< absolutely adhered to there may not be a corresponding
90  ///< compact form of a branch.
91 };
92 
94  "mips-compact-branches",cl::Optional,
96  cl::desc("MIPS Specific: Compact branch policy."),
97  cl::values(
98  clEnumValN(CB_Never, "never", "Do not use compact branches if possible."),
99  clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."),
100  clEnumValN(CB_Always, "always", "Always use compact branches if possible.")
101  )
102 );
103 
104 namespace {
105 
106  typedef MachineBasicBlock::iterator Iter;
107  typedef MachineBasicBlock::reverse_iterator ReverseIter;
109 
110  class RegDefsUses {
111  public:
112  RegDefsUses(const TargetRegisterInfo &TRI);
113 
114  void init(const MachineInstr &MI);
115 
116  /// This function sets all caller-saved registers in Defs.
117  void setCallerSaved(const MachineInstr &MI);
118 
119  /// This function sets all unallocatable registers in Defs.
120  void setUnallocatableRegs(const MachineFunction &MF);
121 
122  /// Set bits in Uses corresponding to MBB's live-out registers except for
123  /// the registers that are live-in to SuccBB.
124  void addLiveOut(const MachineBasicBlock &MBB,
125  const MachineBasicBlock &SuccBB);
126 
127  bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
128 
129  private:
130  bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
131  bool IsDef) const;
132 
133  /// Returns true if Reg or its alias is in RegSet.
134  bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
135 
136  const TargetRegisterInfo &TRI;
137  BitVector Defs, Uses;
138  };
139 
140  /// Base class for inspecting loads and stores.
141  class InspectMemInstr {
142  public:
143  InspectMemInstr(bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
144  virtual ~InspectMemInstr() = default;
145 
146  /// Return true if MI cannot be moved to delay slot.
147  bool hasHazard(const MachineInstr &MI);
148 
149  protected:
150  /// Flags indicating whether loads or stores have been seen.
151  bool OrigSeenLoad = false;
152  bool OrigSeenStore = false;
153  bool SeenLoad = false;
154  bool SeenStore = false;
155 
156  /// Memory instructions are not allowed to move to delay slot if this flag
157  /// is true.
158  bool ForbidMemInstr;
159 
160  private:
161  virtual bool hasHazard_(const MachineInstr &MI) = 0;
162  };
163 
164  /// This subclass rejects any memory instructions.
165  class NoMemInstr : public InspectMemInstr {
166  public:
167  NoMemInstr() : InspectMemInstr(true) {}
168 
169  private:
170  bool hasHazard_(const MachineInstr &MI) override { return true; }
171  };
172 
173  /// This subclass accepts loads from stacks and constant loads.
174  class LoadFromStackOrConst : public InspectMemInstr {
175  public:
176  LoadFromStackOrConst() : InspectMemInstr(false) {}
177 
178  private:
179  bool hasHazard_(const MachineInstr &MI) override;
180  };
181 
182  /// This subclass uses memory dependence information to determine whether a
183  /// memory instruction can be moved to a delay slot.
184  class MemDefsUses : public InspectMemInstr {
185  public:
186  MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
187 
188  private:
190 
191  bool hasHazard_(const MachineInstr &MI) override;
192 
193  /// Update Defs and Uses. Return true if there exist dependences that
194  /// disqualify the delay slot candidate between V and values in Uses and
195  /// Defs.
196  bool updateDefsUses(ValueType V, bool MayStore);
197 
198  /// Get the list of underlying objects of MI's memory operand.
200  SmallVectorImpl<ValueType> &Objects) const;
201 
202  const MachineFrameInfo *MFI;
203  SmallPtrSet<ValueType, 4> Uses, Defs;
204  const DataLayout &DL;
205 
206  /// Flags indicating whether loads or stores with no underlying objects have
207  /// been seen.
208  bool SeenNoObjLoad = false;
209  bool SeenNoObjStore = false;
210  };
211 
212  class Filler : public MachineFunctionPass {
213  public:
214  Filler() : MachineFunctionPass(ID), TM(nullptr) {}
215 
216  StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
217 
218  bool runOnMachineFunction(MachineFunction &F) override {
219  TM = &F.getTarget();
220  bool Changed = false;
221  for (MachineFunction::iterator FI = F.begin(), FE = F.end();
222  FI != FE; ++FI)
223  Changed |= runOnMachineBasicBlock(*FI);
224 
225  // This pass invalidates liveness information when it reorders
226  // instructions to fill delay slot. Without this, -verify-machineinstrs
227  // will fail.
228  if (Changed)
230 
231  return Changed;
232  }
233 
234  MachineFunctionProperties getRequiredProperties() const override {
237  }
238 
239  void getAnalysisUsage(AnalysisUsage &AU) const override {
242  }
243 
244  private:
245  bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
246 
247  Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
248  const DebugLoc &DL);
249 
250  /// This function checks if it is valid to move Candidate to the delay slot
251  /// and returns true if it isn't. It also updates memory and register
252  /// dependence information.
253  bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
254  InspectMemInstr &IM) const;
255 
256  /// This function searches range [Begin, End) for an instruction that can be
257  /// moved to the delay slot. Returns true on success.
258  template<typename IterTy>
259  bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
260  RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
261  IterTy &Filler) const;
262 
263  /// This function searches in the backward direction for an instruction that
264  /// can be moved to the delay slot. Returns true on success.
265  bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
266 
267  /// This function searches MBB in the forward direction for an instruction
268  /// that can be moved to the delay slot. Returns true on success.
269  bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
270 
271  /// This function searches one of MBB's successor blocks for an instruction
272  /// that can be moved to the delay slot and inserts clones of the
273  /// instruction into the successor's predecessor blocks.
274  bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
275 
276  /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
277  /// successor block that is not a landing pad.
278  MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
279 
280  /// This function analyzes MBB and returns an instruction with an unoccupied
281  /// slot that branches to Dst.
282  std::pair<MipsInstrInfo::BranchType, MachineInstr *>
283  getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
284 
285  /// Examine Pred and see if it is possible to insert an instruction into
286  /// one of its branches delay slot or its end.
287  bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
288  RegDefsUses &RegDU, bool &HasMultipleSuccs,
289  BB2BrMap &BrMap) const;
290 
291  bool terminateSearch(const MachineInstr &Candidate) const;
292 
293  const TargetMachine *TM;
294 
295  static char ID;
296  };
297 
298  char Filler::ID = 0;
299 
300 } // end anonymous namespace
301 
302 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
303  return MI->hasDelaySlot() && !MI->isBundledWithSucc();
304 }
305 
306 /// This function inserts clones of Filler into predecessor blocks.
307 static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
308  MachineFunction *MF = Filler->getParent()->getParent();
309 
310  for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
311  if (I->second) {
312  MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
313  ++UsefulSlots;
314  } else {
315  I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
316  }
317  }
318 }
319 
320 /// This function adds registers Filler defines to MBB's live-in register list.
321 static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
322  for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
323  const MachineOperand &MO = Filler->getOperand(I);
324  unsigned R;
325 
326  if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
327  continue;
328 
329 #ifndef NDEBUG
330  const MachineFunction &MF = *MBB.getParent();
332  "Shouldn't move an instruction with unallocatable registers across "
333  "basic block boundaries.");
334 #endif
335 
336  if (!MBB.isLiveIn(R))
337  MBB.addLiveIn(R);
338  }
339 }
340 
341 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
342  : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
343 
344 void RegDefsUses::init(const MachineInstr &MI) {
345  // Add all register operands which are explicit and non-variadic.
346  update(MI, 0, MI.getDesc().getNumOperands());
347 
348  // If MI is a call, add RA to Defs to prevent users of RA from going into
349  // delay slot.
350  if (MI.isCall())
351  Defs.set(Mips::RA);
352 
353  // Add all implicit register operands of branch instructions except
354  // register AT.
355  if (MI.isBranch()) {
356  update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
357  Defs.reset(Mips::AT);
358  }
359 }
360 
361 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
362  assert(MI.isCall());
363 
364  // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
365  // the delay slot. The reason is that RA/RA_64 must not be changed
366  // in the delay slot so that the callee can return to the caller.
367  if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
368  Defs.set(Mips::RA);
369  Defs.set(Mips::RA_64);
370  }
371 
372  // If MI is a call, add all caller-saved registers to Defs.
373  BitVector CallerSavedRegs(TRI.getNumRegs(), true);
374 
375  CallerSavedRegs.reset(Mips::ZERO);
376  CallerSavedRegs.reset(Mips::ZERO_64);
377 
378  for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
379  *R; ++R)
380  for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
381  CallerSavedRegs.reset(*AI);
382 
383  Defs |= CallerSavedRegs;
384 }
385 
386 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
387  BitVector AllocSet = TRI.getAllocatableSet(MF);
388 
389  for (unsigned R : AllocSet.set_bits())
390  for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
391  AllocSet.set(*AI);
392 
393  AllocSet.set(Mips::ZERO);
394  AllocSet.set(Mips::ZERO_64);
395 
396  Defs |= AllocSet.flip();
397 }
398 
399 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
400  const MachineBasicBlock &SuccBB) {
402  SE = MBB.succ_end(); SI != SE; ++SI)
403  if (*SI != &SuccBB)
404  for (const auto &LI : (*SI)->liveins())
405  Uses.set(LI.PhysReg);
406 }
407 
408 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
409  BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
410  bool HasHazard = false;
411 
412  for (unsigned I = Begin; I != End; ++I) {
413  const MachineOperand &MO = MI.getOperand(I);
414 
415  if (MO.isReg() && MO.getReg())
416  HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
417  }
418 
419  Defs |= NewDefs;
420  Uses |= NewUses;
421 
422  return HasHazard;
423 }
424 
425 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
426  unsigned Reg, bool IsDef) const {
427  if (IsDef) {
428  NewDefs.set(Reg);
429  // check whether Reg has already been defined or used.
430  return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
431  }
432 
433  NewUses.set(Reg);
434  // check whether Reg has already been defined.
435  return isRegInSet(Defs, Reg);
436 }
437 
438 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
439  // Check Reg and all aliased Registers.
440  for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
441  if (RegSet.test(*AI))
442  return true;
443  return false;
444 }
445 
446 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
447  if (!MI.mayStore() && !MI.mayLoad())
448  return false;
449 
450  if (ForbidMemInstr)
451  return true;
452 
453  OrigSeenLoad = SeenLoad;
454  OrigSeenStore = SeenStore;
455  SeenLoad |= MI.mayLoad();
456  SeenStore |= MI.mayStore();
457 
458  // If MI is an ordered or volatile memory reference, disallow moving
459  // subsequent loads and stores to delay slot.
460  if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
461  ForbidMemInstr = true;
462  return true;
463  }
464 
465  return hasHazard_(MI);
466 }
467 
468 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
469  if (MI.mayStore())
470  return true;
471 
472  if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
473  return true;
474 
475  if (const PseudoSourceValue *PSV =
476  (*MI.memoperands_begin())->getPseudoValue()) {
477  if (isa<FixedStackPseudoSourceValue>(PSV))
478  return false;
479  return !PSV->isConstant(nullptr) && !PSV->isStack();
480  }
481 
482  return true;
483 }
484 
485 MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
486  : InspectMemInstr(false), MFI(MFI_), DL(DL) {}
487 
488 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
489  bool HasHazard = false;
491 
492  // Check underlying object list.
493  if (getUnderlyingObjects(MI, Objs)) {
495  I != Objs.end(); ++I)
496  HasHazard |= updateDefsUses(*I, MI.mayStore());
497 
498  return HasHazard;
499  }
500 
501  // No underlying objects found.
502  HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
503  HasHazard |= MI.mayLoad() || OrigSeenStore;
504 
505  SeenNoObjLoad |= MI.mayLoad();
506  SeenNoObjStore |= MI.mayStore();
507 
508  return HasHazard;
509 }
510 
511 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
512  if (MayStore)
513  return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
514  SeenNoObjLoad;
515 
516  Uses.insert(V);
517  return Defs.count(V) || SeenNoObjStore;
518 }
519 
520 bool MemDefsUses::
522  SmallVectorImpl<ValueType> &Objects) const {
523  if (!MI.hasOneMemOperand() ||
524  (!(*MI.memoperands_begin())->getValue() &&
525  !(*MI.memoperands_begin())->getPseudoValue()))
526  return false;
527 
528  if (const PseudoSourceValue *PSV =
529  (*MI.memoperands_begin())->getPseudoValue()) {
530  if (!PSV->isAliased(MFI))
531  return false;
532  Objects.push_back(PSV);
533  return true;
534  }
535 
536  const Value *V = (*MI.memoperands_begin())->getValue();
537 
539  GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
540 
541  for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
542  I != E; ++I) {
543  if (!isIdentifiedObject(V))
544  return false;
545 
546  Objects.push_back(*I);
547  }
548 
549  return true;
550 }
551 
552 // Replace Branch with the compact branch instruction.
553 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
554  const DebugLoc &DL) {
555  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
556  const MipsInstrInfo *TII = STI.getInstrInfo();
557 
558  unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
559  Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
560 
561  std::next(Branch)->eraseFromParent();
562  return Branch;
563 }
564 
565 // For given opcode returns opcode of corresponding instruction with short
566 // delay slot.
567 // For the pseudo TAILCALL*_MM instructions return the short delay slot
568 // form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
569 // that is too short to make use of for tail calls.
570 static int getEquivalentCallShort(int Opcode) {
571  switch (Opcode) {
572  case Mips::BGEZAL:
573  return Mips::BGEZALS_MM;
574  case Mips::BLTZAL:
575  return Mips::BLTZALS_MM;
576  case Mips::JAL:
577  return Mips::JALS_MM;
578  case Mips::JALR:
579  return Mips::JALRS_MM;
580  case Mips::JALR16_MM:
581  return Mips::JALRS16_MM;
582  case Mips::TAILCALL_MM:
583  llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
584  case Mips::TAILCALLREG:
585  return Mips::JR16_MM;
586  default:
587  llvm_unreachable("Unexpected call instruction for microMIPS.");
588  }
589 }
590 
591 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
592 /// We assume there is only one delay slot per delayed instruction.
593 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
594  bool Changed = false;
595  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
596  bool InMicroMipsMode = STI.inMicroMipsMode();
597  const MipsInstrInfo *TII = STI.getInstrInfo();
598 
599  if (InMicroMipsMode && STI.hasMips32r6()) {
600  // This is microMIPS32r6 or microMIPS64r6 processor. Delay slot for
601  // branching instructions is not needed.
602  return Changed;
603  }
604 
605  for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
606  if (!hasUnoccupiedSlot(&*I))
607  continue;
608 
609  ++FilledSlots;
610  Changed = true;
611 
612  // Delay slot filling is disabled at -O0.
613  if (!DisableDelaySlotFiller && (TM->getOptLevel() != CodeGenOpt::None)) {
614  bool Filled = false;
615 
616  if (MipsCompactBranchPolicy.getValue() != CB_Always ||
617  !TII->getEquivalentCompactForm(I)) {
618  if (searchBackward(MBB, *I)) {
619  Filled = true;
620  } else if (I->isTerminator()) {
621  if (searchSuccBBs(MBB, I)) {
622  Filled = true;
623  }
624  } else if (searchForward(MBB, I)) {
625  Filled = true;
626  }
627  }
628 
629  if (Filled) {
630  // Get instruction with delay slot.
631  MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
632 
633  if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
634  DSI->isCall()) {
635  // If instruction in delay slot is 16b change opcode to
636  // corresponding instruction with short delay slot.
637 
638  // TODO: Implement an instruction mapping table of 16bit opcodes to
639  // 32bit opcodes so that an instruction can be expanded. This would
640  // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
641  // TODO: Permit b16 when branching backwards to the the same function
642  // if it is in range.
643  DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
644  }
645  continue;
646  }
647  }
648 
649  // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
650  // instead of adding NOP replace this instruction with the corresponding
651  // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
652  // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
653  // be replaced with JRC16_MM.
654 
655  // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
656  // form of the CTI. For indirect jumps this will not require inserting a
657  // NOP and for branches will hopefully avoid requiring a NOP.
658  if ((InMicroMipsMode ||
660  TII->getEquivalentCompactForm(I)) {
661  I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
662  continue;
663  }
664 
665  // Bundle the NOP to the instruction with the delay slot.
666  BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
667  MIBundleBuilder(MBB, I, std::next(I, 2));
668  }
669 
670  return Changed;
671 }
672 
673 template<typename IterTy>
674 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
675  RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
676  IterTy &Filler) const {
677  for (IterTy I = Begin; I != End;) {
678  IterTy CurrI = I;
679  ++I;
680 
681  // skip debug value
682  if (CurrI->isDebugValue())
683  continue;
684 
685  if (terminateSearch(*CurrI))
686  break;
687 
688  assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
689  "Cannot put calls, returns or branches in delay slot.");
690 
691  if (CurrI->isKill()) {
692  CurrI->eraseFromParent();
693  continue;
694  }
695 
696  if (delayHasHazard(*CurrI, RegDU, IM))
697  continue;
698 
699  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
700  if (STI.isTargetNaCl()) {
701  // In NaCl, instructions that must be masked are forbidden in delay slots.
702  // We only check for loads, stores and SP changes. Calls, returns and
703  // branches are not checked because non-NaCl targets never put them in
704  // delay slots.
705  unsigned AddrIdx;
706  if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
707  baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
708  CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
709  continue;
710  }
711 
712  bool InMicroMipsMode = STI.inMicroMipsMode();
713  const MipsInstrInfo *TII = STI.getInstrInfo();
714  unsigned Opcode = (*Slot).getOpcode();
715  // This is complicated by the tail call optimization. For non-PIC code
716  // there is only a 32bit sized unconditional branch which can be assumed
717  // to be able to reach the target. b16 only has a range of +/- 1 KB.
718  // It's entirely possible that the target function is reachable with b16
719  // but we don't have enough information to make that decision.
720  if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
721  (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
722  Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
723  continue;
724 
725  Filler = CurrI;
726  return true;
727  }
728 
729  return false;
730 }
731 
732 bool Filler::searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const {
734  return false;
735 
736  auto *Fn = MBB.getParent();
737  RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
738  MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
739  ReverseIter Filler;
740 
741  RegDU.init(Slot);
742 
743  MachineBasicBlock::iterator SlotI = Slot;
744  if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
745  Filler))
746  return false;
747 
748  MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
749  MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
750  ++UsefulSlots;
751  return true;
752 }
753 
754 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
755  // Can handle only calls.
756  if (DisableForwardSearch || !Slot->isCall())
757  return false;
758 
759  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
760  NoMemInstr NM;
761  Iter Filler;
762 
763  RegDU.setCallerSaved(*Slot);
764 
765  if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
766  return false;
767 
768  MBB.splice(std::next(Slot), &MBB, Filler);
769  MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
770  ++UsefulSlots;
771  return true;
772 }
773 
774 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
776  return false;
777 
778  MachineBasicBlock *SuccBB = selectSuccBB(MBB);
779 
780  if (!SuccBB)
781  return false;
782 
783  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
784  bool HasMultipleSuccs = false;
785  BB2BrMap BrMap;
786  std::unique_ptr<InspectMemInstr> IM;
787  Iter Filler;
788  auto *Fn = MBB.getParent();
789 
790  // Iterate over SuccBB's predecessor list.
791  for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
792  PE = SuccBB->pred_end(); PI != PE; ++PI)
793  if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
794  return false;
795 
796  // Do not allow moving instructions which have unallocatable register operands
797  // across basic block boundaries.
798  RegDU.setUnallocatableRegs(*Fn);
799 
800  // Only allow moving loads from stack or constants if any of the SuccBB's
801  // predecessors have multiple successors.
802  if (HasMultipleSuccs) {
803  IM.reset(new LoadFromStackOrConst());
804  } else {
805  const MachineFrameInfo &MFI = Fn->getFrameInfo();
806  IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
807  }
808 
809  if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
810  Filler))
811  return false;
812 
813  insertDelayFiller(Filler, BrMap);
814  addLiveInRegs(Filler, *SuccBB);
815  Filler->eraseFromParent();
816 
817  return true;
818 }
819 
820 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
821  if (B.succ_empty())
822  return nullptr;
823 
824  // Select the successor with the larget edge weight.
825  auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
826  MachineBasicBlock *S = *std::max_element(
827  B.succ_begin(), B.succ_end(),
828  [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
829  return Prob.getEdgeProbability(&B, Dst0) <
830  Prob.getEdgeProbability(&B, Dst1);
831  });
832  return S->isEHPad() ? nullptr : S;
833 }
834 
835 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
836 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
837  const MipsInstrInfo *TII =
838  MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
839  MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
840  SmallVector<MachineInstr*, 2> BranchInstrs;
842 
844  TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
845 
846  if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
847  return std::make_pair(R, nullptr);
848 
849  if (R != MipsInstrInfo::BT_CondUncond) {
850  if (!hasUnoccupiedSlot(BranchInstrs[0]))
851  return std::make_pair(MipsInstrInfo::BT_None, nullptr);
852 
853  assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
854 
855  return std::make_pair(R, BranchInstrs[0]);
856  }
857 
858  assert((TrueBB == &Dst) || (FalseBB == &Dst));
859 
860  // Examine the conditional branch. See if its slot is occupied.
861  if (hasUnoccupiedSlot(BranchInstrs[0]))
862  return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
863 
864  // If that fails, try the unconditional branch.
865  if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
866  return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
867 
868  return std::make_pair(MipsInstrInfo::BT_None, nullptr);
869 }
870 
871 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
872  RegDefsUses &RegDU, bool &HasMultipleSuccs,
873  BB2BrMap &BrMap) const {
874  std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
875  getBranch(Pred, Succ);
876 
877  // Return if either getBranch wasn't able to analyze the branches or there
878  // were no branches with unoccupied slots.
879  if (P.first == MipsInstrInfo::BT_None)
880  return false;
881 
882  if ((P.first != MipsInstrInfo::BT_Uncond) &&
883  (P.first != MipsInstrInfo::BT_NoBranch)) {
884  HasMultipleSuccs = true;
885  RegDU.addLiveOut(Pred, Succ);
886  }
887 
888  BrMap[&Pred] = P.second;
889  return true;
890 }
891 
892 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
893  InspectMemInstr &IM) const {
894  assert(!Candidate.isKill() &&
895  "KILL instructions should have been eliminated at this point.");
896 
897  bool HasHazard = Candidate.isImplicitDef();
898 
899  HasHazard |= IM.hasHazard(Candidate);
900  HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
901 
902  return HasHazard;
903 }
904 
905 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
906  return (Candidate.isTerminator() || Candidate.isCall() ||
907  Candidate.isPosition() || Candidate.isInlineAsm() ||
908  Candidate.hasUnmodeledSideEffects());
909 }
910 
911 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
912 /// slots in Mips MachineFunctions
const NoneType None
Definition: None.h:24
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
Return the number of bytes of code the specified instruction may be.
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. ...
Definition: DataLayout.h:109
BitVector & set()
Definition: BitVector.h:398
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
typename SuperClass::const_iterator const_iterator
Definition: SmallVector.h:326
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
Definition: MachineInstr.h:456
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
Definition: BitVector.h:130
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Definition: MachineInstr.h:613
DataLayout DL
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.
Definition: MachineInstr.h:276
static bool hasUnoccupiedSlot(const MachineInstr *MI)
A debug info location.
Definition: DebugLoc.h:34
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.
Definition: MachineInstr.h:448
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...
Definition: APFloat.h:42
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.
Definition: MachineInstr.h:600
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.
Definition: MachineInstr.h:282
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...
Definition: MachineInstr.h:240
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.")))
#define F(x, y, z)
Definition: MD5.cpp:55
bool hasDelaySlot(QueryType Type=AnyInBundle) const
Returns true if the specified instruction has a delay slot which must be filled by the code generator...
Definition: MachineInstr.h:534
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...
reverse_iterator rend()
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
Definition: MachineInstr.h:139
bool isImplicitDef() const
Definition: MachineInstr.h:797
ValuesClass values(OptsTy...Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:621
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Function Alias Analysis false
#define P(N)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:284
'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.
BitVector & reset()
Definition: BitVector.h:439
bool isPosition() const
Definition: MachineInstr.h:783
CompactBranchPolicy
static const unsigned End
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
Definition: MachineInstr.h:378
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.
Definition: Pass.h:298
std::vector< MachineBasicBlock * >::const_iterator const_succ_iterator
bool inMicroMipsMode() const
std::vector< MachineBasicBlock * >::iterator pred_iterator
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)
bool hasMips32r6() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
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.
Definition: MachineInstr.h:922
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...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
#define B
Definition: LargeTest.cpp:24
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...
Definition: SmallVector.h:861
bool test(unsigned Idx) const
Definition: BitVector.h:502
bool isInlineAsm() const
Definition: MachineInstr.h:798
bool isKill() const
Definition: MachineInstr.h:796
BitVector & flip()
Definition: BitVector.h:478
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)
Definition: CommandLine.h:596
llvm_unreachable("Unknown RegBank!")
MachineFunctionProperties & set(Property P)
Representation of each machine instruction.
Definition: MachineInstr.h:59
Basic Alias true
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
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.
#define I(x, y, z)
Definition: MD5.cpp:58
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:432
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.
Definition: Value.h:73
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:210
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:56
IRTranslator LLVM IR MI
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
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.
Definition: MachineInstr.h:363