blob: a05c3870f02af0fbf47c0aef1d5c1a7f6307322d [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00006//
Akira Hatanakae2489122011-04-15 21:51:11 +00007//===----------------------------------------------------------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +00008//
Akira Hatanaka1083eb12013-02-14 23:20:15 +00009// Simple pass to fill delay slots with useful instructions.
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000010//
Akira Hatanakae2489122011-04-15 21:51:11 +000011//===----------------------------------------------------------------------===//
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000012
Sasa Stankovic5fddf612014-03-10 20:34:23 +000013#include "MCTargetDesc/MipsMCNaCl.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000014#include "Mips.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000015#include "MipsInstrInfo.h"
Eugene Zelenko79220eae2017-08-03 22:12:30 +000016#include "MipsRegisterInfo.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000017#include "MipsSubtarget.h"
Akira Hatanaka06bd1382013-02-14 23:40:57 +000018#include "llvm/ADT/BitVector.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000019#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/PointerUnion.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000021#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000022#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000024#include "llvm/ADT/StringRef.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000025#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000027#include "llvm/CodeGen/MachineBasicBlock.h"
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +000028#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000029#include "llvm/CodeGen/MachineFunction.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000030#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000031#include "llvm/CodeGen/MachineInstr.h"
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000033#include "llvm/CodeGen/MachineOperand.h"
Daniel Sanders308181e2014-06-12 10:44:10 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Akira Hatanakaeb33ced2013-03-01 00:16:31 +000035#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000036#include "llvm/CodeGen/TargetRegisterInfo.h"
37#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000038#include "llvm/MC/MCInstrDesc.h"
39#include "llvm/MC/MCRegisterInfo.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/CodeGen.h"
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000042#include "llvm/Support/CommandLine.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000043#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Target/TargetMachine.h"
Eugene Zelenko926883e2017-02-01 01:22:51 +000045#include <algorithm>
46#include <cassert>
47#include <iterator>
48#include <memory>
49#include <utility>
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000050
51using namespace llvm;
52
Simon Dardisae201082018-05-11 16:13:53 +000053#define DEBUG_TYPE "mips-delay-slot-filler"
Chandler Carruth84e68b22014-04-22 02:41:26 +000054
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000055STATISTIC(FilledSlots, "Number of delay slots filled");
Akira Hatanaka9e603442011-10-05 01:19:13 +000056STATISTIC(UsefulSlots, "Number of delay slots filled with instructions that"
Akira Hatanaka02e760a2011-10-05 02:22:49 +000057 " are not NOP.");
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +000058
Akira Hatanaka9d957842012-08-22 02:51:28 +000059static cl::opt<bool> DisableDelaySlotFiller(
60 "disable-mips-delay-filler",
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000061 cl::init(false),
Akira Hatanaka1083eb12013-02-14 23:20:15 +000062 cl::desc("Fill all delay slots with NOPs."),
Akira Hatanakaf2619ee2011-09-29 23:52:13 +000063 cl::Hidden);
64
Akira Hatanakae01ff9d2013-03-01 00:50:52 +000065static cl::opt<bool> DisableForwardSearch(
66 "disable-mips-df-forward-search",
67 cl::init(true),
68 cl::desc("Disallow MIPS delay filler to search forward."),
69 cl::Hidden);
70
Akira Hatanakae44e30c2013-03-01 01:02:36 +000071static cl::opt<bool> DisableSuccBBSearch(
72 "disable-mips-df-succbb-search",
73 cl::init(true),
74 cl::desc("Disallow MIPS delay filler to search successor basic blocks."),
75 cl::Hidden);
76
77static cl::opt<bool> DisableBackwardSearch(
78 "disable-mips-df-backward-search",
79 cl::init(false),
80 cl::desc("Disallow MIPS delay filler to search backward."),
81 cl::Hidden);
82
Simon Dardis8d8f2f82016-05-17 10:21:43 +000083enum CompactBranchPolicy {
84 CB_Never, ///< The policy 'never' may in some circumstances or for some
85 ///< ISAs not be absolutely adhered to.
86 CB_Optimal, ///< Optimal is the default and will produce compact branches
87 ///< when delay slots cannot be filled.
88 CB_Always ///< 'always' may in some circumstances may not be
89 ///< absolutely adhered to there may not be a corresponding
90 ///< compact form of a branch.
91};
92
93static cl::opt<CompactBranchPolicy> MipsCompactBranchPolicy(
94 "mips-compact-branches",cl::Optional,
95 cl::init(CB_Optimal),
96 cl::desc("MIPS Specific: Compact branch policy."),
97 cl::values(
98 clEnumValN(CB_Never, "never", "Do not use compact branches if possible."),
99 clEnumValN(CB_Optimal, "optimal", "Use compact branches where appropiate (default)."),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000100 clEnumValN(CB_Always, "always", "Always use compact branches if possible.")
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000101 )
102);
103
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000104namespace {
Eugene Zelenko926883e2017-02-01 01:22:51 +0000105
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000106 using Iter = MachineBasicBlock::iterator;
107 using ReverseIter = MachineBasicBlock::reverse_iterator;
108 using BB2BrMap = SmallDenseMap<MachineBasicBlock *, MachineInstr *, 2>;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000109
Akira Hatanaka979899e2013-02-26 01:30:05 +0000110 class RegDefsUses {
111 public:
Eric Christopher96e72c62015-01-29 23:27:36 +0000112 RegDefsUses(const TargetRegisterInfo &TRI);
Eugene Zelenko926883e2017-02-01 01:22:51 +0000113
Akira Hatanaka979899e2013-02-26 01:30:05 +0000114 void init(const MachineInstr &MI);
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000115
116 /// This function sets all caller-saved registers in Defs.
117 void setCallerSaved(const MachineInstr &MI);
118
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000119 /// This function sets all unallocatable registers in Defs.
120 void setUnallocatableRegs(const MachineFunction &MF);
121
122 /// Set bits in Uses corresponding to MBB's live-out registers except for
123 /// the registers that are live-in to SuccBB.
124 void addLiveOut(const MachineBasicBlock &MBB,
125 const MachineBasicBlock &SuccBB);
126
Akira Hatanaka979899e2013-02-26 01:30:05 +0000127 bool update(const MachineInstr &MI, unsigned Begin, unsigned End);
128
129 private:
130 bool checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses, unsigned Reg,
131 bool IsDef) const;
132
133 /// Returns true if Reg or its alias is in RegSet.
134 bool isRegInSet(const BitVector &RegSet, unsigned Reg) const;
135
136 const TargetRegisterInfo &TRI;
137 BitVector Defs, Uses;
138 };
139
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000140 /// Base class for inspecting loads and stores.
141 class InspectMemInstr {
142 public:
Eugene Zelenko926883e2017-02-01 01:22:51 +0000143 InspectMemInstr(bool ForbidMemInstr_) : ForbidMemInstr(ForbidMemInstr_) {}
144 virtual ~InspectMemInstr() = default;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000145
146 /// Return true if MI cannot be moved to delay slot.
147 bool hasHazard(const MachineInstr &MI);
148
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000149 protected:
150 /// Flags indicating whether loads or stores have been seen.
Eugene Zelenko926883e2017-02-01 01:22:51 +0000151 bool OrigSeenLoad = false;
152 bool OrigSeenStore = false;
153 bool SeenLoad = false;
154 bool SeenStore = false;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000155
156 /// Memory instructions are not allowed to move to delay slot if this flag
157 /// is true.
158 bool ForbidMemInstr;
159
160 private:
161 virtual bool hasHazard_(const MachineInstr &MI) = 0;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000162 };
163
164 /// This subclass rejects any memory instructions.
165 class NoMemInstr : public InspectMemInstr {
166 public:
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000167 NoMemInstr() : InspectMemInstr(true) {}
Eugene Zelenko926883e2017-02-01 01:22:51 +0000168
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000169 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000170 bool hasHazard_(const MachineInstr &MI) override { return true; }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000171 };
172
173 /// This subclass accepts loads from stacks and constant loads.
174 class LoadFromStackOrConst : public InspectMemInstr {
175 public:
176 LoadFromStackOrConst() : InspectMemInstr(false) {}
Eugene Zelenko926883e2017-02-01 01:22:51 +0000177
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000178 private:
Craig Topper56c590a2014-04-29 07:58:02 +0000179 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000180 };
181
182 /// This subclass uses memory dependence information to determine whether a
183 /// memory instruction can be moved to a delay slot.
184 class MemDefsUses : public InspectMemInstr {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000185 public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000186 MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000187
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000188 private:
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000189 using ValueType = PointerUnion<const Value *, const PseudoSourceValue *>;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000190
Craig Topper56c590a2014-04-29 07:58:02 +0000191 bool hasHazard_(const MachineInstr &MI) override;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000192
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000193 /// Update Defs and Uses. Return true if there exist dependences that
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000194 /// disqualify the delay slot candidate between V and values in Uses and
195 /// Defs.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000196 bool updateDefsUses(ValueType V, bool MayStore);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000197
198 /// Get the list of underlying objects of MI's memory operand.
199 bool getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000200 SmallVectorImpl<ValueType> &Objects) const;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000201
202 const MachineFrameInfo *MFI;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000203 SmallPtrSet<ValueType, 4> Uses, Defs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000204 const DataLayout &DL;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000205
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000206 /// Flags indicating whether loads or stores with no underlying objects have
207 /// been seen.
Eugene Zelenko926883e2017-02-01 01:22:51 +0000208 bool SeenNoObjLoad = false;
209 bool SeenNoObjStore = false;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000210 };
211
Simon Dardisae201082018-05-11 16:13:53 +0000212 class MipsDelaySlotFiller : public MachineFunctionPass {
Akira Hatanakaa0612812013-02-07 21:32:32 +0000213 public:
Simon Dardisae201082018-05-11 16:13:53 +0000214 MipsDelaySlotFiller() : MachineFunctionPass(ID) {
215 initializeMipsDelaySlotFillerPass(*PassRegistry::getPassRegistry());
216 }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000217
Mehdi Amini117296c2016-10-01 02:56:57 +0000218 StringRef getPassName() const override { return "Mips Delay Slot Filler"; }
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000219
Craig Topper56c590a2014-04-29 07:58:02 +0000220 bool runOnMachineFunction(MachineFunction &F) override {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000221 TM = &F.getTarget();
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000222 bool Changed = false;
223 for (MachineFunction::iterator FI = F.begin(), FE = F.end();
224 FI != FE; ++FI)
225 Changed |= runOnMachineBasicBlock(*FI);
Daniel Sanders308181e2014-06-12 10:44:10 +0000226
227 // This pass invalidates liveness information when it reorders
228 // instructions to fill delay slot. Without this, -verify-machineinstrs
229 // will fail.
230 if (Changed)
231 F.getRegInfo().invalidateLiveness();
232
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000233 return Changed;
234 }
235
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000236 MachineFunctionProperties getRequiredProperties() const override {
237 return MachineFunctionProperties().set(
Matthias Braun1eb47362016-08-25 01:27:13 +0000238 MachineFunctionProperties::Property::NoVRegs);
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000239 }
240
Craig Topper56c590a2014-04-29 07:58:02 +0000241 void getAnalysisUsage(AnalysisUsage &AU) const override {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000242 AU.addRequired<MachineBranchProbabilityInfo>();
243 MachineFunctionPass::getAnalysisUsage(AU);
244 }
Akira Hatanakaa0612812013-02-07 21:32:32 +0000245
Simon Dardisae201082018-05-11 16:13:53 +0000246 static char ID;
247
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000248 private:
Akira Hatanakaa0612812013-02-07 21:32:32 +0000249 bool runOnMachineBasicBlock(MachineBasicBlock &MBB);
250
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000251 Iter replaceWithCompactBranch(MachineBasicBlock &MBB, Iter Branch,
252 const DebugLoc &DL);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000253
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000254 /// This function checks if it is valid to move Candidate to the delay slot
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000255 /// and returns true if it isn't. It also updates memory and register
256 /// dependence information.
257 bool delayHasHazard(const MachineInstr &Candidate, RegDefsUses &RegDU,
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000258 InspectMemInstr &IM) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000259
Akira Hatanakaf815db52013-03-01 00:26:14 +0000260 /// This function searches range [Begin, End) for an instruction that can be
261 /// moved to the delay slot. Returns true on success.
262 template<typename IterTy>
263 bool searchRange(MachineBasicBlock &MBB, IterTy Begin, IterTy End,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000264 RegDefsUses &RegDU, InspectMemInstr &IM, Iter Slot,
265 IterTy &Filler) const;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000266
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000267 /// This function searches in the backward direction for an instruction that
268 /// can be moved to the delay slot. Returns true on success.
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000269 bool searchBackward(MachineBasicBlock &MBB, MachineInstr &Slot) const;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000270
271 /// This function searches MBB in the forward direction for an instruction
272 /// that can be moved to the delay slot. Returns true on success.
273 bool searchForward(MachineBasicBlock &MBB, Iter Slot) const;
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000274
Akira Hatanaka1ff803f2013-03-25 20:11:16 +0000275 /// This function searches one of MBB's successor blocks for an instruction
276 /// that can be moved to the delay slot and inserts clones of the
277 /// instruction into the successor's predecessor blocks.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000278 bool searchSuccBBs(MachineBasicBlock &MBB, Iter Slot) const;
279
Akira Hatanakae9e588d2013-03-01 02:17:02 +0000280 /// Pick a successor block of MBB. Return NULL if MBB doesn't have a
281 /// successor block that is not a landing pad.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000282 MachineBasicBlock *selectSuccBB(MachineBasicBlock &B) const;
283
284 /// This function analyzes MBB and returns an instruction with an unoccupied
285 /// slot that branches to Dst.
286 std::pair<MipsInstrInfo::BranchType, MachineInstr *>
287 getBranch(MachineBasicBlock &MBB, const MachineBasicBlock &Dst) const;
288
289 /// Examine Pred and see if it is possible to insert an instruction into
290 /// one of its branches delay slot or its end.
291 bool examinePred(MachineBasicBlock &Pred, const MachineBasicBlock &Succ,
292 RegDefsUses &RegDU, bool &HasMultipleSuccs,
293 BB2BrMap &BrMap) const;
294
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000295 bool terminateSearch(const MachineInstr &Candidate) const;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000296
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000297 const TargetMachine *TM = nullptr;
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000298 };
Eugene Zelenko926883e2017-02-01 01:22:51 +0000299
Eugene Zelenko926883e2017-02-01 01:22:51 +0000300} // end anonymous namespace
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000301
Simon Dardisae201082018-05-11 16:13:53 +0000302char MipsDelaySlotFiller::ID = 0;
Eugene Zelenko79220eae2017-08-03 22:12:30 +0000303
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000304static bool hasUnoccupiedSlot(const MachineInstr *MI) {
305 return MI->hasDelaySlot() && !MI->isBundledWithSucc();
306}
307
Simon Dardisae201082018-05-11 16:13:53 +0000308INITIALIZE_PASS(MipsDelaySlotFiller, DEBUG_TYPE,
309 "Fill delay slot for MIPS", false, false)
310
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000311/// This function inserts clones of Filler into predecessor blocks.
312static void insertDelayFiller(Iter Filler, const BB2BrMap &BrMap) {
313 MachineFunction *MF = Filler->getParent()->getParent();
314
315 for (BB2BrMap::const_iterator I = BrMap.begin(); I != BrMap.end(); ++I) {
316 if (I->second) {
317 MIBundleBuilder(I->second).append(MF->CloneMachineInstr(&*Filler));
318 ++UsefulSlots;
319 } else {
320 I->first->insert(I->first->end(), MF->CloneMachineInstr(&*Filler));
321 }
322 }
323}
324
325/// This function adds registers Filler defines to MBB's live-in register list.
326static void addLiveInRegs(Iter Filler, MachineBasicBlock &MBB) {
327 for (unsigned I = 0, E = Filler->getNumOperands(); I != E; ++I) {
328 const MachineOperand &MO = Filler->getOperand(I);
329 unsigned R;
330
331 if (!MO.isReg() || !MO.isDef() || !(R = MO.getReg()))
332 continue;
333
334#ifndef NDEBUG
335 const MachineFunction &MF = *MBB.getParent();
Eric Christopher96e72c62015-01-29 23:27:36 +0000336 assert(MF.getSubtarget().getRegisterInfo()->getAllocatableSet(MF).test(R) &&
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000337 "Shouldn't move an instruction with unallocatable registers across "
338 "basic block boundaries.");
339#endif
340
341 if (!MBB.isLiveIn(R))
342 MBB.addLiveIn(R);
343 }
344}
345
Eric Christopher96e72c62015-01-29 23:27:36 +0000346RegDefsUses::RegDefsUses(const TargetRegisterInfo &TRI)
347 : TRI(TRI), Defs(TRI.getNumRegs(), false), Uses(TRI.getNumRegs(), false) {}
Akira Hatanaka979899e2013-02-26 01:30:05 +0000348
349void RegDefsUses::init(const MachineInstr &MI) {
350 // Add all register operands which are explicit and non-variadic.
351 update(MI, 0, MI.getDesc().getNumOperands());
352
353 // If MI is a call, add RA to Defs to prevent users of RA from going into
354 // delay slot.
355 if (MI.isCall())
356 Defs.set(Mips::RA);
357
358 // Add all implicit register operands of branch instructions except
359 // register AT.
360 if (MI.isBranch()) {
361 update(MI, MI.getDesc().getNumOperands(), MI.getNumOperands());
362 Defs.reset(Mips::AT);
363 }
364}
365
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000366void RegDefsUses::setCallerSaved(const MachineInstr &MI) {
367 assert(MI.isCall());
368
Vasileios Kalintiris70b744e2015-05-14 13:17:56 +0000369 // Add RA/RA_64 to Defs to prevent users of RA/RA_64 from going into
370 // the delay slot. The reason is that RA/RA_64 must not be changed
371 // in the delay slot so that the callee can return to the caller.
372 if (MI.definesRegister(Mips::RA) || MI.definesRegister(Mips::RA_64)) {
373 Defs.set(Mips::RA);
374 Defs.set(Mips::RA_64);
375 }
376
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000377 // If MI is a call, add all caller-saved registers to Defs.
378 BitVector CallerSavedRegs(TRI.getNumRegs(), true);
379
380 CallerSavedRegs.reset(Mips::ZERO);
381 CallerSavedRegs.reset(Mips::ZERO_64);
382
Eric Christopher7af952872015-03-11 21:41:28 +0000383 for (const MCPhysReg *R = TRI.getCalleeSavedRegs(MI.getParent()->getParent());
384 *R; ++R)
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000385 for (MCRegAliasIterator AI(*R, &TRI, true); AI.isValid(); ++AI)
386 CallerSavedRegs.reset(*AI);
387
388 Defs |= CallerSavedRegs;
389}
390
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000391void RegDefsUses::setUnallocatableRegs(const MachineFunction &MF) {
392 BitVector AllocSet = TRI.getAllocatableSet(MF);
393
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +0000394 for (unsigned R : AllocSet.set_bits())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000395 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
396 AllocSet.set(*AI);
397
398 AllocSet.set(Mips::ZERO);
399 AllocSet.set(Mips::ZERO_64);
400
401 Defs |= AllocSet.flip();
402}
403
404void RegDefsUses::addLiveOut(const MachineBasicBlock &MBB,
405 const MachineBasicBlock &SuccBB) {
406 for (MachineBasicBlock::const_succ_iterator SI = MBB.succ_begin(),
407 SE = MBB.succ_end(); SI != SE; ++SI)
408 if (*SI != &SuccBB)
Matthias Braund9da1622015-09-09 18:08:03 +0000409 for (const auto &LI : (*SI)->liveins())
410 Uses.set(LI.PhysReg);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000411}
412
Akira Hatanaka979899e2013-02-26 01:30:05 +0000413bool RegDefsUses::update(const MachineInstr &MI, unsigned Begin, unsigned End) {
414 BitVector NewDefs(TRI.getNumRegs()), NewUses(TRI.getNumRegs());
415 bool HasHazard = false;
416
417 for (unsigned I = Begin; I != End; ++I) {
418 const MachineOperand &MO = MI.getOperand(I);
419
420 if (MO.isReg() && MO.getReg())
421 HasHazard |= checkRegDefsUses(NewDefs, NewUses, MO.getReg(), MO.isDef());
422 }
423
424 Defs |= NewDefs;
425 Uses |= NewUses;
426
427 return HasHazard;
428}
429
430bool RegDefsUses::checkRegDefsUses(BitVector &NewDefs, BitVector &NewUses,
431 unsigned Reg, bool IsDef) const {
432 if (IsDef) {
433 NewDefs.set(Reg);
434 // check whether Reg has already been defined or used.
435 return (isRegInSet(Defs, Reg) || isRegInSet(Uses, Reg));
436 }
437
438 NewUses.set(Reg);
439 // check whether Reg has already been defined.
440 return isRegInSet(Defs, Reg);
441}
442
443bool RegDefsUses::isRegInSet(const BitVector &RegSet, unsigned Reg) const {
444 // Check Reg and all aliased Registers.
445 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
446 if (RegSet.test(*AI))
447 return true;
448 return false;
449}
450
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000451bool InspectMemInstr::hasHazard(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000452 if (!MI.mayStore() && !MI.mayLoad())
453 return false;
454
455 if (ForbidMemInstr)
456 return true;
457
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000458 OrigSeenLoad = SeenLoad;
459 OrigSeenStore = SeenStore;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000460 SeenLoad |= MI.mayLoad();
461 SeenStore |= MI.mayStore();
462
463 // If MI is an ordered or volatile memory reference, disallow moving
464 // subsequent loads and stores to delay slot.
465 if (MI.hasOrderedMemoryRef() && (OrigSeenLoad || OrigSeenStore)) {
466 ForbidMemInstr = true;
467 return true;
468 }
469
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000470 return hasHazard_(MI);
471}
472
473bool LoadFromStackOrConst::hasHazard_(const MachineInstr &MI) {
474 if (MI.mayStore())
475 return true;
476
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000477 if (!MI.hasOneMemOperand() || !(*MI.memoperands_begin())->getPseudoValue())
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000478 return true;
479
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000480 if (const PseudoSourceValue *PSV =
481 (*MI.memoperands_begin())->getPseudoValue()) {
482 if (isa<FixedStackPseudoSourceValue>(PSV))
483 return false;
Alex Lorenze40c8a22015-08-11 23:09:45 +0000484 return !PSV->isConstant(nullptr) && !PSV->isStack();
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000485 }
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000486
487 return true;
488}
489
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000490MemDefsUses::MemDefsUses(const DataLayout &DL, const MachineFrameInfo *MFI_)
Eugene Zelenko926883e2017-02-01 01:22:51 +0000491 : InspectMemInstr(false), MFI(MFI_), DL(DL) {}
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000492
493bool MemDefsUses::hasHazard_(const MachineInstr &MI) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000494 bool HasHazard = false;
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000495 SmallVector<ValueType, 4> Objs;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000496
497 // Check underlying object list.
498 if (getUnderlyingObjects(MI, Objs)) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000499 for (SmallVectorImpl<ValueType>::const_iterator I = Objs.begin();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000500 I != Objs.end(); ++I)
501 HasHazard |= updateDefsUses(*I, MI.mayStore());
502
503 return HasHazard;
504 }
505
506 // No underlying objects found.
507 HasHazard = MI.mayStore() && (OrigSeenLoad || OrigSeenStore);
508 HasHazard |= MI.mayLoad() || OrigSeenStore;
509
510 SeenNoObjLoad |= MI.mayLoad();
511 SeenNoObjStore |= MI.mayStore();
512
513 return HasHazard;
514}
515
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000516bool MemDefsUses::updateDefsUses(ValueType V, bool MayStore) {
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000517 if (MayStore)
David Blaikie70573dc2014-11-19 07:49:26 +0000518 return !Defs.insert(V).second || Uses.count(V) || SeenNoObjStore ||
519 SeenNoObjLoad;
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000520
521 Uses.insert(V);
522 return Defs.count(V) || SeenNoObjStore;
523}
524
525bool MemDefsUses::
526getUnderlyingObjects(const MachineInstr &MI,
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000527 SmallVectorImpl<ValueType> &Objects) const {
528 if (!MI.hasOneMemOperand() ||
529 (!(*MI.memoperands_begin())->getValue() &&
530 !(*MI.memoperands_begin())->getPseudoValue()))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000531 return false;
532
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000533 if (const PseudoSourceValue *PSV =
534 (*MI.memoperands_begin())->getPseudoValue()) {
535 if (!PSV->isAliased(MFI))
536 return false;
537 Objects.push_back(PSV);
538 return true;
539 }
540
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000541 const Value *V = (*MI.memoperands_begin())->getValue();
542
543 SmallVector<Value *, 4> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000544 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000545
Craig Topper31ee5862013-07-03 15:07:05 +0000546 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), E = Objs.end();
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000547 I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000548 if (!isIdentifiedObject(V))
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000549 return false;
550
551 Objects.push_back(*I);
552 }
553
554 return true;
555}
556
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000557// Replace Branch with the compact branch instruction.
Simon Dardisae201082018-05-11 16:13:53 +0000558Iter MipsDelaySlotFiller::replaceWithCompactBranch(MachineBasicBlock &MBB,
559 Iter Branch,
560 const DebugLoc &DL) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000561 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
562 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000563
Daniel Sanderse8efff32016-03-14 16:24:05 +0000564 unsigned NewOpcode = TII->getEquivalentCompactForm(Branch);
565 Branch = TII->genInstrWithNewOpc(NewOpcode, Branch);
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000566
Daniel Sanderse8efff32016-03-14 16:24:05 +0000567 std::next(Branch)->eraseFromParent();
Jozef Kolek3b8ddb62014-11-21 22:04:35 +0000568 return Branch;
569}
570
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000571// For given opcode returns opcode of corresponding instruction with short
572// delay slot.
Hiroshi Inouea89d4b52017-06-30 09:11:50 +0000573// For the pseudo TAILCALL*_MM instructions return the short delay slot
Simon Dardis57f4ae42016-08-04 09:17:07 +0000574// form. Unfortunately, TAILCALL<->b16 is denied as b16 has a limited range
575// that is too short to make use of for tail calls.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000576static int getEquivalentCallShort(int Opcode) {
577 switch (Opcode) {
578 case Mips::BGEZAL:
579 return Mips::BGEZALS_MM;
580 case Mips::BLTZAL:
581 return Mips::BLTZALS_MM;
582 case Mips::JAL:
Simon Dardis0f2f5972018-04-25 14:12:57 +0000583 case Mips::JAL_MM:
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000584 return Mips::JALS_MM;
585 case Mips::JALR:
586 return Mips::JALRS_MM;
587 case Mips::JALR16_MM:
588 return Mips::JALRS16_MM;
Simon Dardis57f4ae42016-08-04 09:17:07 +0000589 case Mips::TAILCALL_MM:
590 llvm_unreachable("Attempting to shorten the TAILCALL_MM pseudo!");
Simon Dardisea343152016-08-18 13:22:43 +0000591 case Mips::TAILCALLREG:
Simon Dardis57f4ae42016-08-04 09:17:07 +0000592 return Mips::JR16_MM;
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000593 default:
594 llvm_unreachable("Unexpected call instruction for microMIPS.");
595 }
596}
597
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000598/// runOnMachineBasicBlock - Fill in delay slots for the given basic block.
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000599/// We assume there is only one delay slot per delayed instruction.
Simon Dardisae201082018-05-11 16:13:53 +0000600bool MipsDelaySlotFiller::runOnMachineBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000601 bool Changed = false;
Eric Christopher6b6db772015-02-02 23:03:43 +0000602 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
Eric Christopher96e72c62015-01-29 23:27:36 +0000603 bool InMicroMipsMode = STI.inMicroMipsMode();
604 const MipsInstrInfo *TII = STI.getInstrInfo();
Akira Hatanakae7b06972011-10-05 01:30:09 +0000605
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
Simon Dardiseb5bfd92017-11-23 12:38:04 +0000610 // Delay slot filling is disabled at -O0, or in microMIPS32R6.
611 if (!DisableDelaySlotFiller && (TM->getOptLevel() != CodeGenOpt::None) &&
612 !(InMicroMipsMode && STI.hasMips32r6())) {
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000613
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000614 bool Filled = false;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000615
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000616 if (MipsCompactBranchPolicy.getValue() != CB_Always ||
617 !TII->getEquivalentCompactForm(I)) {
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000618 if (searchBackward(MBB, *I)) {
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000619 Filled = true;
620 } else if (I->isTerminator()) {
621 if (searchSuccBBs(MBB, I)) {
622 Filled = true;
623 }
624 } else if (searchForward(MBB, I)) {
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000625 Filled = true;
Zoran Jovanovic37bca102014-11-10 17:27:56 +0000626 }
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000627 }
628
629 if (Filled) {
630 // Get instruction with delay slot.
Duncan P. N. Exon Smith670900b2016-07-15 23:09:47 +0000631 MachineBasicBlock::instr_iterator DSI = I.getInstrIterator();
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000632
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000633 if (InMicroMipsMode && TII->getInstSizeInBytes(*std::next(DSI)) == 2 &&
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000634 DSI->isCall()) {
635 // If instruction in delay slot is 16b change opcode to
636 // corresponding instruction with short delay slot.
Simon Dardis57f4ae42016-08-04 09:17:07 +0000637
638 // TODO: Implement an instruction mapping table of 16bit opcodes to
639 // 32bit opcodes so that an instruction can be expanded. This would
640 // save 16 bits as a TAILCALL_MM pseudo requires a fullsized nop.
Hiroshi Inoue290adb32018-01-22 05:54:46 +0000641 // TODO: Permit b16 when branching backwards to the same function
Simon Dardis57f4ae42016-08-04 09:17:07 +0000642 // if it is in range.
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000643 DSI->setDesc(TII->get(getEquivalentCallShort(DSI->getOpcode())));
644 }
Simon Dardiseb5bfd92017-11-23 12:38:04 +0000645 ++FilledSlots;
646 Changed = true;
Zoran Jovanovicb554bba2014-11-25 10:50:00 +0000647 continue;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000648 }
649 }
Akira Hatanaka5ac78682012-06-13 23:25:52 +0000650
Simon Dardisd9d41f52016-04-05 12:50:29 +0000651 // For microMIPS if instruction is BEQ or BNE with one ZERO register, then
652 // instead of adding NOP replace this instruction with the corresponding
653 // compact branch instruction, i.e. BEQZC or BNEZC. Additionally
654 // PseudoReturn and PseudoIndirectBranch are expanded to JR_MM, so they can
655 // be replaced with JRC16_MM.
Daniel Sanderse8efff32016-03-14 16:24:05 +0000656
657 // For MIPSR6 attempt to produce the corresponding compact (no delay slot)
Simon Dardisd9d41f52016-04-05 12:50:29 +0000658 // form of the CTI. For indirect jumps this will not require inserting a
659 // NOP and for branches will hopefully avoid requiring a NOP.
Simon Dardis8d8f2f82016-05-17 10:21:43 +0000660 if ((InMicroMipsMode ||
661 (STI.hasMips32r6() && MipsCompactBranchPolicy != CB_Never)) &&
662 TII->getEquivalentCompactForm(I)) {
Daniel Sanderse8efff32016-03-14 16:24:05 +0000663 I = replaceWithCompactBranch(MBB, I, I->getDebugLoc());
Simon Dardiseb5bfd92017-11-23 12:38:04 +0000664 Changed = true;
Daniel Sanderse8efff32016-03-14 16:24:05 +0000665 continue;
666 }
667
Jozef Kolek650a61a2015-02-13 17:51:27 +0000668 // Bundle the NOP to the instruction with the delay slot.
669 BuildMI(MBB, std::next(I), I->getDebugLoc(), TII->get(Mips::NOP));
670 MIBundleBuilder(MBB, I, std::next(I, 2));
Simon Dardiseb5bfd92017-11-23 12:38:04 +0000671 ++FilledSlots;
672 Changed = true;
Akira Hatanakaa0612812013-02-07 21:32:32 +0000673 }
674
Bruno Cardoso Lopes0b97ce72007-08-18 01:50:47 +0000675 return Changed;
676}
677
Simon Dardisae201082018-05-11 16:13:53 +0000678template <typename IterTy>
679bool MipsDelaySlotFiller::searchRange(MachineBasicBlock &MBB, IterTy Begin,
680 IterTy End, RegDefsUses &RegDU,
681 InspectMemInstr &IM, Iter Slot,
682 IterTy &Filler) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000683 for (IterTy I = Begin; I != End;) {
684 IterTy CurrI = I;
685 ++I;
686
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000687 // skip debug value
Shiva Chen801bf7e2018-05-09 02:42:00 +0000688 if (CurrI->isDebugInstr())
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000689 continue;
690
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000691 if (terminateSearch(*CurrI))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000692 break;
693
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000694 assert((!CurrI->isCall() && !CurrI->isReturn() && !CurrI->isBranch()) &&
Akira Hatanakaeb33ced2013-03-01 00:16:31 +0000695 "Cannot put calls, returns or branches in delay slot.");
696
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000697 if (CurrI->isKill()) {
698 CurrI->eraseFromParent();
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000699 continue;
700 }
701
702 if (delayHasHazard(*CurrI, RegDU, IM))
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000703 continue;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000704
Eric Christopher6b6db772015-02-02 23:03:43 +0000705 const MipsSubtarget &STI = MBB.getParent()->getSubtarget<MipsSubtarget>();
706 if (STI.isTargetNaCl()) {
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000707 // In NaCl, instructions that must be masked are forbidden in delay slots.
708 // We only check for loads, stores and SP changes. Calls, returns and
709 // branches are not checked because non-NaCl targets never put them in
710 // delay slots.
711 unsigned AddrIdx;
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000712 if ((isBasePlusOffsetMemoryAccess(CurrI->getOpcode(), &AddrIdx) &&
713 baseRegNeedsLoadStoreMask(CurrI->getOperand(AddrIdx).getReg())) ||
714 CurrI->modifiesRegister(Mips::SP, STI.getRegisterInfo()))
Sasa Stankovic5fddf612014-03-10 20:34:23 +0000715 continue;
716 }
717
Eric Christopher6b6db772015-02-02 23:03:43 +0000718 bool InMicroMipsMode = STI.inMicroMipsMode();
719 const MipsInstrInfo *TII = STI.getInstrInfo();
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000720 unsigned Opcode = (*Slot).getOpcode();
Simon Dardis57f4ae42016-08-04 09:17:07 +0000721 // This is complicated by the tail call optimization. For non-PIC code
722 // there is only a 32bit sized unconditional branch which can be assumed
723 // to be able to reach the target. b16 only has a range of +/- 1 KB.
724 // It's entirely possible that the target function is reachable with b16
725 // but we don't have enough information to make that decision.
726 if (InMicroMipsMode && TII->getInstSizeInBytes(*CurrI) == 2 &&
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000727 (Opcode == Mips::JR || Opcode == Mips::PseudoIndirectBranch ||
Petar Jovanovic60831062019-02-22 14:53:58 +0000728 Opcode == Mips::PseudoIndirectBranch_MM ||
Simon Dardis57f4ae42016-08-04 09:17:07 +0000729 Opcode == Mips::PseudoReturn || Opcode == Mips::TAILCALL))
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000730 continue;
Simon Atanasyana9e87652018-09-19 18:46:29 +0000731 // Instructions LWP/SWP and MOVEP should not be in a delay slot as that
Zoran Jovanovic3a7654c2018-06-13 12:51:37 +0000732 // results in unpredictable behaviour
Simon Atanasyana9e87652018-09-19 18:46:29 +0000733 if (InMicroMipsMode && (Opcode == Mips::LWP_MM || Opcode == Mips::SWP_MM ||
734 Opcode == Mips::MOVEP_MM))
Zoran Jovanovic3a7654c2018-06-13 12:51:37 +0000735 continue;
Jozef Koleke7cad7a2015-01-13 15:59:17 +0000736
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000737 Filler = CurrI;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000738 return true;
739 }
740
741 return false;
742}
743
Simon Dardisae201082018-05-11 16:13:53 +0000744bool MipsDelaySlotFiller::searchBackward(MachineBasicBlock &MBB,
745 MachineInstr &Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000746 if (DisableBackwardSearch)
747 return false;
748
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000749 auto *Fn = MBB.getParent();
750 RegDefsUses RegDU(*Fn->getSubtarget().getRegisterInfo());
Matthias Braun941a7052016-07-28 18:40:00 +0000751 MemDefsUses MemDU(Fn->getDataLayout(), &Fn->getFrameInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000752 ReverseIter Filler;
Akira Hatanakaf815db52013-03-01 00:26:14 +0000753
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000754 RegDU.init(Slot);
Akira Hatanakaf815db52013-03-01 00:26:14 +0000755
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000756 MachineBasicBlock::iterator SlotI = Slot;
757 if (!searchRange(MBB, ++SlotI.getReverse(), MBB.rend(), RegDU, MemDU, Slot,
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000758 Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000759 return false;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000760
Duncan P. N. Exon Smith18720962016-09-11 18:51:28 +0000761 MBB.splice(std::next(SlotI), &MBB, Filler.getReverse());
762 MIBundleBuilder(MBB, SlotI, std::next(SlotI, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000763 ++UsefulSlots;
764 return true;
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000765}
766
Simon Dardisae201082018-05-11 16:13:53 +0000767bool MipsDelaySlotFiller::searchForward(MachineBasicBlock &MBB,
768 Iter Slot) const {
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000769 // Can handle only calls.
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000770 if (DisableForwardSearch || !Slot->isCall())
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000771 return false;
772
Eric Christopher96e72c62015-01-29 23:27:36 +0000773 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000774 NoMemInstr NM;
775 Iter Filler;
776
777 RegDU.setCallerSaved(*Slot);
778
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000779 if (!searchRange(MBB, std::next(Slot), MBB.end(), RegDU, NM, Slot, Filler))
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000780 return false;
Akira Hatanaka5d4e4ea2011-10-05 01:23:39 +0000781
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000782 MBB.splice(std::next(Slot), &MBB, Filler);
783 MIBundleBuilder(MBB, Slot, std::next(Slot, 2));
Akira Hatanaka4c0a7122013-10-07 19:33:02 +0000784 ++UsefulSlots;
785 return true;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000786}
787
Simon Dardisae201082018-05-11 16:13:53 +0000788bool MipsDelaySlotFiller::searchSuccBBs(MachineBasicBlock &MBB,
789 Iter Slot) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000790 if (DisableSuccBBSearch)
791 return false;
792
793 MachineBasicBlock *SuccBB = selectSuccBB(MBB);
794
795 if (!SuccBB)
796 return false;
797
Eric Christopher96e72c62015-01-29 23:27:36 +0000798 RegDefsUses RegDU(*MBB.getParent()->getSubtarget().getRegisterInfo());
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000799 bool HasMultipleSuccs = false;
800 BB2BrMap BrMap;
Benjamin Kramerd2da7202014-04-21 09:34:48 +0000801 std::unique_ptr<InspectMemInstr> IM;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000802 Iter Filler;
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000803 auto *Fn = MBB.getParent();
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000804
805 // Iterate over SuccBB's predecessor list.
806 for (MachineBasicBlock::pred_iterator PI = SuccBB->pred_begin(),
807 PE = SuccBB->pred_end(); PI != PE; ++PI)
808 if (!examinePred(**PI, *SuccBB, RegDU, HasMultipleSuccs, BrMap))
809 return false;
810
811 // Do not allow moving instructions which have unallocatable register operands
812 // across basic block boundaries.
Mehdi Aminibd7287e2015-07-16 06:11:10 +0000813 RegDU.setUnallocatableRegs(*Fn);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000814
815 // Only allow moving loads from stack or constants if any of the SuccBB's
816 // predecessors have multiple successors.
817 if (HasMultipleSuccs) {
818 IM.reset(new LoadFromStackOrConst());
819 } else {
Matthias Braun941a7052016-07-28 18:40:00 +0000820 const MachineFrameInfo &MFI = Fn->getFrameInfo();
821 IM.reset(new MemDefsUses(Fn->getDataLayout(), &MFI));
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000822 }
823
Vasileios Kalintiris87614902015-03-04 12:37:58 +0000824 if (!searchRange(MBB, SuccBB->begin(), SuccBB->end(), RegDU, *IM, Slot,
825 Filler))
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000826 return false;
827
828 insertDelayFiller(Filler, BrMap);
829 addLiveInRegs(Filler, *SuccBB);
830 Filler->eraseFromParent();
831
832 return true;
833}
834
Simon Dardisae201082018-05-11 16:13:53 +0000835MachineBasicBlock *
836MipsDelaySlotFiller::selectSuccBB(MachineBasicBlock &B) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000837 if (B.succ_empty())
Craig Topper062a2ba2014-04-25 05:30:21 +0000838 return nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000839
840 // Select the successor with the larget edge weight.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000841 auto &Prob = getAnalysis<MachineBranchProbabilityInfo>();
Cong Hou1938f2e2015-11-24 08:51:23 +0000842 MachineBasicBlock *S = *std::max_element(
843 B.succ_begin(), B.succ_end(),
844 [&](const MachineBasicBlock *Dst0, const MachineBasicBlock *Dst1) {
845 return Prob.getEdgeProbability(&B, Dst0) <
846 Prob.getEdgeProbability(&B, Dst1);
847 });
Reid Kleckner0e288232015-08-27 23:27:47 +0000848 return S->isEHPad() ? nullptr : S;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000849}
850
851std::pair<MipsInstrInfo::BranchType, MachineInstr *>
Simon Dardisae201082018-05-11 16:13:53 +0000852MipsDelaySlotFiller::getBranch(MachineBasicBlock &MBB,
853 const MachineBasicBlock &Dst) const {
Eric Christopher6b6db772015-02-02 23:03:43 +0000854 const MipsInstrInfo *TII =
855 MBB.getParent()->getSubtarget<MipsSubtarget>().getInstrInfo();
Craig Topper062a2ba2014-04-25 05:30:21 +0000856 MachineBasicBlock *TrueBB = nullptr, *FalseBB = nullptr;
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000857 SmallVector<MachineInstr*, 2> BranchInstrs;
858 SmallVector<MachineOperand, 2> Cond;
859
860 MipsInstrInfo::BranchType R =
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000861 TII->analyzeBranch(MBB, TrueBB, FalseBB, Cond, false, BranchInstrs);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000862
863 if ((R == MipsInstrInfo::BT_None) || (R == MipsInstrInfo::BT_NoBranch))
Craig Topper062a2ba2014-04-25 05:30:21 +0000864 return std::make_pair(R, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000865
866 if (R != MipsInstrInfo::BT_CondUncond) {
867 if (!hasUnoccupiedSlot(BranchInstrs[0]))
Craig Topper062a2ba2014-04-25 05:30:21 +0000868 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000869
870 assert(((R != MipsInstrInfo::BT_Uncond) || (TrueBB == &Dst)));
871
872 return std::make_pair(R, BranchInstrs[0]);
873 }
874
875 assert((TrueBB == &Dst) || (FalseBB == &Dst));
876
877 // Examine the conditional branch. See if its slot is occupied.
878 if (hasUnoccupiedSlot(BranchInstrs[0]))
879 return std::make_pair(MipsInstrInfo::BT_Cond, BranchInstrs[0]);
880
881 // If that fails, try the unconditional branch.
882 if (hasUnoccupiedSlot(BranchInstrs[1]) && (FalseBB == &Dst))
883 return std::make_pair(MipsInstrInfo::BT_Uncond, BranchInstrs[1]);
884
Craig Topper062a2ba2014-04-25 05:30:21 +0000885 return std::make_pair(MipsInstrInfo::BT_None, nullptr);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000886}
887
Simon Dardisae201082018-05-11 16:13:53 +0000888bool MipsDelaySlotFiller::examinePred(MachineBasicBlock &Pred,
889 const MachineBasicBlock &Succ,
890 RegDefsUses &RegDU,
891 bool &HasMultipleSuccs,
892 BB2BrMap &BrMap) const {
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000893 std::pair<MipsInstrInfo::BranchType, MachineInstr *> P =
Simon Dardisae201082018-05-11 16:13:53 +0000894 getBranch(Pred, Succ);
Akira Hatanaka8f7bfb32013-03-01 02:03:51 +0000895
896 // Return if either getBranch wasn't able to analyze the branches or there
897 // were no branches with unoccupied slots.
898 if (P.first == MipsInstrInfo::BT_None)
899 return false;
900
901 if ((P.first != MipsInstrInfo::BT_Uncond) &&
902 (P.first != MipsInstrInfo::BT_NoBranch)) {
903 HasMultipleSuccs = true;
904 RegDU.addLiveOut(Pred, Succ);
905 }
906
907 BrMap[&Pred] = P.second;
908 return true;
909}
910
Simon Dardisae201082018-05-11 16:13:53 +0000911bool MipsDelaySlotFiller::delayHasHazard(const MachineInstr &Candidate,
912 RegDefsUses &RegDU,
913 InspectMemInstr &IM) const {
Vasileios Kalintirisbb60cfb2015-04-17 12:01:02 +0000914 assert(!Candidate.isKill() &&
915 "KILL instructions should have been eliminated at this point.");
916
917 bool HasHazard = Candidate.isImplicitDef();
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000918
Akira Hatanakae01ff9d2013-03-01 00:50:52 +0000919 HasHazard |= IM.hasHazard(Candidate);
Akira Hatanaka979899e2013-02-26 01:30:05 +0000920 HasHazard |= RegDU.update(Candidate, 0, Candidate.getNumOperands());
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000921
Akira Hatanaka06bd1382013-02-14 23:40:57 +0000922 return HasHazard;
Akira Hatanakaf2619ee2011-09-29 23:52:13 +0000923}
924
Simon Dardisae201082018-05-11 16:13:53 +0000925bool MipsDelaySlotFiller::terminateSearch(const MachineInstr &Candidate) const {
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000926 return (Candidate.isTerminator() || Candidate.isCall() ||
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000927 Candidate.isPosition() || Candidate.isInlineAsm() ||
Akira Hatanakadfd2f242013-02-14 23:11:24 +0000928 Candidate.hasUnmodeledSideEffects());
929}
Eugene Zelenko926883e2017-02-01 01:22:51 +0000930
931/// createMipsDelaySlotFillerPass - Returns a pass that fills in delay
932/// slots in Mips MachineFunctions
Simon Dardisae201082018-05-11 16:13:53 +0000933FunctionPass *llvm::createMipsDelaySlotFillerPass() { return new MipsDelaySlotFiller(); }