LLVM  3.7.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 "MipsTargetMachine.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Statistic.h"
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "delay-slot-filler"
36 
37 STATISTIC(FilledSlots, "Number of delay slots filled");
38 STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
39  " are not NOP.");
40 
42  "disable-mips-delay-filler",
43  cl::init(false),
44  cl::desc("Fill all delay slots with NOPs."),
45  cl::Hidden);
46 
48  "disable-mips-df-forward-search",
49  cl::init(true),
50  cl::desc("Disallow MIPS delay filler to search forward."),
51  cl::Hidden);
52 
54  "disable-mips-df-succbb-search",
55  cl::init(true),
56  cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
57  cl::Hidden);
58 
60  "disable-mips-df-backward-search",
61  cl::init(false),
62  cl::desc("Disallow MIPS delay filler to search backward."),
63  cl::Hidden);
64 
65 namespace {
66  typedef MachineBasicBlock::iterator Iter;
67  typedef MachineBasicBlock::reverse_iterator ReverseIter;
69 
70  class RegDefsUses {
71  public:
72  RegDefsUses(const TargetRegisterInfo &TRI);
73  void init(const MachineInstr &MI);
74 
75  /// This function sets all caller-saved registers in Defs.
76  void setCallerSaved(const MachineInstr &MI);
77 
78  /// This function sets all unallocatable registers in Defs.
79  void setUnallocatableRegs(const MachineFunction &MF);
80 
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);
85 
86  bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
87 
88  private:
89  bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
90  bool IsDef) const;
91 
92  /// Returns true if Reg or its alias is in RegSet.
93  bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
94 
95  const TargetRegisterInfo &TRI;
96  BitVector Defs, Uses;
97  };
98 
99  /// Base class for inspecting loads and stores.
100  class InspectMemInstr {
101  public:
102  InspectMemInstr(bool ForbidMemInstr_)
103  : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
104  SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
105 
106  /// Return true if MI cannot be moved to delay slot.
107  bool hasHazard(const MachineInstr &MI);
108 
109  virtual ~InspectMemInstr() {}
110 
111  protected:
112  /// Flags indicating whether loads or stores have been seen.
113  bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
114 
115  /// Memory instructions are not allowed to move to delay slot if this flag
116  /// is true.
117  bool ForbidMemInstr;
118 
119  private:
120  virtual bool hasHazard_(const MachineInstr &MI) = 0;
121  };
122 
123  /// This subclass rejects any memory instructions.
124  class NoMemInstr : public InspectMemInstr {
125  public:
126  NoMemInstr() : InspectMemInstr(true) {}
127  private:
128  bool hasHazard_(const MachineInstr &MI) override { return true; }
129  };
130 
131  /// This subclass accepts loads from stacks and constant loads.
132  class LoadFromStackOrConst : public InspectMemInstr {
133  public:
134  LoadFromStackOrConst() : InspectMemInstr(false) {}
135  private:
136  bool hasHazard_(const MachineInstr &MI) override;
137  };
138 
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 {
142  public:
143  MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
144 
145  private:
147 
148  bool hasHazard_(const MachineInstr &MI) override;
149 
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
152  /// Defs.
153  bool updateDefsUses(ValueType V, bool MayStore);
154 
155  /// Get the list of underlying objects of MI's memory operand.
157  SmallVectorImpl<ValueType> &Objects) const;
158 
159  const MachineFrameInfo *MFI;
160  SmallPtrSet<ValueType, 4> Uses, Defs;
161  const DataLayout &DL;
162 
163  /// Flags indicating whether loads or stores with no underlying objects have
164  /// been seen.
165  bool SeenNoObjLoad, SeenNoObjStore;
166  };
167 
168  class Filler : public MachineFunctionPass {
169  public:
170  Filler(TargetMachine &tm)
171  : MachineFunctionPass(ID), TM(tm) { }
172 
173  const char *getPassName() const override {
174  return "Mips Delay Slot Filler";
175  }
176 
177  bool runOnMachineFunction(MachineFunction &F) override {
178  bool Changed = false;
179  for (MachineFunction::iterator FI = F.begin(), FE = F.end();
180  FI != FE; ++FI)
181  Changed |= runOnMachineBasicBlock(*FI);
182 
183  // This pass invalidates liveness information when it reorders
184  // instructions to fill delay slot. Without this, -verify-machineinstrs
185  // will fail.
186  if (Changed)
188 
189  return Changed;
190  }
191 
192  void getAnalysisUsage(AnalysisUsage &AU) const override {
195  }
196 
197  private:
198  bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
199 
200  Iter replaceWithCompactBranch(MachineBasicBlock &MBB,
201  Iter Branch, DebugLoc DL);
202 
203  Iter replaceWithCompactJump(MachineBasicBlock &MBB,
204  Iter Jump, DebugLoc DL);
205 
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;
211 
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;
218 
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;
222 
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;
226 
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;
231 
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;
235 
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;
240 
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;
246 
247  bool terminateSearch(const MachineInstr &Candidate) const;
248 
249  TargetMachine &TM;
250 
251  static char ID;
252  };
253  char Filler::ID = 0;
254 } // end of anonymous namespace
255 
256 static bool hasUnoccupiedSlot(const MachineInstr *MI) {
257  return MI->hasDelaySlot() && !MI->isBundledWithSucc();
258 }
259 
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();
263 
264  for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
265  if (I->second) {
266  MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
267  ++UsefulSlots;
268  } else {
269  I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
270  }
271  }
272 }
273 
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);
278  unsigned R;
279 
280  if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
281  continue;
282 
283 #ifndef NDEBUG
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.");
288 #endif
289 
290  if (!MBB.isLiveIn(R))
291  MBB.addLiveIn(R);
292  }
293 }
294 
295 RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
296  : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
297 
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());
301 
302  // If MI is a call, add RA to Defs to prevent users of RA from going into
303  // delay slot.
304  if (MI.isCall())
305  Defs.set(Mips::RA);
306 
307  // Add all implicit register operands of branch instructions except
308  // register AT.
309  if (MI.isBranch()) {
310  update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
311  Defs.reset(Mips::AT);
312  }
313 }
314 
315 void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
316  assert(MI.isCall());
317 
318  // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
319  // the delay slot. The reason is that RA/RA_64 must not be changed
320  // in the delay slot so that the callee can return to the caller.
321  if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
322  Defs.set(Mips::RA);
323  Defs.set(Mips::RA_64);
324  }
325 
326  // If MI is a call, add all caller-saved registers to Defs.
327  BitVector CallerSavedRegs(TRI.getNumRegs(), true);
328 
329  CallerSavedRegs.reset(Mips::ZERO);
330  CallerSavedRegs.reset(Mips::ZERO_64);
331 
332  for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
333  *R; ++R)
334  for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
335  CallerSavedRegs.reset(*AI);
336 
337  Defs |= CallerSavedRegs;
338 }
339 
340 void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
341  BitVector AllocSet = TRI.getAllocatableSet(MF);
342 
343  for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
344  for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
345  AllocSet.set(*AI);
346 
347  AllocSet.set(Mips::ZERO);
348  AllocSet.set(Mips::ZERO_64);
349 
350  Defs |= AllocSet.flip();
351 }
352 
353 void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
354  const MachineBasicBlock &SuccBB) {
356  SE = MBB.succ_end(); SI != SE; ++SI)
357  if (*SI != &SuccBB)
358  for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
359  LE = (*SI)->livein_end(); LI != LE; ++LI)
360  Uses.set(*LI);
361 }
362 
363 bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
364  BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
365  bool HasHazard = false;
366 
367  for (unsigned I = Begin; I != End; ++I) {
368  const MachineOperand &MO = MI.getOperand(I);
369 
370  if (MO.isReg() && MO.getReg())
371  HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
372  }
373 
374  Defs |= NewDefs;
375  Uses |= NewUses;
376 
377  return HasHazard;
378 }
379 
380 bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
381  unsigned Reg, bool IsDef) const {
382  if (IsDef) {
383  NewDefs.set(Reg);
384  // check whether Reg has already been defined or used.
385  return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
386  }
387 
388  NewUses.set(Reg);
389  // check whether Reg has already been defined.
390  return isRegInSet(Defs, Reg);
391 }
392 
393 bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
394  // Check Reg and all aliased Registers.
395  for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
396  if (RegSet.test(*AI))
397  return true;
398  return false;
399 }
400 
401 bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
402  if (!MI.mayStore() && !MI.mayLoad())
403  return false;
404 
405  if (ForbidMemInstr)
406  return true;
407 
408  OrigSeenLoad = SeenLoad;
409  OrigSeenStore = SeenStore;
410  SeenLoad |= MI.mayLoad();
411  SeenStore |= MI.mayStore();
412 
413  // If MI is an ordered or volatile memory reference, disallow moving
414  // subsequent loads and stores to delay slot.
415  if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
416  ForbidMemInstr = true;
417  return true;
418  }
419 
420  return hasHazard_(MI);
421 }
422 
423 bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
424  if (MI.mayStore())
425  return true;
426 
427  if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
428  return true;
429 
430  if (const PseudoSourceValue *PSV =
431  (*MI.memoperands_begin())->getPseudoValue()) {
432  if (isa<FixedStackPseudoSourceValue>(PSV))
433  return false;
434  return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
435  }
436 
437  return true;
438 }
439 
440 MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
441  : InspectMemInstr(false), MFI(MFI_), DL(DL), SeenNoObjLoad(false),
442  SeenNoObjStore(false) {}
443 
444 bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
445  bool HasHazard = false;
447 
448  // Check underlying object list.
449  if (getUnderlyingObjects(MI, Objs)) {
451  I != Objs.end(); ++I)
452  HasHazard |= updateDefsUses(*I, MI.mayStore());
453 
454  return HasHazard;
455  }
456 
457  // No underlying objects found.
458  HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
459  HasHazard |= MI.mayLoad() || OrigSeenStore;
460 
461  SeenNoObjLoad |= MI.mayLoad();
462  SeenNoObjStore |= MI.mayStore();
463 
464  return HasHazard;
465 }
466 
467 bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
468  if (MayStore)
469  return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
470  SeenNoObjLoad;
471 
472  Uses.insert(V);
473  return Defs.count(V) || SeenNoObjStore;
474 }
475 
476 bool MemDefsUses::
478  SmallVectorImpl<ValueType> &Objects) const {
479  if (!MI.hasOneMemOperand() ||
480  (!(*MI.memoperands_begin())->getValue() &&
481  !(*MI.memoperands_begin())->getPseudoValue()))
482  return false;
483 
484  if (const PseudoSourceValue *PSV =
485  (*MI.memoperands_begin())->getPseudoValue()) {
486  if (!PSV->isAliased(MFI))
487  return false;
488  Objects.push_back(PSV);
489  return true;
490  }
491 
492  const Value *V = (*MI.memoperands_begin())->getValue();
493 
495  GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
496 
497  for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
498  I != E; ++I) {
499  if (!isIdentifiedObject(V))
500  return false;
501 
502  Objects.push_back(*I);
503  }
504 
505  return true;
506 }
507 
508 // Replace Branch with the compact branch instruction.
509 Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB,
510  Iter Branch, DebugLoc DL) {
511  const MipsInstrInfo *TII =
512  MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
513 
514  unsigned NewOpcode =
515  (((unsigned) Branch->getOpcode()) == Mips::BEQ) ? Mips::BEQZC_MM
516  : Mips::BNEZC_MM;
517 
518  const MCInstrDesc &NewDesc = TII->get(NewOpcode);
519  MachineInstrBuilder MIB = BuildMI(MBB, Branch, DL, NewDesc);
520 
521  MIB.addReg(Branch->getOperand(0).getReg());
522  MIB.addMBB(Branch->getOperand(2).getMBB());
523 
524  Iter tmpIter = Branch;
525  Branch = std::prev(Branch);
526  MBB.erase(tmpIter);
527 
528  return Branch;
529 }
530 
531 // Replace Jumps with the compact jump instruction.
532 Iter Filler::replaceWithCompactJump(MachineBasicBlock &MBB,
533  Iter Jump, DebugLoc DL) {
534  const MipsInstrInfo *TII =
535  MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
536 
537  const MCInstrDesc &NewDesc = TII->get(Mips::JRC16_MM);
538  MachineInstrBuilder MIB = BuildMI(MBB, Jump, DL, NewDesc);
539 
540  MIB.addReg(Jump->getOperand(0).getReg());
541 
542  Iter tmpIter = Jump;
543  Jump = std::prev(Jump);
544  MBB.erase(tmpIter);
545 
546  return Jump;
547 }
548 
549 // For given opcode returns opcode of corresponding instruction with short
550 // delay slot.
551 static int getEquivalentCallShort(int Opcode) {
552  switch (Opcode) {
553  case Mips::BGEZAL:
554  return Mips::BGEZALS_MM;
555  case Mips::BLTZAL:
556  return Mips::BLTZALS_MM;
557  case Mips::JAL:
558  return Mips::JALS_MM;
559  case Mips::JALR:
560  return Mips::JALRS_MM;
561  case Mips::JALR16_MM:
562  return Mips::JALRS16_MM;
563  default:
564  llvm_unreachable("Unexpected call instruction for microMIPS.");
565  }
566 }
567 
568 /// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
569 /// We assume there is only one delay slot per delayed instruction.
570 bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
571  bool Changed = false;
572  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
573  bool InMicroMipsMode = STI.inMicroMipsMode();
574  const MipsInstrInfo *TII = STI.getInstrInfo();
575 
576  for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
577  if (!hasUnoccupiedSlot(&*I))
578  continue;
579 
580  ++FilledSlots;
581  Changed = true;
582 
583  // Delay slot filling is disabled at -O0.
584  if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
585  bool Filled = false;
586 
587  if (searchBackward(MBB, I)) {
588  Filled = true;
589  } else if (I->isTerminator()) {
590  if (searchSuccBBs(MBB, I)) {
591  Filled = true;
592  }
593  } else if (searchForward(MBB, I)) {
594  Filled = true;
595  }
596 
597  if (Filled) {
598  // Get instruction with delay slot.
600 
601  if (InMicroMipsMode && TII->GetInstSizeInBytes(std::next(DSI)) == 2 &&
602  DSI->isCall()) {
603  // If instruction in delay slot is 16b change opcode to
604  // corresponding instruction with short delay slot.
605  DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
606  }
607 
608  continue;
609  }
610  }
611 
612  // If instruction is BEQ or BNE with one ZERO register, then instead of
613  // adding NOP replace this instruction with the corresponding compact
614  // branch instruction, i.e. BEQZC or BNEZC.
615  unsigned Opcode = I->getOpcode();
616  if (InMicroMipsMode) {
617  switch (Opcode) {
618  case Mips::BEQ:
619  case Mips::BNE:
620  if (((unsigned) I->getOperand(1).getReg()) == Mips::ZERO) {
621  I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
622  continue;
623  }
624  break;
625  case Mips::JR:
626  case Mips::PseudoReturn:
627  case Mips::PseudoIndirectBranch:
628  // For microMIPS the PseudoReturn and PseudoIndirectBranch are allways
629  // expanded to JR_MM, so they can be replaced with JRC16_MM.
630  I = replaceWithCompactJump(MBB, I, I->getDebugLoc());
631  continue;
632  default:
633  break;
634  }
635  }
636  // Bundle the NOP to the instruction with the delay slot.
637  BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
638  MIBundleBuilder(MBB, I, std::next(I, 2));
639  }
640 
641  return Changed;
642 }
643 
644 /// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
645 /// slots in Mips MachineFunctions
647  return new Filler(tm);
648 }
649 
650 template<typename IterTy>
651 bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
652  RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
653  IterTy &Filler) const {
654  bool IsReverseIter = std::is_convertible<IterTy, ReverseIter>::value;
655 
656  for (IterTy I = Begin; I != End;) {
657  IterTy CurrI = I;
658  ++I;
659 
660  // skip debug value
661  if (CurrI->isDebugValue())
662  continue;
663 
664  if (terminateSearch(*CurrI))
665  break;
666 
667  assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
668  "Cannot put calls, returns or branches in delay slot.");
669 
670  if (CurrI->isKill()) {
671  CurrI->eraseFromParent();
672 
673  // This special case is needed for reverse iterators, because when we
674  // erase an instruction, the iterators are updated to point to the next
675  // instruction.
676  if (IsReverseIter && I != End)
677  I = CurrI;
678  continue;
679  }
680 
681  if (delayHasHazard(*CurrI, RegDU, IM))
682  continue;
683 
684  const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
685  if (STI.isTargetNaCl()) {
686  // In NaCl, instructions that must be masked are forbidden in delay slots.
687  // We only check for loads, stores and SP changes. Calls, returns and
688  // branches are not checked because non-NaCl targets never put them in
689  // delay slots.
690  unsigned AddrIdx;
691  if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
692  baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
693  CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
694  continue;
695  }
696 
697  bool InMicroMipsMode = STI.inMicroMipsMode();
698  const MipsInstrInfo *TII = STI.getInstrInfo();
699  unsigned Opcode = (*Slot).getOpcode();
700  if (InMicroMipsMode && TII->GetInstSizeInBytes(&(*CurrI)) == 2 &&
701  (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
702  Opcode == Mips::PseudoReturn))
703  continue;
704 
705  Filler = CurrI;
706  return true;
707  }
708 
709  return false;
710 }
711 
712 bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
714  return false;
715 
716  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
717  MemDefsUses MemDU(*TM.getDataLayout(), MBB.getParent()->getFrameInfo());
718  ReverseIter Filler;
719 
720  RegDU.init(*Slot);
721 
722  if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Slot,
723  Filler))
724  return false;
725 
726  MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
727  MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
728  ++UsefulSlots;
729  return true;
730 }
731 
732 bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
733  // Can handle only calls.
734  if (DisableForwardSearch || !Slot->isCall())
735  return false;
736 
737  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
738  NoMemInstr NM;
739  Iter Filler;
740 
741  RegDU.setCallerSaved(*Slot);
742 
743  if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
744  return false;
745 
746  MBB.splice(std::next(Slot), &MBB, Filler);
747  MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
748  ++UsefulSlots;
749  return true;
750 }
751 
752 bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
754  return false;
755 
756  MachineBasicBlock *SuccBB = selectSuccBB(MBB);
757 
758  if (!SuccBB)
759  return false;
760 
761  RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
762  bool HasMultipleSuccs = false;
763  BB2BrMap BrMap;
764  std::unique_ptr<InspectMemInstr> IM;
765  Iter Filler;
766 
767  // Iterate over SuccBB's predecessor list.
768  for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
769  PE = SuccBB->pred_end(); PI != PE; ++PI)
770  if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
771  return false;
772 
773  // Do not allow moving instructions which have unallocatable register operands
774  // across basic block boundaries.
775  RegDU.setUnallocatableRegs(*MBB.getParent());
776 
777  // Only allow moving loads from stack or constants if any of the SuccBB's
778  // predecessors have multiple successors.
779  if (HasMultipleSuccs) {
780  IM.reset(new LoadFromStackOrConst());
781  } else {
782  const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
783  IM.reset(new MemDefsUses(*TM.getDataLayout(), MFI));
784  }
785 
786  if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
787  Filler))
788  return false;
789 
790  insertDelayFiller(Filler, BrMap);
791  addLiveInRegs(Filler, *SuccBB);
792  Filler->eraseFromParent();
793 
794  return true;
795 }
796 
797 MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
798  if (B.succ_empty())
799  return nullptr;
800 
801  // Select the successor with the larget edge weight.
802  auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
803  MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
804  [&](const MachineBasicBlock *Dst0,
805  const MachineBasicBlock *Dst1) {
806  return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
807  });
808  return S->isLandingPad() ? nullptr : S;
809 }
810 
811 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
812 Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
813  const MipsInstrInfo *TII =
814  MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
815  MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
816  SmallVector<MachineInstr*, 2> BranchInstrs;
818 
820  TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
821 
822  if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
823  return std::make_pair(R, nullptr);
824 
825  if (R != MipsInstrInfo::BT_CondUncond) {
826  if (!hasUnoccupiedSlot(BranchInstrs[0]))
827  return std::make_pair(MipsInstrInfo::BT_None, nullptr);
828 
829  assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
830 
831  return std::make_pair(R, BranchInstrs[0]);
832  }
833 
834  assert((TrueBB == &Dst) || (FalseBB == &Dst));
835 
836  // Examine the conditional branch. See if its slot is occupied.
837  if (hasUnoccupiedSlot(BranchInstrs[0]))
838  return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
839 
840  // If that fails, try the unconditional branch.
841  if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
842  return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
843 
844  return std::make_pair(MipsInstrInfo::BT_None, nullptr);
845 }
846 
847 bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
848  RegDefsUses &RegDU, bool &HasMultipleSuccs,
849  BB2BrMap &BrMap) const {
850  std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
851  getBranch(Pred, Succ);
852 
853  // Return if either getBranch wasn't able to analyze the branches or there
854  // were no branches with unoccupied slots.
855  if (P.first == MipsInstrInfo::BT_None)
856  return false;
857 
858  if ((P.first != MipsInstrInfo::BT_Uncond) &&
859  (P.first != MipsInstrInfo::BT_NoBranch)) {
860  HasMultipleSuccs = true;
861  RegDU.addLiveOut(Pred, Succ);
862  }
863 
864  BrMap[&Pred] = P.second;
865  return true;
866 }
867 
868 bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
869  InspectMemInstr &IM) const {
870  assert(!Candidate.isKill() &&
871  "KILL instructions should have been eliminated at this point.");
872 
873  bool HasHazard = Candidate.isImplicitDef();
874 
875  HasHazard |= IM.hasHazard(Candidate);
876  HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
877 
878  return HasHazard;
879 }
880 
881 bool Filler::terminateSearch(const MachineInstr &Candidate) const {
882  return (Candidate.isTerminator() || Candidate.isCall() ||
883  Candidate.isPosition() || Candidate.isInlineAsm() ||
884  Candidate.hasUnmodeledSideEffects());
885 }
const NoneType None
Definition: None.h:23
const MachineFunction * getParent() const
getParent - Return the MachineFunction containing this basic block.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:104
BitVector & set()
Definition: BitVector.h:218
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
Definition: BitVector.h:156
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
Definition: MachineInstr.h:427
STATISTIC(NumFunctions,"Total number of functions")
bool isBasePlusOffsetMemoryAccess(unsigned Opcode, unsigned *AddrIdx, bool *IsStore=nullptr)
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
Definition: BitVector.h:165
std::vector< unsigned >::const_iterator livein_iterator
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:138
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Definition: MachineInstr.h:579
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...
void addLiveIn(unsigned Reg)
Adds the specified register as a live in.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:264
static bool hasUnoccupiedSlot(const MachineInstr *MI)
A debug info location.
Definition: DebugLoc.h:34
F(f)
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...
Instructions::iterator instr_iterator
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
Definition: MachineInstr.h:419
static cl::opt< bool > DisableDelaySlotFiller("disable-mips-delay-filler", cl::init(false), cl::desc("Fill all delay slots with NOPs."), cl::Hidden)
AnalysisUsage & addRequired()
bool AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Branch Analysis.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
static void getUnderlyingObjects(const Value *V, SmallVectorImpl< Value * > &Objects, const DataLayout &DL)
getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects and adds support for basic ptrto...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
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:566
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)
#define false
Definition: ConvertUTF.c:65
unsigned getNumOperands() const
Access to explicit operands of the instruction.
Definition: MachineInstr.h:271
bool isIdentifiedObject(const Value *V)
isIdentifiedObject - 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:221
static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB)
This function adds registers Filler defines to MBB's live-in register list.
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:500
static cl::opt< bool > DisableBackwardSearch("disable-mips-df-backward-search", cl::init(false), cl::desc("Disallow MIPS delay filler to search backward."), cl::Hidden)
std::vector< MachineBasicBlock * >::iterator pred_iterator
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
getAllocatableSet - Returns a bitset indexed by register number indicating if a register is allocatab...
reverse_iterator rend()
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:120
bool isImplicitDef() const
Definition: MachineInstr.h:759
bundle_iterator< MachineInstr, instr_iterator > iterator
#define P(N)
#define true
Definition: ConvertUTF.c:66
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:325
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:273
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
BitVector & reset()
Definition: BitVector.h:259
bool isPosition() const
Definition: MachineInstr.h:746
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
Definition: MachineInstr.h:352
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:294
bool inMicroMipsMode() const
MachineInstrBuilder BuildMI(MachineFunction &MF, DebugLoc DL, const MCInstrDesc &MCID)
BuildMI - Builder interface.
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...
bool definesRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr fully defines the specified register.
Definition: MachineInstr.h:866
bool isTargetNaCl() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
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:322
bool isInlineAsm() const
Definition: MachineInstr.h:760
bool isKill() const
Definition: MachineInstr.h:758
BitVector & flip()
Definition: BitVector.h:298
MachineFrameInfo * getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
FunctionPass * createMipsDelaySlotFillerPass(MipsTargetMachine &TM)
createMipsDelaySlotFillerPass - Returns a pass that fills in delay slots in Mips MachineFunctions ...
PseudoSourceValue - Special value supplied for machine level alias analysis.
static int getEquivalentCallShort(int Opcode)
Representation of each machine instruction.
Definition: MachineInstr.h:51
bool isLandingPad() const
isLandingPad - Returns true if the block is a landing pad.
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 '...
bool isLiveIn(unsigned Reg) const
isLiveIn - Return true if the specified register is in the live in set.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
#define I(x, y, z)
Definition: MD5.cpp:54
bool isCall(QueryType Type=AnyInBundle) const
Definition: MachineInstr.h:403
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.
std::vector< MachineBasicBlock * >::const_iterator const_succ_iterator
std::reverse_iterator< iterator > reverse_iterator
LLVM Value Representation.
Definition: Value.h:69
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
Definition: MCInstrDesc.h:185
BasicBlockListType::iterator iterator
Primary interface to the complete machine description for the target machine.
unsigned GetInstSizeInBytes(const MachineInstr *MI) const
Return the number of bytes of code the specified instruction may be.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
addReg - Add a new virtual register operand...
Helper class for constructing bundles of MachineInstrs.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
Definition: MachineInstr.h:340