blob: f8daec9e50f0550f0ec5ec4685076d45b4e5a88e [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"
Daniel Sanders308181e2014-06-12 10:44:10 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000027#include "llvm/CodeGen/PseudoSourceValue.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000028#include "llvm/Support/CommandLine.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000029#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetMachine.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000031#include "llvm/Target/TargetRegisterInfo.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000032
33using namespace llvm;
34
Chandler Carruth84e68b22014-04-22 02:41:26 +000035#define DEBUG_TYPE "delay-slot-filler"
36
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000037STATISTIC(FilledSlots, "Number of delay slots filled");
Akira Hatanaka9e603442011-10-05 01:19:13 +000038STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
Akira Hatanaka02e760a2011-10-05 02:22:49 +000039 " are not NOP.");
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000040
Akira Hatanaka9d957842012-08-22 02:51:28 +000041static cl::opt<bool> DisableDelaySlotFiller(
42 "disable-mips-delay-filler",
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000043 cl::init(false),
Akira Hatanaka1083eb12013-02-14 23:20:15 +000044 cl::desc("Fill all delay slots with NOPs."),
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000045 cl::Hidden);
46
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000047static cl::opt<bool> DisableForwardSearch(
48 "disable-mips-df-forward-search",
49 cl::init(true),
50 cl::desc("Disallow MIPS delay filler to search forward."),
51 cl::Hidden);
52
Akira Hatanakae44e30c2013-03-01 01:02:36 +000053static cl::opt<bool> DisableSuccBBSearch(
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
59static cl::opt<bool> DisableBackwardSearch(
60 "disable-mips-df-backward-search",
61 cl::init(false),
62 cl::desc("Disallow MIPS delay filler to search backward."),
63 cl::Hidden);
64
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000065namespace {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000066 typedef MachineBasicBlock::iterator Iter;
67 typedef MachineBasicBlock::reverse_iterator ReverseIter;
68 typedef SmallDenseMap<MachineBasicBlock*, MachineInstr*, 2> BB2BrMap;
69
Akira Hatanaka979899e2013-02-26 01:30:05 +000070 class RegDefsUses {
71 public:
72 RegDefsUses(TargetMachine &TM);
73 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000074
75 /// This function sets all caller-saved registers in Defs.
76 void setCallerSaved(const MachineInstr &MI);
77
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000078 /// 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
Akira Hatanaka979899e2013-02-26 01:30:05 +000086 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
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000099 /// Base class for inspecting loads and stores.
100 class InspectMemInstr {
101 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000102 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
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000109 virtual ~InspectMemInstr() {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000110
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;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000121 };
122
123 /// This subclass rejects any memory instructions.
124 class NoMemInstr : public InspectMemInstr {
125 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000126 NoMemInstr() : InspectMemInstr(true) {}
127 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000128 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000129 };
130
131 /// This subclass accepts loads from stacks and constant loads.
132 class LoadFromStackOrConst : public InspectMemInstr {
133 public:
134 LoadFromStackOrConst() : InspectMemInstr(false) {}
135 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000136 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000137 };
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 {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000142 public:
143 MemDefsUses(const MachineFrameInfo *MFI);
144
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000145 private:
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000146 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
147
Craig Topper56c590a2014-04-29 07:58:02 +0000148 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000149
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000150 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000151 /// disqualify the delay slot candidate between V and values in Uses and
152 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000153 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000154
155 /// Get the list of underlying objects of MI's memory operand.
156 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000157 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000158
159 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000160 SmallPtrSet<ValueType, 4> Uses, Defs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000161
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000162 /// Flags indicating whether loads or stores with no underlying objects have
163 /// been seen.
164 bool SeenNoObjLoad, SeenNoObjStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000165 };
166
Akira Hatanakaa0612812013-02-07 21:32:32 +0000167 class Filler : public MachineFunctionPass {
168 public:
Bruno Cardoso Lopesfde21cf2010-12-09 17:31:11 +0000169 Filler(TargetMachine &tm)
Bill Wendlingead89ef2013-06-07 07:04:14 +0000170 : MachineFunctionPass(ID), TM(tm) { }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000171
Craig Topper56c590a2014-04-29 07:58:02 +0000172 const char *getPassName() const override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000173 return "Mips Delay Slot Filler";
174 }
175
Craig Topper56c590a2014-04-29 07:58:02 +0000176 bool runOnMachineFunction(MachineFunction &F) override {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000177 bool Changed = false;
178 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
179 FI != FE; ++FI)
180 Changed |= runOnMachineBasicBlock(*FI);
Daniel Sanders308181e2014-06-12 10:44:10 +0000181
182 // This pass invalidates liveness information when it reorders
183 // instructions to fill delay slot. Without this, -verify-machineinstrs
184 // will fail.
185 if (Changed)
186 F.getRegInfo().invalidateLiveness();
187
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000188 return Changed;
189 }
190
Craig Topper56c590a2014-04-29 07:58:02 +0000191 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000192 AU.addRequired<MachineBranchProbabilityInfo>();
193 MachineFunctionPass::getAnalysisUsage(AU);
194 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000195
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000196 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000197 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
198
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000199 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000200 /// and returns true if it isn't. It also updates memory and register
201 /// dependence information.
202 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000203 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000204
Akira Hatanakaf815db52013-03-01 00:26:14 +0000205 /// This function searches range [Begin, End) for an instruction that can be
206 /// moved to the delay slot. Returns true on success.
207 template<typename IterTy>
208 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000209 RegDefsUses &RegDU, InspectMemInstr &IM,
210 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000211
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000212 /// This function searches in the backward direction for an instruction that
213 /// can be moved to the delay slot. Returns true on success.
214 bool searchBackward(MachineBasicBlock &MBB, Iter Slot) const;
215
216 /// This function searches MBB in the forward direction for an instruction
217 /// that can be moved to the delay slot. Returns true on success.
218 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000219
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000220 /// This function searches one of MBB's successor blocks for an instruction
221 /// that can be moved to the delay slot and inserts clones of the
222 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000223 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
224
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000225 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
226 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000227 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
228
229 /// This function analyzes MBB and returns an instruction with an unoccupied
230 /// slot that branches to Dst.
231 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
232 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
233
234 /// Examine Pred and see if it is possible to insert an instruction into
235 /// one of its branches delay slot or its end.
236 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
237 RegDefsUses &RegDU, bool &HasMultipleSuccs,
238 BB2BrMap &BrMap) const;
239
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000240 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000241
Akira Hatanakaa0612812013-02-07 21:32:32 +0000242 TargetMachine &TM;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000243
Akira Hatanakaa0612812013-02-07 21:32:32 +0000244 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000245 };
246 char Filler::ID = 0;
247} // end of anonymous namespace
248
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000249static bool hasUnoccupiedSlot(const MachineInstr *MI) {
250 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
251}
252
253/// This function inserts clones of Filler into predecessor blocks.
254static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
255 MachineFunction *MF = Filler->getParent()->getParent();
256
257 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
258 if (I->second) {
259 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
260 ++UsefulSlots;
261 } else {
262 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
263 }
264 }
265}
266
267/// This function adds registers Filler defines to MBB's live-in register list.
268static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
269 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
270 const MachineOperand &MO = Filler->getOperand(I);
271 unsigned R;
272
273 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
274 continue;
275
276#ifndef NDEBUG
277 const MachineFunction &MF = *MBB.getParent();
Eric Christopherd9134482014-08-04 21:25:23 +0000278 assert(MF.getTarget()
279 .getSubtargetImpl()
280 ->getRegisterInfo()
281 ->getAllocatableSet(MF)
282 .test(R) &&
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000283 "Shouldn't move an instruction with unallocatable registers across "
284 "basic block boundaries.");
285#endif
286
287 if (!MBB.isLiveIn(R))
288 MBB.addLiveIn(R);
289 }
290}
291
Akira Hatanaka979899e2013-02-26 01:30:05 +0000292RegDefsUses::RegDefsUses(TargetMachine &TM)
Eric Christopherd9134482014-08-04 21:25:23 +0000293 : TRI(*TM.getSubtargetImpl()->getRegisterInfo()),
294 Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
Akira Hatanaka979899e2013-02-26 01:30:05 +0000295
296void RegDefsUses::init(const MachineInstr &MI) {
297 // Add all register operands which are explicit and non-variadic.
298 update(MI, 0, MI.getDesc().getNumOperands());
299
300 // If MI is a call, add RA to Defs to prevent users of RA from going into
301 // delay slot.
302 if (MI.isCall())
303 Defs.set(Mips::RA);
304
305 // Add all implicit register operands of branch instructions except
306 // register AT.
307 if (MI.isBranch()) {
308 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
309 Defs.reset(Mips::AT);
310 }
311}
312
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000313void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
314 assert(MI.isCall());
315
316 // If MI is a call, add all caller-saved registers to Defs.
317 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
318
319 CallerSavedRegs.reset(Mips::ZERO);
320 CallerSavedRegs.reset(Mips::ZERO_64);
321
322 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(); *R; ++R)
323 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
324 CallerSavedRegs.reset(*AI);
325
326 Defs |= CallerSavedRegs;
327}
328
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000329void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
330 BitVector AllocSet = TRI.getAllocatableSet(MF);
331
332 for (int R = AllocSet.find_first(); R != -1; R = AllocSet.find_next(R))
333 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
334 AllocSet.set(*AI);
335
336 AllocSet.set(Mips::ZERO);
337 AllocSet.set(Mips::ZERO_64);
338
339 Defs |= AllocSet.flip();
340}
341
342void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
343 const MachineBasicBlock &SuccBB) {
344 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
345 SE = MBB.succ_end(); SI != SE; ++SI)
346 if (*SI != &SuccBB)
347 for (MachineBasicBlock::livein_iterator LI = (*SI)->livein_begin(),
348 LE = (*SI)->livein_end(); LI != LE; ++LI)
349 Uses.set(*LI);
350}
351
Akira Hatanaka979899e2013-02-26 01:30:05 +0000352bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
353 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
354 bool HasHazard = false;
355
356 for (unsigned I = Begin; I != End; ++I) {
357 const MachineOperand &MO = MI.getOperand(I);
358
359 if (MO.isReg() && MO.getReg())
360 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
361 }
362
363 Defs |= NewDefs;
364 Uses |= NewUses;
365
366 return HasHazard;
367}
368
369bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
370 unsigned Reg, bool IsDef) const {
371 if (IsDef) {
372 NewDefs.set(Reg);
373 // check whether Reg has already been defined or used.
374 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
375 }
376
377 NewUses.set(Reg);
378 // check whether Reg has already been defined.
379 return isRegInSet(Defs, Reg);
380}
381
382bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
383 // Check Reg and all aliased Registers.
384 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
385 if (RegSet.test(*AI))
386 return true;
387 return false;
388}
389
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000390bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000391 if (!MI.mayStore() && !MI.mayLoad())
392 return false;
393
394 if (ForbidMemInstr)
395 return true;
396
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000397 OrigSeenLoad = SeenLoad;
398 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000399 SeenLoad |= MI.mayLoad();
400 SeenStore |= MI.mayStore();
401
402 // If MI is an ordered or volatile memory reference, disallow moving
403 // subsequent loads and stores to delay slot.
404 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
405 ForbidMemInstr = true;
406 return true;
407 }
408
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000409 return hasHazard_(MI);
410}
411
412bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
413 if (MI.mayStore())
414 return true;
415
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000416 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000417 return true;
418
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000419 if (const PseudoSourceValue *PSV =
420 (*MI.memoperands_begin())->getPseudoValue()) {
421 if (isa<FixedStackPseudoSourceValue>(PSV))
422 return false;
Craig Topper062a2ba2014-04-25 05:30:21 +0000423 return !PSV->isConstant(nullptr) && PSV != PseudoSourceValue::getStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000424 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000425
426 return true;
427}
428
429MemDefsUses::MemDefsUses(const MachineFrameInfo *MFI_)
430 : InspectMemInstr(false), MFI(MFI_), SeenNoObjLoad(false),
431 SeenNoObjStore(false) {}
432
433bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000434 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000435 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000436
437 // Check underlying object list.
438 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000439 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000440 I != Objs.end(); ++I)
441 HasHazard |= updateDefsUses(*I, MI.mayStore());
442
443 return HasHazard;
444 }
445
446 // No underlying objects found.
447 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
448 HasHazard |= MI.mayLoad() || OrigSeenStore;
449
450 SeenNoObjLoad |= MI.mayLoad();
451 SeenNoObjStore |= MI.mayStore();
452
453 return HasHazard;
454}
455
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000456bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000457 if (MayStore)
458 return !Defs.insert(V) || Uses.count(V) || SeenNoObjStore || SeenNoObjLoad;
459
460 Uses.insert(V);
461 return Defs.count(V) || SeenNoObjStore;
462}
463
464bool MemDefsUses::
465getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000466 SmallVectorImpl<ValueType> &Objects) const {
467 if (!MI.hasOneMemOperand() ||
468 (!(*MI.memoperands_begin())->getValue() &&
469 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000470 return false;
471
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000472 if (const PseudoSourceValue *PSV =
473 (*MI.memoperands_begin())->getPseudoValue()) {
474 if (!PSV->isAliased(MFI))
475 return false;
476 Objects.push_back(PSV);
477 return true;
478 }
479
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000480 const Value *V = (*MI.memoperands_begin())->getValue();
481
482 SmallVector<Value *, 4> Objs;
483 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
484
Craig Topper31ee5862013-07-03 15:07:05 +0000485 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000486 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000487 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000488 return false;
489
490 Objects.push_back(*I);
491 }
492
493 return true;
494}
495
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000496/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000497/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000498bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000499 bool Changed = false;
Akira Hatanakae7b06972011-10-05 01:30:09 +0000500
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000501 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000502 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000503 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000504
Akira Hatanakaa0612812013-02-07 21:32:32 +0000505 ++FilledSlots;
506 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000507
Akira Hatanakaa0612812013-02-07 21:32:32 +0000508 // Delay slot filling is disabled at -O0.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000509 if (!DisableDelaySlotFiller && (TM.getOptLevel() != CodeGenOpt::None)) {
510 if (searchBackward(MBB, I))
511 continue;
512
513 if (I->isTerminator()) {
514 if (searchSuccBBs(MBB, I))
515 continue;
516 } else if (searchForward(MBB, I)) {
517 continue;
518 }
519 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000520
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000521 // Bundle the NOP to the instruction with the delay slot.
Eric Christopherd9134482014-08-04 21:25:23 +0000522 const MipsInstrInfo *TII = static_cast<const MipsInstrInfo *>(
523 TM.getSubtargetImpl()->getInstrInfo());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000524 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
525 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000526 }
527
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000528 return Changed;
529}
530
531/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
532/// slots in Mips MachineFunctions
533FunctionPass *llvm::createMipsDelaySlotFillerPass(MipsTargetMachine &tm) {
534 return new Filler(tm);
535}
536
Akira Hatanakaf815db52013-03-01 00:26:14 +0000537template<typename IterTy>
538bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000539 RegDefsUses &RegDU, InspectMemInstr& IM,
Akira Hatanakaf815db52013-03-01 00:26:14 +0000540 IterTy &Filler) const {
541 for (IterTy I = Begin; I != End; ++I) {
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000542 // skip debug value
543 if (I->isDebugValue())
544 continue;
545
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000546 if (terminateSearch(*I))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000547 break;
548
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000549 assert((!I->isCall() && !I->isReturn() && !I->isBranch()) &&
550 "Cannot put calls, returns or branches in delay slot.");
551
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000552 if (delayHasHazard(*I, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000553 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000554
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000555 if (TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
556 // In NaCl, instructions that must be masked are forbidden in delay slots.
557 // We only check for loads, stores and SP changes. Calls, returns and
558 // branches are not checked because non-NaCl targets never put them in
559 // delay slots.
560 unsigned AddrIdx;
Eric Christopherd9134482014-08-04 21:25:23 +0000561 if ((isBasePlusOffsetMemoryAccess(I->getOpcode(), &AddrIdx) &&
562 baseRegNeedsLoadStoreMask(I->getOperand(AddrIdx).getReg())) ||
563 I->modifiesRegister(Mips::SP,
564 TM.getSubtargetImpl()->getRegisterInfo()))
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000565 continue;
566 }
567
Akira Hatanakaf815db52013-03-01 00:26:14 +0000568 Filler = I;
569 return true;
570 }
571
572 return false;
573}
574
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000575bool Filler::searchBackward(MachineBasicBlock &MBB, Iter Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000576 if (DisableBackwardSearch)
577 return false;
578
Akira Hatanakaf815db52013-03-01 00:26:14 +0000579 RegDefsUses RegDU(TM);
580 MemDefsUses MemDU(MBB.getParent()->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000581 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000582
583 RegDU.init(*Slot);
584
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000585 if (!searchRange(MBB, ReverseIter(Slot), MBB.rend(), RegDU, MemDU, Filler))
586 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000587
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000588 MBB.splice(std::next(Slot), &MBB, std::next(Filler).base());
589 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000590 ++UsefulSlots;
591 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000592}
593
594bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
595 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000596 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000597 return false;
598
599 RegDefsUses RegDU(TM);
600 NoMemInstr NM;
601 Iter Filler;
602
603 RegDU.setCallerSaved(*Slot);
604
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000605 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000606 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000607
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000608 MBB.splice(std::next(Slot), &MBB, Filler);
609 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000610 ++UsefulSlots;
611 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000612}
613
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000614bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
615 if (DisableSuccBBSearch)
616 return false;
617
618 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
619
620 if (!SuccBB)
621 return false;
622
623 RegDefsUses RegDU(TM);
624 bool HasMultipleSuccs = false;
625 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000626 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000627 Iter Filler;
628
629 // Iterate over SuccBB's predecessor list.
630 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
631 PE = SuccBB->pred_end(); PI != PE; ++PI)
632 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
633 return false;
634
635 // Do not allow moving instructions which have unallocatable register operands
636 // across basic block boundaries.
637 RegDU.setUnallocatableRegs(*MBB.getParent());
638
639 // Only allow moving loads from stack or constants if any of the SuccBB's
640 // predecessors have multiple successors.
641 if (HasMultipleSuccs) {
642 IM.reset(new LoadFromStackOrConst());
643 } else {
644 const MachineFrameInfo *MFI = MBB.getParent()->getFrameInfo();
645 IM.reset(new MemDefsUses(MFI));
646 }
647
648 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Filler))
649 return false;
650
651 insertDelayFiller(Filler, BrMap);
652 addLiveInRegs(Filler, *SuccBB);
653 Filler->eraseFromParent();
654
655 return true;
656}
657
658MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
659 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000660 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000661
662 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000663 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
664 MachineBasicBlock *S = *std::max_element(B.succ_begin(), B.succ_end(),
665 [&](const MachineBasicBlock *Dst0,
666 const MachineBasicBlock *Dst1) {
667 return Prob.getEdgeWeight(&B, Dst0) < Prob.getEdgeWeight(&B, Dst1);
668 });
Craig Topper062a2ba2014-04-25 05:30:21 +0000669 return S->isLandingPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000670}
671
672std::pair<MipsInstrInfo::BranchType, MachineInstr *>
673Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
674 const MipsInstrInfo *TII =
Eric Christopherd9134482014-08-04 21:25:23 +0000675 static_cast<const MipsInstrInfo *>(TM.getSubtargetImpl()->getInstrInfo());
Craig Topper062a2ba2014-04-25 05:30:21 +0000676 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000677 SmallVector<MachineInstr*, 2> BranchInstrs;
678 SmallVector<MachineOperand, 2> Cond;
679
680 MipsInstrInfo::BranchType R =
681 TII->AnalyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
682
683 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000684 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000685
686 if (R != MipsInstrInfo::BT_CondUncond) {
687 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000688 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000689
690 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
691
692 return std::make_pair(R, BranchInstrs[0]);
693 }
694
695 assert((TrueBB == &Dst) || (FalseBB == &Dst));
696
697 // Examine the conditional branch. See if its slot is occupied.
698 if (hasUnoccupiedSlot(BranchInstrs[0]))
699 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
700
701 // If that fails, try the unconditional branch.
702 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
703 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
704
Craig Topper062a2ba2014-04-25 05:30:21 +0000705 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000706}
707
708bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
709 RegDefsUses &RegDU, bool &HasMultipleSuccs,
710 BB2BrMap &BrMap) const {
711 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
712 getBranch(Pred, Succ);
713
714 // Return if either getBranch wasn't able to analyze the branches or there
715 // were no branches with unoccupied slots.
716 if (P.first == MipsInstrInfo::BT_None)
717 return false;
718
719 if ((P.first != MipsInstrInfo::BT_Uncond) &&
720 (P.first != MipsInstrInfo::BT_NoBranch)) {
721 HasMultipleSuccs = true;
722 RegDU.addLiveOut(Pred, Succ);
723 }
724
725 BrMap[&Pred] = P.second;
726 return true;
727}
728
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000729bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000730 InspectMemInstr &IM) const {
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000731 bool HasHazard = (Candidate.isImplicitDef() || Candidate.isKill());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000732
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000733 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000734 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000735
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000736 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000737}
738
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000739bool Filler::terminateSearch(const MachineInstr &Candidate) const {
740 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000741 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000742 Candidate.hasUnmodeledSideEffects());
743}