blob: d01ff0168825c3cdea16ebdff2ddcd32b28667a2 [file] [log] [blame]
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001//===- HexagonHardwareLoops.cpp - Identify and generate hardware loops ----===//
Tony Linthicum1213a7a2011-12-12 21:14:40 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass identifies loops where we can generate the Hexagon hardware
11// loop instruction. The hardware loop can perform loop branches with a
12// zero-cycle overhead.
13//
14// The pattern that defines the induction variable can changed depending on
15// prior optimizations. For example, the IndVarSimplify phase run by 'opt'
16// normalizes induction variables, and the Loop Strength Reduction pass
17// run by 'llc' may also make changes to the induction variable.
18// The pattern detected by this phase is due to running Strength Reduction.
19//
20// Criteria for hardware loops:
21// - Countable loops (w/ ind. var for a trip count)
22// - Assumes loops are normalized by IndVarSimplify
23// - Try inner-most loops first
Tony Linthicum1213a7a2011-12-12 21:14:40 +000024// - No function calls in loops.
25//
26//===----------------------------------------------------------------------===//
27
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000028#include "HexagonInstrInfo.h"
Eric Christopher2c44f432015-02-02 19:05:28 +000029#include "HexagonSubtarget.h"
Eugene Zelenko4d060b72017-07-29 00:56:56 +000030#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/STLExtras.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000032#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/SmallVector.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000034#include "llvm/ADT/Statistic.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000035#include "llvm/ADT/StringRef.h"
36#include "llvm/CodeGen/MachineBasicBlock.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000037#include "llvm/CodeGen/MachineDominators.h"
38#include "llvm/CodeGen/MachineFunction.h"
39#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000040#include "llvm/CodeGen/MachineInstr.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000041#include "llvm/CodeGen/MachineInstrBuilder.h"
42#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000043#include "llvm/CodeGen/MachineOperand.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000044#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000045#include "llvm/IR/Constants.h"
46#include "llvm/IR/DebugLoc.h"
47#include "llvm/Pass.h"
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000048#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000049#include "llvm/Support/Debug.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000050#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/MathExtras.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000052#include "llvm/Support/raw_ostream.h"
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000053#include "llvm/Target/TargetRegisterInfo.h"
54#include <cassert>
55#include <cstdint>
56#include <cstdlib>
57#include <iterator>
58#include <map>
59#include <set>
Eugene Zelenko4d060b72017-07-29 00:56:56 +000060#include <string>
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000061#include <utility>
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000062#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000063
64using namespace llvm;
65
Chandler Carruth84e68b22014-04-22 02:41:26 +000066#define DEBUG_TYPE "hwloops"
67
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000068#ifndef NDEBUG
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000069static cl::opt<int> HWLoopLimit("hexagon-max-hwloop", cl::Hidden, cl::init(-1));
70
71// Option to create preheader only for a specific function.
72static cl::opt<std::string> PHFn("hexagon-hwloop-phfn", cl::Hidden,
73 cl::init(""));
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000074#endif
75
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000076// Option to create a preheader if one doesn't exist.
77static cl::opt<bool> HWCreatePreheader("hexagon-hwloop-preheader",
78 cl::Hidden, cl::init(true),
79 cl::desc("Add a preheader to a hardware loop if one doesn't exist"));
80
Krzysztof Parzyszek06a2b6b2016-07-27 21:20:54 +000081// Turn it off by default. If a preheader block is not created here, the
82// software pipeliner may be unable to find a block suitable to serve as
83// a preheader. In that case SWP will not run.
84static cl::opt<bool> SpecPreheader("hwloop-spec-preheader", cl::init(false),
85 cl::Hidden, cl::ZeroOrMore, cl::desc("Allow speculation of preheader "
86 "instructions"));
87
Tony Linthicum1213a7a2011-12-12 21:14:40 +000088STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
89
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000090namespace llvm {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000091
Colin LeMahieu56efafc2015-06-15 19:05:35 +000092 FunctionPass *createHexagonHardwareLoops();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000093 void initializeHexagonHardwareLoopsPass(PassRegistry&);
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000094
95} // end namespace llvm
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000096
Tony Linthicum1213a7a2011-12-12 21:14:40 +000097namespace {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +000098
Tony Linthicum1213a7a2011-12-12 21:14:40 +000099 class CountValue;
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000100
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000101 struct HexagonHardwareLoops : public MachineFunctionPass {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000102 MachineLoopInfo *MLI;
103 MachineRegisterInfo *MRI;
104 MachineDominatorTree *MDT;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000105 const HexagonInstrInfo *TII;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000106 const HexagonRegisterInfo *TRI;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000107#ifndef NDEBUG
108 static int Counter;
109#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000110
111 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000112 static char ID;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000113
Krzysztof Parzyszek3818aea2017-10-20 16:56:33 +0000114 HexagonHardwareLoops() : MachineFunctionPass(ID) {}
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000115
Craig Topper906c2cd2014-04-29 07:58:16 +0000116 bool runOnMachineFunction(MachineFunction &MF) override;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000117
Mehdi Amini117296c2016-10-01 02:56:57 +0000118 StringRef getPassName() const override { return "Hexagon Hardware Loops"; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000119
Craig Topper906c2cd2014-04-29 07:58:16 +0000120 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000121 AU.addRequired<MachineDominatorTree>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000122 AU.addRequired<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000123 MachineFunctionPass::getAnalysisUsage(AU);
124 }
125
126 private:
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000127 using LoopFeederMap = std::map<unsigned, MachineInstr *>;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000128
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000129 /// Kinds of comparisons in the compare instructions.
130 struct Comparison {
131 enum Kind {
132 EQ = 0x01,
133 NE = 0x02,
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000134 L = 0x04,
135 G = 0x08,
136 U = 0x40,
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000137 LTs = L,
138 LEs = L | EQ,
139 GTs = G,
140 GEs = G | EQ,
141 LTu = L | U,
142 LEu = L | EQ | U,
143 GTu = G | U,
144 GEu = G | EQ | U
145 };
146
147 static Kind getSwappedComparison(Kind Cmp) {
148 assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
149 if ((Cmp & L) || (Cmp & G))
150 return (Kind)(Cmp ^ (L|G));
151 return Cmp;
152 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000153
154 static Kind getNegatedComparison(Kind Cmp) {
155 if ((Cmp & L) || (Cmp & G))
156 return (Kind)((Cmp ^ (L | G)) ^ EQ);
157 if ((Cmp & NE) || (Cmp & EQ))
158 return (Kind)(Cmp ^ (EQ | NE));
159 return (Kind)0;
160 }
161
162 static bool isSigned(Kind Cmp) {
163 return (Cmp & (L | G) && !(Cmp & U));
164 }
165
166 static bool isUnsigned(Kind Cmp) {
167 return (Cmp & U);
168 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000169 };
170
171 /// \brief Find the register that contains the loop controlling
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000172 /// induction variable.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000173 /// If successful, it will return true and set the \p Reg, \p IVBump
174 /// and \p IVOp arguments. Otherwise it will return false.
175 /// The returned induction register is the register R that follows the
176 /// following induction pattern:
177 /// loop:
178 /// R = phi ..., [ R.next, LatchBlock ]
179 /// R.next = R + #bump
180 /// if (R.next < #N) goto loop
181 /// IVBump is the immediate value added to R, and IVOp is the instruction
182 /// "R.next = R + #bump".
183 bool findInductionRegister(MachineLoop *L, unsigned &Reg,
184 int64_t &IVBump, MachineInstr *&IVOp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000185
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000186 /// \brief Return the comparison kind for the specified opcode.
187 Comparison::Kind getComparisonKind(unsigned CondOpc,
188 MachineOperand *InitialValue,
189 const MachineOperand *Endvalue,
190 int64_t IVBump) const;
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000191
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000192 /// \brief Analyze the statements in a loop to determine if the loop
193 /// has a computable trip count and, if so, return a value that represents
194 /// the trip count expression.
195 CountValue *getLoopTripCount(MachineLoop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000196 SmallVectorImpl<MachineInstr *> &OldInsts);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000197
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000198 /// \brief Return the expression that represents the number of times
199 /// a loop iterates. The function takes the operands that represent the
200 /// loop start value, loop end value, and induction value. Based upon
201 /// these operands, the function attempts to compute the trip count.
202 /// If the trip count is not directly available (as an immediate value,
203 /// or a register), the function will attempt to insert computation of it
204 /// to the loop's preheader.
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000205 CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
206 const MachineOperand *End, unsigned IVReg,
207 int64_t IVBump, Comparison::Kind Cmp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000208
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000209 /// \brief Return true if the instruction is not valid within a hardware
210 /// loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000211 bool isInvalidLoopOperation(const MachineInstr *MI,
212 bool IsInnerHWLoop) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000213
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000214 /// \brief Return true if the loop contains an instruction that inhibits
215 /// using the hardware loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000216 bool containsInvalidInstruction(MachineLoop *L, bool IsInnerHWLoop) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000217
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000218 /// \brief Given a loop, check if we can convert it to a hardware loop.
219 /// If so, then perform the conversion and return true.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000220 bool convertToHardwareLoop(MachineLoop *L, bool &L0used, bool &L1used);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000221
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000222 /// \brief Return true if the instruction is now dead.
223 bool isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000224 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000225
226 /// \brief Remove the instruction if it is now dead.
227 void removeIfDead(MachineInstr *MI);
228
229 /// \brief Make sure that the "bump" instruction executes before the
230 /// compare. We need that for the IV fixup, so that the compare
231 /// instruction would not use a bumped value that has not yet been
232 /// defined. If the instructions are out of order, try to reorder them.
233 bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
234
Brendon Cahoon9376e992015-05-14 14:15:08 +0000235 /// \brief Return true if MO and MI pair is visited only once. If visited
236 /// more than once, this indicates there is recursion. In such a case,
237 /// return false.
238 bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *A, MachineInstr *MI,
239 const MachineOperand *MO,
240 LoopFeederMap &LoopFeederPhi) const;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000241
Brendon Cahoon9376e992015-05-14 14:15:08 +0000242 /// \brief Return true if the Phi may generate a value that may underflow,
243 /// or may wrap.
244 bool phiMayWrapOrUnderflow(MachineInstr *Phi, const MachineOperand *EndVal,
245 MachineBasicBlock *MBB, MachineLoop *L,
246 LoopFeederMap &LoopFeederPhi) const;
247
248 /// \brief Return true if the induction variable may underflow an unsigned
249 /// value in the first iteration.
250 bool loopCountMayWrapOrUnderFlow(const MachineOperand *InitVal,
251 const MachineOperand *EndVal,
252 MachineBasicBlock *MBB, MachineLoop *L,
253 LoopFeederMap &LoopFeederPhi) const;
254
255 /// \brief Check if the given operand has a compile-time known constant
256 /// value. Return true if yes, and false otherwise. When returning true, set
257 /// Val to the corresponding constant value.
258 bool checkForImmediate(const MachineOperand &MO, int64_t &Val) const;
259
260 /// \brief Check if the operand has a compile-time known constant value.
261 bool isImmediate(const MachineOperand &MO) const {
262 int64_t V;
263 return checkForImmediate(MO, V);
264 }
265
266 /// \brief Return the immediate for the specified operand.
267 int64_t getImmediate(const MachineOperand &MO) const {
268 int64_t V;
269 if (!checkForImmediate(MO, V))
270 llvm_unreachable("Invalid operand");
271 return V;
272 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000273
274 /// \brief Reset the given machine operand to now refer to a new immediate
275 /// value. Assumes that the operand was already referencing an immediate
276 /// value, either directly, or via a register.
277 void setImmediate(MachineOperand &MO, int64_t Val);
278
Mandeep Singh Grang1be19e62017-09-15 20:01:43 +0000279 /// \brief Fix the data flow of the induction variable.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000280 /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
281 /// |
282 /// +-> back to phi
283 /// where "bump" is the increment of the induction variable:
284 /// iv = iv + #const.
285 /// Due to some prior code transformations, the actual flow may look
286 /// like this:
287 /// phi -+-> bump ---> back to phi
288 /// |
289 /// +-> comparison-in-latch (against upper_bound-bump),
290 /// i.e. the comparison that controls the loop execution may be using
291 /// the value of the induction variable from before the increment.
292 ///
293 /// Return true if the loop's flow is the desired one (i.e. it's
294 /// either been fixed, or no fixing was necessary).
295 /// Otherwise, return false. This can happen if the induction variable
296 /// couldn't be identified, or if the value in the latch's comparison
297 /// cannot be adjusted to reflect the post-bump value.
298 bool fixupInductionVariable(MachineLoop *L);
299
300 /// \brief Given a loop, if it does not have a preheader, create one.
301 /// Return the block that is the preheader.
302 MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000303 };
304
305 char HexagonHardwareLoops::ID = 0;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000306#ifndef NDEBUG
307 int HexagonHardwareLoops::Counter = 0;
308#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000309
Sid Manning67a89362014-08-28 14:16:32 +0000310 /// \brief Abstraction for a trip count of a loop. A smaller version
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000311 /// of the MachineOperand class without the concerns of changing the
312 /// operand representation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000313 class CountValue {
314 public:
315 enum CountValueType {
316 CV_Register,
317 CV_Immediate
318 };
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000319
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000320 private:
321 CountValueType Kind;
322 union Values {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000323 struct {
324 unsigned Reg;
325 unsigned Sub;
326 } R;
327 unsigned ImmVal;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000328 } Contents;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000329
330 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000331 explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
332 Kind = t;
333 if (Kind == CV_Register) {
334 Contents.R.Reg = v;
335 Contents.R.Sub = u;
336 } else {
337 Contents.ImmVal = v;
338 }
339 }
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000340
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000341 bool isReg() const { return Kind == CV_Register; }
342 bool isImm() const { return Kind == CV_Immediate; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000343
344 unsigned getReg() const {
345 assert(isReg() && "Wrong CountValue accessor");
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000346 return Contents.R.Reg;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000347 }
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000348
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000349 unsigned getSubReg() const {
350 assert(isReg() && "Wrong CountValue accessor");
351 return Contents.R.Sub;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000352 }
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000353
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000354 unsigned getImm() const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000355 assert(isImm() && "Wrong CountValue accessor");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000356 return Contents.ImmVal;
357 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000358
Eric Christopher2c44f432015-02-02 19:05:28 +0000359 void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000360 if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
361 if (isImm()) { OS << Contents.ImmVal; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000362 }
363 };
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000364
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000365} // end anonymous namespace
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000366
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000367INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
368 "Hexagon Hardware Loops", false, false)
369INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
370INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
371INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
372 "Hexagon Hardware Loops", false, false)
373
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000374FunctionPass *llvm::createHexagonHardwareLoops() {
375 return new HexagonHardwareLoops();
376}
377
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000378bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
379 DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
Andrew Kaylor5b444a22016-04-26 19:46:28 +0000380 if (skipFunction(*MF.getFunction()))
381 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000382
383 bool Changed = false;
384
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000385 MLI = &getAnalysis<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000386 MRI = &MF.getRegInfo();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000387 MDT = &getAnalysis<MachineDominatorTree>();
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000388 const HexagonSubtarget &HST = MF.getSubtarget<HexagonSubtarget>();
389 TII = HST.getInstrInfo();
390 TRI = HST.getRegisterInfo();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000391
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000392 for (auto &L : *MLI)
393 if (!L->getParentLoop()) {
394 bool L0Used = false;
395 bool L1Used = false;
396 Changed |= convertToHardwareLoop(L, L0Used, L1Used);
397 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000398
399 return Changed;
400}
401
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000402bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
403 unsigned &Reg,
404 int64_t &IVBump,
405 MachineInstr *&IVOp
406 ) const {
407 MachineBasicBlock *Header = L->getHeader();
Sjoerd Meijer58156712016-08-15 08:22:42 +0000408 MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000409 MachineBasicBlock *Latch = L->getLoopLatch();
Sjoerd Meijer58156712016-08-15 08:22:42 +0000410 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000411 if (!Header || !Preheader || !Latch || !ExitingBlock)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000412 return false;
413
414 // This pair represents an induction register together with an immediate
415 // value that will be added to it in each loop iteration.
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000416 using RegisterBump = std::pair<unsigned, int64_t>;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000417
418 // Mapping: R.next -> (R, bump), where R, R.next and bump are derived
419 // from an induction operation
420 // R.next = R + bump
421 // where bump is an immediate value.
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000422 using InductionMap = std::map<unsigned, RegisterBump>;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000423
424 InductionMap IndMap;
425
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000426 using instr_iterator = MachineBasicBlock::instr_iterator;
427
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000428 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
429 I != E && I->isPHI(); ++I) {
430 MachineInstr *Phi = &*I;
431
432 // Have a PHI instruction. Get the operand that corresponds to the
433 // latch block, and see if is a result of an addition of form "reg+imm",
434 // where the "reg" is defined by the PHI node we are looking at.
435 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
436 if (Phi->getOperand(i+1).getMBB() != Latch)
437 continue;
438
439 unsigned PhiOpReg = Phi->getOperand(i).getReg();
440 MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000441
Sjoerd Meijer724023a2016-09-14 08:20:03 +0000442 if (DI->getDesc().isAdd()) {
Brendon Cahoon9376e992015-05-14 14:15:08 +0000443 // If the register operand to the add is the PHI we're looking at, this
444 // meets the induction pattern.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000445 unsigned IndReg = DI->getOperand(1).getReg();
Brendon Cahoon9376e992015-05-14 14:15:08 +0000446 MachineOperand &Opnd2 = DI->getOperand(2);
447 int64_t V;
448 if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000449 unsigned UpdReg = DI->getOperand(0).getReg();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000450 IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
451 }
452 }
453 } // for (i)
454 } // for (instr)
455
456 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000457 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000458 bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000459 if (NotAnalyzed)
460 return false;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000461
Brendon Cahoondf43e682015-05-08 16:16:29 +0000462 unsigned PredR, PredPos, PredRegFlags;
463 if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
464 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000465
466 MachineInstr *PredI = MRI->getVRegDef(PredR);
467 if (!PredI->isCompare())
468 return false;
469
470 unsigned CmpReg1 = 0, CmpReg2 = 0;
471 int CmpImm = 0, CmpMask = 0;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000472 bool CmpAnalyzed =
473 TII->analyzeCompare(*PredI, CmpReg1, CmpReg2, CmpMask, CmpImm);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000474 // Fail if the compare was not analyzed, or it's not comparing a register
475 // with an immediate value. Not checking the mask here, since we handle
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000476 // the individual compare opcodes (including A4_cmpb*) later on.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000477 if (!CmpAnalyzed)
478 return false;
479
480 // Exactly one of the input registers to the comparison should be among
481 // the induction registers.
482 InductionMap::iterator IndMapEnd = IndMap.end();
483 InductionMap::iterator F = IndMapEnd;
484 if (CmpReg1 != 0) {
485 InductionMap::iterator F1 = IndMap.find(CmpReg1);
486 if (F1 != IndMapEnd)
487 F = F1;
488 }
489 if (CmpReg2 != 0) {
490 InductionMap::iterator F2 = IndMap.find(CmpReg2);
491 if (F2 != IndMapEnd) {
492 if (F != IndMapEnd)
493 return false;
494 F = F2;
495 }
496 }
497 if (F == IndMapEnd)
498 return false;
499
500 Reg = F->second.first;
501 IVBump = F->second.second;
502 IVOp = MRI->getVRegDef(F->first);
503 return true;
504}
505
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000506// Return the comparison kind for the specified opcode.
507HexagonHardwareLoops::Comparison::Kind
508HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
509 MachineOperand *InitialValue,
510 const MachineOperand *EndValue,
511 int64_t IVBump) const {
512 Comparison::Kind Cmp = (Comparison::Kind)0;
513 switch (CondOpc) {
514 case Hexagon::C2_cmpeqi:
515 case Hexagon::C2_cmpeq:
516 case Hexagon::C2_cmpeqp:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000517 Cmp = Comparison::EQ;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000518 break;
519 case Hexagon::C4_cmpneq:
520 case Hexagon::C4_cmpneqi:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000521 Cmp = Comparison::NE;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000522 break;
523 case Hexagon::C4_cmplte:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000524 Cmp = Comparison::LEs;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000525 break;
526 case Hexagon::C4_cmplteu:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000527 Cmp = Comparison::LEu;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000528 break;
529 case Hexagon::C2_cmpgtui:
530 case Hexagon::C2_cmpgtu:
531 case Hexagon::C2_cmpgtup:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000532 Cmp = Comparison::GTu;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000533 break;
534 case Hexagon::C2_cmpgti:
535 case Hexagon::C2_cmpgt:
536 case Hexagon::C2_cmpgtp:
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000537 Cmp = Comparison::GTs;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000538 break;
539 default:
540 return (Comparison::Kind)0;
541 }
542 return Cmp;
543}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000544
545/// \brief Analyze the statements in a loop to determine if the loop has
546/// a computable trip count and, if so, return a value that represents
547/// the trip count expression.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000548///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000549/// This function iterates over the phi nodes in the loop to check for
550/// induction variable patterns that are used in the calculation for
551/// the number of time the loop is executed.
552CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000553 SmallVectorImpl<MachineInstr *> &OldInsts) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000554 MachineBasicBlock *TopMBB = L->getTopBlock();
555 MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
556 assert(PI != TopMBB->pred_end() &&
557 "Loop must have more than one incoming edge!");
558 MachineBasicBlock *Backedge = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000559 if (PI == TopMBB->pred_end()) // dead loop?
Craig Topper062a2ba2014-04-25 05:30:21 +0000560 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000561 MachineBasicBlock *Incoming = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000562 if (PI != TopMBB->pred_end()) // multiple backedges?
Craig Topper062a2ba2014-04-25 05:30:21 +0000563 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000564
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000565 // Make sure there is one incoming and one backedge and determine which
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000566 // is which.
567 if (L->contains(Incoming)) {
568 if (L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000569 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000570 std::swap(Incoming, Backedge);
571 } else if (!L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000572 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000573
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000574 // Look for the cmp instruction to determine if we can get a useful trip
575 // count. The trip count can be either a register or an immediate. The
576 // location of the value depends upon the type (reg or imm).
Sjoerd Meijer58156712016-08-15 08:22:42 +0000577 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000578 if (!ExitingBlock)
Craig Topper062a2ba2014-04-25 05:30:21 +0000579 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000580
581 unsigned IVReg = 0;
582 int64_t IVBump = 0;
583 MachineInstr *IVOp;
584 bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
585 if (!FoundIV)
Craig Topper062a2ba2014-04-25 05:30:21 +0000586 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000587
Sjoerd Meijer58156712016-08-15 08:22:42 +0000588 MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000589
Craig Topper062a2ba2014-04-25 05:30:21 +0000590 MachineOperand *InitialValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000591 MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000592 MachineBasicBlock *Latch = L->getLoopLatch();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000593 for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
594 MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
595 if (MBB == Preheader)
596 InitialValue = &IV_Phi->getOperand(i);
597 else if (MBB == Latch)
598 IVReg = IV_Phi->getOperand(i).getReg(); // Want IV reg after bump.
599 }
600 if (!InitialValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000601 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000602
603 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000604 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000605 bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000606 if (NotAnalyzed)
Craig Topper062a2ba2014-04-25 05:30:21 +0000607 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000608
609 MachineBasicBlock *Header = L->getHeader();
610 // TB must be non-null. If FB is also non-null, one of them must be
611 // the header. Otherwise, branch to TB could be exiting the loop, and
612 // the fall through can go to the header.
Brendon Cahoon254e6562015-05-13 14:54:24 +0000613 assert (TB && "Exit block without a branch?");
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000614 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +0000615 MachineBasicBlock *LTB = nullptr, *LFB = nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000616 SmallVector<MachineOperand,2> LCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000617 bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000618 if (NotAnalyzed)
619 return nullptr;
620 if (TB == Latch)
Brendon Cahoon254e6562015-05-13 14:54:24 +0000621 TB = (LTB == Header) ? LTB : LFB;
622 else
623 FB = (LTB == Header) ? LTB: LFB;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000624 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000625 assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
626 if (!TB || (FB && TB != Header && FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000627 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000628
629 // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
630 // to put imm(0), followed by P in the vector Cond.
631 // If TB is not the header, it means that the "not-taken" path must lead
632 // to the header.
Brendon Cahoondf43e682015-05-08 16:16:29 +0000633 bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
634 unsigned PredReg, PredPos, PredRegFlags;
635 if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
636 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000637 MachineInstr *CondI = MRI->getVRegDef(PredReg);
638 unsigned CondOpc = CondI->getOpcode();
639
640 unsigned CmpReg1 = 0, CmpReg2 = 0;
641 int Mask = 0, ImmValue = 0;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000642 bool AnalyzedCmp =
643 TII->analyzeCompare(*CondI, CmpReg1, CmpReg2, Mask, ImmValue);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000644 if (!AnalyzedCmp)
Craig Topper062a2ba2014-04-25 05:30:21 +0000645 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000646
647 // The comparison operator type determines how we compute the loop
648 // trip count.
649 OldInsts.push_back(CondI);
650 OldInsts.push_back(IVOp);
651
652 // Sadly, the following code gets information based on the position
653 // of the operands in the compare instruction. This has to be done
654 // this way, because the comparisons check for a specific relationship
655 // between the operands (e.g. is-less-than), rather than to find out
656 // what relationship the operands are in (as on PPC).
657 Comparison::Kind Cmp;
658 bool isSwapped = false;
659 const MachineOperand &Op1 = CondI->getOperand(1);
660 const MachineOperand &Op2 = CondI->getOperand(2);
Craig Topper062a2ba2014-04-25 05:30:21 +0000661 const MachineOperand *EndValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000662
663 if (Op1.isReg()) {
664 if (Op2.isImm() || Op1.getReg() == IVReg)
665 EndValue = &Op2;
666 else {
667 EndValue = &Op1;
668 isSwapped = true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000669 }
670 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000671
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000672 if (!EndValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000673 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000674
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000675 Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
676 if (!Cmp)
677 return nullptr;
678 if (Negated)
679 Cmp = Comparison::getNegatedComparison(Cmp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000680 if (isSwapped)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000681 Cmp = Comparison::getSwappedComparison(Cmp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000682
683 if (InitialValue->isReg()) {
684 unsigned R = InitialValue->getReg();
685 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
Krzysztof Parzyszek3818aea2017-10-20 16:56:33 +0000686 if (!MDT->properlyDominates(DefBB, Header)) {
687 int64_t V;
688 if (!checkForImmediate(*InitialValue, V))
689 return nullptr;
690 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000691 OldInsts.push_back(MRI->getVRegDef(R));
692 }
693 if (EndValue->isReg()) {
694 unsigned R = EndValue->getReg();
695 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
Krzysztof Parzyszek3818aea2017-10-20 16:56:33 +0000696 if (!MDT->properlyDominates(DefBB, Header)) {
697 int64_t V;
698 if (!checkForImmediate(*EndValue, V))
699 return nullptr;
700 }
Brendon Cahoon485bea742015-05-14 17:31:40 +0000701 OldInsts.push_back(MRI->getVRegDef(R));
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000702 }
703
704 return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000705}
706
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000707/// \brief Helper function that returns the expression that represents the
708/// number of times a loop iterates. The function takes the operands that
709/// represent the loop start value, loop end value, and induction value.
710/// Based upon these operands, the function attempts to compute the trip count.
711CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
712 const MachineOperand *Start,
713 const MachineOperand *End,
714 unsigned IVReg,
715 int64_t IVBump,
716 Comparison::Kind Cmp) const {
717 // Cannot handle comparison EQ, i.e. while (A == B).
718 if (Cmp == Comparison::EQ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000719 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000720
721 // Check if either the start or end values are an assignment of an immediate.
722 // If so, use the immediate value rather than the register.
723 if (Start->isReg()) {
724 const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
Brendon Cahoon485bea742015-05-14 17:31:40 +0000725 if (StartValInstr && (StartValInstr->getOpcode() == Hexagon::A2_tfrsi ||
726 StartValInstr->getOpcode() == Hexagon::A2_tfrpi))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000727 Start = &StartValInstr->getOperand(1);
728 }
729 if (End->isReg()) {
730 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
Brendon Cahoon485bea742015-05-14 17:31:40 +0000731 if (EndValInstr && (EndValInstr->getOpcode() == Hexagon::A2_tfrsi ||
732 EndValInstr->getOpcode() == Hexagon::A2_tfrpi))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000733 End = &EndValInstr->getOperand(1);
734 }
735
Brendon Cahoon9376e992015-05-14 14:15:08 +0000736 if (!Start->isReg() && !Start->isImm())
737 return nullptr;
738 if (!End->isReg() && !End->isImm())
739 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000740
741 bool CmpLess = Cmp & Comparison::L;
742 bool CmpGreater = Cmp & Comparison::G;
743 bool CmpHasEqual = Cmp & Comparison::EQ;
744
745 // Avoid certain wrap-arounds. This doesn't detect all wrap-arounds.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000746 if (CmpLess && IVBump < 0)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000747 // Loop going while iv is "less" with the iv value going down. Must wrap.
Craig Topper062a2ba2014-04-25 05:30:21 +0000748 return nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000749
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000750 if (CmpGreater && IVBump > 0)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000751 // Loop going while iv is "greater" with the iv value going up. Must wrap.
Craig Topper062a2ba2014-04-25 05:30:21 +0000752 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000753
Brendon Cahoon9376e992015-05-14 14:15:08 +0000754 // Phis that may feed into the loop.
755 LoopFeederMap LoopFeederPhi;
756
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000757 // Check if the initial value may be zero and can be decremented in the first
Brendon Cahoon9376e992015-05-14 14:15:08 +0000758 // iteration. If the value is zero, the endloop instruction will not decrement
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000759 // the loop counter, so we shouldn't generate a hardware loop in this case.
Brendon Cahoon9376e992015-05-14 14:15:08 +0000760 if (loopCountMayWrapOrUnderFlow(Start, End, Loop->getLoopPreheader(), Loop,
761 LoopFeederPhi))
762 return nullptr;
763
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000764 if (Start->isImm() && End->isImm()) {
765 // Both, start and end are immediates.
766 int64_t StartV = Start->getImm();
767 int64_t EndV = End->getImm();
768 int64_t Dist = EndV - StartV;
769 if (Dist == 0)
Craig Topper062a2ba2014-04-25 05:30:21 +0000770 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000771
772 bool Exact = (Dist % IVBump) == 0;
773
774 if (Cmp == Comparison::NE) {
775 if (!Exact)
Craig Topper062a2ba2014-04-25 05:30:21 +0000776 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000777 if ((Dist < 0) ^ (IVBump < 0))
Craig Topper062a2ba2014-04-25 05:30:21 +0000778 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000779 }
780
781 // For comparisons that include the final value (i.e. include equality
782 // with the final value), we need to increase the distance by 1.
783 if (CmpHasEqual)
784 Dist = Dist > 0 ? Dist+1 : Dist-1;
785
Brendon Cahoon9376e992015-05-14 14:15:08 +0000786 // For the loop to iterate, CmpLess should imply Dist > 0. Similarly,
787 // CmpGreater should imply Dist < 0. These conditions could actually
788 // fail, for example, in unreachable code (which may still appear to be
789 // reachable in the CFG).
790 if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
791 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000792
793 // "Normalized" distance, i.e. with the bump set to +-1.
Brendon Cahoon9376e992015-05-14 14:15:08 +0000794 int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump - 1)) / IVBump
795 : (-Dist + (-IVBump - 1)) / (-IVBump);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000796 assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
797
798 uint64_t Count = Dist1;
799
800 if (Count > 0xFFFFFFFFULL)
Craig Topper062a2ba2014-04-25 05:30:21 +0000801 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000802
803 return new CountValue(CountValue::CV_Immediate, Count);
804 }
805
806 // A general case: Start and End are some values, but the actual
807 // iteration count may not be available. If it is not, insert
808 // a computation of it into the preheader.
809
810 // If the induction variable bump is not a power of 2, quit.
811 // Othwerise we'd need a general integer division.
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000812 if (!isPowerOf2_64(std::abs(IVBump)))
Craig Topper062a2ba2014-04-25 05:30:21 +0000813 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000814
Sjoerd Meijer58156712016-08-15 08:22:42 +0000815 MachineBasicBlock *PH = MLI->findLoopPreheader(Loop, SpecPreheader);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000816 assert (PH && "Should have a preheader by now");
817 MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000818 DebugLoc DL;
819 if (InsertPos != PH->end())
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000820 DL = InsertPos->getDebugLoc();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000821
822 // If Start is an immediate and End is a register, the trip count
823 // will be "reg - imm". Hexagon's "subtract immediate" instruction
824 // is actually "reg + -imm".
825
826 // If the loop IV is going downwards, i.e. if the bump is negative,
827 // then the iteration count (computed as End-Start) will need to be
828 // negated. To avoid the negation, just swap Start and End.
829 if (IVBump < 0) {
830 std::swap(Start, End);
831 IVBump = -IVBump;
832 }
833 // Cmp may now have a wrong direction, e.g. LEs may now be GEs.
834 // Signedness, and "including equality" are preserved.
835
836 bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
837 bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
838
839 int64_t StartV = 0, EndV = 0;
840 if (Start->isImm())
841 StartV = Start->getImm();
842 if (End->isImm())
843 EndV = End->getImm();
844
845 int64_t AdjV = 0;
846 // To compute the iteration count, we would need this computation:
847 // Count = (End - Start + (IVBump-1)) / IVBump
848 // or, when CmpHasEqual:
849 // Count = (End - Start + (IVBump-1)+1) / IVBump
850 // The "IVBump-1" part is the adjustment (AdjV). We can avoid
851 // generating an instruction specifically to add it if we can adjust
852 // the immediate values for Start or End.
853
854 if (CmpHasEqual) {
855 // Need to add 1 to the total iteration count.
856 if (Start->isImm())
857 StartV--;
858 else if (End->isImm())
859 EndV++;
860 else
861 AdjV += 1;
862 }
863
864 if (Cmp != Comparison::NE) {
865 if (Start->isImm())
866 StartV -= (IVBump-1);
867 else if (End->isImm())
868 EndV += (IVBump-1);
869 else
870 AdjV += (IVBump-1);
871 }
872
873 unsigned R = 0, SR = 0;
874 if (Start->isReg()) {
875 R = Start->getReg();
876 SR = Start->getSubReg();
877 } else {
878 R = End->getReg();
879 SR = End->getSubReg();
880 }
881 const TargetRegisterClass *RC = MRI->getRegClass(R);
882 // Hardware loops cannot handle 64-bit registers. If it's a double
883 // register, it has to have a subregister.
884 if (!SR && RC == &Hexagon::DoubleRegsRegClass)
Craig Topper062a2ba2014-04-25 05:30:21 +0000885 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000886 const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
887
888 // Compute DistR (register with the distance between Start and End).
889 unsigned DistR, DistSR;
890
891 // Avoid special case, where the start value is an imm(0).
892 if (Start->isImm() && StartV == 0) {
893 DistR = End->getReg();
894 DistSR = End->getSubReg();
895 } else {
Colin LeMahieue88447d2014-11-21 21:19:18 +0000896 const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
Colin LeMahieu27d50072015-02-05 18:38:08 +0000897 (RegToImm ? TII->get(Hexagon::A2_subri) :
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000898 TII->get(Hexagon::A2_addi));
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000899 if (RegToReg || RegToImm) {
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000900 unsigned SubR = MRI->createVirtualRegister(IntRC);
901 MachineInstrBuilder SubIB =
902 BuildMI(*PH, InsertPos, DL, SubD, SubR);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000903
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000904 if (RegToReg)
905 SubIB.addReg(End->getReg(), 0, End->getSubReg())
906 .addReg(Start->getReg(), 0, Start->getSubReg());
907 else
908 SubIB.addImm(EndV)
909 .addReg(Start->getReg(), 0, Start->getSubReg());
910 DistR = SubR;
911 } else {
912 // If the loop has been unrolled, we should use the original loop count
913 // instead of recalculating the value. This will avoid additional
914 // 'Add' instruction.
915 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
916 if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
917 EndValInstr->getOperand(2).getImm() == StartV) {
918 DistR = EndValInstr->getOperand(1).getReg();
919 } else {
920 unsigned SubR = MRI->createVirtualRegister(IntRC);
921 MachineInstrBuilder SubIB =
922 BuildMI(*PH, InsertPos, DL, SubD, SubR);
923 SubIB.addReg(End->getReg(), 0, End->getSubReg())
924 .addImm(-StartV);
925 DistR = SubR;
926 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000927 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000928 DistSR = 0;
929 }
930
931 // From DistR, compute AdjR (register with the adjusted distance).
932 unsigned AdjR, AdjSR;
933
934 if (AdjV == 0) {
935 AdjR = DistR;
936 AdjSR = DistSR;
937 } else {
938 // Generate CountR = ADD DistR, AdjVal
939 unsigned AddR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000940 MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000941 BuildMI(*PH, InsertPos, DL, AddD, AddR)
942 .addReg(DistR, 0, DistSR)
943 .addImm(AdjV);
944
945 AdjR = AddR;
946 AdjSR = 0;
947 }
948
949 // From AdjR, compute CountR (register with the final count).
950 unsigned CountR, CountSR;
951
952 if (IVBump == 1) {
953 CountR = AdjR;
954 CountSR = AdjSR;
955 } else {
956 // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
957 unsigned Shift = Log2_32(IVBump);
958
959 // Generate NormR = LSR DistR, Shift.
960 unsigned LsrR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuaa1bade2014-12-16 23:36:15 +0000961 const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000962 BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
963 .addReg(AdjR, 0, AdjSR)
964 .addImm(Shift);
965
966 CountR = LsrR;
967 CountSR = 0;
968 }
969
970 return new CountValue(CountValue::CV_Register, CountR, CountSR);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000971}
972
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000973/// \brief Return true if the operation is invalid within hardware loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000974bool HexagonHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI,
975 bool IsInnerHWLoop) const {
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000976 // Call is not allowed because the callee may use a hardware loop except for
977 // the case when the call never returns.
Krzysztof Parzyszek1b689da2016-08-11 21:14:25 +0000978 if (MI->getDesc().isCall())
979 return !TII->doesNotReturn(*MI);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000980
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000981 // Check if the instruction defines a hardware loop register.
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000982 using namespace Hexagon;
Eugene Zelenko4d060b72017-07-29 00:56:56 +0000983
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000984 static const unsigned Regs01[] = { LC0, SA0, LC1, SA1 };
985 static const unsigned Regs1[] = { LC1, SA1 };
986 auto CheckRegs = IsInnerHWLoop ? makeArrayRef(Regs01, array_lengthof(Regs01))
987 : makeArrayRef(Regs1, array_lengthof(Regs1));
988 for (unsigned R : CheckRegs)
989 if (MI->modifiesRegister(R, TRI))
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000990 return true;
Krzysztof Parzyszek1aaf41a2017-02-17 22:14:51 +0000991
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000992 return false;
993}
994
Brendon Cahoond11c92a2015-05-13 17:56:03 +0000995/// \brief Return true if the loop contains an instruction that inhibits
996/// the use of the hardware loop instruction.
997bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
998 bool IsInnerHWLoop) const {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000999 const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001000 DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001001 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1002 MachineBasicBlock *MBB = Blocks[i];
1003 for (MachineBasicBlock::iterator
1004 MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
1005 const MachineInstr *MI = &*MII;
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001006 if (isInvalidLoopOperation(MI, IsInnerHWLoop)) {
1007 DEBUG(dbgs()<< "\nCannot convert to hw_loop due to:"; MI->dump(););
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001008 return true;
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001009 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001010 }
1011 }
1012 return false;
1013}
1014
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001015/// \brief Returns true if the instruction is dead. This was essentially
1016/// copied from DeadMachineInstructionElim::isDead, but with special cases
1017/// for inline asm, physical registers and instructions with side effects
1018/// removed.
1019bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +00001020 SmallVectorImpl<MachineInstr *> &DeadPhis) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001021 // Examine each operand.
1022 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1023 const MachineOperand &MO = MI->getOperand(i);
1024 if (!MO.isReg() || !MO.isDef())
1025 continue;
1026
1027 unsigned Reg = MO.getReg();
1028 if (MRI->use_nodbg_empty(Reg))
1029 continue;
1030
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001031 using use_nodbg_iterator = MachineRegisterInfo::use_nodbg_iterator;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001032
1033 // This instruction has users, but if the only user is the phi node for the
1034 // parent block, and the only use of that phi node is this instruction, then
1035 // this instruction is dead: both it (and the phi node) can be removed.
1036 use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
1037 use_nodbg_iterator End = MRI->use_nodbg_end();
Owen Anderson16c6bf42014-03-13 23:12:04 +00001038 if (std::next(I) != End || !I->getParent()->isPHI())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001039 return false;
1040
Owen Anderson16c6bf42014-03-13 23:12:04 +00001041 MachineInstr *OnePhi = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001042 for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
1043 const MachineOperand &OPO = OnePhi->getOperand(j);
1044 if (!OPO.isReg() || !OPO.isDef())
1045 continue;
1046
1047 unsigned OPReg = OPO.getReg();
1048 use_nodbg_iterator nextJ;
1049 for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
1050 J != End; J = nextJ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001051 nextJ = std::next(J);
Owen Anderson16c6bf42014-03-13 23:12:04 +00001052 MachineOperand &Use = *J;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001053 MachineInstr *UseMI = Use.getParent();
1054
Brendon Cahoon9376e992015-05-14 14:15:08 +00001055 // If the phi node has a user that is not MI, bail.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001056 if (MI != UseMI)
1057 return false;
1058 }
1059 }
1060 DeadPhis.push_back(OnePhi);
1061 }
1062
1063 // If there are no defs with uses, the instruction is dead.
1064 return true;
1065}
1066
1067void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
1068 // This procedure was essentially copied from DeadMachineInstructionElim.
1069
1070 SmallVector<MachineInstr*, 1> DeadPhis;
1071 if (isDead(MI, DeadPhis)) {
1072 DEBUG(dbgs() << "HW looping will remove: " << *MI);
1073
1074 // It is possible that some DBG_VALUE instructions refer to this
1075 // instruction. Examine each def operand for such references;
1076 // if found, mark the DBG_VALUE as undef (but don't delete it).
1077 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1078 const MachineOperand &MO = MI->getOperand(i);
1079 if (!MO.isReg() || !MO.isDef())
1080 continue;
1081 unsigned Reg = MO.getReg();
1082 MachineRegisterInfo::use_iterator nextI;
1083 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
1084 E = MRI->use_end(); I != E; I = nextI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001085 nextI = std::next(I); // I is invalidated by the setReg
Owen Anderson16c6bf42014-03-13 23:12:04 +00001086 MachineOperand &Use = *I;
1087 MachineInstr *UseMI = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001088 if (UseMI == MI)
1089 continue;
1090 if (Use.isDebug())
1091 UseMI->getOperand(0).setReg(0U);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001092 }
1093 }
1094
1095 MI->eraseFromParent();
1096 for (unsigned i = 0; i < DeadPhis.size(); ++i)
1097 DeadPhis[i]->eraseFromParent();
1098 }
1099}
1100
1101/// \brief Check if the loop is a candidate for converting to a hardware
1102/// loop. If so, then perform the transformation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001103///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001104/// This function works on innermost loops first. A loop can be converted
1105/// if it is a counting loop; either a register value or an immediate.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001106///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001107/// The code makes several assumptions about the representation of the loop
1108/// in llvm.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001109bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
1110 bool &RecL0used,
1111 bool &RecL1used) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001112 // This is just for sanity.
1113 assert(L->getHeader() && "Loop without a header?");
1114
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001115 bool Changed = false;
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001116 bool L0Used = false;
1117 bool L1Used = false;
1118
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001119 // Process nested loops first.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001120 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
1121 Changed |= convertToHardwareLoop(*I, RecL0used, RecL1used);
1122 L0Used |= RecL0used;
1123 L1Used |= RecL1used;
1124 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001125
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001126 // If a nested loop has been converted, then we can't convert this loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001127 if (Changed && L0Used && L1Used)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001128 return Changed;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001129
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001130 unsigned LOOP_i;
1131 unsigned LOOP_r;
1132 unsigned ENDLOOP;
1133
1134 // Flag used to track loopN instruction:
1135 // 1 - Hardware loop is being generated for the inner most loop.
1136 // 0 - Hardware loop is being generated for the outer loop.
1137 unsigned IsInnerHWLoop = 1;
1138
1139 if (L0Used) {
1140 LOOP_i = Hexagon::J2_loop1i;
1141 LOOP_r = Hexagon::J2_loop1r;
1142 ENDLOOP = Hexagon::ENDLOOP1;
1143 IsInnerHWLoop = 0;
1144 } else {
1145 LOOP_i = Hexagon::J2_loop0i;
1146 LOOP_r = Hexagon::J2_loop0r;
1147 ENDLOOP = Hexagon::ENDLOOP0;
1148 }
1149
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001150#ifndef NDEBUG
1151 // Stop trying after reaching the limit (if any).
1152 int Limit = HWLoopLimit;
1153 if (Limit >= 0) {
1154 if (Counter >= HWLoopLimit)
1155 return false;
1156 Counter++;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001157 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001158#endif
1159
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001160 // Does the loop contain any invalid instructions?
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001161 if (containsInvalidInstruction(L, IsInnerHWLoop))
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001162 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001163
Sjoerd Meijer58156712016-08-15 08:22:42 +00001164 MachineBasicBlock *LastMBB = L->findLoopControlBlock();
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001165 // Don't generate hw loop if the loop has more than one exit.
Craig Topper062a2ba2014-04-25 05:30:21 +00001166 if (!LastMBB)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001167 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001168
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001169 MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001170 if (LastI == LastMBB->end())
Matthew Curtis7a938112012-12-07 21:03:15 +00001171 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001172
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001173 // Is the induction variable bump feeding the latch condition?
1174 if (!fixupInductionVariable(L))
1175 return false;
1176
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001177 // Ensure the loop has a preheader: the loop instruction will be
1178 // placed there.
Sjoerd Meijer58156712016-08-15 08:22:42 +00001179 MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001180 if (!Preheader) {
1181 Preheader = createPreheaderForLoop(L);
1182 if (!Preheader)
1183 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001184 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001185
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001186 MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1187
1188 SmallVector<MachineInstr*, 2> OldInsts;
1189 // Are we able to determine the trip count for the loop?
1190 CountValue *TripCount = getLoopTripCount(L, OldInsts);
Craig Topper062a2ba2014-04-25 05:30:21 +00001191 if (!TripCount)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001192 return false;
1193
1194 // Is the trip count available in the preheader?
1195 if (TripCount->isReg()) {
1196 // There will be a use of the register inserted into the preheader,
1197 // so make sure that the register is actually defined at that point.
1198 MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1199 MachineBasicBlock *BBDef = TCDef->getParent();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001200 if (!MDT->dominates(BBDef, Preheader))
1201 return false;
Matthew Curtis7a938112012-12-07 21:03:15 +00001202 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001203
1204 // Determine the loop start.
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001205 MachineBasicBlock *TopBlock = L->getTopBlock();
Sjoerd Meijer58156712016-08-15 08:22:42 +00001206 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001207 MachineBasicBlock *LoopStart = nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001208 if (ExitingBlock != L->getLoopLatch()) {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001209 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001210 SmallVector<MachineOperand, 2> Cond;
1211
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001212 if (TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false))
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001213 return false;
1214
1215 if (L->contains(TB))
1216 LoopStart = TB;
1217 else if (L->contains(FB))
1218 LoopStart = FB;
1219 else
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001220 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001221 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001222 else
1223 LoopStart = TopBlock;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001224
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001225 // Convert the loop to a hardware loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001226 DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001227 DebugLoc DL;
Matthew Curtis7a938112012-12-07 21:03:15 +00001228 if (InsertPos != Preheader->end())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001229 DL = InsertPos->getDebugLoc();
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001230
1231 if (TripCount->isReg()) {
1232 // Create a copy of the loop count register.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001233 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1234 BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1235 .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
Benjamin Kramerbde91762012-06-02 10:20:22 +00001236 // Add the Loop instruction to the beginning of the loop.
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001237 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r)).addMBB(LoopStart)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001238 .addReg(CountReg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001239 } else {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001240 assert(TripCount->isImm() && "Expecting immediate value for trip count");
1241 // Add the Loop immediate instruction to the beginning of the loop,
1242 // if the immediate fits in the instructions. Otherwise, we need to
1243 // create a new virtual register.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001244 int64_t CountImm = TripCount->getImm();
Krzysztof Parzyszek55772972017-09-15 15:46:05 +00001245 if (!TII->isValidOffset(LOOP_i, CountImm, TRI)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001246 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001247 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001248 .addImm(CountImm);
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001249 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001250 .addMBB(LoopStart).addReg(CountReg);
1251 } else
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001252 BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_i))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001253 .addMBB(LoopStart).addImm(CountImm);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001254 }
1255
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001256 // Make sure the loop start always has a reference in the CFG. We need
1257 // to create a BlockAddress operand to get this mechanism to work both the
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001258 // MachineBasicBlock and BasicBlock objects need the flag set.
1259 LoopStart->setHasAddressTaken();
1260 // This line is needed to set the hasAddressTaken flag on the BasicBlock
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001261 // object.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001262 BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
1263
1264 // Replace the loop branch with an endloop instruction.
Matthew Curtis7a938112012-12-07 21:03:15 +00001265 DebugLoc LastIDL = LastI->getDebugLoc();
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001266 BuildMI(*LastMBB, LastI, LastIDL, TII->get(ENDLOOP)).addMBB(LoopStart);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001267
1268 // The loop ends with either:
1269 // - a conditional branch followed by an unconditional branch, or
1270 // - a conditional branch to the loop start.
Colin LeMahieudb0b13c2014-12-10 21:24:10 +00001271 if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1272 LastI->getOpcode() == Hexagon::J2_jumpf) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001273 // Delete one and change/add an uncond. branch to out of the loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001274 MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1275 LastI = LastMBB->erase(LastI);
1276 if (!L->contains(BranchTarget)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001277 if (LastI != LastMBB->end())
1278 LastI = LastMBB->erase(LastI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001279 SmallVector<MachineOperand, 0> Cond;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001280 TII->insertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001281 }
1282 } else {
1283 // Conditional branch to loop start; just delete it.
1284 LastMBB->erase(LastI);
1285 }
1286 delete TripCount;
1287
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001288 // The induction operation and the comparison may now be
1289 // unneeded. If these are unneeded, then remove them.
1290 for (unsigned i = 0; i < OldInsts.size(); ++i)
1291 removeIfDead(OldInsts[i]);
1292
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001293 ++NumHWLoops;
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001294
1295 // Set RecL1used and RecL0used only after hardware loop has been
1296 // successfully generated. Doing it earlier can cause wrong loop instruction
1297 // to be used.
1298 if (L0Used) // Loop0 was already used. So, the correct loop must be loop1.
1299 RecL1used = true;
1300 else
1301 RecL0used = true;
1302
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001303 return true;
1304}
1305
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001306bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1307 MachineInstr *CmpI) {
1308 assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1309
1310 MachineBasicBlock *BB = BumpI->getParent();
1311 if (CmpI->getParent() != BB)
1312 return false;
1313
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001314 using instr_iterator = MachineBasicBlock::instr_iterator;
1315
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001316 // Check if things are in order to begin with.
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +00001317 for (instr_iterator I(BumpI), E = BB->instr_end(); I != E; ++I)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001318 if (&*I == CmpI)
1319 return true;
1320
1321 // Out of order.
1322 unsigned PredR = CmpI->getOperand(0).getReg();
1323 bool FoundBump = false;
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001324 instr_iterator CmpIt = CmpI->getIterator(), NextIt = std::next(CmpIt);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001325 for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1326 MachineInstr *In = &*I;
1327 for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1328 MachineOperand &MO = In->getOperand(i);
1329 if (MO.isReg() && MO.isUse()) {
1330 if (MO.getReg() == PredR) // Found an intervening use of PredR.
1331 return false;
1332 }
1333 }
1334
1335 if (In == BumpI) {
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001336 BB->splice(++BumpI->getIterator(), BB, CmpI->getIterator());
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001337 FoundBump = true;
1338 break;
1339 }
1340 }
1341 assert (FoundBump && "Cannot determine instruction order");
1342 return FoundBump;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001343}
1344
Brendon Cahoon9376e992015-05-14 14:15:08 +00001345/// This function is required to break recursion. Visiting phis in a loop may
1346/// result in recursion during compilation. We break the recursion by making
1347/// sure that we visit a MachineOperand and its definition in a
1348/// MachineInstruction only once. If we attempt to visit more than once, then
1349/// there is recursion, and will return false.
1350bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
1351 MachineInstr *MI,
1352 const MachineOperand *MO,
1353 LoopFeederMap &LoopFeederPhi) const {
1354 if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
1355 const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
1356 DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
1357 // Ignore all BBs that form Loop.
1358 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1359 MachineBasicBlock *MBB = Blocks[i];
1360 if (A == MBB)
1361 return false;
1362 }
1363 MachineInstr *Def = MRI->getVRegDef(MO->getReg());
1364 LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
1365 return true;
1366 } else
1367 // Already visited node.
1368 return false;
1369}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001370
Brendon Cahoon9376e992015-05-14 14:15:08 +00001371/// Return true if a Phi may generate a value that can underflow.
1372/// This function calls loopCountMayWrapOrUnderFlow for each Phi operand.
1373bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1374 MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
1375 MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
1376 assert(Phi->isPHI() && "Expecting a Phi.");
1377 // Walk through each Phi, and its used operands. Make sure that
1378 // if there is recursion in Phi, we won't generate hardware loops.
1379 for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
1380 if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
1381 if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
1382 Phi->getParent(), L, LoopFeederPhi))
1383 return true;
1384 return false;
1385}
1386
1387/// Return true if the induction variable can underflow in the first iteration.
1388/// An example, is an initial unsigned value that is 0 and is decrement in the
1389/// first itertion of a do-while loop. In this case, we cannot generate a
1390/// hardware loop because the endloop instruction does not decrement the loop
1391/// counter if it is <= 1. We only need to perform this analysis if the
1392/// initial value is a register.
1393///
1394/// This function assumes the initial value may underfow unless proven
1395/// otherwise. If the type is signed, then we don't care because signed
1396/// underflow is undefined. We attempt to prove the initial value is not
1397/// zero by perfoming a crude analysis of the loop counter. This function
1398/// checks if the initial value is used in any comparison prior to the loop
1399/// and, if so, assumes the comparison is a range check. This is inexact,
1400/// but will catch the simple cases.
1401bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1402 const MachineOperand *InitVal, const MachineOperand *EndVal,
1403 MachineBasicBlock *MBB, MachineLoop *L,
1404 LoopFeederMap &LoopFeederPhi) const {
1405 // Only check register values since they are unknown.
1406 if (!InitVal->isReg())
1407 return false;
1408
1409 if (!EndVal->isImm())
1410 return false;
1411
1412 // A register value that is assigned an immediate is a known value, and it
1413 // won't underflow in the first iteration.
1414 int64_t Imm;
1415 if (checkForImmediate(*InitVal, Imm))
1416 return (EndVal->getImm() == Imm);
1417
1418 unsigned Reg = InitVal->getReg();
1419
1420 // We don't know the value of a physical register.
1421 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1422 return true;
1423
1424 MachineInstr *Def = MRI->getVRegDef(Reg);
1425 if (!Def)
1426 return true;
1427
1428 // If the initial value is a Phi or copy and the operands may not underflow,
1429 // then the definition cannot be underflow either.
1430 if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
1431 L, LoopFeederPhi))
1432 return false;
1433 if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
1434 EndVal, Def->getParent(),
1435 L, LoopFeederPhi))
1436 return false;
1437
1438 // Iterate over the uses of the initial value. If the initial value is used
1439 // in a compare, then we assume this is a range check that ensures the loop
1440 // doesn't underflow. This is not an exact test and should be improved.
1441 for (MachineRegisterInfo::use_instr_nodbg_iterator I = MRI->use_instr_nodbg_begin(Reg),
1442 E = MRI->use_instr_nodbg_end(); I != E; ++I) {
1443 MachineInstr *MI = &*I;
1444 unsigned CmpReg1 = 0, CmpReg2 = 0;
1445 int CmpMask = 0, CmpValue = 0;
1446
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001447 if (!TII->analyzeCompare(*MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
Brendon Cahoon9376e992015-05-14 14:15:08 +00001448 continue;
1449
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001450 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Brendon Cahoon9376e992015-05-14 14:15:08 +00001451 SmallVector<MachineOperand, 2> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001452 if (TII->analyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
Brendon Cahoon9376e992015-05-14 14:15:08 +00001453 continue;
1454
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001455 Comparison::Kind Cmp =
1456 getComparisonKind(MI->getOpcode(), nullptr, nullptr, 0);
Brendon Cahoon9376e992015-05-14 14:15:08 +00001457 if (Cmp == 0)
1458 continue;
1459 if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
1460 Cmp = Comparison::getNegatedComparison(Cmp);
1461 if (CmpReg2 != 0 && CmpReg2 == Reg)
1462 Cmp = Comparison::getSwappedComparison(Cmp);
1463
1464 // Signed underflow is undefined.
1465 if (Comparison::isSigned(Cmp))
1466 return false;
1467
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001468 // Check if there is a comparison of the initial value. If the initial value
Brendon Cahoon9376e992015-05-14 14:15:08 +00001469 // is greater than or not equal to another value, then assume this is a
1470 // range check.
1471 if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1472 return false;
1473 }
1474
1475 // OK - this is a hack that needs to be improved. We really need to analyze
1476 // the instructions performed on the initial value. This works on the simplest
1477 // cases only.
1478 if (!Def->isCopy() && !Def->isPHI())
1479 return false;
1480
1481 return true;
1482}
1483
1484bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
1485 int64_t &Val) const {
1486 if (MO.isImm()) {
1487 Val = MO.getImm();
1488 return true;
1489 }
1490 if (!MO.isReg())
1491 return false;
1492
1493 // MO is a register. Check whether it is defined as an immediate value,
1494 // and if so, get the value of it in TV. That value will then need to be
1495 // processed to handle potential subregisters in MO.
1496 int64_t TV;
1497
1498 unsigned R = MO.getReg();
1499 if (!TargetRegisterInfo::isVirtualRegister(R))
1500 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001501 MachineInstr *DI = MRI->getVRegDef(R);
1502 unsigned DOpc = DI->getOpcode();
1503 switch (DOpc) {
Brendon Cahoon9376e992015-05-14 14:15:08 +00001504 case TargetOpcode::COPY:
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001505 case Hexagon::A2_tfrsi:
Colin LeMahieu0f850bd2014-12-19 20:29:29 +00001506 case Hexagon::A2_tfrpi:
Krzysztof Parzyszeka3386502016-08-10 16:46:36 +00001507 case Hexagon::CONST32:
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001508 case Hexagon::CONST64:
Brendon Cahoon9376e992015-05-14 14:15:08 +00001509 // Call recursively to avoid an extra check whether operand(1) is
1510 // indeed an immediate (it could be a global address, for example),
1511 // plus we can handle COPY at the same time.
1512 if (!checkForImmediate(DI->getOperand(1), TV))
1513 return false;
1514 break;
Brendon Cahoon9376e992015-05-14 14:15:08 +00001515 case Hexagon::A2_combineii:
1516 case Hexagon::A4_combineir:
1517 case Hexagon::A4_combineii:
1518 case Hexagon::A4_combineri:
1519 case Hexagon::A2_combinew: {
1520 const MachineOperand &S1 = DI->getOperand(1);
1521 const MachineOperand &S2 = DI->getOperand(2);
1522 int64_t V1, V2;
1523 if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
1524 return false;
Vitaly Bukabcb66222017-02-11 12:44:03 +00001525 TV = V2 | (static_cast<uint64_t>(V1) << 32);
Brendon Cahoon9376e992015-05-14 14:15:08 +00001526 break;
1527 }
1528 case TargetOpcode::REG_SEQUENCE: {
1529 const MachineOperand &S1 = DI->getOperand(1);
1530 const MachineOperand &S3 = DI->getOperand(3);
1531 int64_t V1, V3;
1532 if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
1533 return false;
1534 unsigned Sub2 = DI->getOperand(2).getImm();
1535 unsigned Sub4 = DI->getOperand(4).getImm();
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001536 if (Sub2 == Hexagon::isub_lo && Sub4 == Hexagon::isub_hi)
Brendon Cahoon9376e992015-05-14 14:15:08 +00001537 TV = V1 | (V3 << 32);
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001538 else if (Sub2 == Hexagon::isub_hi && Sub4 == Hexagon::isub_lo)
Brendon Cahoon9376e992015-05-14 14:15:08 +00001539 TV = V3 | (V1 << 32);
1540 else
1541 llvm_unreachable("Unexpected form of REG_SEQUENCE");
1542 break;
1543 }
1544
1545 default:
1546 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001547 }
Brendon Cahoon9376e992015-05-14 14:15:08 +00001548
Simon Pilgrim6ba672e2016-11-17 19:21:20 +00001549 // By now, we should have successfully obtained the immediate value defining
Brendon Cahoon9376e992015-05-14 14:15:08 +00001550 // the register referenced in MO. Handle a potential use of a subregister.
1551 switch (MO.getSubReg()) {
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001552 case Hexagon::isub_lo:
Brendon Cahoon9376e992015-05-14 14:15:08 +00001553 Val = TV & 0xFFFFFFFFULL;
1554 break;
Krzysztof Parzyszeka5409972016-11-09 16:19:08 +00001555 case Hexagon::isub_hi:
Brendon Cahoon9376e992015-05-14 14:15:08 +00001556 Val = (TV >> 32) & 0xFFFFFFFFULL;
1557 break;
1558 default:
1559 Val = TV;
1560 break;
1561 }
1562 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001563}
1564
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001565void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1566 if (MO.isImm()) {
1567 MO.setImm(Val);
1568 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001569 }
1570
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001571 assert(MO.isReg());
1572 unsigned R = MO.getReg();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001573 MachineInstr *DI = MRI->getVRegDef(R);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001574
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001575 const TargetRegisterClass *RC = MRI->getRegClass(R);
1576 unsigned NewR = MRI->createVirtualRegister(RC);
1577 MachineBasicBlock &B = *DI->getParent();
1578 DebugLoc DL = DI->getDebugLoc();
Brendon Cahoon9376e992015-05-14 14:15:08 +00001579 BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001580 MO.setReg(NewR);
1581}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001582
Brendon Cahoon9376e992015-05-14 14:15:08 +00001583static bool isImmValidForOpcode(unsigned CmpOpc, int64_t Imm) {
1584 // These two instructions are not extendable.
1585 if (CmpOpc == Hexagon::A4_cmpbeqi)
1586 return isUInt<8>(Imm);
1587 if (CmpOpc == Hexagon::A4_cmpbgti)
1588 return isInt<8>(Imm);
1589 // The rest of the comparison-with-immediate instructions are extendable.
1590 return true;
1591}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001592
1593bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1594 MachineBasicBlock *Header = L->getHeader();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001595 MachineBasicBlock *Latch = L->getLoopLatch();
Sjoerd Meijer58156712016-08-15 08:22:42 +00001596 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001597
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001598 if (!(Header && Latch && ExitingBlock))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001599 return false;
1600
1601 // These data structures follow the same concept as the corresponding
1602 // ones in findInductionRegister (where some comments are).
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001603 using RegisterBump = std::pair<unsigned, int64_t>;
1604 using RegisterInduction = std::pair<unsigned, RegisterBump>;
1605 using RegisterInductionSet = std::set<RegisterInduction>;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001606
1607 // Register candidates for induction variables, with their associated bumps.
1608 RegisterInductionSet IndRegs;
1609
1610 // Look for induction patterns:
1611 // vreg1 = PHI ..., [ latch, vreg2 ]
1612 // vreg2 = ADD vreg1, imm
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001613 using instr_iterator = MachineBasicBlock::instr_iterator;
1614
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001615 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1616 I != E && I->isPHI(); ++I) {
1617 MachineInstr *Phi = &*I;
1618
1619 // Have a PHI instruction.
1620 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1621 if (Phi->getOperand(i+1).getMBB() != Latch)
1622 continue;
1623
1624 unsigned PhiReg = Phi->getOperand(i).getReg();
1625 MachineInstr *DI = MRI->getVRegDef(PhiReg);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001626
Sjoerd Meijer724023a2016-09-14 08:20:03 +00001627 if (DI->getDesc().isAdd()) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001628 // If the register operand to the add/sub is the PHI we are looking
1629 // at, this meets the induction pattern.
1630 unsigned IndReg = DI->getOperand(1).getReg();
Brendon Cahoon9376e992015-05-14 14:15:08 +00001631 MachineOperand &Opnd2 = DI->getOperand(2);
1632 int64_t V;
1633 if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001634 unsigned UpdReg = DI->getOperand(0).getReg();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001635 IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001636 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001637 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001638 } // for (i)
1639 } // for (instr)
1640
1641 if (IndRegs.empty())
1642 return false;
1643
Craig Topper062a2ba2014-04-25 05:30:21 +00001644 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001645 SmallVector<MachineOperand,2> Cond;
1646 // AnalyzeBranch returns true if it fails to analyze branch.
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001647 bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
Brendon Cahoon254e6562015-05-13 14:54:24 +00001648 if (NotAnalyzed || Cond.empty())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001649 return false;
1650
Brendon Cahoon254e6562015-05-13 14:54:24 +00001651 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001652 MachineBasicBlock *LTB = nullptr, *LFB = nullptr;
Brendon Cahoon254e6562015-05-13 14:54:24 +00001653 SmallVector<MachineOperand,2> LCond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001654 bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
Brendon Cahoon254e6562015-05-13 14:54:24 +00001655 if (NotAnalyzed)
1656 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001657
Brendon Cahoon254e6562015-05-13 14:54:24 +00001658 // Since latch is not the exiting block, the latch branch should be an
1659 // unconditional branch to the loop header.
1660 if (TB == Latch)
1661 TB = (LTB == Header) ? LTB : LFB;
1662 else
1663 FB = (LTB == Header) ? LTB : LFB;
1664 }
1665 if (TB != Header) {
1666 if (FB != Header) {
1667 // The latch/exit block does not go back to the header.
1668 return false;
1669 }
1670 // FB is the header (i.e., uncond. jump to branch header)
1671 // In this case, the LoopBody -> TB should not be a back edge otherwise
1672 // it could result in an infinite loop after conversion to hw_loop.
1673 // This case can happen when the Latch has two jumps like this:
1674 // Jmp_c OuterLoopHeader <-- TB
1675 // Jmp InnerLoopHeader <-- FB
1676 if (MDT->dominates(TB, FB))
1677 return false;
1678 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001679
1680 // Expecting a predicate register as a condition. It won't be a hardware
1681 // predicate register at this point yet, just a vreg.
1682 // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1683 // into Cond, followed by the predicate register. For non-negated branches
1684 // it's just the register.
1685 unsigned CSz = Cond.size();
1686 if (CSz != 1 && CSz != 2)
1687 return false;
1688
Brendon Cahoon254e6562015-05-13 14:54:24 +00001689 if (!Cond[CSz-1].isReg())
1690 return false;
1691
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001692 unsigned P = Cond[CSz-1].getReg();
1693 MachineInstr *PredDef = MRI->getVRegDef(P);
1694
1695 if (!PredDef->isCompare())
1696 return false;
1697
1698 SmallSet<unsigned,2> CmpRegs;
Craig Topper062a2ba2014-04-25 05:30:21 +00001699 MachineOperand *CmpImmOp = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001700
1701 // Go over all operands to the compare and look for immediate and register
1702 // operands. Assume that if the compare has a single register use and a
1703 // single immediate operand, then the register is being compared with the
1704 // immediate value.
1705 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1706 MachineOperand &MO = PredDef->getOperand(i);
1707 if (MO.isReg()) {
1708 // Skip all implicit references. In one case there was:
1709 // %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1710 if (MO.isImplicit())
1711 continue;
1712 if (MO.isUse()) {
Brendon Cahoon9376e992015-05-14 14:15:08 +00001713 if (!isImmediate(MO)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001714 CmpRegs.insert(MO.getReg());
1715 continue;
1716 }
1717 // Consider the register to be the "immediate" operand.
1718 if (CmpImmOp)
1719 return false;
1720 CmpImmOp = &MO;
1721 }
1722 } else if (MO.isImm()) {
1723 if (CmpImmOp) // A second immediate argument? Confusing. Bail out.
1724 return false;
1725 CmpImmOp = &MO;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001726 }
1727 }
1728
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001729 if (CmpRegs.empty())
1730 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001731
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001732 // Check if the compared register follows the order we want. Fix if needed.
1733 for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1734 I != E; ++I) {
1735 // This is a success. If the register used in the comparison is one that
1736 // we have identified as a bumped (updated) induction register, there is
1737 // nothing to do.
1738 if (CmpRegs.count(I->first))
1739 return true;
1740
1741 // Otherwise, if the register being compared comes out of a PHI node,
1742 // and has been recognized as following the induction pattern, and is
1743 // compared against an immediate, we can fix it.
1744 const RegisterBump &RB = I->second;
1745 if (CmpRegs.count(RB.first)) {
Brendon Cahoon7c8a3b02015-05-14 20:36:19 +00001746 if (!CmpImmOp) {
1747 // If both operands to the compare instruction are registers, see if
1748 // it can be changed to use induction register as one of the operands.
1749 MachineInstr *IndI = nullptr;
1750 MachineInstr *nonIndI = nullptr;
1751 MachineOperand *IndMO = nullptr;
1752 MachineOperand *nonIndMO = nullptr;
1753
1754 for (unsigned i = 1, n = PredDef->getNumOperands(); i < n; ++i) {
1755 MachineOperand &MO = PredDef->getOperand(i);
1756 if (MO.isReg() && MO.getReg() == RB.first) {
1757 DEBUG(dbgs() << "\n DefMI(" << i << ") = "
1758 << *(MRI->getVRegDef(I->first)));
1759 if (IndI)
1760 return false;
1761
1762 IndI = MRI->getVRegDef(I->first);
1763 IndMO = &MO;
1764 } else if (MO.isReg()) {
1765 DEBUG(dbgs() << "\n DefMI(" << i << ") = "
1766 << *(MRI->getVRegDef(MO.getReg())));
1767 if (nonIndI)
1768 return false;
1769
1770 nonIndI = MRI->getVRegDef(MO.getReg());
1771 nonIndMO = &MO;
1772 }
1773 }
1774 if (IndI && nonIndI &&
1775 nonIndI->getOpcode() == Hexagon::A2_addi &&
1776 nonIndI->getOperand(2).isImm() &&
1777 nonIndI->getOperand(2).getImm() == - RB.second) {
1778 bool Order = orderBumpCompare(IndI, PredDef);
1779 if (Order) {
1780 IndMO->setReg(I->first);
1781 nonIndMO->setReg(nonIndI->getOperand(1).getReg());
1782 return true;
1783 }
1784 }
1785 return false;
1786 }
1787
1788 // It is not valid to do this transformation on an unsigned comparison
1789 // because it may underflow.
Eugene Zelenko26e8c7d2016-12-16 01:00:40 +00001790 Comparison::Kind Cmp =
1791 getComparisonKind(PredDef->getOpcode(), nullptr, nullptr, 0);
Brendon Cahoon7c8a3b02015-05-14 20:36:19 +00001792 if (!Cmp || Comparison::isUnsigned(Cmp))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001793 return false;
1794
Brendon Cahoon9376e992015-05-14 14:15:08 +00001795 // If the register is being compared against an immediate, try changing
1796 // the compare instruction to use induction register and adjust the
1797 // immediate operand.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001798 int64_t CmpImm = getImmediate(*CmpImmOp);
1799 int64_t V = RB.second;
Brendon Cahoon9376e992015-05-14 14:15:08 +00001800 // Handle Overflow (64-bit).
1801 if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
1802 ((V < 0) && (CmpImm < INT64_MIN - V)))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001803 return false;
1804 CmpImm += V;
Brendon Cahoon9376e992015-05-14 14:15:08 +00001805 // Most comparisons of register against an immediate value allow
1806 // the immediate to be constant-extended. There are some exceptions
1807 // though. Make sure the new combination will work.
1808 if (CmpImmOp->isImm())
1809 if (!isImmValidForOpcode(PredDef->getOpcode(), CmpImm))
1810 return false;
1811
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001812 // Make sure that the compare happens after the bump. Otherwise,
1813 // after the fixup, the compare would use a yet-undefined register.
1814 MachineInstr *BumpI = MRI->getVRegDef(I->first);
1815 bool Order = orderBumpCompare(BumpI, PredDef);
1816 if (!Order)
1817 return false;
1818
1819 // Finally, fix the compare instruction.
1820 setImmediate(*CmpImmOp, CmpImm);
1821 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1822 MachineOperand &MO = PredDef->getOperand(i);
1823 if (MO.isReg() && MO.getReg() == RB.first) {
1824 MO.setReg(I->first);
1825 return true;
1826 }
1827 }
1828 }
1829 }
1830
1831 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001832}
1833
Krzysztof Parzyszek06a2b6b2016-07-27 21:20:54 +00001834/// createPreheaderForLoop - Create a preheader for a given loop.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001835MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1836 MachineLoop *L) {
Sjoerd Meijer58156712016-08-15 08:22:42 +00001837 if (MachineBasicBlock *TmpPH = MLI->findLoopPreheader(L, SpecPreheader))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001838 return TmpPH;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001839 if (!HWCreatePreheader)
1840 return nullptr;
1841
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001842 MachineBasicBlock *Header = L->getHeader();
1843 MachineBasicBlock *Latch = L->getLoopLatch();
Sjoerd Meijer58156712016-08-15 08:22:42 +00001844 MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001845 MachineFunction *MF = Header->getParent();
1846 DebugLoc DL;
1847
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001848#ifndef NDEBUG
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001849 if ((!PHFn.empty()) && (PHFn != MF->getName()))
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001850 return nullptr;
1851#endif
1852
1853 if (!Latch || !ExitingBlock || Header->hasAddressTaken())
Craig Topper062a2ba2014-04-25 05:30:21 +00001854 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001855
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001856 using instr_iterator = MachineBasicBlock::instr_iterator;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001857
1858 // Verify that all existing predecessors have analyzable branches
1859 // (or no branches at all).
Eugene Zelenko4d060b72017-07-29 00:56:56 +00001860 using MBBVector = std::vector<MachineBasicBlock *>;
1861
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001862 MBBVector Preds(Header->pred_begin(), Header->pred_end());
1863 SmallVector<MachineOperand,2> Tmp1;
Craig Topper062a2ba2014-04-25 05:30:21 +00001864 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001865
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001866 if (TII->analyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
Craig Topper062a2ba2014-04-25 05:30:21 +00001867 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001868
1869 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1870 MachineBasicBlock *PB = *I;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001871 bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp1, false);
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001872 if (NotAnalyzed)
1873 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001874 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001875
1876 MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
Duncan P. N. Exon Smitha72c6e22015-10-20 00:46:39 +00001877 MF->insert(Header->getIterator(), NewPH);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001878
1879 if (Header->pred_size() > 2) {
1880 // Ensure that the header has only two predecessors: the preheader and
1881 // the loop latch. Any additional predecessors of the header should
Brendon Cahoond11c92a2015-05-13 17:56:03 +00001882 // join at the newly created preheader. Inspect all PHI nodes from the
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001883 // header and create appropriate corresponding PHI nodes in the preheader.
1884
1885 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1886 I != E && I->isPHI(); ++I) {
1887 MachineInstr *PN = &*I;
1888
1889 const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1890 MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1891 NewPH->insert(NewPH->end(), NewPN);
1892
1893 unsigned PR = PN->getOperand(0).getReg();
1894 const TargetRegisterClass *RC = MRI->getRegClass(PR);
1895 unsigned NewPR = MRI->createVirtualRegister(RC);
1896 NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1897
1898 // Copy all non-latch operands of a header's PHI node to the newly
1899 // created PHI node in the preheader.
1900 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1901 unsigned PredR = PN->getOperand(i).getReg();
Brendon Cahoon485bea742015-05-14 17:31:40 +00001902 unsigned PredRSub = PN->getOperand(i).getSubReg();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001903 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1904 if (PredB == Latch)
1905 continue;
1906
Brendon Cahoon485bea742015-05-14 17:31:40 +00001907 MachineOperand MO = MachineOperand::CreateReg(PredR, false);
1908 MO.setSubReg(PredRSub);
1909 NewPN->addOperand(MO);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001910 NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1911 }
1912
1913 // Remove copied operands from the old PHI node and add the value
1914 // coming from the preheader's PHI.
1915 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1916 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1917 if (PredB != Latch) {
1918 PN->RemoveOperand(i+1);
1919 PN->RemoveOperand(i);
1920 }
1921 }
1922 PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1923 PN->addOperand(MachineOperand::CreateMBB(NewPH));
1924 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001925 } else {
1926 assert(Header->pred_size() == 2);
1927
1928 // The header has only two predecessors, but the non-latch predecessor
1929 // is not a preheader (e.g. it has other successors, etc.)
1930 // In such a case we don't need any extra PHI nodes in the new preheader,
1931 // all we need is to adjust existing PHIs in the header to now refer to
1932 // the new preheader.
1933 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1934 I != E && I->isPHI(); ++I) {
1935 MachineInstr *PN = &*I;
1936 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1937 MachineOperand &MO = PN->getOperand(i+1);
1938 if (MO.getMBB() != Latch)
1939 MO.setMBB(NewPH);
1940 }
1941 }
1942 }
1943
1944 // "Reroute" the CFG edges to link in the new preheader.
1945 // If any of the predecessors falls through to the header, insert a branch
1946 // to the new preheader in that place.
1947 SmallVector<MachineOperand,1> Tmp2;
1948 SmallVector<MachineOperand,1> EmptyCond;
1949
Craig Topper062a2ba2014-04-25 05:30:21 +00001950 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001951
1952 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1953 MachineBasicBlock *PB = *I;
1954 if (PB != Latch) {
1955 Tmp2.clear();
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001956 bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001957 (void)NotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001958 assert (!NotAnalyzed && "Should be analyzable!");
1959 if (TB != Header && (Tmp2.empty() || FB != Header))
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001960 TII->insertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001961 PB->ReplaceUsesOfBlockWith(Header, NewPH);
1962 }
1963 }
1964
1965 // It can happen that the latch block will fall through into the header.
1966 // Insert an unconditional branch to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001967 TB = FB = nullptr;
Jacques Pienaar71c30a12016-07-15 14:41:04 +00001968 bool LatchNotAnalyzed = TII->analyzeBranch(*Latch, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001969 (void)LatchNotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001970 assert (!LatchNotAnalyzed && "Should be analyzable!");
1971 if (!TB && !FB)
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001972 TII->insertBranch(*Latch, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001973
1974 // Finally, the branch from the preheader to the header.
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +00001975 TII->insertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001976 NewPH->addSuccessor(Header);
1977
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001978 MachineLoop *ParentLoop = L->getParentLoop();
1979 if (ParentLoop)
1980 ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
1981
1982 // Update the dominator information with the new preheader.
1983 if (MDT) {
Krzysztof Parzyszek06a2b6b2016-07-27 21:20:54 +00001984 if (MachineDomTreeNode *HN = MDT->getNode(Header)) {
1985 if (MachineDomTreeNode *DHN = HN->getIDom()) {
1986 MDT->addNewBlock(NewPH, DHN->getBlock());
1987 MDT->changeImmediateDominator(Header, NewPH);
1988 }
1989 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001990 }
1991
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001992 return NewPH;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001993}