blob: c88d05c36c6de88e8db9793de18105910a485ec9 [file] [log] [blame]
Eugene Zelenko79220eae2017-08-03 22:12:30 +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"
Eugene Zelenko79220eae2017-08-03 22:12:30 +000017#include "MipsRegisterInfo.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000018#include "MipsSubtarget.h"
Akira Hatanaka06bd1382013-02-14 23:40:57 +000019#include "llvm/ADT/BitVector.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/PointerUnion.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000022#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000023#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000025#include "llvm/ADT/StringRef.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000026#include "llvm/Analysis/AliasAnalysis.h"
27#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000029#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000030#include "llvm/CodeGen/MachineFunction.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000031#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000032#include "llvm/CodeGen/MachineInstr.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000034#include "llvm/CodeGen/MachineOperand.h"
Daniel Sanders308181e2014-06-12 10:44:10 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000036#include "llvm/CodeGen/PseudoSourceValue.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000037#include "llvm/MC/MCInstrDesc.h"
38#include "llvm/MC/MCRegisterInfo.h"
39#include "llvm/Support/Casting.h"
40#include "llvm/Support/CodeGen.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000041#include "llvm/Support/CommandLine.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000042#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Target/TargetMachine.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000044#include "llvm/Target/TargetRegisterInfo.h"
Eugene Zelenko79220eae2017-08-03 22:12:30 +000045#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000046#include <algorithm>
47#include <cassert>
48#include <iterator>
49#include <memory>
50#include <utility>
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000051
52using namespace llvm;
53
Chandler Carruth84e68b22014-04-22 02:41:26 +000054#define DEBUG_TYPE "delay-slot-filler"
55
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000056STATISTIC(FilledSlots, "Number of delay slots filled");
Akira Hatanaka9e603442011-10-05 01:19:13 +000057STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
Akira Hatanaka02e760a2011-10-05 02:22:49 +000058 " are not NOP.");
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000059
Akira Hatanaka9d957842012-08-22 02:51:28 +000060static cl::opt<bool> DisableDelaySlotFiller(
61 "disable-mips-delay-filler",
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000062 cl::init(false),
Akira Hatanaka1083eb12013-02-14 23:20:15 +000063 cl::desc("Fill all delay slots with NOPs."),
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000064 cl::Hidden);
65
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000066static cl::opt<bool> DisableForwardSearch(
67 "disable-mips-df-forward-search",
68 cl::init(true),
69 cl::desc("Disallow MIPS delay filler to search forward."),
70 cl::Hidden);
71
Akira Hatanakae44e30c2013-03-01 01:02:36 +000072static cl::opt<bool> DisableSuccBBSearch(
73 "disable-mips-df-succbb-search",
74 cl::init(true),
75 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
76 cl::Hidden);
77
78static cl::opt<bool> DisableBackwardSearch(
79 "disable-mips-df-backward-search",
80 cl::init(false),
81 cl::desc("Disallow MIPS delay filler to search backward."),
82 cl::Hidden);
83
Simon Dardis8d8f2f82016-05-17 10:21:43 +000084enum CompactBranchPolicy {
85 CB_Never, ///< The policy 'never' may in some circumstances or for some
86 ///< ISAs not be absolutely adhered to.
87 CB_Optimal, ///< Optimal is the default and will produce compact branches
88 ///< when delay slots cannot be filled.
89 CB_Always ///< 'always' may in some circumstances may not be
90 ///< absolutely adhered to there may not be a corresponding
91 ///< compact form of a branch.
92};
93
94static cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy(
95 "mips-compact-branches",cl::Optional,
96 cl::init(CB_Optimal),
97 cl::desc("MIPS Specific: Compact branch policy."),
98 cl::values(
99 clEnumValN(CB_Never, "never", "Do not use compact branches if possible."),
100 clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000101 clEnumValN(CB_Always, "always", "Always use compact branches if possible.")
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000102 )
103);
104
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000105namespace {
Eugene Zelenko926883e2017-02-01 01:22:51 +0000106
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000107 using Iter = MachineBasicBlock::iterator;
108 using ReverseIter = MachineBasicBlock::reverse_iterator;
109 using BB2BrMap = SmallDenseMap<MachineBasicBlock *, MachineInstr *, 2>;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000110
Akira Hatanaka979899e2013-02-26 01:30:05 +0000111 class RegDefsUses {
112 public:
Eric Christopher96e72c62015-01-29 23:27:36 +0000113 RegDefsUses(const TargetRegisterInfo &TRI);
Eugene Zelenko926883e2017-02-01 01:22:51 +0000114
Akira Hatanaka979899e2013-02-26 01:30:05 +0000115 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000116
117 /// This function sets all caller-saved registers in Defs.
118 void setCallerSaved(const MachineInstr &MI);
119
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000120 /// This function sets all unallocatable registers in Defs.
121 void setUnallocatableRegs(const MachineFunction &MF);
122
123 /// Set bits in Uses corresponding to MBB's live-out registers except for
124 /// the registers that are live-in to SuccBB.
125 void addLiveOut(const MachineBasicBlock &MBB,
126 const MachineBasicBlock &SuccBB);
127
Akira Hatanaka979899e2013-02-26 01:30:05 +0000128 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
129
130 private:
131 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
132 bool IsDef) const;
133
134 /// Returns true if Reg or its alias is in RegSet.
135 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
136
137 const TargetRegisterInfo &TRI;
138 BitVector Defs, Uses;
139 };
140
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000141 /// Base class for inspecting loads and stores.
142 class InspectMemInstr {
143 public:
Eugene Zelenko926883e2017-02-01 01:22:51 +0000144 InspectMemInstr(bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
145 virtual ~InspectMemInstr() = default;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000146
147 /// Return true if MI cannot be moved to delay slot.
148 bool hasHazard(const MachineInstr &MI);
149
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000150 protected:
151 /// Flags indicating whether loads or stores have been seen.
Eugene Zelenko926883e2017-02-01 01:22:51 +0000152 bool OrigSeenLoad = false;
153 bool OrigSeenStore = false;
154 bool SeenLoad = false;
155 bool SeenStore = false;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000156
157 /// Memory instructions are not allowed to move to delay slot if this flag
158 /// is true.
159 bool ForbidMemInstr;
160
161 private:
162 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000163 };
164
165 /// This subclass rejects any memory instructions.
166 class NoMemInstr : public InspectMemInstr {
167 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000168 NoMemInstr() : InspectMemInstr(true) {}
Eugene Zelenko926883e2017-02-01 01:22:51 +0000169
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000170 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000171 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000172 };
173
174 /// This subclass accepts loads from stacks and constant loads.
175 class LoadFromStackOrConst : public InspectMemInstr {
176 public:
177 LoadFromStackOrConst() : InspectMemInstr(false) {}
Eugene Zelenko926883e2017-02-01 01:22:51 +0000178
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000179 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000180 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000181 };
182
183 /// This subclass uses memory dependence information to determine whether a
184 /// memory instruction can be moved to a delay slot.
185 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000186 public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000187 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000188
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000189 private:
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000190 using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000191
Craig Topper56c590a2014-04-29 07:58:02 +0000192 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000193
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000194 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000195 /// disqualify the delay slot candidate between V and values in Uses and
196 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000197 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000198
199 /// Get the list of underlying objects of MI's memory operand.
200 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000201 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000202
203 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000204 SmallPtrSet<ValueType, 4> Uses, Defs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000205 const DataLayout &DL;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000206
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000207 /// Flags indicating whether loads or stores with no underlying objects have
208 /// been seen.
Eugene Zelenko926883e2017-02-01 01:22:51 +0000209 bool SeenNoObjLoad = false;
210 bool SeenNoObjStore = false;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000211 };
212
Akira Hatanakaa0612812013-02-07 21:32:32 +0000213 class Filler : public MachineFunctionPass {
214 public:
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000215 Filler() : MachineFunctionPass(ID) {}
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000216
Mehdi Amini117296c2016-10-01 02:56:57 +0000217 StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000218
Craig Topper56c590a2014-04-29 07:58:02 +0000219 bool runOnMachineFunction(MachineFunction &F) override {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000220 TM = &F.getTarget();
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000221 bool Changed = false;
222 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
223 FI != FE; ++FI)
224 Changed |= runOnMachineBasicBlock(*FI);
Daniel Sanders308181e2014-06-12 10:44:10 +0000225
226 // This pass invalidates liveness information when it reorders
227 // instructions to fill delay slot. Without this, -verify-machineinstrs
228 // will fail.
229 if (Changed)
230 F.getRegInfo().invalidateLiveness();
231
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000232 return Changed;
233 }
234
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000235 MachineFunctionProperties getRequiredProperties() const override {
236 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000237 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000238 }
239
Craig Topper56c590a2014-04-29 07:58:02 +0000240 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000241 AU.addRequired<MachineBranchProbabilityInfo>();
242 MachineFunctionPass::getAnalysisUsage(AU);
243 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000244
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000245 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000246 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
247
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000248 Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
249 const DebugLoc &DL);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000250
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000251 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000252 /// and returns true if it isn't. It also updates memory and register
253 /// dependence information.
254 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000255 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000256
Akira Hatanakaf815db52013-03-01 00:26:14 +0000257 /// This function searches range [Begin, End) for an instruction that can be
258 /// moved to the delay slot. Returns true on success.
259 template<typename IterTy>
260 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000261 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
262 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000263
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000264 /// This function searches in the backward direction for an instruction that
265 /// can be moved to the delay slot. Returns true on success.
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000266 bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000267
268 /// This function searches MBB in the forward direction for an instruction
269 /// that can be moved to the delay slot. Returns true on success.
270 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000271
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000272 /// This function searches one of MBB's successor blocks for an instruction
273 /// that can be moved to the delay slot and inserts clones of the
274 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000275 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
276
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000277 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
278 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000279 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
280
281 /// This function analyzes MBB and returns an instruction with an unoccupied
282 /// slot that branches to Dst.
283 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
284 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
285
286 /// Examine Pred and see if it is possible to insert an instruction into
287 /// one of its branches delay slot or its end.
288 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
289 RegDefsUses &RegDU, bool &HasMultipleSuccs,
290 BB2BrMap &BrMap) const;
291
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000292 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000293
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000294 const TargetMachine *TM = nullptr;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000295
Akira Hatanakaa0612812013-02-07 21:32:32 +0000296 static char ID;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000297 };
Eugene Zelenko926883e2017-02-01 01:22:51 +0000298
Eugene Zelenko926883e2017-02-01 01:22:51 +0000299} // end anonymous namespace
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000300
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000301char Filler::ID = 0;
302
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000303static bool hasUnoccupiedSlot(const MachineInstr *MI) {
304 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
305}
306
307/// This function inserts clones of Filler into predecessor blocks.
308static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
309 MachineFunction *MF = Filler->getParent()->getParent();
310
311 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
312 if (I->second) {
313 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
314 ++UsefulSlots;
315 } else {
316 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
317 }
318 }
319}
320
321/// This function adds registers Filler defines to MBB's live-in register list.
322static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
323 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
324 const MachineOperand &MO = Filler->getOperand(I);
325 unsigned R;
326
327 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
328 continue;
329
330#ifndef NDEBUG
331 const MachineFunction &MF = *MBB.getParent();
Eric Christopher96e72c62015-01-29 23:27:36 +0000332 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000333 "Shouldn't move an instruction with unallocatable registers across "
334 "basic block boundaries.");
335#endif
336
337 if (!MBB.isLiveIn(R))
338 MBB.addLiveIn(R);
339 }
340}
341
Eric Christopher96e72c62015-01-29 23:27:36 +0000342RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
343 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
Akira Hatanaka979899e2013-02-26 01:30:05 +0000344
345void RegDefsUses::init(const MachineInstr &MI) {
346 // Add all register operands which are explicit and non-variadic.
347 update(MI, 0, MI.getDesc().getNumOperands());
348
349 // If MI is a call, add RA to Defs to prevent users of RA from going into
350 // delay slot.
351 if (MI.isCall())
352 Defs.set(Mips::RA);
353
354 // Add all implicit register operands of branch instructions except
355 // register AT.
356 if (MI.isBranch()) {
357 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
358 Defs.reset(Mips::AT);
359 }
360}
361
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000362void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
363 assert(MI.isCall());
364
Vasileios Kalintiris70b744e2015-05-14 13:17:56 +0000365 // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
366 // the delay slot. The reason is that RA/RA_64 must not be changed
367 // in the delay slot so that the callee can return to the caller.
368 if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
369 Defs.set(Mips::RA);
370 Defs.set(Mips::RA_64);
371 }
372
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000373 // If MI is a call, add all caller-saved registers to Defs.
374 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
375
376 CallerSavedRegs.reset(Mips::ZERO);
377 CallerSavedRegs.reset(Mips::ZERO_64);
378
Eric Christopher7af952872015-03-11 21:41:28 +0000379 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
380 *R; ++R)
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000381 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
382 CallerSavedRegs.reset(*AI);
383
384 Defs |= CallerSavedRegs;
385}
386
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000387void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
388 BitVector AllocSet = TRI.getAllocatableSet(MF);
389
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000390 for (unsigned R : AllocSet.set_bits())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000391 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
392 AllocSet.set(*AI);
393
394 AllocSet.set(Mips::ZERO);
395 AllocSet.set(Mips::ZERO_64);
396
397 Defs |= AllocSet.flip();
398}
399
400void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
401 const MachineBasicBlock &SuccBB) {
402 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
403 SE = MBB.succ_end(); SI != SE; ++SI)
404 if (*SI != &SuccBB)
Matthias Braund9da1622015-09-09 18:08:03 +0000405 for (const auto &LI : (*SI)->liveins())
406 Uses.set(LI.PhysReg);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000407}
408
Akira Hatanaka979899e2013-02-26 01:30:05 +0000409bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
410 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
411 bool HasHazard = false;
412
413 for (unsigned I = Begin; I != End; ++I) {
414 const MachineOperand &MO = MI.getOperand(I);
415
416 if (MO.isReg() && MO.getReg())
417 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
418 }
419
420 Defs |= NewDefs;
421 Uses |= NewUses;
422
423 return HasHazard;
424}
425
426bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
427 unsigned Reg, bool IsDef) const {
428 if (IsDef) {
429 NewDefs.set(Reg);
430 // check whether Reg has already been defined or used.
431 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
432 }
433
434 NewUses.set(Reg);
435 // check whether Reg has already been defined.
436 return isRegInSet(Defs, Reg);
437}
438
439bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
440 // Check Reg and all aliased Registers.
441 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
442 if (RegSet.test(*AI))
443 return true;
444 return false;
445}
446
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000447bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000448 if (!MI.mayStore() && !MI.mayLoad())
449 return false;
450
451 if (ForbidMemInstr)
452 return true;
453
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000454 OrigSeenLoad = SeenLoad;
455 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000456 SeenLoad |= MI.mayLoad();
457 SeenStore |= MI.mayStore();
458
459 // If MI is an ordered or volatile memory reference, disallow moving
460 // subsequent loads and stores to delay slot.
461 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
462 ForbidMemInstr = true;
463 return true;
464 }
465
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000466 return hasHazard_(MI);
467}
468
469bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
470 if (MI.mayStore())
471 return true;
472
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000473 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000474 return true;
475
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000476 if (const PseudoSourceValue *PSV =
477 (*MI.memoperands_begin())->getPseudoValue()) {
478 if (isa<FixedStackPseudoSourceValue>(PSV))
479 return false;
Alex Lorenze40c8a22015-08-11 23:09:45 +0000480 return !PSV->isConstant(nullptr) && !PSV->isStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000481 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000482
483 return true;
484}
485
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
Eugene Zelenko926883e2017-02-01 01:22:51 +0000487 : InspectMemInstr(false), MFI(MFI_), DL(DL) {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000488
489bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000490 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000491 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000492
493 // Check underlying object list.
494 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000495 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000496 I != Objs.end(); ++I)
497 HasHazard |= updateDefsUses(*I, MI.mayStore());
498
499 return HasHazard;
500 }
501
502 // No underlying objects found.
503 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
504 HasHazard |= MI.mayLoad() || OrigSeenStore;
505
506 SeenNoObjLoad |= MI.mayLoad();
507 SeenNoObjStore |= MI.mayStore();
508
509 return HasHazard;
510}
511
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000512bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000513 if (MayStore)
David Blaikie70573dc2014-11-19 07:49:26 +0000514 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
515 SeenNoObjLoad;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000516
517 Uses.insert(V);
518 return Defs.count(V) || SeenNoObjStore;
519}
520
521bool MemDefsUses::
522getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000523 SmallVectorImpl<ValueType> &Objects) const {
524 if (!MI.hasOneMemOperand() ||
525 (!(*MI.memoperands_begin())->getValue() &&
526 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000527 return false;
528
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000529 if (const PseudoSourceValue *PSV =
530 (*MI.memoperands_begin())->getPseudoValue()) {
531 if (!PSV->isAliased(MFI))
532 return false;
533 Objects.push_back(PSV);
534 return true;
535 }
536
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000537 const Value *V = (*MI.memoperands_begin())->getValue();
538
539 SmallVector<Value *, 4> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000540 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000541
Craig Topper31ee5862013-07-03 15:07:05 +0000542 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000543 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000544 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000545 return false;
546
547 Objects.push_back(*I);
548 }
549
550 return true;
551}
552
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000553// Replace Branch with the compact branch instruction.
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000554Iter Filler::replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
555 const DebugLoc &DL) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000556 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
557 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000558
Daniel Sanderse8efff32016-03-14 16:24:05 +0000559 unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
560 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000561
Daniel Sanderse8efff32016-03-14 16:24:05 +0000562 std::next(Branch)->eraseFromParent();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000563 return Branch;
564}
565
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000566// For given opcode returns opcode of corresponding instruction with short
567// delay slot.
Hiroshi Inouea89d4b52017-06-30 09:11:50 +0000568// For the pseudo TAILCALL*_MM instructions return the short delay slot
Simon Dardis57f4ae42016-08-04 09:17:07 +0000569// form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
570// that is too short to make use of for tail calls.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000571static int getEquivalentCallShort(int Opcode) {
572 switch (Opcode) {
573 case Mips::BGEZAL:
574 return Mips::BGEZALS_MM;
575 case Mips::BLTZAL:
576 return Mips::BLTZALS_MM;
577 case Mips::JAL:
578 return Mips::JALS_MM;
579 case Mips::JALR:
580 return Mips::JALRS_MM;
581 case Mips::JALR16_MM:
582 return Mips::JALRS16_MM;
Simon Dardis57f4ae42016-08-04 09:17:07 +0000583 case Mips::TAILCALL_MM:
584 llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
Simon Dardisea343152016-08-18 13:22:43 +0000585 case Mips::TAILCALLREG:
Simon Dardis57f4ae42016-08-04 09:17:07 +0000586 return Mips::JR16_MM;
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000587 default:
588 llvm_unreachable("Unexpected call instruction for microMIPS.");
589 }
590}
591
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000592/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000593/// We assume there is only one delay slot per delayed instruction.
Akira Hatanaka1083eb12013-02-14 23:20:15 +0000594bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000595 bool Changed = false;
Eric Christopher6b6db772015-02-02 23:03:43 +0000596 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
Eric Christopher96e72c62015-01-29 23:27:36 +0000597 bool InMicroMipsMode = STI.inMicroMipsMode();
598 const MipsInstrInfo *TII = STI.getInstrInfo();
Akira Hatanakae7b06972011-10-05 01:30:09 +0000599
Hrvoje Vargac45baf22016-03-23 10:29:38 +0000600 if (InMicroMipsMode && STI.hasMips32r6()) {
601 // This is microMIPS32r6 or microMIPS64r6 processor. Delay slot for
602 // branching instructions is not needed.
603 return Changed;
604 }
605
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000606 for (Iter I = MBB.begin(); I != MBB.end(); ++I) {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000607 if (!hasUnoccupiedSlot(&*I))
Akira Hatanakaa0612812013-02-07 21:32:32 +0000608 continue;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000609
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000610 ++FilledSlots;
611 Changed = true;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000612
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000613 // Delay slot filling is disabled at -O0.
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000614 if (!DisableDelaySlotFiller && (TM->getOptLevel() != CodeGenOpt::None)) {
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000615 bool Filled = false;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000616
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000617 if (MipsCompactBranchPolicy.getValue() != CB_Always ||
618 !TII->getEquivalentCompactForm(I)) {
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000619 if (searchBackward(MBB, *I)) {
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000620 Filled = true;
621 } else if (I->isTerminator()) {
622 if (searchSuccBBs(MBB, I)) {
623 Filled = true;
624 }
625 } else if (searchForward(MBB, I)) {
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000626 Filled = true;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000627 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000628 }
629
630 if (Filled) {
631 // Get instruction with delay slot.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000632 MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000633
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000634 if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000635 DSI->isCall()) {
636 // If instruction in delay slot is 16b change opcode to
637 // corresponding instruction with short delay slot.
Simon Dardis57f4ae42016-08-04 09:17:07 +0000638
639 // TODO: Implement an instruction mapping table of 16bit opcodes to
640 // 32bit opcodes so that an instruction can be expanded. This would
641 // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
642 // TODO: Permit b16 when branching backwards to the the same function
643 // if it is in range.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000644 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
645 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000646 continue;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000647 }
648 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000649
Simon Dardisd9d41f52016-04-05 12:50:29 +0000650 // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
651 // instead of adding NOP replace this instruction with the corresponding
652 // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
653 // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
654 // be replaced with JRC16_MM.
Daniel Sanderse8efff32016-03-14 16:24:05 +0000655
656 // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
Simon Dardisd9d41f52016-04-05 12:50:29 +0000657 // form of the CTI. For indirect jumps this will not require inserting a
658 // NOP and for branches will hopefully avoid requiring a NOP.
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000659 if ((InMicroMipsMode ||
660 (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
661 TII->getEquivalentCompactForm(I)) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000662 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
663 continue;
664 }
665
Jozef Kolek650a61a2015-02-13 17:51:27 +0000666 // Bundle the NOP to the instruction with the delay slot.
667 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
668 MIBundleBuilder(MBB, I, std::next(I, 2));
Akira Hatanakaa0612812013-02-07 21:32:32 +0000669 }
670
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000671 return Changed;
672}
673
Akira Hatanakaf815db52013-03-01 00:26:14 +0000674template<typename IterTy>
675bool Filler::searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000676 RegDefsUses &RegDU, InspectMemInstr& IM, Iter Slot,
677 IterTy &Filler) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000678 for (IterTy I = Begin; I != End;) {
679 IterTy CurrI = I;
680 ++I;
681
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000682 // skip debug value
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000683 if (CurrI->isDebugValue())
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000684 continue;
685
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000686 if (terminateSearch(*CurrI))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000687 break;
688
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000689 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000690 "Cannot put calls, returns or branches in delay slot.");
691
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000692 if (CurrI->isKill()) {
693 CurrI->eraseFromParent();
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000694 continue;
695 }
696
697 if (delayHasHazard(*CurrI, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000698 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000699
Eric Christopher6b6db772015-02-02 23:03:43 +0000700 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
701 if (STI.isTargetNaCl()) {
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000702 // In NaCl, instructions that must be masked are forbidden in delay slots.
703 // We only check for loads, stores and SP changes. Calls, returns and
704 // branches are not checked because non-NaCl targets never put them in
705 // delay slots.
706 unsigned AddrIdx;
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000707 if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
708 baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
709 CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000710 continue;
711 }
712
Eric Christopher6b6db772015-02-02 23:03:43 +0000713 bool InMicroMipsMode = STI.inMicroMipsMode();
714 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000715 unsigned Opcode = (*Slot).getOpcode();
Simon Dardis57f4ae42016-08-04 09:17:07 +0000716 // This is complicated by the tail call optimization. For non-PIC code
717 // there is only a 32bit sized unconditional branch which can be assumed
718 // to be able to reach the target. b16 only has a range of +/- 1 KB.
719 // It's entirely possible that the target function is reachable with b16
720 // but we don't have enough information to make that decision.
721 if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000722 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
Simon Dardis57f4ae42016-08-04 09:17:07 +0000723 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000724 continue;
725
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000726 Filler = CurrI;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000727 return true;
728 }
729
730 return false;
731}
732
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000733bool Filler::searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000734 if (DisableBackwardSearch)
735 return false;
736
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000737 auto *Fn = MBB.getParent();
738 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
Matthias Braun941a7052016-07-28 18:40:00 +0000739 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000740 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000741
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000742 RegDU.init(Slot);
Akira Hatanakaf815db52013-03-01 00:26:14 +0000743
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000744 MachineBasicBlock::iterator SlotI = Slot;
745 if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000746 Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000747 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000748
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000749 MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
750 MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000751 ++UsefulSlots;
752 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000753}
754
755bool Filler::searchForward(MachineBasicBlock &MBB, Iter Slot) const {
756 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000757 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000758 return false;
759
Eric Christopher96e72c62015-01-29 23:27:36 +0000760 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000761 NoMemInstr NM;
762 Iter Filler;
763
764 RegDU.setCallerSaved(*Slot);
765
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000766 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000767 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000768
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000769 MBB.splice(std::next(Slot), &MBB, Filler);
770 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000771 ++UsefulSlots;
772 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000773}
774
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000775bool Filler::searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const {
776 if (DisableSuccBBSearch)
777 return false;
778
779 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
780
781 if (!SuccBB)
782 return false;
783
Eric Christopher96e72c62015-01-29 23:27:36 +0000784 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000785 bool HasMultipleSuccs = false;
786 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000787 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000788 Iter Filler;
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000789 auto *Fn = MBB.getParent();
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000790
791 // Iterate over SuccBB's predecessor list.
792 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
793 PE = SuccBB->pred_end(); PI != PE; ++PI)
794 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
795 return false;
796
797 // Do not allow moving instructions which have unallocatable register operands
798 // across basic block boundaries.
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000799 RegDU.setUnallocatableRegs(*Fn);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000800
801 // Only allow moving loads from stack or constants if any of the SuccBB's
802 // predecessors have multiple successors.
803 if (HasMultipleSuccs) {
804 IM.reset(new LoadFromStackOrConst());
805 } else {
Matthias Braun941a7052016-07-28 18:40:00 +0000806 const MachineFrameInfo &MFI = Fn->getFrameInfo();
807 IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000808 }
809
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000810 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
811 Filler))
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000812 return false;
813
814 insertDelayFiller(Filler, BrMap);
815 addLiveInRegs(Filler, *SuccBB);
816 Filler->eraseFromParent();
817
818 return true;
819}
820
821MachineBasicBlock *Filler::selectSuccBB(MachineBasicBlock &B) const {
822 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000823 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000824
825 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000826 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
Cong Hou1938f2e2015-11-24 08:51:23 +0000827 MachineBasicBlock *S = *std::max_element(
828 B.succ_begin(), B.succ_end(),
829 [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
830 return Prob.getEdgeProbability(&B, Dst0) <
831 Prob.getEdgeProbability(&B, Dst1);
832 });
Reid Kleckner0e288232015-08-27 23:27:47 +0000833 return S->isEHPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000834}
835
836std::pair<MipsInstrInfo::BranchType, MachineInstr *>
837Filler::getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const {
Eric Christopher6b6db772015-02-02 23:03:43 +0000838 const MipsInstrInfo *TII =
839 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +0000840 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000841 SmallVector<MachineInstr*, 2> BranchInstrs;
842 SmallVector<MachineOperand, 2> Cond;
843
844 MipsInstrInfo::BranchType R =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000845 TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000846
847 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000848 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000849
850 if (R != MipsInstrInfo::BT_CondUncond) {
851 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000852 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000853
854 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
855
856 return std::make_pair(R, BranchInstrs[0]);
857 }
858
859 assert((TrueBB == &Dst) || (FalseBB == &Dst));
860
861 // Examine the conditional branch. See if its slot is occupied.
862 if (hasUnoccupiedSlot(BranchInstrs[0]))
863 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
864
865 // If that fails, try the unconditional branch.
866 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
867 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
868
Craig Topper062a2ba2014-04-25 05:30:21 +0000869 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000870}
871
872bool Filler::examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
873 RegDefsUses &RegDU, bool &HasMultipleSuccs,
874 BB2BrMap &BrMap) const {
875 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
876 getBranch(Pred, Succ);
877
878 // Return if either getBranch wasn't able to analyze the branches or there
879 // were no branches with unoccupied slots.
880 if (P.first == MipsInstrInfo::BT_None)
881 return false;
882
883 if ((P.first != MipsInstrInfo::BT_Uncond) &&
884 (P.first != MipsInstrInfo::BT_NoBranch)) {
885 HasMultipleSuccs = true;
886 RegDU.addLiveOut(Pred, Succ);
887 }
888
889 BrMap[&Pred] = P.second;
890 return true;
891}
892
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000893bool Filler::delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000894 InspectMemInstr &IM) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000895 assert(!Candidate.isKill() &&
896 "KILL instructions should have been eliminated at this point.");
897
898 bool HasHazard = Candidate.isImplicitDef();
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000899
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000900 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000901 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000902
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000903 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000904}
905
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000906bool Filler::terminateSearch(const MachineInstr &Candidate) const {
907 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000908 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000909 Candidate.hasUnmodeledSideEffects());
910}
Eugene Zelenko926883e2017-02-01 01:22:51 +0000911
912/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
913/// slots in Mips MachineFunctions
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000914FunctionPass *llvm::createMipsDelaySlotFillerPass() { return new Filler(); }