blob: d6c7cac27300fb7c29de02c3253269be1ec1e24b [file] [log] [blame]
Akira Hatanaka1083eb12013-02-14 23:20:15 +00001//===-- MipsDelaySlotFiller.cpp - Mips Delay Slot Filler ------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00007//
Akira Hatanakae2489122011-04-15 21:51:11 +00008//===----------------------------------------------------------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00009//
Akira Hatanaka1083eb12013-02-14 23:20:15 +000010// Simple pass to fill delay slots with useful instructions.
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000011//
Akira Hatanakae2489122011-04-15 21:51:11 +000012//===----------------------------------------------------------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000013
Sasa Stankovic5fddf612014-03-10 20:34:23 +000014#include "MCTargetDesc/MipsMCNaCl.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000015#include "Mips.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000016#include "MipsInstrInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000017#include "MipsTargetMachine.h"
Akira Hatanaka06bd1382013-02-14 23:40:57 +000018#include "llvm/ADT/BitVector.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000019#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Statistic.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000021#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/ValueTracking.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000023#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000026#include "llvm/CodeGen/PseudoSourceValue.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000027#include "llvm/Support/CommandLine.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000028#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Target/TargetMachine.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000030#include "llvm/Target/TargetRegisterInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000031
32using namespace llvm;
33
Chandler Carruth84e68b22014-04-22 02:41:26 +000034#define DEBUG_TYPE "delay-slot-filler"
35
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000036STATISTIC(FilledSlots, "Number of delay slots filled");
Akira Hatanaka9e603442011-10-05 01:19:13 +000037STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
Akira Hatanaka02e760a2011-10-05 02:22:49 +000038 " are not NOP.");
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000039
Akira Hatanaka9d957842012-08-22 02:51:28 +000040static cl::opt<bool> DisableDelaySlotFiller(
41 "disable-mips-delay-filler",
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000042 cl::init(false),
Akira Hatanaka1083eb12013-02-14 23:20:15 +000043 cl::desc("Fill all delay slots with NOPs."),
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000044 cl::Hidden);
45
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000046static cl::opt<bool> DisableForwardSearch(
47 "disable-mips-df-forward-search",
48 cl::init(true),
49 cl::desc("Disallow MIPS delay filler to search forward."),
50 cl::Hidden);
51
Akira Hatanakae44e30c2013-03-01 01:02:36 +000052static cl::opt<bool> DisableSuccBBSearch(
53 "disable-mips-df-succbb-search",
54 cl::init(true),
55 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
56 cl::Hidden);
57
58static cl::opt<bool> DisableBackwardSearch(
59 "disable-mips-df-backward-search",
60 cl::init(false),
61 cl::desc("Disallow MIPS delay filler to search backward."),
62 cl::Hidden);
63
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000064namespace {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000065 typedef MachineBasicBlock::iterator Iter;
66 typedef MachineBasicBlock::reverse_iterator ReverseIter;
67 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
68
Akira Hatanaka979899e2013-02-26 01:30:05 +000069 class RegDefsUses {
70 public:
71 RegDefsUses(TargetMachine &TM);
72 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000073
74 /// This function sets all caller-saved registers in Defs.
75 void setCallerSaved(const MachineInstr &MI);
76
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000077 /// This function sets all unallocatable registers in Defs.
78 void setUnallocatableRegs(const MachineFunction &MF);
79
80 /// Set bits in Uses corresponding to MBB's live-out registers except for
81 /// the registers that are live-in to SuccBB.
82 void addLiveOut(const MachineBasicBlock &MBB,
83 const MachineBasicBlock &SuccBB);
84
Akira Hatanaka979899e2013-02-26 01:30:05 +000085 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
86
87 private:
88 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
89 bool IsDef) const;
90
91 /// Returns true if Reg or its alias is in RegSet.
92 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
93
94 const TargetRegisterInfo &TRI;
95 BitVector Defs, Uses;
96 };
97
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000098 /// Base class for inspecting loads and stores.
99 class InspectMemInstr {
100 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000101 InspectMemInstr(bool ForbidMemInstr_)
102 : OrigSeenLoad(false), OrigSeenStore(false), SeenLoad(false),
103 SeenStore(false), ForbidMemInstr(ForbidMemInstr_) {}
104
105 /// Return true if MI cannot be moved to delay slot.
106 bool hasHazard(const MachineInstr &MI);
107
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000108 virtual ~InspectMemInstr() {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000109
110 protected:
111 /// Flags indicating whether loads or stores have been seen.
112 bool OrigSeenLoad, OrigSeenStore, SeenLoad, SeenStore;
113
114 /// Memory instructions are not allowed to move to delay slot if this flag
115 /// is true.
116 bool ForbidMemInstr;
117
118 private:
119 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000120 };
121
122 /// This subclass rejects any memory instructions.
123 class NoMemInstr : public InspectMemInstr {
124 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000125 NoMemInstr() : InspectMemInstr(true) {}
126 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000127 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000128 };
129
130 /// This subclass accepts loads from stacks and constant loads.
131 class LoadFromStackOrConst : public InspectMemInstr {
132 public:
133 LoadFromStackOrConst() : InspectMemInstr(false) {}
134 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000135 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000136 };
137
138 /// This subclass uses memory dependence information to determine whether a
139 /// memory instruction can be moved to a delay slot.
140 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000141 public:
142 MemDefsUses(const MachineFrameInfo *MFI);
143
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000144 private:
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000145 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
146
Craig Topper56c590a2014-04-29 07:58:02 +0000147 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000148
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000149 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000150 /// disqualify the delay slot candidate between V and values in Uses and
151 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000152 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000153
154 /// Get the list of underlying objects of MI's memory operand.
155 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000156 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000157
158 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000159 SmallPtrSet<ValueType, 4> Uses, Defs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000160
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000161 /// Flags indicating whether loads or stores with no underlying objects have
162 /// been seen.
163 bool SeenNoObjLoad, SeenNoObjStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000164 };
165
Akira Hatanakaa0612812013-02-07 21:32:32 +0000166 class Filler : public MachineFunctionPass {
167 public:
Bruno Cardoso Lopesfde21cf2010-12-09 17:31:11 +0000168 Filler(TargetMachine &tm)
Bill Wendlingead89ef2013-06-07 07:04:14 +0000169 : MachineFunctionPass(ID), TM(tm) { }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000170
Craig Topper56c590a2014-04-29 07:58:02 +0000171 const char *getPassName() const override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000172 return "Mips Delay Slot Filler";
173 }
174
Craig Topper56c590a2014-04-29 07:58:02 +0000175 bool runOnMachineFunction(MachineFunction &F) override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000176 bool Changed = false;
177 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
178 FI != FE; ++FI)
179 Changed |= runOnMachineBasicBlock(*FI);
180 return Changed;
181 }
182
Craig Topper56c590a2014-04-29 07:58:02 +0000183 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000184 AU.addRequired<MachineBranchProbabilityInfo>();
185 MachineFunctionPass::getAnalysisUsage(AU);
186 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000187
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000188 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000189 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
190
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000191 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000192 /// and returns true if it isn't. It also updates memory and register
193 /// dependence information.
194 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000195 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000196
Akira Hatanakaf815db52013-03-01 00:26:14 +0000197 /// This function searches range [Begin, End) for an instruction that can be
198 /// moved to the delay slot. Returns true on success.
199 template<typename IterTy>
200 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000201 RegDefsUses &RegDU, InspectMemInstr &IM,
202 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000203
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000204 /// This function searches in the backward direction for an instruction that
205 /// can be moved to the delay slot. Returns true on success.
206 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
207
208 /// This function searches MBB in the forward direction for an instruction
209 /// that can be moved to the delay slot. Returns true on success.
210 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000211
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000212 /// This function searches one of MBB's successor blocks for an instruction
213 /// that can be moved to the delay slot and inserts clones of the
214 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000215 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
216
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000217 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
218 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000219 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
220
221 /// This function analyzes MBB and returns an instruction with an unoccupied
222 /// slot that branches to Dst.
223 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
224 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
225
226 /// Examine Pred and see if it is possible to insert an instruction into
227 /// one of its branches delay slot or its end.
228 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
229 RegDefsUses &RegDU, bool &HasMultipleSuccs,
230 BB2BrMap &BrMap) const;
231
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000232 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000233
Akira Hatanakaa0612812013-02-07 21:32:32 +0000234 TargetMachine &TM;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000235
Akira Hatanakaa0612812013-02-07 21:32:32 +0000236 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000237 };
238 char Filler::ID = 0;
239} // end of anonymous namespace
240
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000241static bool hasUnoccupiedSlot(const MachineInstr *MI) {
242 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
243}
244
245/// This function inserts clones of Filler into predecessor blocks.
246static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
247 MachineFunction *MF = Filler->getParent()->getParent();
248
249 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
250 if (I->second) {
251 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
252 ++UsefulSlots;
253 } else {
254 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
255 }
256 }
257}
258
259/// This function adds registers Filler defines to MBB's live-in register list.
260static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
261 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
262 const MachineOperand &MO = Filler->getOperand(I);
263 unsigned R;
264
265 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
266 continue;
267
268#ifndef NDEBUG
269 const MachineFunction &MF = *MBB.getParent();
270 assert(MF.getTarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
271 "Shouldn't move an instruction with unallocatable registers across "
272 "basic block boundaries.");
273#endif
274
275 if (!MBB.isLiveIn(R))
276 MBB.addLiveIn(R);
277 }
278}
279
Akira Hatanaka979899e2013-02-26 01:30:05 +0000280RegDefsUses::RegDefsUses(TargetMachine &TM)
281 : TRI(*TM.getRegisterInfo()), Defs(TRI.getNumRegs(), false),
282 Uses(TRI.getNumRegs(), false) {}
283
284void RegDefsUses::init(const MachineInstr &MI) {
285 // Add all register operands which are explicit and non-variadic.
286 update(MI, 0, MI.getDesc().getNumOperands());
287
288 // If MI is a call, add RA to Defs to prevent users of RA from going into
289 // delay slot.
290 if (MI.isCall())
291 Defs.set(Mips::RA);
292
293 // Add all implicit register operands of branch instructions except
294 // register AT.
295 if (MI.isBranch()) {
296 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
297 Defs.reset(Mips::AT);
298 }
299}
300
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000301void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
302 assert(MI.isCall());
303
304 // If MI is a call, add all caller-saved registers to Defs.
305 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
306
307 CallerSavedRegs.reset(Mips::ZERO);
308 CallerSavedRegs.reset(Mips::ZERO_64);
309
310 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
311 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
312 CallerSavedRegs.reset(*AI);
313
314 Defs |= CallerSavedRegs;
315}
316
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000317void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
318 BitVector AllocSet = TRI.getAllocatableSet(MF);
319
320 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
321 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
322 AllocSet.set(*AI);
323
324 AllocSet.set(Mips::ZERO);
325 AllocSet.set(Mips::ZERO_64);
326
327 Defs |= AllocSet.flip();
328}
329
330void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
331 const MachineBasicBlock &SuccBB) {
332 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
333 SE = MBB.succ_end(); SI != SE; ++SI)
334 if (*SI != &SuccBB)
335 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
336 LE = (*SI)->livein_end(); LI != LE; ++LI)
337 Uses.set(*LI);
338}
339
Akira Hatanaka979899e2013-02-26 01:30:05 +0000340bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
341 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
342 bool HasHazard = false;
343
344 for (unsigned I = Begin; I != End; ++I) {
345 const MachineOperand &MO = MI.getOperand(I);
346
347 if (MO.isReg() && MO.getReg())
348 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
349 }
350
351 Defs |= NewDefs;
352 Uses |= NewUses;
353
354 return HasHazard;
355}
356
357bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
358 unsigned Reg, bool IsDef) const {
359 if (IsDef) {
360 NewDefs.set(Reg);
361 // check whether Reg has already been defined or used.
362 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
363 }
364
365 NewUses.set(Reg);
366 // check whether Reg has already been defined.
367 return isRegInSet(Defs, Reg);
368}
369
370bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
371 // Check Reg and all aliased Registers.
372 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
373 if (RegSet.test(*AI))
374 return true;
375 return false;
376}
377
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000378bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000379 if (!MI.mayStore() && !MI.mayLoad())
380 return false;
381
382 if (ForbidMemInstr)
383 return true;
384
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000385 OrigSeenLoad = SeenLoad;
386 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000387 SeenLoad |= MI.mayLoad();
388 SeenStore |= MI.mayStore();
389
390 // If MI is an ordered or volatile memory reference, disallow moving
391 // subsequent loads and stores to delay slot.
392 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
393 ForbidMemInstr = true;
394 return true;
395 }
396
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000397 return hasHazard_(MI);
398}
399
400bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
401 if (MI.mayStore())
402 return true;
403
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000404 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000405 return true;
406
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000407 if (const PseudoSourceValue *PSV =
408 (*MI.memoperands_begin())->getPseudoValue()) {
409 if (isa<FixedStackPseudoSourceValue>(PSV))
410 return false;
Craig Topper062a2ba2014-04-25 05:30:21 +0000411 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000412 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000413
414 return true;
415}
416
417MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
418 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
419 SeenNoObjStore(false) {}
420
421bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000422 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000423 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000424
425 // Check underlying object list.
426 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000427 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000428 I != Objs.end(); ++I)
429 HasHazard |= updateDefsUses(*I, MI.mayStore());
430
431 return HasHazard;
432 }
433
434 // No underlying objects found.
435 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
436 HasHazard |= MI.mayLoad() || OrigSeenStore;
437
438 SeenNoObjLoad |= MI.mayLoad();
439 SeenNoObjStore |= MI.mayStore();
440
441 return HasHazard;
442}
443
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000444bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000445 if (MayStore)
446 return !Defs.insert(V) || Uses.count(V) || SeenNoObjStore || SeenNoObjLoad;
447
448 Uses.insert(V);
449 return Defs.count(V) || SeenNoObjStore;
450}
451
452bool MemDefsUses::
453getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000454 SmallVectorImpl<ValueType> &Objects) const {
455 if (!MI.hasOneMemOperand() ||
456 (!(*MI.memoperands_begin())->getValue() &&
457 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000458 return false;
459
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000460 if (const PseudoSourceValue *PSV =
461 (*MI.memoperands_begin())->getPseudoValue()) {
462 if (!PSV->isAliased(MFI))
463 return false;
464 Objects.push_back(PSV);
465 return true;
466 }
467
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000468 const Value *V = (*MI.memoperands_begin())->getValue();
469
470 SmallVector<Value *, 4> Objs;
471 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
472
Craig Topper31ee5862013-07-03 15:07:05 +0000473 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000474 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000475 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000476 return false;
477
478 Objects.push_back(*I);
479 }
480
481 return true;
482}
483
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000484/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000485/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000486bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000487 bool Changed = false;
Akira Hatanakae7b06972011-10-05 01:30:09 +0000488
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000489 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000490 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000491 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000492
Akira Hatanakaa0612812013-02-07 21:32:32 +0000493 ++FilledSlots;
494 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000495
Akira Hatanakaa0612812013-02-07 21:32:32 +0000496 // Delay slot filling is disabled at -O0.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000497 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
498 if (searchBackward(MBB, I))
499 continue;
500
501 if (I->isTerminator()) {
502 if (searchSuccBBs(MBB, I))
503 continue;
504 } else if (searchForward(MBB, I)) {
505 continue;
506 }
507 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000508
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000509 // Bundle the NOP to the instruction with the delay slot.
Bill Wendlingead89ef2013-06-07 07:04:14 +0000510 const MipsInstrInfo *TII =
511 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000512 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
513 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000514 }
515
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000516 return Changed;
517}
518
519/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
520/// slots in Mips MachineFunctions
521FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
522 return new Filler(tm);
523}
524
Akira Hatanakaf815db52013-03-01 00:26:14 +0000525template<typename IterTy>
526bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000527 RegDefsUses &RegDU, InspectMemInstr& IM,
Akira Hatanakaf815db52013-03-01 00:26:14 +0000528 IterTy &Filler) const {
529 for (IterTy I = Begin; I != End; ++I) {
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000530 // skip debug value
531 if (I->isDebugValue())
532 continue;
533
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000534 if (terminateSearch(*I))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000535 break;
536
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000537 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
538 "Cannot put calls, returns or branches in delay slot.");
539
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000540 if (delayHasHazard(*I, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000541 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000542
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000543 if (TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
544 // In NaCl, instructions that must be masked are forbidden in delay slots.
545 // We only check for loads, stores and SP changes. Calls, returns and
546 // branches are not checked because non-NaCl targets never put them in
547 // delay slots.
548 unsigned AddrIdx;
549 if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx)
550 && baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg()))
551 || I->modifiesRegister(Mips::SP, TM.getRegisterInfo()))
552 continue;
553 }
554
Akira Hatanakaf815db52013-03-01 00:26:14 +0000555 Filler = I;
556 return true;
557 }
558
559 return false;
560}
561
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000562bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000563 if (DisableBackwardSearch)
564 return false;
565
Akira Hatanakaf815db52013-03-01 00:26:14 +0000566 RegDefsUses RegDU(TM);
567 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000568 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000569
570 RegDU.init(*Slot);
571
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000572 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler))
573 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000574
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000575 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
576 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000577 ++UsefulSlots;
578 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000579}
580
581bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
582 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000583 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000584 return false;
585
586 RegDefsUses RegDU(TM);
587 NoMemInstr NM;
588 Iter Filler;
589
590 RegDU.setCallerSaved(*Slot);
591
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000592 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000593 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000594
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000595 MBB.splice(std::next(Slot), &MBB, Filler);
596 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000597 ++UsefulSlots;
598 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000599}
600
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000601bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
602 if (DisableSuccBBSearch)
603 return false;
604
605 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
606
607 if (!SuccBB)
608 return false;
609
610 RegDefsUses RegDU(TM);
611 bool HasMultipleSuccs = false;
612 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000613 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000614 Iter Filler;
615
616 // Iterate over SuccBB's predecessor list.
617 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
618 PE = SuccBB->pred_end(); PI != PE; ++PI)
619 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
620 return false;
621
622 // Do not allow moving instructions which have unallocatable register operands
623 // across basic block boundaries.
624 RegDU.setUnallocatableRegs(*MBB.getParent());
625
626 // Only allow moving loads from stack or constants if any of the SuccBB's
627 // predecessors have multiple successors.
628 if (HasMultipleSuccs) {
629 IM.reset(new LoadFromStackOrConst());
630 } else {
631 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
632 IM.reset(new MemDefsUses(MFI));
633 }
634
635 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler))
636 return false;
637
638 insertDelayFiller(Filler, BrMap);
639 addLiveInRegs(Filler, *SuccBB);
640 Filler->eraseFromParent();
641
642 return true;
643}
644
645MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
646 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000647 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000648
649 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000650 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
651 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
652 [&](const MachineBasicBlock *Dst0,
653 const MachineBasicBlock *Dst1) {
654 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
655 });
Craig Topper062a2ba2014-04-25 05:30:21 +0000656 return S->isLandingPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000657}
658
659std::pair<MipsInstrInfo::BranchType, MachineInstr *>
660Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
661 const MipsInstrInfo *TII =
662 static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
Craig Topper062a2ba2014-04-25 05:30:21 +0000663 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000664 SmallVector<MachineInstr*, 2> BranchInstrs;
665 SmallVector<MachineOperand, 2> Cond;
666
667 MipsInstrInfo::BranchType R =
668 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
669
670 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000671 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000672
673 if (R != MipsInstrInfo::BT_CondUncond) {
674 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000675 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000676
677 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
678
679 return std::make_pair(R, BranchInstrs[0]);
680 }
681
682 assert((TrueBB == &Dst) || (FalseBB == &Dst));
683
684 // Examine the conditional branch. See if its slot is occupied.
685 if (hasUnoccupiedSlot(BranchInstrs[0]))
686 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
687
688 // If that fails, try the unconditional branch.
689 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
690 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
691
Craig Topper062a2ba2014-04-25 05:30:21 +0000692 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000693}
694
695bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
696 RegDefsUses &RegDU, bool &HasMultipleSuccs,
697 BB2BrMap &BrMap) const {
698 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
699 getBranch(Pred, Succ);
700
701 // Return if either getBranch wasn't able to analyze the branches or there
702 // were no branches with unoccupied slots.
703 if (P.first == MipsInstrInfo::BT_None)
704 return false;
705
706 if ((P.first != MipsInstrInfo::BT_Uncond) &&
707 (P.first != MipsInstrInfo::BT_NoBranch)) {
708 HasMultipleSuccs = true;
709 RegDU.addLiveOut(Pred, Succ);
710 }
711
712 BrMap[&Pred] = P.second;
713 return true;
714}
715
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000716bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000717 InspectMemInstr &IM) const {
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000718 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000719
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000720 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000721 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000722
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000723 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000724}
725
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000726bool Filler::terminateSearch(const MachineInstr &Candidate) const {
727 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000728 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000729 Candidate.hasUnmodeledSideEffects());
730}