blob: 0cad3d04c142287b334076fa1b6a33a26bc64df5 [file] [log] [blame]
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001//===-- HexagonHardwareLoops.cpp - Identify and generate hardware loops ---===//
2//
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
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000028#include "llvm/ADT/SmallSet.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000029#include "Hexagon.h"
Eric Christopher2c44f432015-02-02 19:05:28 +000030#include "HexagonSubtarget.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000031#include "llvm/ADT/Statistic.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000032#include "llvm/CodeGen/MachineDominators.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineFunctionPass.h"
35#include "llvm/CodeGen/MachineInstrBuilder.h"
36#include "llvm/CodeGen/MachineLoopInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/PassSupport.h"
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000039#include "llvm/Support/CommandLine.h"
Tony Linthicum1213a7a2011-12-12 21:14:40 +000040#include "llvm/Support/Debug.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include <algorithm>
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000044#include <vector>
Tony Linthicum1213a7a2011-12-12 21:14:40 +000045
46using namespace llvm;
47
Chandler Carruth84e68b22014-04-22 02:41:26 +000048#define DEBUG_TYPE "hwloops"
49
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000050#ifndef NDEBUG
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000051static cl::opt<int> HWLoopLimit("hexagon-max-hwloop", cl::Hidden, cl::init(-1));
52
53// Option to create preheader only for a specific function.
54static cl::opt<std::string> PHFn("hexagon-hwloop-phfn", cl::Hidden,
55 cl::init(""));
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000056#endif
57
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000058// Option to create a preheader if one doesn't exist.
59static cl::opt<bool> HWCreatePreheader("hexagon-hwloop-preheader",
60 cl::Hidden, cl::init(true),
61 cl::desc("Add a preheader to a hardware loop if one doesn't exist"));
62
Tony Linthicum1213a7a2011-12-12 21:14:40 +000063STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
64
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000065namespace llvm {
66 void initializeHexagonHardwareLoopsPass(PassRegistry&);
67}
68
Tony Linthicum1213a7a2011-12-12 21:14:40 +000069namespace {
70 class CountValue;
71 struct HexagonHardwareLoops : public MachineFunctionPass {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000072 MachineLoopInfo *MLI;
73 MachineRegisterInfo *MRI;
74 MachineDominatorTree *MDT;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000075 const HexagonInstrInfo *TII;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000076#ifndef NDEBUG
77 static int Counter;
78#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +000079
80 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000081 static char ID;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000082
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000083 HexagonHardwareLoops() : MachineFunctionPass(ID) {
84 initializeHexagonHardwareLoopsPass(*PassRegistry::getPassRegistry());
85 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +000086
Craig Topper906c2cd2014-04-29 07:58:16 +000087 bool runOnMachineFunction(MachineFunction &MF) override;
Tony Linthicum1213a7a2011-12-12 21:14:40 +000088
Craig Topper906c2cd2014-04-29 07:58:16 +000089 const char *getPassName() const override { return "Hexagon Hardware Loops"; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +000090
Craig Topper906c2cd2014-04-29 07:58:16 +000091 void getAnalysisUsage(AnalysisUsage &AU) const override {
Tony Linthicum1213a7a2011-12-12 21:14:40 +000092 AU.addRequired<MachineDominatorTree>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000093 AU.addRequired<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +000094 MachineFunctionPass::getAnalysisUsage(AU);
95 }
96
97 private:
Brendon Cahoonbece8ed2015-05-08 20:18:21 +000098
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +000099 /// Kinds of comparisons in the compare instructions.
100 struct Comparison {
101 enum Kind {
102 EQ = 0x01,
103 NE = 0x02,
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000104 L = 0x04,
105 G = 0x08,
106 U = 0x40,
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000107 LTs = L,
108 LEs = L | EQ,
109 GTs = G,
110 GEs = G | EQ,
111 LTu = L | U,
112 LEu = L | EQ | U,
113 GTu = G | U,
114 GEu = G | EQ | U
115 };
116
117 static Kind getSwappedComparison(Kind Cmp) {
118 assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
119 if ((Cmp & L) || (Cmp & G))
120 return (Kind)(Cmp ^ (L|G));
121 return Cmp;
122 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000123
124 static Kind getNegatedComparison(Kind Cmp) {
125 if ((Cmp & L) || (Cmp & G))
126 return (Kind)((Cmp ^ (L | G)) ^ EQ);
127 if ((Cmp & NE) || (Cmp & EQ))
128 return (Kind)(Cmp ^ (EQ | NE));
129 return (Kind)0;
130 }
131
132 static bool isSigned(Kind Cmp) {
133 return (Cmp & (L | G) && !(Cmp & U));
134 }
135
136 static bool isUnsigned(Kind Cmp) {
137 return (Cmp & U);
138 }
139
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000140 };
141
142 /// \brief Find the register that contains the loop controlling
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000143 /// induction variable.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000144 /// If successful, it will return true and set the \p Reg, \p IVBump
145 /// and \p IVOp arguments. Otherwise it will return false.
146 /// The returned induction register is the register R that follows the
147 /// following induction pattern:
148 /// loop:
149 /// R = phi ..., [ R.next, LatchBlock ]
150 /// R.next = R + #bump
151 /// if (R.next < #N) goto loop
152 /// IVBump is the immediate value added to R, and IVOp is the instruction
153 /// "R.next = R + #bump".
154 bool findInductionRegister(MachineLoop *L, unsigned &Reg,
155 int64_t &IVBump, MachineInstr *&IVOp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000156
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000157 /// \brief Return the comparison kind for the specified opcode.
158 Comparison::Kind getComparisonKind(unsigned CondOpc,
159 MachineOperand *InitialValue,
160 const MachineOperand *Endvalue,
161 int64_t IVBump) const;
162
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000163 /// \brief Analyze the statements in a loop to determine if the loop
164 /// has a computable trip count and, if so, return a value that represents
165 /// the trip count expression.
166 CountValue *getLoopTripCount(MachineLoop *L,
Craig Topperb94011f2013-07-14 04:42:23 +0000167 SmallVectorImpl<MachineInstr *> &OldInsts);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000168
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000169 /// \brief Return the expression that represents the number of times
170 /// a loop iterates. The function takes the operands that represent the
171 /// loop start value, loop end value, and induction value. Based upon
172 /// these operands, the function attempts to compute the trip count.
173 /// If the trip count is not directly available (as an immediate value,
174 /// or a register), the function will attempt to insert computation of it
175 /// to the loop's preheader.
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000176 CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
177 const MachineOperand *End, unsigned IVReg,
178 int64_t IVBump, Comparison::Kind Cmp) const;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000179
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000180 /// \brief Return true if the instruction is not valid within a hardware
181 /// loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000182 bool isInvalidLoopOperation(const MachineInstr *MI) const;
183
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000184 /// \brief Return true if the loop contains an instruction that inhibits
185 /// using the hardware loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000186 bool containsInvalidInstruction(MachineLoop *L) const;
187
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000188 /// \brief Given a loop, check if we can convert it to a hardware loop.
189 /// If so, then perform the conversion and return true.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000190 bool convertToHardwareLoop(MachineLoop *L);
191
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000192 /// \brief Return true if the instruction is now dead.
193 bool isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000194 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000195
196 /// \brief Remove the instruction if it is now dead.
197 void removeIfDead(MachineInstr *MI);
198
199 /// \brief Make sure that the "bump" instruction executes before the
200 /// compare. We need that for the IV fixup, so that the compare
201 /// instruction would not use a bumped value that has not yet been
202 /// defined. If the instructions are out of order, try to reorder them.
203 bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
204
205 /// \brief Get the instruction that loads an immediate value into \p R,
206 /// or 0 if such an instruction does not exist.
207 MachineInstr *defWithImmediate(unsigned R);
208
209 /// \brief Get the immediate value referenced to by \p MO, either for
210 /// immediate operands, or for register operands, where the register
211 /// was defined with an immediate value.
212 int64_t getImmediate(MachineOperand &MO);
213
214 /// \brief Reset the given machine operand to now refer to a new immediate
215 /// value. Assumes that the operand was already referencing an immediate
216 /// value, either directly, or via a register.
217 void setImmediate(MachineOperand &MO, int64_t Val);
218
219 /// \brief Fix the data flow of the induction varible.
220 /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
221 /// |
222 /// +-> back to phi
223 /// where "bump" is the increment of the induction variable:
224 /// iv = iv + #const.
225 /// Due to some prior code transformations, the actual flow may look
226 /// like this:
227 /// phi -+-> bump ---> back to phi
228 /// |
229 /// +-> comparison-in-latch (against upper_bound-bump),
230 /// i.e. the comparison that controls the loop execution may be using
231 /// the value of the induction variable from before the increment.
232 ///
233 /// Return true if the loop's flow is the desired one (i.e. it's
234 /// either been fixed, or no fixing was necessary).
235 /// Otherwise, return false. This can happen if the induction variable
236 /// couldn't be identified, or if the value in the latch's comparison
237 /// cannot be adjusted to reflect the post-bump value.
238 bool fixupInductionVariable(MachineLoop *L);
239
240 /// \brief Given a loop, if it does not have a preheader, create one.
241 /// Return the block that is the preheader.
242 MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000243 };
244
245 char HexagonHardwareLoops::ID = 0;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000246#ifndef NDEBUG
247 int HexagonHardwareLoops::Counter = 0;
248#endif
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000249
Sid Manning67a89362014-08-28 14:16:32 +0000250 /// \brief Abstraction for a trip count of a loop. A smaller version
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000251 /// of the MachineOperand class without the concerns of changing the
252 /// operand representation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000253 class CountValue {
254 public:
255 enum CountValueType {
256 CV_Register,
257 CV_Immediate
258 };
259 private:
260 CountValueType Kind;
261 union Values {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000262 struct {
263 unsigned Reg;
264 unsigned Sub;
265 } R;
266 unsigned ImmVal;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000267 } Contents;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000268
269 public:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000270 explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
271 Kind = t;
272 if (Kind == CV_Register) {
273 Contents.R.Reg = v;
274 Contents.R.Sub = u;
275 } else {
276 Contents.ImmVal = v;
277 }
278 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000279 bool isReg() const { return Kind == CV_Register; }
280 bool isImm() const { return Kind == CV_Immediate; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000281
282 unsigned getReg() const {
283 assert(isReg() && "Wrong CountValue accessor");
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000284 return Contents.R.Reg;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000285 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000286 unsigned getSubReg() const {
287 assert(isReg() && "Wrong CountValue accessor");
288 return Contents.R.Sub;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000289 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000290 unsigned getImm() const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000291 assert(isImm() && "Wrong CountValue accessor");
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000292 return Contents.ImmVal;
293 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000294
Eric Christopher2c44f432015-02-02 19:05:28 +0000295 void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000296 if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
297 if (isImm()) { OS << Contents.ImmVal; }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000298 }
299 };
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000300} // end anonymous namespace
301
302
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000303INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
304 "Hexagon Hardware Loops", false, false)
305INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
306INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
307INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
308 "Hexagon Hardware Loops", false, false)
309
310
311/// \brief Returns true if the instruction is a hardware loop instruction.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000312static bool isHardwareLoop(const MachineInstr *MI) {
Colin LeMahieu5ccbb122014-12-19 00:06:53 +0000313 return MI->getOpcode() == Hexagon::J2_loop0r ||
314 MI->getOpcode() == Hexagon::J2_loop0i;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000315}
316
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000317FunctionPass *llvm::createHexagonHardwareLoops() {
318 return new HexagonHardwareLoops();
319}
320
321
322bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
323 DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
324
325 bool Changed = false;
326
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000327 MLI = &getAnalysis<MachineLoopInfo>();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000328 MRI = &MF.getRegInfo();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000329 MDT = &getAnalysis<MachineDominatorTree>();
Eric Christopher2c44f432015-02-02 19:05:28 +0000330 TII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000331
332 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end();
333 I != E; ++I) {
334 MachineLoop *L = *I;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000335 if (!L->getParentLoop())
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000336 Changed |= convertToHardwareLoop(L);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000337 }
338
339 return Changed;
340}
341
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000342/// \brief Return the latch block if it's one of the exiting blocks. Otherwise,
343/// return the exiting block. Return 'null' when multiple exiting blocks are
344/// present.
345static MachineBasicBlock* getExitingBlock(MachineLoop *L) {
346 if (MachineBasicBlock *Latch = L->getLoopLatch()) {
347 if (L->isLoopExiting(Latch))
348 return Latch;
349 else
350 return L->getExitingBlock();
351 }
352 return nullptr;
353}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000354
355bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
356 unsigned &Reg,
357 int64_t &IVBump,
358 MachineInstr *&IVOp
359 ) const {
360 MachineBasicBlock *Header = L->getHeader();
361 MachineBasicBlock *Preheader = L->getLoopPreheader();
362 MachineBasicBlock *Latch = L->getLoopLatch();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000363 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
364 if (!Header || !Preheader || !Latch || !ExitingBlock)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000365 return false;
366
367 // This pair represents an induction register together with an immediate
368 // value that will be added to it in each loop iteration.
369 typedef std::pair<unsigned,int64_t> RegisterBump;
370
371 // Mapping: R.next -> (R, bump), where R, R.next and bump are derived
372 // from an induction operation
373 // R.next = R + bump
374 // where bump is an immediate value.
375 typedef std::map<unsigned,RegisterBump> InductionMap;
376
377 InductionMap IndMap;
378
379 typedef MachineBasicBlock::instr_iterator instr_iterator;
380 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
381 I != E && I->isPHI(); ++I) {
382 MachineInstr *Phi = &*I;
383
384 // Have a PHI instruction. Get the operand that corresponds to the
385 // latch block, and see if is a result of an addition of form "reg+imm",
386 // where the "reg" is defined by the PHI node we are looking at.
387 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
388 if (Phi->getOperand(i+1).getMBB() != Latch)
389 continue;
390
391 unsigned PhiOpReg = Phi->getOperand(i).getReg();
392 MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
393 unsigned UpdOpc = DI->getOpcode();
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000394 bool isAdd = (UpdOpc == Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000395
396 if (isAdd) {
397 // If the register operand to the add is the PHI we're
398 // looking at, this meets the induction pattern.
399 unsigned IndReg = DI->getOperand(1).getReg();
400 if (MRI->getVRegDef(IndReg) == Phi) {
401 unsigned UpdReg = DI->getOperand(0).getReg();
402 int64_t V = DI->getOperand(2).getImm();
403 IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
404 }
405 }
406 } // for (i)
407 } // for (instr)
408
409 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000410 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000411 bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000412 if (NotAnalyzed)
413 return false;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000414
Brendon Cahoondf43e682015-05-08 16:16:29 +0000415 unsigned PredR, PredPos, PredRegFlags;
416 if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
417 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000418
419 MachineInstr *PredI = MRI->getVRegDef(PredR);
420 if (!PredI->isCompare())
421 return false;
422
423 unsigned CmpReg1 = 0, CmpReg2 = 0;
424 int CmpImm = 0, CmpMask = 0;
425 bool CmpAnalyzed = TII->analyzeCompare(PredI, CmpReg1, CmpReg2,
426 CmpMask, CmpImm);
427 // Fail if the compare was not analyzed, or it's not comparing a register
428 // with an immediate value. Not checking the mask here, since we handle
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000429 // the individual compare opcodes (including A4_cmpb*) later on.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000430 if (!CmpAnalyzed)
431 return false;
432
433 // Exactly one of the input registers to the comparison should be among
434 // the induction registers.
435 InductionMap::iterator IndMapEnd = IndMap.end();
436 InductionMap::iterator F = IndMapEnd;
437 if (CmpReg1 != 0) {
438 InductionMap::iterator F1 = IndMap.find(CmpReg1);
439 if (F1 != IndMapEnd)
440 F = F1;
441 }
442 if (CmpReg2 != 0) {
443 InductionMap::iterator F2 = IndMap.find(CmpReg2);
444 if (F2 != IndMapEnd) {
445 if (F != IndMapEnd)
446 return false;
447 F = F2;
448 }
449 }
450 if (F == IndMapEnd)
451 return false;
452
453 Reg = F->second.first;
454 IVBump = F->second.second;
455 IVOp = MRI->getVRegDef(F->first);
456 return true;
457}
458
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000459// Return the comparison kind for the specified opcode.
460HexagonHardwareLoops::Comparison::Kind
461HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
462 MachineOperand *InitialValue,
463 const MachineOperand *EndValue,
464 int64_t IVBump) const {
465 Comparison::Kind Cmp = (Comparison::Kind)0;
466 switch (CondOpc) {
467 case Hexagon::C2_cmpeqi:
468 case Hexagon::C2_cmpeq:
469 case Hexagon::C2_cmpeqp:
470 Cmp = Comparison::Kind::EQ;
471 break;
472 case Hexagon::C4_cmpneq:
473 case Hexagon::C4_cmpneqi:
474 Cmp = Comparison::Kind::NE;
475 break;
476 case Hexagon::C4_cmplte:
477 Cmp = Comparison::Kind::LEs;
478 break;
479 case Hexagon::C4_cmplteu:
480 Cmp = Comparison::Kind::LEu;
481 break;
482 case Hexagon::C2_cmpgtui:
483 case Hexagon::C2_cmpgtu:
484 case Hexagon::C2_cmpgtup:
485 Cmp = Comparison::Kind::GTu;
486 break;
487 case Hexagon::C2_cmpgti:
488 case Hexagon::C2_cmpgt:
489 case Hexagon::C2_cmpgtp:
490 Cmp = Comparison::Kind::GTs;
491 break;
492 default:
493 return (Comparison::Kind)0;
494 }
495 return Cmp;
496}
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000497
498/// \brief Analyze the statements in a loop to determine if the loop has
499/// a computable trip count and, if so, return a value that represents
500/// the trip count expression.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000501///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000502/// This function iterates over the phi nodes in the loop to check for
503/// induction variable patterns that are used in the calculation for
504/// the number of time the loop is executed.
505CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000506 SmallVectorImpl<MachineInstr *> &OldInsts) {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000507 MachineBasicBlock *TopMBB = L->getTopBlock();
508 MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
509 assert(PI != TopMBB->pred_end() &&
510 "Loop must have more than one incoming edge!");
511 MachineBasicBlock *Backedge = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000512 if (PI == TopMBB->pred_end()) // dead loop?
Craig Topper062a2ba2014-04-25 05:30:21 +0000513 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000514 MachineBasicBlock *Incoming = *PI++;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000515 if (PI != TopMBB->pred_end()) // multiple backedges?
Craig Topper062a2ba2014-04-25 05:30:21 +0000516 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000517
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000518 // Make sure there is one incoming and one backedge and determine which
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000519 // is which.
520 if (L->contains(Incoming)) {
521 if (L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000522 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000523 std::swap(Incoming, Backedge);
524 } else if (!L->contains(Backedge))
Craig Topper062a2ba2014-04-25 05:30:21 +0000525 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000526
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000527 // Look for the cmp instruction to determine if we can get a useful trip
528 // count. The trip count can be either a register or an immediate. The
529 // location of the value depends upon the type (reg or imm).
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000530 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
531 if (!ExitingBlock)
Craig Topper062a2ba2014-04-25 05:30:21 +0000532 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000533
534 unsigned IVReg = 0;
535 int64_t IVBump = 0;
536 MachineInstr *IVOp;
537 bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
538 if (!FoundIV)
Craig Topper062a2ba2014-04-25 05:30:21 +0000539 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000540
541 MachineBasicBlock *Preheader = L->getLoopPreheader();
542
Craig Topper062a2ba2014-04-25 05:30:21 +0000543 MachineOperand *InitialValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000544 MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000545 MachineBasicBlock *Latch = L->getLoopLatch();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000546 for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
547 MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
548 if (MBB == Preheader)
549 InitialValue = &IV_Phi->getOperand(i);
550 else if (MBB == Latch)
551 IVReg = IV_Phi->getOperand(i).getReg(); // Want IV reg after bump.
552 }
553 if (!InitialValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000554 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000555
556 SmallVector<MachineOperand,2> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +0000557 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000558 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
559 if (NotAnalyzed)
Craig Topper062a2ba2014-04-25 05:30:21 +0000560 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000561
562 MachineBasicBlock *Header = L->getHeader();
563 // TB must be non-null. If FB is also non-null, one of them must be
564 // the header. Otherwise, branch to TB could be exiting the loop, and
565 // the fall through can go to the header.
566 assert (TB && "Latch block without a branch?");
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000567 if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
568 MachineBasicBlock *LTB = 0, *LFB = 0;
569 SmallVector<MachineOperand,2> LCond;
570 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, LTB, LFB, LCond, false);
571 if (NotAnalyzed)
572 return nullptr;
573 if (TB == Latch)
574 (LTB == Header) ? TB = LTB: TB = LFB;
575 else // FB == Latch
576 (LTB == Header) ? FB = LTB: FB = LFB;
577 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000578 assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
579 if (!TB || (FB && TB != Header && FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000580 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000581
582 // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
583 // to put imm(0), followed by P in the vector Cond.
584 // If TB is not the header, it means that the "not-taken" path must lead
585 // to the header.
Brendon Cahoondf43e682015-05-08 16:16:29 +0000586 bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
587 unsigned PredReg, PredPos, PredRegFlags;
588 if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
589 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000590 MachineInstr *CondI = MRI->getVRegDef(PredReg);
591 unsigned CondOpc = CondI->getOpcode();
592
593 unsigned CmpReg1 = 0, CmpReg2 = 0;
594 int Mask = 0, ImmValue = 0;
595 bool AnalyzedCmp = TII->analyzeCompare(CondI, CmpReg1, CmpReg2,
596 Mask, ImmValue);
597 if (!AnalyzedCmp)
Craig Topper062a2ba2014-04-25 05:30:21 +0000598 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000599
600 // The comparison operator type determines how we compute the loop
601 // trip count.
602 OldInsts.push_back(CondI);
603 OldInsts.push_back(IVOp);
604
605 // Sadly, the following code gets information based on the position
606 // of the operands in the compare instruction. This has to be done
607 // this way, because the comparisons check for a specific relationship
608 // between the operands (e.g. is-less-than), rather than to find out
609 // what relationship the operands are in (as on PPC).
610 Comparison::Kind Cmp;
611 bool isSwapped = false;
612 const MachineOperand &Op1 = CondI->getOperand(1);
613 const MachineOperand &Op2 = CondI->getOperand(2);
Craig Topper062a2ba2014-04-25 05:30:21 +0000614 const MachineOperand *EndValue = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000615
616 if (Op1.isReg()) {
617 if (Op2.isImm() || Op1.getReg() == IVReg)
618 EndValue = &Op2;
619 else {
620 EndValue = &Op1;
621 isSwapped = true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000622 }
623 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000624
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000625 if (!EndValue)
Craig Topper062a2ba2014-04-25 05:30:21 +0000626 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000627
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000628 Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
629 if (!Cmp)
630 return nullptr;
631 if (Negated)
632 Cmp = Comparison::getNegatedComparison(Cmp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000633 if (isSwapped)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000634 Cmp = Comparison::getSwappedComparison(Cmp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000635
636 if (InitialValue->isReg()) {
637 unsigned R = InitialValue->getReg();
638 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
639 if (!MDT->properlyDominates(DefBB, Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000640 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000641 OldInsts.push_back(MRI->getVRegDef(R));
642 }
643 if (EndValue->isReg()) {
644 unsigned R = EndValue->getReg();
645 MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
646 if (!MDT->properlyDominates(DefBB, Header))
Craig Topper062a2ba2014-04-25 05:30:21 +0000647 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000648 }
649
650 return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000651}
652
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000653/// \brief Helper function that returns the expression that represents the
654/// number of times a loop iterates. The function takes the operands that
655/// represent the loop start value, loop end value, and induction value.
656/// Based upon these operands, the function attempts to compute the trip count.
657CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
658 const MachineOperand *Start,
659 const MachineOperand *End,
660 unsigned IVReg,
661 int64_t IVBump,
662 Comparison::Kind Cmp) const {
663 // Cannot handle comparison EQ, i.e. while (A == B).
664 if (Cmp == Comparison::EQ)
Craig Topper062a2ba2014-04-25 05:30:21 +0000665 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000666
667 // Check if either the start or end values are an assignment of an immediate.
668 // If so, use the immediate value rather than the register.
669 if (Start->isReg()) {
670 const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000671 if (StartValInstr && StartValInstr->getOpcode() == Hexagon::A2_tfrsi)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000672 Start = &StartValInstr->getOperand(1);
673 }
674 if (End->isReg()) {
675 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
Colin LeMahieu4af437f2014-12-09 20:23:30 +0000676 if (EndValInstr && EndValInstr->getOpcode() == Hexagon::A2_tfrsi)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000677 End = &EndValInstr->getOperand(1);
678 }
679
680 assert (Start->isReg() || Start->isImm());
681 assert (End->isReg() || End->isImm());
682
683 bool CmpLess = Cmp & Comparison::L;
684 bool CmpGreater = Cmp & Comparison::G;
685 bool CmpHasEqual = Cmp & Comparison::EQ;
686
687 // Avoid certain wrap-arounds. This doesn't detect all wrap-arounds.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000688 if (CmpLess && IVBump < 0)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000689 // Loop going while iv is "less" with the iv value going down. Must wrap.
Craig Topper062a2ba2014-04-25 05:30:21 +0000690 return nullptr;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000691
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000692 // If loop executes while iv is "greater" with the iv value going up, then
693 // the iv must wrap.
694 if (CmpGreater && IVBump > 0)
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000695 // Loop going while iv is "greater" with the iv value going up. Must wrap.
Craig Topper062a2ba2014-04-25 05:30:21 +0000696 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000697
698 if (Start->isImm() && End->isImm()) {
699 // Both, start and end are immediates.
700 int64_t StartV = Start->getImm();
701 int64_t EndV = End->getImm();
702 int64_t Dist = EndV - StartV;
703 if (Dist == 0)
Craig Topper062a2ba2014-04-25 05:30:21 +0000704 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000705
706 bool Exact = (Dist % IVBump) == 0;
707
708 if (Cmp == Comparison::NE) {
709 if (!Exact)
Craig Topper062a2ba2014-04-25 05:30:21 +0000710 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000711 if ((Dist < 0) ^ (IVBump < 0))
Craig Topper062a2ba2014-04-25 05:30:21 +0000712 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000713 }
714
715 // For comparisons that include the final value (i.e. include equality
716 // with the final value), we need to increase the distance by 1.
717 if (CmpHasEqual)
718 Dist = Dist > 0 ? Dist+1 : Dist-1;
719
720 // assert (CmpLess => Dist > 0);
721 assert ((!CmpLess || Dist > 0) && "Loop should never iterate!");
722 // assert (CmpGreater => Dist < 0);
723 assert ((!CmpGreater || Dist < 0) && "Loop should never iterate!");
724
725 // "Normalized" distance, i.e. with the bump set to +-1.
726 int64_t Dist1 = (IVBump > 0) ? (Dist + (IVBump-1)) / IVBump
727 : (-Dist + (-IVBump-1)) / (-IVBump);
728 assert (Dist1 > 0 && "Fishy thing. Both operands have the same sign.");
729
730 uint64_t Count = Dist1;
731
732 if (Count > 0xFFFFFFFFULL)
Craig Topper062a2ba2014-04-25 05:30:21 +0000733 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000734
735 return new CountValue(CountValue::CV_Immediate, Count);
736 }
737
738 // A general case: Start and End are some values, but the actual
739 // iteration count may not be available. If it is not, insert
740 // a computation of it into the preheader.
741
742 // If the induction variable bump is not a power of 2, quit.
743 // Othwerise we'd need a general integer division.
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +0000744 if (!isPowerOf2_64(std::abs(IVBump)))
Craig Topper062a2ba2014-04-25 05:30:21 +0000745 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000746
747 MachineBasicBlock *PH = Loop->getLoopPreheader();
748 assert (PH && "Should have a preheader by now");
749 MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000750 DebugLoc DL;
751 if (InsertPos != PH->end())
752 InsertPos->getDebugLoc();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000753
754 // If Start is an immediate and End is a register, the trip count
755 // will be "reg - imm". Hexagon's "subtract immediate" instruction
756 // is actually "reg + -imm".
757
758 // If the loop IV is going downwards, i.e. if the bump is negative,
759 // then the iteration count (computed as End-Start) will need to be
760 // negated. To avoid the negation, just swap Start and End.
761 if (IVBump < 0) {
762 std::swap(Start, End);
763 IVBump = -IVBump;
764 }
765 // Cmp may now have a wrong direction, e.g. LEs may now be GEs.
766 // Signedness, and "including equality" are preserved.
767
768 bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
769 bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
770
771 int64_t StartV = 0, EndV = 0;
772 if (Start->isImm())
773 StartV = Start->getImm();
774 if (End->isImm())
775 EndV = End->getImm();
776
777 int64_t AdjV = 0;
778 // To compute the iteration count, we would need this computation:
779 // Count = (End - Start + (IVBump-1)) / IVBump
780 // or, when CmpHasEqual:
781 // Count = (End - Start + (IVBump-1)+1) / IVBump
782 // The "IVBump-1" part is the adjustment (AdjV). We can avoid
783 // generating an instruction specifically to add it if we can adjust
784 // the immediate values for Start or End.
785
786 if (CmpHasEqual) {
787 // Need to add 1 to the total iteration count.
788 if (Start->isImm())
789 StartV--;
790 else if (End->isImm())
791 EndV++;
792 else
793 AdjV += 1;
794 }
795
796 if (Cmp != Comparison::NE) {
797 if (Start->isImm())
798 StartV -= (IVBump-1);
799 else if (End->isImm())
800 EndV += (IVBump-1);
801 else
802 AdjV += (IVBump-1);
803 }
804
805 unsigned R = 0, SR = 0;
806 if (Start->isReg()) {
807 R = Start->getReg();
808 SR = Start->getSubReg();
809 } else {
810 R = End->getReg();
811 SR = End->getSubReg();
812 }
813 const TargetRegisterClass *RC = MRI->getRegClass(R);
814 // Hardware loops cannot handle 64-bit registers. If it's a double
815 // register, it has to have a subregister.
816 if (!SR && RC == &Hexagon::DoubleRegsRegClass)
Craig Topper062a2ba2014-04-25 05:30:21 +0000817 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000818 const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
819
820 // Compute DistR (register with the distance between Start and End).
821 unsigned DistR, DistSR;
822
823 // Avoid special case, where the start value is an imm(0).
824 if (Start->isImm() && StartV == 0) {
825 DistR = End->getReg();
826 DistSR = End->getSubReg();
827 } else {
Colin LeMahieue88447d2014-11-21 21:19:18 +0000828 const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
Colin LeMahieu27d50072015-02-05 18:38:08 +0000829 (RegToImm ? TII->get(Hexagon::A2_subri) :
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000830 TII->get(Hexagon::A2_addi));
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000831 if (RegToReg || RegToImm) {
832 unsigned SubR = MRI->createVirtualRegister(IntRC);
833 MachineInstrBuilder SubIB =
834 BuildMI(*PH, InsertPos, DL, SubD, SubR);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000835
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000836 if (RegToReg)
837 SubIB.addReg(End->getReg(), 0, End->getSubReg())
838 .addReg(Start->getReg(), 0, Start->getSubReg());
839 else
840 SubIB.addImm(EndV)
841 .addReg(Start->getReg(), 0, Start->getSubReg());
842 DistR = SubR;
843 } else {
844 // If the loop has been unrolled, we should use the original loop count
845 // instead of recalculating the value. This will avoid additional
846 // 'Add' instruction.
847 const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
848 if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
849 EndValInstr->getOperand(2).getImm() == StartV) {
850 DistR = EndValInstr->getOperand(1).getReg();
851 } else {
852 unsigned SubR = MRI->createVirtualRegister(IntRC);
853 MachineInstrBuilder SubIB =
854 BuildMI(*PH, InsertPos, DL, SubD, SubR);
855 SubIB.addReg(End->getReg(), 0, End->getSubReg())
856 .addImm(-StartV);
857 DistR = SubR;
858 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000859 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000860 DistSR = 0;
861 }
862
863 // From DistR, compute AdjR (register with the adjusted distance).
864 unsigned AdjR, AdjSR;
865
866 if (AdjV == 0) {
867 AdjR = DistR;
868 AdjSR = DistSR;
869 } else {
870 // Generate CountR = ADD DistR, AdjVal
871 unsigned AddR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuf297dbe2015-02-05 17:49:13 +0000872 MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000873 BuildMI(*PH, InsertPos, DL, AddD, AddR)
874 .addReg(DistR, 0, DistSR)
875 .addImm(AdjV);
876
877 AdjR = AddR;
878 AdjSR = 0;
879 }
880
881 // From AdjR, compute CountR (register with the final count).
882 unsigned CountR, CountSR;
883
884 if (IVBump == 1) {
885 CountR = AdjR;
886 CountSR = AdjSR;
887 } else {
888 // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
889 unsigned Shift = Log2_32(IVBump);
890
891 // Generate NormR = LSR DistR, Shift.
892 unsigned LsrR = MRI->createVirtualRegister(IntRC);
Colin LeMahieuaa1bade2014-12-16 23:36:15 +0000893 const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000894 BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
895 .addReg(AdjR, 0, AdjSR)
896 .addImm(Shift);
897
898 CountR = LsrR;
899 CountSR = 0;
900 }
901
902 return new CountValue(CountValue::CV_Register, CountR, CountSR);
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000903}
904
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000905
906/// \brief Return true if the operation is invalid within hardware loop.
907bool HexagonHardwareLoops::isInvalidLoopOperation(
908 const MachineInstr *MI) const {
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000909
Brendon Cahoonbece8ed2015-05-08 20:18:21 +0000910 // Call is not allowed because the callee may use a hardware loop except for
911 // the case when the call never returns.
912 if (MI->getDesc().isCall() && MI->getOpcode() != Hexagon::CALLv3nr)
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000913 return true;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000914
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000915 // do not allow nested hardware loops
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000916 if (isHardwareLoop(MI))
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000917 return true;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000918
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000919 // check if the instruction defines a hardware loop register
920 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
921 const MachineOperand &MO = MI->getOperand(i);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000922 if (!MO.isReg() || !MO.isDef())
923 continue;
924 unsigned R = MO.getReg();
925 if (R == Hexagon::LC0 || R == Hexagon::LC1 ||
926 R == Hexagon::SA0 || R == Hexagon::SA1)
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000927 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000928 }
929 return false;
930}
931
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000932
933/// \brief - Return true if the loop contains an instruction that inhibits
934/// the use of the hardware loop function.
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000935bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L) const {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000936 const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000937 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
938 MachineBasicBlock *MBB = Blocks[i];
939 for (MachineBasicBlock::iterator
940 MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
941 const MachineInstr *MI = &*MII;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000942 if (isInvalidLoopOperation(MI))
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000943 return true;
Tony Linthicum1213a7a2011-12-12 21:14:40 +0000944 }
945 }
946 return false;
947}
948
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000949
950/// \brief Returns true if the instruction is dead. This was essentially
951/// copied from DeadMachineInstructionElim::isDead, but with special cases
952/// for inline asm, physical registers and instructions with side effects
953/// removed.
954bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
Craig Topperb94011f2013-07-14 04:42:23 +0000955 SmallVectorImpl<MachineInstr *> &DeadPhis) const {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000956 // Examine each operand.
957 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
958 const MachineOperand &MO = MI->getOperand(i);
959 if (!MO.isReg() || !MO.isDef())
960 continue;
961
962 unsigned Reg = MO.getReg();
963 if (MRI->use_nodbg_empty(Reg))
964 continue;
965
966 typedef MachineRegisterInfo::use_nodbg_iterator use_nodbg_iterator;
967
968 // This instruction has users, but if the only user is the phi node for the
969 // parent block, and the only use of that phi node is this instruction, then
970 // this instruction is dead: both it (and the phi node) can be removed.
971 use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
972 use_nodbg_iterator End = MRI->use_nodbg_end();
Owen Anderson16c6bf42014-03-13 23:12:04 +0000973 if (std::next(I) != End || !I->getParent()->isPHI())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000974 return false;
975
Owen Anderson16c6bf42014-03-13 23:12:04 +0000976 MachineInstr *OnePhi = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000977 for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
978 const MachineOperand &OPO = OnePhi->getOperand(j);
979 if (!OPO.isReg() || !OPO.isDef())
980 continue;
981
982 unsigned OPReg = OPO.getReg();
983 use_nodbg_iterator nextJ;
984 for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
985 J != End; J = nextJ) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000986 nextJ = std::next(J);
Owen Anderson16c6bf42014-03-13 23:12:04 +0000987 MachineOperand &Use = *J;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +0000988 MachineInstr *UseMI = Use.getParent();
989
990 // If the phi node has a user that is not MI, bail...
991 if (MI != UseMI)
992 return false;
993 }
994 }
995 DeadPhis.push_back(OnePhi);
996 }
997
998 // If there are no defs with uses, the instruction is dead.
999 return true;
1000}
1001
1002void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
1003 // This procedure was essentially copied from DeadMachineInstructionElim.
1004
1005 SmallVector<MachineInstr*, 1> DeadPhis;
1006 if (isDead(MI, DeadPhis)) {
1007 DEBUG(dbgs() << "HW looping will remove: " << *MI);
1008
1009 // It is possible that some DBG_VALUE instructions refer to this
1010 // instruction. Examine each def operand for such references;
1011 // if found, mark the DBG_VALUE as undef (but don't delete it).
1012 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1013 const MachineOperand &MO = MI->getOperand(i);
1014 if (!MO.isReg() || !MO.isDef())
1015 continue;
1016 unsigned Reg = MO.getReg();
1017 MachineRegisterInfo::use_iterator nextI;
1018 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
1019 E = MRI->use_end(); I != E; I = nextI) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001020 nextI = std::next(I); // I is invalidated by the setReg
Owen Anderson16c6bf42014-03-13 23:12:04 +00001021 MachineOperand &Use = *I;
1022 MachineInstr *UseMI = I->getParent();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001023 if (UseMI == MI)
1024 continue;
1025 if (Use.isDebug())
1026 UseMI->getOperand(0).setReg(0U);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001027 }
1028 }
1029
1030 MI->eraseFromParent();
1031 for (unsigned i = 0; i < DeadPhis.size(); ++i)
1032 DeadPhis[i]->eraseFromParent();
1033 }
1034}
1035
1036/// \brief Check if the loop is a candidate for converting to a hardware
1037/// loop. If so, then perform the transformation.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001038///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001039/// This function works on innermost loops first. A loop can be converted
1040/// if it is a counting loop; either a register value or an immediate.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001041///
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001042/// The code makes several assumptions about the representation of the loop
1043/// in llvm.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001044bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001045 // This is just for sanity.
1046 assert(L->getHeader() && "Loop without a header?");
1047
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001048 bool Changed = false;
1049 // Process nested loops first.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001050 for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001051 Changed |= convertToHardwareLoop(*I);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001052
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001053 // If a nested loop has been converted, then we can't convert this loop.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001054 if (Changed)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001055 return Changed;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001056
1057#ifndef NDEBUG
1058 // Stop trying after reaching the limit (if any).
1059 int Limit = HWLoopLimit;
1060 if (Limit >= 0) {
1061 if (Counter >= HWLoopLimit)
1062 return false;
1063 Counter++;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001064 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001065#endif
1066
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001067 // Does the loop contain any invalid instructions?
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001068 if (containsInvalidInstruction(L))
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001069 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001070
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001071 MachineBasicBlock *LastMBB = L->getExitingBlock();
1072 // Don't generate hw loop if the loop has more than one exit.
Craig Topper062a2ba2014-04-25 05:30:21 +00001073 if (!LastMBB)
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001074 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001075
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001076 MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001077 if (LastI == LastMBB->end())
Matthew Curtis7a938112012-12-07 21:03:15 +00001078 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001079
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001080 // Is the induction variable bump feeding the latch condition?
1081 if (!fixupInductionVariable(L))
1082 return false;
1083
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001084 // Ensure the loop has a preheader: the loop instruction will be
1085 // placed there.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001086 MachineBasicBlock *Preheader = L->getLoopPreheader();
1087 if (!Preheader) {
1088 Preheader = createPreheaderForLoop(L);
1089 if (!Preheader)
1090 return false;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001091 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001092
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001093 MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1094
1095 SmallVector<MachineInstr*, 2> OldInsts;
1096 // Are we able to determine the trip count for the loop?
1097 CountValue *TripCount = getLoopTripCount(L, OldInsts);
Craig Topper062a2ba2014-04-25 05:30:21 +00001098 if (!TripCount)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001099 return false;
1100
1101 // Is the trip count available in the preheader?
1102 if (TripCount->isReg()) {
1103 // There will be a use of the register inserted into the preheader,
1104 // so make sure that the register is actually defined at that point.
1105 MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1106 MachineBasicBlock *BBDef = TCDef->getParent();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001107 if (!MDT->dominates(BBDef, Preheader))
1108 return false;
Matthew Curtis7a938112012-12-07 21:03:15 +00001109 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001110
1111 // Determine the loop start.
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001112 MachineBasicBlock *TopBlock = L->getTopBlock();
1113 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1114 MachineBasicBlock *LoopStart = 0;
1115 if (ExitingBlock != L->getLoopLatch()) {
1116 MachineBasicBlock *TB = 0, *FB = 0;
1117 SmallVector<MachineOperand, 2> Cond;
1118
1119 if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false))
1120 return false;
1121
1122 if (L->contains(TB))
1123 LoopStart = TB;
1124 else if (L->contains(FB))
1125 LoopStart = FB;
1126 else
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001127 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001128 }
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001129 else
1130 LoopStart = TopBlock;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001131
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001132 // Convert the loop to a hardware loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001133 DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001134 DebugLoc DL;
Matthew Curtis7a938112012-12-07 21:03:15 +00001135 if (InsertPos != Preheader->end())
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001136 DL = InsertPos->getDebugLoc();
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001137
1138 if (TripCount->isReg()) {
1139 // Create a copy of the loop count register.
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001140 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1141 BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1142 .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
Benjamin Kramerbde91762012-06-02 10:20:22 +00001143 // Add the Loop instruction to the beginning of the loop.
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001144 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::J2_loop0r))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001145 .addMBB(LoopStart)
1146 .addReg(CountReg);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001147 } else {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001148 assert(TripCount->isImm() && "Expecting immediate value for trip count");
1149 // Add the Loop immediate instruction to the beginning of the loop,
1150 // if the immediate fits in the instructions. Otherwise, we need to
1151 // create a new virtual register.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001152 int64_t CountImm = TripCount->getImm();
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001153 if (!TII->isValidOffset(Hexagon::J2_loop0i, CountImm)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001154 unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001155 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001156 .addImm(CountImm);
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001157 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::J2_loop0r))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001158 .addMBB(LoopStart).addReg(CountReg);
1159 } else
Colin LeMahieu5ccbb122014-12-19 00:06:53 +00001160 BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::J2_loop0i))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001161 .addMBB(LoopStart).addImm(CountImm);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001162 }
1163
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001164 // Make sure the loop start always has a reference in the CFG. We need
1165 // to create a BlockAddress operand to get this mechanism to work both the
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001166 // MachineBasicBlock and BasicBlock objects need the flag set.
1167 LoopStart->setHasAddressTaken();
1168 // This line is needed to set the hasAddressTaken flag on the BasicBlock
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001169 // object.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001170 BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
1171
1172 // Replace the loop branch with an endloop instruction.
Matthew Curtis7a938112012-12-07 21:03:15 +00001173 DebugLoc LastIDL = LastI->getDebugLoc();
1174 BuildMI(*LastMBB, LastI, LastIDL,
1175 TII->get(Hexagon::ENDLOOP0)).addMBB(LoopStart);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001176
1177 // The loop ends with either:
1178 // - a conditional branch followed by an unconditional branch, or
1179 // - a conditional branch to the loop start.
Colin LeMahieudb0b13c2014-12-10 21:24:10 +00001180 if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1181 LastI->getOpcode() == Hexagon::J2_jumpf) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001182 // Delete one and change/add an uncond. branch to out of the loop.
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001183 MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1184 LastI = LastMBB->erase(LastI);
1185 if (!L->contains(BranchTarget)) {
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001186 if (LastI != LastMBB->end())
1187 LastI = LastMBB->erase(LastI);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001188 SmallVector<MachineOperand, 0> Cond;
Craig Topper062a2ba2014-04-25 05:30:21 +00001189 TII->InsertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001190 }
1191 } else {
1192 // Conditional branch to loop start; just delete it.
1193 LastMBB->erase(LastI);
1194 }
1195 delete TripCount;
1196
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001197 // The induction operation and the comparison may now be
1198 // unneeded. If these are unneeded, then remove them.
1199 for (unsigned i = 0; i < OldInsts.size(); ++i)
1200 removeIfDead(OldInsts[i]);
1201
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001202 ++NumHWLoops;
1203 return true;
1204}
1205
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001206
1207bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1208 MachineInstr *CmpI) {
1209 assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1210
1211 MachineBasicBlock *BB = BumpI->getParent();
1212 if (CmpI->getParent() != BB)
1213 return false;
1214
1215 typedef MachineBasicBlock::instr_iterator instr_iterator;
1216 // Check if things are in order to begin with.
1217 for (instr_iterator I = BumpI, E = BB->instr_end(); I != E; ++I)
1218 if (&*I == CmpI)
1219 return true;
1220
1221 // Out of order.
1222 unsigned PredR = CmpI->getOperand(0).getReg();
1223 bool FoundBump = false;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001224 instr_iterator CmpIt = CmpI, NextIt = std::next(CmpIt);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001225 for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1226 MachineInstr *In = &*I;
1227 for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1228 MachineOperand &MO = In->getOperand(i);
1229 if (MO.isReg() && MO.isUse()) {
1230 if (MO.getReg() == PredR) // Found an intervening use of PredR.
1231 return false;
1232 }
1233 }
1234
1235 if (In == BumpI) {
1236 instr_iterator After = BumpI;
1237 instr_iterator From = CmpI;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001238 BB->splice(std::next(After), BB, From);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001239 FoundBump = true;
1240 break;
1241 }
1242 }
1243 assert (FoundBump && "Cannot determine instruction order");
1244 return FoundBump;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001245}
1246
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001247
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001248MachineInstr *HexagonHardwareLoops::defWithImmediate(unsigned R) {
1249 MachineInstr *DI = MRI->getVRegDef(R);
1250 unsigned DOpc = DI->getOpcode();
1251 switch (DOpc) {
Colin LeMahieu4af437f2014-12-09 20:23:30 +00001252 case Hexagon::A2_tfrsi:
Colin LeMahieu0f850bd2014-12-19 20:29:29 +00001253 case Hexagon::A2_tfrpi:
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001254 case Hexagon::CONST32_Int_Real:
1255 case Hexagon::CONST64_Int_Real:
1256 return DI;
1257 }
Craig Topper062a2ba2014-04-25 05:30:21 +00001258 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001259}
1260
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001261
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001262int64_t HexagonHardwareLoops::getImmediate(MachineOperand &MO) {
1263 if (MO.isImm())
1264 return MO.getImm();
1265 assert(MO.isReg());
1266 unsigned R = MO.getReg();
1267 MachineInstr *DI = defWithImmediate(R);
1268 assert(DI && "Need an immediate operand");
1269 // All currently supported "define-with-immediate" instructions have the
1270 // actual immediate value in the operand(1).
1271 int64_t v = DI->getOperand(1).getImm();
1272 return v;
1273}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001274
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001275
1276void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1277 if (MO.isImm()) {
1278 MO.setImm(Val);
1279 return;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001280 }
1281
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001282 assert(MO.isReg());
1283 unsigned R = MO.getReg();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001284 MachineInstr *DI = MRI->getVRegDef(R);
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001285
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001286 const TargetRegisterClass *RC = MRI->getRegClass(R);
1287 unsigned NewR = MRI->createVirtualRegister(RC);
1288 MachineBasicBlock &B = *DI->getParent();
1289 DebugLoc DL = DI->getDebugLoc();
1290 BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR)
1291 .addImm(Val);
1292 MO.setReg(NewR);
1293}
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001294
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001295
1296bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1297 MachineBasicBlock *Header = L->getHeader();
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001298 MachineBasicBlock *Latch = L->getLoopLatch();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001299 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001300
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001301 if (!(Header && Latch && ExitingBlock))
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001302 return false;
1303
1304 // These data structures follow the same concept as the corresponding
1305 // ones in findInductionRegister (where some comments are).
1306 typedef std::pair<unsigned,int64_t> RegisterBump;
1307 typedef std::pair<unsigned,RegisterBump> RegisterInduction;
1308 typedef std::set<RegisterInduction> RegisterInductionSet;
1309
1310 // Register candidates for induction variables, with their associated bumps.
1311 RegisterInductionSet IndRegs;
1312
1313 // Look for induction patterns:
1314 // vreg1 = PHI ..., [ latch, vreg2 ]
1315 // vreg2 = ADD vreg1, imm
1316 typedef MachineBasicBlock::instr_iterator instr_iterator;
1317 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1318 I != E && I->isPHI(); ++I) {
1319 MachineInstr *Phi = &*I;
1320
1321 // Have a PHI instruction.
1322 for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1323 if (Phi->getOperand(i+1).getMBB() != Latch)
1324 continue;
1325
1326 unsigned PhiReg = Phi->getOperand(i).getReg();
1327 MachineInstr *DI = MRI->getVRegDef(PhiReg);
1328 unsigned UpdOpc = DI->getOpcode();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001329 bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001330
1331 if (isAdd) {
1332 // If the register operand to the add/sub is the PHI we are looking
1333 // at, this meets the induction pattern.
1334 unsigned IndReg = DI->getOperand(1).getReg();
1335 if (MRI->getVRegDef(IndReg) == Phi) {
1336 unsigned UpdReg = DI->getOperand(0).getReg();
1337 int64_t V = DI->getOperand(2).getImm();
1338 IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001339 }
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001340 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001341 } // for (i)
1342 } // for (instr)
1343
1344 if (IndRegs.empty())
1345 return false;
1346
Craig Topper062a2ba2014-04-25 05:30:21 +00001347 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001348 SmallVector<MachineOperand,2> Cond;
1349 // AnalyzeBranch returns true if it fails to analyze branch.
1350 bool NotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Cond, false);
1351 if (NotAnalyzed)
1352 return false;
1353
1354 // Check if the latch branch is unconditional.
1355 if (Cond.empty())
1356 return false;
1357
1358 if (TB != Header && FB != Header)
1359 // The latch does not go back to the header. Not a latch we know and love.
1360 return false;
1361
1362 // Expecting a predicate register as a condition. It won't be a hardware
1363 // predicate register at this point yet, just a vreg.
1364 // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1365 // into Cond, followed by the predicate register. For non-negated branches
1366 // it's just the register.
1367 unsigned CSz = Cond.size();
1368 if (CSz != 1 && CSz != 2)
1369 return false;
1370
1371 unsigned P = Cond[CSz-1].getReg();
1372 MachineInstr *PredDef = MRI->getVRegDef(P);
1373
1374 if (!PredDef->isCompare())
1375 return false;
1376
1377 SmallSet<unsigned,2> CmpRegs;
Craig Topper062a2ba2014-04-25 05:30:21 +00001378 MachineOperand *CmpImmOp = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001379
1380 // Go over all operands to the compare and look for immediate and register
1381 // operands. Assume that if the compare has a single register use and a
1382 // single immediate operand, then the register is being compared with the
1383 // immediate value.
1384 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1385 MachineOperand &MO = PredDef->getOperand(i);
1386 if (MO.isReg()) {
1387 // Skip all implicit references. In one case there was:
1388 // %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1389 if (MO.isImplicit())
1390 continue;
1391 if (MO.isUse()) {
1392 unsigned R = MO.getReg();
1393 if (!defWithImmediate(R)) {
1394 CmpRegs.insert(MO.getReg());
1395 continue;
1396 }
1397 // Consider the register to be the "immediate" operand.
1398 if (CmpImmOp)
1399 return false;
1400 CmpImmOp = &MO;
1401 }
1402 } else if (MO.isImm()) {
1403 if (CmpImmOp) // A second immediate argument? Confusing. Bail out.
1404 return false;
1405 CmpImmOp = &MO;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001406 }
1407 }
1408
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001409 if (CmpRegs.empty())
1410 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001411
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001412 // Check if the compared register follows the order we want. Fix if needed.
1413 for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1414 I != E; ++I) {
1415 // This is a success. If the register used in the comparison is one that
1416 // we have identified as a bumped (updated) induction register, there is
1417 // nothing to do.
1418 if (CmpRegs.count(I->first))
1419 return true;
1420
1421 // Otherwise, if the register being compared comes out of a PHI node,
1422 // and has been recognized as following the induction pattern, and is
1423 // compared against an immediate, we can fix it.
1424 const RegisterBump &RB = I->second;
1425 if (CmpRegs.count(RB.first)) {
1426 if (!CmpImmOp)
1427 return false;
1428
1429 int64_t CmpImm = getImmediate(*CmpImmOp);
1430 int64_t V = RB.second;
1431 if (V > 0 && CmpImm+V < CmpImm) // Overflow (64-bit).
1432 return false;
1433 if (V < 0 && CmpImm+V > CmpImm) // Overflow (64-bit).
1434 return false;
1435 CmpImm += V;
1436 // Some forms of cmp-immediate allow u9 and s10. Assume the worst case
1437 // scenario, i.e. an 8-bit value.
1438 if (CmpImmOp->isImm() && !isInt<8>(CmpImm))
1439 return false;
1440
1441 // Make sure that the compare happens after the bump. Otherwise,
1442 // after the fixup, the compare would use a yet-undefined register.
1443 MachineInstr *BumpI = MRI->getVRegDef(I->first);
1444 bool Order = orderBumpCompare(BumpI, PredDef);
1445 if (!Order)
1446 return false;
1447
1448 // Finally, fix the compare instruction.
1449 setImmediate(*CmpImmOp, CmpImm);
1450 for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1451 MachineOperand &MO = PredDef->getOperand(i);
1452 if (MO.isReg() && MO.getReg() == RB.first) {
1453 MO.setReg(I->first);
1454 return true;
1455 }
1456 }
1457 }
1458 }
1459
1460 return false;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001461}
1462
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001463
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001464/// \brief Create a preheader for a given loop.
1465MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1466 MachineLoop *L) {
1467 if (MachineBasicBlock *TmpPH = L->getLoopPreheader())
1468 return TmpPH;
1469
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001470 if (!HWCreatePreheader)
1471 return nullptr;
1472
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001473 MachineBasicBlock *Header = L->getHeader();
1474 MachineBasicBlock *Latch = L->getLoopLatch();
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001475 MachineBasicBlock *ExitingBlock = getExitingBlock(L);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001476 MachineFunction *MF = Header->getParent();
1477 DebugLoc DL;
1478
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001479#ifndef NDEBUG
1480 if ((PHFn != "") && (PHFn != MF->getName()))
1481 return nullptr;
1482#endif
1483
1484 if (!Latch || !ExitingBlock || Header->hasAddressTaken())
Craig Topper062a2ba2014-04-25 05:30:21 +00001485 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001486
1487 typedef MachineBasicBlock::instr_iterator instr_iterator;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001488
1489 // Verify that all existing predecessors have analyzable branches
1490 // (or no branches at all).
1491 typedef std::vector<MachineBasicBlock*> MBBVector;
1492 MBBVector Preds(Header->pred_begin(), Header->pred_end());
1493 SmallVector<MachineOperand,2> Tmp1;
Craig Topper062a2ba2014-04-25 05:30:21 +00001494 MachineBasicBlock *TB = nullptr, *FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001495
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001496 if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
Craig Topper062a2ba2014-04-25 05:30:21 +00001497 return nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001498
1499 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1500 MachineBasicBlock *PB = *I;
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001501 bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp1, false);
1502 if (NotAnalyzed)
1503 return nullptr;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001504 }
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001505
1506 MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
1507 MF->insert(Header, NewPH);
1508
1509 if (Header->pred_size() > 2) {
1510 // Ensure that the header has only two predecessors: the preheader and
1511 // the loop latch. Any additional predecessors of the header should
1512 // join at the newly created preheader. Inspect all PHI nodes from the
1513 // header and create appropriate corresponding PHI nodes in the preheader.
1514
1515 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1516 I != E && I->isPHI(); ++I) {
1517 MachineInstr *PN = &*I;
1518
1519 const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1520 MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1521 NewPH->insert(NewPH->end(), NewPN);
1522
1523 unsigned PR = PN->getOperand(0).getReg();
1524 const TargetRegisterClass *RC = MRI->getRegClass(PR);
1525 unsigned NewPR = MRI->createVirtualRegister(RC);
1526 NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1527
1528 // Copy all non-latch operands of a header's PHI node to the newly
1529 // created PHI node in the preheader.
1530 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1531 unsigned PredR = PN->getOperand(i).getReg();
1532 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1533 if (PredB == Latch)
1534 continue;
1535
1536 NewPN->addOperand(MachineOperand::CreateReg(PredR, false));
1537 NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1538 }
1539
1540 // Remove copied operands from the old PHI node and add the value
1541 // coming from the preheader's PHI.
1542 for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1543 MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1544 if (PredB != Latch) {
1545 PN->RemoveOperand(i+1);
1546 PN->RemoveOperand(i);
1547 }
1548 }
1549 PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1550 PN->addOperand(MachineOperand::CreateMBB(NewPH));
1551 }
1552
1553 } else {
1554 assert(Header->pred_size() == 2);
1555
1556 // The header has only two predecessors, but the non-latch predecessor
1557 // is not a preheader (e.g. it has other successors, etc.)
1558 // In such a case we don't need any extra PHI nodes in the new preheader,
1559 // all we need is to adjust existing PHIs in the header to now refer to
1560 // the new preheader.
1561 for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1562 I != E && I->isPHI(); ++I) {
1563 MachineInstr *PN = &*I;
1564 for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1565 MachineOperand &MO = PN->getOperand(i+1);
1566 if (MO.getMBB() != Latch)
1567 MO.setMBB(NewPH);
1568 }
1569 }
1570 }
1571
1572 // "Reroute" the CFG edges to link in the new preheader.
1573 // If any of the predecessors falls through to the header, insert a branch
1574 // to the new preheader in that place.
1575 SmallVector<MachineOperand,1> Tmp2;
1576 SmallVector<MachineOperand,1> EmptyCond;
1577
Craig Topper062a2ba2014-04-25 05:30:21 +00001578 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001579
1580 for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1581 MachineBasicBlock *PB = *I;
1582 if (PB != Latch) {
1583 Tmp2.clear();
1584 bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001585 (void)NotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001586 assert (!NotAnalyzed && "Should be analyzable!");
1587 if (TB != Header && (Tmp2.empty() || FB != Header))
Craig Topper062a2ba2014-04-25 05:30:21 +00001588 TII->InsertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001589 PB->ReplaceUsesOfBlockWith(Header, NewPH);
1590 }
1591 }
1592
1593 // It can happen that the latch block will fall through into the header.
1594 // Insert an unconditional branch to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001595 TB = FB = nullptr;
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001596 bool LatchNotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Tmp2, false);
Alp Tokercb402912014-01-24 17:20:08 +00001597 (void)LatchNotAnalyzed; // suppress compiler warning
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001598 assert (!LatchNotAnalyzed && "Should be analyzable!");
1599 if (!TB && !FB)
Craig Topper062a2ba2014-04-25 05:30:21 +00001600 TII->InsertBranch(*Latch, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001601
1602 // Finally, the branch from the preheader to the header.
Craig Topper062a2ba2014-04-25 05:30:21 +00001603 TII->InsertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001604 NewPH->addSuccessor(Header);
1605
Brendon Cahoonbece8ed2015-05-08 20:18:21 +00001606 MachineLoop *ParentLoop = L->getParentLoop();
1607 if (ParentLoop)
1608 ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
1609
1610 // Update the dominator information with the new preheader.
1611 if (MDT) {
1612 MachineDomTreeNode *HDom = MDT->getNode(Header);
1613 MDT->addNewBlock(NewPH, HDom->getIDom()->getBlock());
1614 MDT->changeImmediateDominator(Header, NewPH);
1615 }
1616
Krzysztof Parzyszek9a278f12013-02-11 21:37:55 +00001617 return NewPH;
Tony Linthicum1213a7a2011-12-12 21:14:40 +00001618}