xref: /llvm-project/llvm/lib/Target/Hexagon/HexagonHardwareLoops.cpp (revision 58156715b4038928c87615fcbb2c223e3c33a57f)
1 //===-- 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
24 //  - No function calls in loops.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #include "llvm/ADT/SmallSet.h"
29 #include "Hexagon.h"
30 #include "HexagonSubtarget.h"
31 #include "llvm/ADT/Statistic.h"
32 #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"
38 #include "llvm/PassSupport.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include <algorithm>
44 #include <vector>
45 
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "hwloops"
49 
50 #ifndef NDEBUG
51 static cl::opt<int> HWLoopLimit("hexagon-max-hwloop", cl::Hidden, cl::init(-1));
52 
53 // Option to create preheader only for a specific function.
54 static cl::opt<std::string> PHFn("hexagon-hwloop-phfn", cl::Hidden,
55                                  cl::init(""));
56 #endif
57 
58 // Option to create a preheader if one doesn't exist.
59 static 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 
63 // Turn it off by default. If a preheader block is not created here, the
64 // software pipeliner may be unable to find a block suitable to serve as
65 // a preheader. In that case SWP will not run.
66 static cl::opt<bool> SpecPreheader("hwloop-spec-preheader", cl::init(false),
67   cl::Hidden, cl::ZeroOrMore, cl::desc("Allow speculation of preheader "
68   "instructions"));
69 
70 STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
71 
72 namespace llvm {
73   FunctionPass *createHexagonHardwareLoops();
74   void initializeHexagonHardwareLoopsPass(PassRegistry&);
75 }
76 
77 namespace {
78   class CountValue;
79   struct HexagonHardwareLoops : public MachineFunctionPass {
80     MachineLoopInfo            *MLI;
81     MachineRegisterInfo        *MRI;
82     MachineDominatorTree       *MDT;
83     const HexagonInstrInfo     *TII;
84 #ifndef NDEBUG
85     static int Counter;
86 #endif
87 
88   public:
89     static char ID;
90 
91     HexagonHardwareLoops() : MachineFunctionPass(ID) {
92       initializeHexagonHardwareLoopsPass(*PassRegistry::getPassRegistry());
93     }
94 
95     bool runOnMachineFunction(MachineFunction &MF) override;
96 
97     const char *getPassName() const override { return "Hexagon Hardware Loops"; }
98 
99     void getAnalysisUsage(AnalysisUsage &AU) const override {
100       AU.addRequired<MachineDominatorTree>();
101       AU.addRequired<MachineLoopInfo>();
102       MachineFunctionPass::getAnalysisUsage(AU);
103     }
104 
105   private:
106     typedef std::map<unsigned, MachineInstr *> LoopFeederMap;
107 
108     /// Kinds of comparisons in the compare instructions.
109     struct Comparison {
110       enum Kind {
111         EQ  = 0x01,
112         NE  = 0x02,
113         L   = 0x04,
114         G   = 0x08,
115         U   = 0x40,
116         LTs = L,
117         LEs = L | EQ,
118         GTs = G,
119         GEs = G | EQ,
120         LTu = L      | U,
121         LEu = L | EQ | U,
122         GTu = G      | U,
123         GEu = G | EQ | U
124       };
125 
126       static Kind getSwappedComparison(Kind Cmp) {
127         assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
128         if ((Cmp & L) || (Cmp & G))
129           return (Kind)(Cmp ^ (L|G));
130         return Cmp;
131       }
132 
133       static Kind getNegatedComparison(Kind Cmp) {
134         if ((Cmp & L) || (Cmp & G))
135           return (Kind)((Cmp ^ (L | G)) ^ EQ);
136         if ((Cmp & NE) || (Cmp & EQ))
137           return (Kind)(Cmp ^ (EQ | NE));
138         return (Kind)0;
139       }
140 
141       static bool isSigned(Kind Cmp) {
142         return (Cmp & (L | G) && !(Cmp & U));
143       }
144 
145       static bool isUnsigned(Kind Cmp) {
146         return (Cmp & U);
147       }
148 
149     };
150 
151     /// \brief Find the register that contains the loop controlling
152     /// induction variable.
153     /// If successful, it will return true and set the \p Reg, \p IVBump
154     /// and \p IVOp arguments.  Otherwise it will return false.
155     /// The returned induction register is the register R that follows the
156     /// following induction pattern:
157     /// loop:
158     ///   R = phi ..., [ R.next, LatchBlock ]
159     ///   R.next = R + #bump
160     ///   if (R.next < #N) goto loop
161     /// IVBump is the immediate value added to R, and IVOp is the instruction
162     /// "R.next = R + #bump".
163     bool findInductionRegister(MachineLoop *L, unsigned &Reg,
164                                int64_t &IVBump, MachineInstr *&IVOp) const;
165 
166     /// \brief Return the comparison kind for the specified opcode.
167     Comparison::Kind getComparisonKind(unsigned CondOpc,
168                                        MachineOperand *InitialValue,
169                                        const MachineOperand *Endvalue,
170                                        int64_t IVBump) const;
171 
172     /// \brief Analyze the statements in a loop to determine if the loop
173     /// has a computable trip count and, if so, return a value that represents
174     /// the trip count expression.
175     CountValue *getLoopTripCount(MachineLoop *L,
176                                  SmallVectorImpl<MachineInstr *> &OldInsts);
177 
178     /// \brief Return the expression that represents the number of times
179     /// a loop iterates.  The function takes the operands that represent the
180     /// loop start value, loop end value, and induction value.  Based upon
181     /// these operands, the function attempts to compute the trip count.
182     /// If the trip count is not directly available (as an immediate value,
183     /// or a register), the function will attempt to insert computation of it
184     /// to the loop's preheader.
185     CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
186                              const MachineOperand *End, unsigned IVReg,
187                              int64_t IVBump, Comparison::Kind Cmp) const;
188 
189     /// \brief Return true if the instruction is not valid within a hardware
190     /// loop.
191     bool isInvalidLoopOperation(const MachineInstr *MI,
192                                 bool IsInnerHWLoop) const;
193 
194     /// \brief Return true if the loop contains an instruction that inhibits
195     /// using the hardware loop.
196     bool containsInvalidInstruction(MachineLoop *L, bool IsInnerHWLoop) const;
197 
198     /// \brief Given a loop, check if we can convert it to a hardware loop.
199     /// If so, then perform the conversion and return true.
200     bool convertToHardwareLoop(MachineLoop *L, bool &L0used, bool &L1used);
201 
202     /// \brief Return true if the instruction is now dead.
203     bool isDead(const MachineInstr *MI,
204                 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
205 
206     /// \brief Remove the instruction if it is now dead.
207     void removeIfDead(MachineInstr *MI);
208 
209     /// \brief Make sure that the "bump" instruction executes before the
210     /// compare.  We need that for the IV fixup, so that the compare
211     /// instruction would not use a bumped value that has not yet been
212     /// defined.  If the instructions are out of order, try to reorder them.
213     bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
214 
215     /// \brief Return true if MO and MI pair is visited only once. If visited
216     /// more than once, this indicates there is recursion. In such a case,
217     /// return false.
218     bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *A, MachineInstr *MI,
219                       const MachineOperand *MO,
220                       LoopFeederMap &LoopFeederPhi) const;
221 
222     /// \brief Return true if the Phi may generate a value that may underflow,
223     /// or may wrap.
224     bool phiMayWrapOrUnderflow(MachineInstr *Phi, const MachineOperand *EndVal,
225                                MachineBasicBlock *MBB, MachineLoop *L,
226                                LoopFeederMap &LoopFeederPhi) const;
227 
228     /// \brief Return true if the induction variable may underflow an unsigned
229     /// value in the first iteration.
230     bool loopCountMayWrapOrUnderFlow(const MachineOperand *InitVal,
231                                      const MachineOperand *EndVal,
232                                      MachineBasicBlock *MBB, MachineLoop *L,
233                                      LoopFeederMap &LoopFeederPhi) const;
234 
235     /// \brief Check if the given operand has a compile-time known constant
236     /// value. Return true if yes, and false otherwise. When returning true, set
237     /// Val to the corresponding constant value.
238     bool checkForImmediate(const MachineOperand &MO, int64_t &Val) const;
239 
240     /// \brief Check if the operand has a compile-time known constant value.
241     bool isImmediate(const MachineOperand &MO) const {
242       int64_t V;
243       return checkForImmediate(MO, V);
244     }
245 
246     /// \brief Return the immediate for the specified operand.
247     int64_t getImmediate(const MachineOperand &MO) const {
248       int64_t V;
249       if (!checkForImmediate(MO, V))
250         llvm_unreachable("Invalid operand");
251       return V;
252     }
253 
254     /// \brief Reset the given machine operand to now refer to a new immediate
255     /// value.  Assumes that the operand was already referencing an immediate
256     /// value, either directly, or via a register.
257     void setImmediate(MachineOperand &MO, int64_t Val);
258 
259     /// \brief Fix the data flow of the induction varible.
260     /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
261     ///                                     |
262     ///                                     +-> back to phi
263     /// where "bump" is the increment of the induction variable:
264     ///   iv = iv + #const.
265     /// Due to some prior code transformations, the actual flow may look
266     /// like this:
267     ///   phi -+-> bump ---> back to phi
268     ///        |
269     ///        +-> comparison-in-latch (against upper_bound-bump),
270     /// i.e. the comparison that controls the loop execution may be using
271     /// the value of the induction variable from before the increment.
272     ///
273     /// Return true if the loop's flow is the desired one (i.e. it's
274     /// either been fixed, or no fixing was necessary).
275     /// Otherwise, return false.  This can happen if the induction variable
276     /// couldn't be identified, or if the value in the latch's comparison
277     /// cannot be adjusted to reflect the post-bump value.
278     bool fixupInductionVariable(MachineLoop *L);
279 
280     /// \brief Given a loop, if it does not have a preheader, create one.
281     /// Return the block that is the preheader.
282     MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
283   };
284 
285   char HexagonHardwareLoops::ID = 0;
286 #ifndef NDEBUG
287   int HexagonHardwareLoops::Counter = 0;
288 #endif
289 
290   /// \brief Abstraction for a trip count of a loop. A smaller version
291   /// of the MachineOperand class without the concerns of changing the
292   /// operand representation.
293   class CountValue {
294   public:
295     enum CountValueType {
296       CV_Register,
297       CV_Immediate
298     };
299   private:
300     CountValueType Kind;
301     union Values {
302       struct {
303         unsigned Reg;
304         unsigned Sub;
305       } R;
306       unsigned ImmVal;
307     } Contents;
308 
309   public:
310     explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
311       Kind = t;
312       if (Kind == CV_Register) {
313         Contents.R.Reg = v;
314         Contents.R.Sub = u;
315       } else {
316         Contents.ImmVal = v;
317       }
318     }
319     bool isReg() const { return Kind == CV_Register; }
320     bool isImm() const { return Kind == CV_Immediate; }
321 
322     unsigned getReg() const {
323       assert(isReg() && "Wrong CountValue accessor");
324       return Contents.R.Reg;
325     }
326     unsigned getSubReg() const {
327       assert(isReg() && "Wrong CountValue accessor");
328       return Contents.R.Sub;
329     }
330     unsigned getImm() const {
331       assert(isImm() && "Wrong CountValue accessor");
332       return Contents.ImmVal;
333     }
334 
335     void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
336       if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
337       if (isImm()) { OS << Contents.ImmVal; }
338     }
339   };
340 } // end anonymous namespace
341 
342 
343 INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
344                       "Hexagon Hardware Loops", false, false)
345 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
346 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
347 INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
348                     "Hexagon Hardware Loops", false, false)
349 
350 FunctionPass *llvm::createHexagonHardwareLoops() {
351   return new HexagonHardwareLoops();
352 }
353 
354 bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
355   DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
356   if (skipFunction(*MF.getFunction()))
357     return false;
358 
359   bool Changed = false;
360 
361   MLI = &getAnalysis<MachineLoopInfo>();
362   MRI = &MF.getRegInfo();
363   MDT = &getAnalysis<MachineDominatorTree>();
364   TII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
365 
366   for (auto &L : *MLI)
367     if (!L->getParentLoop()) {
368       bool L0Used = false;
369       bool L1Used = false;
370       Changed |= convertToHardwareLoop(L, L0Used, L1Used);
371     }
372 
373   return Changed;
374 }
375 
376 bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
377                                                  unsigned &Reg,
378                                                  int64_t &IVBump,
379                                                  MachineInstr *&IVOp
380                                                  ) const {
381   MachineBasicBlock *Header = L->getHeader();
382   MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
383   MachineBasicBlock *Latch = L->getLoopLatch();
384   MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
385   if (!Header || !Preheader || !Latch || !ExitingBlock)
386     return false;
387 
388   // This pair represents an induction register together with an immediate
389   // value that will be added to it in each loop iteration.
390   typedef std::pair<unsigned,int64_t> RegisterBump;
391 
392   // Mapping:  R.next -> (R, bump), where R, R.next and bump are derived
393   // from an induction operation
394   //   R.next = R + bump
395   // where bump is an immediate value.
396   typedef std::map<unsigned,RegisterBump> InductionMap;
397 
398   InductionMap IndMap;
399 
400   typedef MachineBasicBlock::instr_iterator instr_iterator;
401   for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
402        I != E && I->isPHI(); ++I) {
403     MachineInstr *Phi = &*I;
404 
405     // Have a PHI instruction.  Get the operand that corresponds to the
406     // latch block, and see if is a result of an addition of form "reg+imm",
407     // where the "reg" is defined by the PHI node we are looking at.
408     for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
409       if (Phi->getOperand(i+1).getMBB() != Latch)
410         continue;
411 
412       unsigned PhiOpReg = Phi->getOperand(i).getReg();
413       MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
414       unsigned UpdOpc = DI->getOpcode();
415       bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
416 
417       if (isAdd) {
418         // If the register operand to the add is the PHI we're looking at, this
419         // meets the induction pattern.
420         unsigned IndReg = DI->getOperand(1).getReg();
421         MachineOperand &Opnd2 = DI->getOperand(2);
422         int64_t V;
423         if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
424           unsigned UpdReg = DI->getOperand(0).getReg();
425           IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
426         }
427       }
428     }  // for (i)
429   }  // for (instr)
430 
431   SmallVector<MachineOperand,2> Cond;
432   MachineBasicBlock *TB = nullptr, *FB = nullptr;
433   bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
434   if (NotAnalyzed)
435     return false;
436 
437   unsigned PredR, PredPos, PredRegFlags;
438   if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
439     return false;
440 
441   MachineInstr *PredI = MRI->getVRegDef(PredR);
442   if (!PredI->isCompare())
443     return false;
444 
445   unsigned CmpReg1 = 0, CmpReg2 = 0;
446   int CmpImm = 0, CmpMask = 0;
447   bool CmpAnalyzed =
448       TII->analyzeCompare(*PredI, CmpReg1, CmpReg2, CmpMask, CmpImm);
449   // Fail if the compare was not analyzed, or it's not comparing a register
450   // with an immediate value.  Not checking the mask here, since we handle
451   // the individual compare opcodes (including A4_cmpb*) later on.
452   if (!CmpAnalyzed)
453     return false;
454 
455   // Exactly one of the input registers to the comparison should be among
456   // the induction registers.
457   InductionMap::iterator IndMapEnd = IndMap.end();
458   InductionMap::iterator F = IndMapEnd;
459   if (CmpReg1 != 0) {
460     InductionMap::iterator F1 = IndMap.find(CmpReg1);
461     if (F1 != IndMapEnd)
462       F = F1;
463   }
464   if (CmpReg2 != 0) {
465     InductionMap::iterator F2 = IndMap.find(CmpReg2);
466     if (F2 != IndMapEnd) {
467       if (F != IndMapEnd)
468         return false;
469       F = F2;
470     }
471   }
472   if (F == IndMapEnd)
473     return false;
474 
475   Reg = F->second.first;
476   IVBump = F->second.second;
477   IVOp = MRI->getVRegDef(F->first);
478   return true;
479 }
480 
481 // Return the comparison kind for the specified opcode.
482 HexagonHardwareLoops::Comparison::Kind
483 HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
484                                         MachineOperand *InitialValue,
485                                         const MachineOperand *EndValue,
486                                         int64_t IVBump) const {
487   Comparison::Kind Cmp = (Comparison::Kind)0;
488   switch (CondOpc) {
489   case Hexagon::C2_cmpeqi:
490   case Hexagon::C2_cmpeq:
491   case Hexagon::C2_cmpeqp:
492     Cmp = Comparison::EQ;
493     break;
494   case Hexagon::C4_cmpneq:
495   case Hexagon::C4_cmpneqi:
496     Cmp = Comparison::NE;
497     break;
498   case Hexagon::C4_cmplte:
499     Cmp = Comparison::LEs;
500     break;
501   case Hexagon::C4_cmplteu:
502     Cmp = Comparison::LEu;
503     break;
504   case Hexagon::C2_cmpgtui:
505   case Hexagon::C2_cmpgtu:
506   case Hexagon::C2_cmpgtup:
507     Cmp = Comparison::GTu;
508     break;
509   case Hexagon::C2_cmpgti:
510   case Hexagon::C2_cmpgt:
511   case Hexagon::C2_cmpgtp:
512     Cmp = Comparison::GTs;
513     break;
514   default:
515     return (Comparison::Kind)0;
516   }
517   return Cmp;
518 }
519 
520 /// \brief Analyze the statements in a loop to determine if the loop has
521 /// a computable trip count and, if so, return a value that represents
522 /// the trip count expression.
523 ///
524 /// This function iterates over the phi nodes in the loop to check for
525 /// induction variable patterns that are used in the calculation for
526 /// the number of time the loop is executed.
527 CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
528     SmallVectorImpl<MachineInstr *> &OldInsts) {
529   MachineBasicBlock *TopMBB = L->getTopBlock();
530   MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
531   assert(PI != TopMBB->pred_end() &&
532          "Loop must have more than one incoming edge!");
533   MachineBasicBlock *Backedge = *PI++;
534   if (PI == TopMBB->pred_end())  // dead loop?
535     return nullptr;
536   MachineBasicBlock *Incoming = *PI++;
537   if (PI != TopMBB->pred_end())  // multiple backedges?
538     return nullptr;
539 
540   // Make sure there is one incoming and one backedge and determine which
541   // is which.
542   if (L->contains(Incoming)) {
543     if (L->contains(Backedge))
544       return nullptr;
545     std::swap(Incoming, Backedge);
546   } else if (!L->contains(Backedge))
547     return nullptr;
548 
549   // Look for the cmp instruction to determine if we can get a useful trip
550   // count.  The trip count can be either a register or an immediate.  The
551   // location of the value depends upon the type (reg or imm).
552   MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
553   if (!ExitingBlock)
554     return nullptr;
555 
556   unsigned IVReg = 0;
557   int64_t IVBump = 0;
558   MachineInstr *IVOp;
559   bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
560   if (!FoundIV)
561     return nullptr;
562 
563   MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
564 
565   MachineOperand *InitialValue = nullptr;
566   MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
567   MachineBasicBlock *Latch = L->getLoopLatch();
568   for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
569     MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
570     if (MBB == Preheader)
571       InitialValue = &IV_Phi->getOperand(i);
572     else if (MBB == Latch)
573       IVReg = IV_Phi->getOperand(i).getReg();  // Want IV reg after bump.
574   }
575   if (!InitialValue)
576     return nullptr;
577 
578   SmallVector<MachineOperand,2> Cond;
579   MachineBasicBlock *TB = nullptr, *FB = nullptr;
580   bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
581   if (NotAnalyzed)
582     return nullptr;
583 
584   MachineBasicBlock *Header = L->getHeader();
585   // TB must be non-null.  If FB is also non-null, one of them must be
586   // the header.  Otherwise, branch to TB could be exiting the loop, and
587   // the fall through can go to the header.
588   assert (TB && "Exit block without a branch?");
589   if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
590     MachineBasicBlock *LTB = 0, *LFB = 0;
591     SmallVector<MachineOperand,2> LCond;
592     bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
593     if (NotAnalyzed)
594       return nullptr;
595     if (TB == Latch)
596       TB = (LTB == Header) ? LTB : LFB;
597     else
598       FB = (LTB == Header) ? LTB: LFB;
599   }
600   assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
601   if (!TB || (FB && TB != Header && FB != Header))
602     return nullptr;
603 
604   // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
605   // to put imm(0), followed by P in the vector Cond.
606   // If TB is not the header, it means that the "not-taken" path must lead
607   // to the header.
608   bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
609   unsigned PredReg, PredPos, PredRegFlags;
610   if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
611     return nullptr;
612   MachineInstr *CondI = MRI->getVRegDef(PredReg);
613   unsigned CondOpc = CondI->getOpcode();
614 
615   unsigned CmpReg1 = 0, CmpReg2 = 0;
616   int Mask = 0, ImmValue = 0;
617   bool AnalyzedCmp =
618       TII->analyzeCompare(*CondI, CmpReg1, CmpReg2, Mask, ImmValue);
619   if (!AnalyzedCmp)
620     return nullptr;
621 
622   // The comparison operator type determines how we compute the loop
623   // trip count.
624   OldInsts.push_back(CondI);
625   OldInsts.push_back(IVOp);
626 
627   // Sadly, the following code gets information based on the position
628   // of the operands in the compare instruction.  This has to be done
629   // this way, because the comparisons check for a specific relationship
630   // between the operands (e.g. is-less-than), rather than to find out
631   // what relationship the operands are in (as on PPC).
632   Comparison::Kind Cmp;
633   bool isSwapped = false;
634   const MachineOperand &Op1 = CondI->getOperand(1);
635   const MachineOperand &Op2 = CondI->getOperand(2);
636   const MachineOperand *EndValue = nullptr;
637 
638   if (Op1.isReg()) {
639     if (Op2.isImm() || Op1.getReg() == IVReg)
640       EndValue = &Op2;
641     else {
642       EndValue = &Op1;
643       isSwapped = true;
644     }
645   }
646 
647   if (!EndValue)
648     return nullptr;
649 
650   Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
651   if (!Cmp)
652     return nullptr;
653   if (Negated)
654     Cmp = Comparison::getNegatedComparison(Cmp);
655   if (isSwapped)
656     Cmp = Comparison::getSwappedComparison(Cmp);
657 
658   if (InitialValue->isReg()) {
659     unsigned R = InitialValue->getReg();
660     MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
661     if (!MDT->properlyDominates(DefBB, Header))
662       return nullptr;
663     OldInsts.push_back(MRI->getVRegDef(R));
664   }
665   if (EndValue->isReg()) {
666     unsigned R = EndValue->getReg();
667     MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
668     if (!MDT->properlyDominates(DefBB, Header))
669       return nullptr;
670     OldInsts.push_back(MRI->getVRegDef(R));
671   }
672 
673   return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
674 }
675 
676 /// \brief Helper function that returns the expression that represents the
677 /// number of times a loop iterates.  The function takes the operands that
678 /// represent the loop start value, loop end value, and induction value.
679 /// Based upon these operands, the function attempts to compute the trip count.
680 CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
681                                                const MachineOperand *Start,
682                                                const MachineOperand *End,
683                                                unsigned IVReg,
684                                                int64_t IVBump,
685                                                Comparison::Kind Cmp) const {
686   // Cannot handle comparison EQ, i.e. while (A == B).
687   if (Cmp == Comparison::EQ)
688     return nullptr;
689 
690   // Check if either the start or end values are an assignment of an immediate.
691   // If so, use the immediate value rather than the register.
692   if (Start->isReg()) {
693     const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
694     if (StartValInstr && (StartValInstr->getOpcode() == Hexagon::A2_tfrsi ||
695                           StartValInstr->getOpcode() == Hexagon::A2_tfrpi))
696       Start = &StartValInstr->getOperand(1);
697   }
698   if (End->isReg()) {
699     const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
700     if (EndValInstr && (EndValInstr->getOpcode() == Hexagon::A2_tfrsi ||
701                         EndValInstr->getOpcode() == Hexagon::A2_tfrpi))
702       End = &EndValInstr->getOperand(1);
703   }
704 
705   if (!Start->isReg() && !Start->isImm())
706     return nullptr;
707   if (!End->isReg() && !End->isImm())
708     return nullptr;
709 
710   bool CmpLess =     Cmp & Comparison::L;
711   bool CmpGreater =  Cmp & Comparison::G;
712   bool CmpHasEqual = Cmp & Comparison::EQ;
713 
714   // Avoid certain wrap-arounds.  This doesn't detect all wrap-arounds.
715   if (CmpLess && IVBump < 0)
716     // Loop going while iv is "less" with the iv value going down.  Must wrap.
717     return nullptr;
718 
719   if (CmpGreater && IVBump > 0)
720     // Loop going while iv is "greater" with the iv value going up.  Must wrap.
721     return nullptr;
722 
723   // Phis that may feed into the loop.
724   LoopFeederMap LoopFeederPhi;
725 
726   // Check if the initial value may be zero and can be decremented in the first
727   // iteration. If the value is zero, the endloop instruction will not decrement
728   // the loop counter, so we shouldn't generate a hardware loop in this case.
729   if (loopCountMayWrapOrUnderFlow(Start, End, Loop->getLoopPreheader(), Loop,
730                                   LoopFeederPhi))
731       return nullptr;
732 
733   if (Start->isImm() && End->isImm()) {
734     // Both, start and end are immediates.
735     int64_t StartV = Start->getImm();
736     int64_t EndV = End->getImm();
737     int64_t Dist = EndV - StartV;
738     if (Dist == 0)
739       return nullptr;
740 
741     bool Exact = (Dist % IVBump) == 0;
742 
743     if (Cmp == Comparison::NE) {
744       if (!Exact)
745         return nullptr;
746       if ((Dist < 0) ^ (IVBump < 0))
747         return nullptr;
748     }
749 
750     // For comparisons that include the final value (i.e. include equality
751     // with the final value), we need to increase the distance by 1.
752     if (CmpHasEqual)
753       Dist = Dist > 0 ? Dist+1 : Dist-1;
754 
755     // For the loop to iterate, CmpLess should imply Dist > 0.  Similarly,
756     // CmpGreater should imply Dist < 0.  These conditions could actually
757     // fail, for example, in unreachable code (which may still appear to be
758     // reachable in the CFG).
759     if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
760       return nullptr;
761 
762     // "Normalized" distance, i.e. with the bump set to +-1.
763     int64_t Dist1 = (IVBump > 0) ? (Dist +  (IVBump - 1)) / IVBump
764                                  : (-Dist + (-IVBump - 1)) / (-IVBump);
765     assert (Dist1 > 0 && "Fishy thing.  Both operands have the same sign.");
766 
767     uint64_t Count = Dist1;
768 
769     if (Count > 0xFFFFFFFFULL)
770       return nullptr;
771 
772     return new CountValue(CountValue::CV_Immediate, Count);
773   }
774 
775   // A general case: Start and End are some values, but the actual
776   // iteration count may not be available.  If it is not, insert
777   // a computation of it into the preheader.
778 
779   // If the induction variable bump is not a power of 2, quit.
780   // Othwerise we'd need a general integer division.
781   if (!isPowerOf2_64(std::abs(IVBump)))
782     return nullptr;
783 
784   MachineBasicBlock *PH = MLI->findLoopPreheader(Loop, SpecPreheader);
785   assert (PH && "Should have a preheader by now");
786   MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
787   DebugLoc DL;
788   if (InsertPos != PH->end())
789     DL = InsertPos->getDebugLoc();
790 
791   // If Start is an immediate and End is a register, the trip count
792   // will be "reg - imm".  Hexagon's "subtract immediate" instruction
793   // is actually "reg + -imm".
794 
795   // If the loop IV is going downwards, i.e. if the bump is negative,
796   // then the iteration count (computed as End-Start) will need to be
797   // negated.  To avoid the negation, just swap Start and End.
798   if (IVBump < 0) {
799     std::swap(Start, End);
800     IVBump = -IVBump;
801   }
802   // Cmp may now have a wrong direction, e.g.  LEs may now be GEs.
803   // Signedness, and "including equality" are preserved.
804 
805   bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
806   bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
807 
808   int64_t StartV = 0, EndV = 0;
809   if (Start->isImm())
810     StartV = Start->getImm();
811   if (End->isImm())
812     EndV = End->getImm();
813 
814   int64_t AdjV = 0;
815   // To compute the iteration count, we would need this computation:
816   //   Count = (End - Start + (IVBump-1)) / IVBump
817   // or, when CmpHasEqual:
818   //   Count = (End - Start + (IVBump-1)+1) / IVBump
819   // The "IVBump-1" part is the adjustment (AdjV).  We can avoid
820   // generating an instruction specifically to add it if we can adjust
821   // the immediate values for Start or End.
822 
823   if (CmpHasEqual) {
824     // Need to add 1 to the total iteration count.
825     if (Start->isImm())
826       StartV--;
827     else if (End->isImm())
828       EndV++;
829     else
830       AdjV += 1;
831   }
832 
833   if (Cmp != Comparison::NE) {
834     if (Start->isImm())
835       StartV -= (IVBump-1);
836     else if (End->isImm())
837       EndV += (IVBump-1);
838     else
839       AdjV += (IVBump-1);
840   }
841 
842   unsigned R = 0, SR = 0;
843   if (Start->isReg()) {
844     R = Start->getReg();
845     SR = Start->getSubReg();
846   } else {
847     R = End->getReg();
848     SR = End->getSubReg();
849   }
850   const TargetRegisterClass *RC = MRI->getRegClass(R);
851   // Hardware loops cannot handle 64-bit registers.  If it's a double
852   // register, it has to have a subregister.
853   if (!SR && RC == &Hexagon::DoubleRegsRegClass)
854     return nullptr;
855   const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
856 
857   // Compute DistR (register with the distance between Start and End).
858   unsigned DistR, DistSR;
859 
860   // Avoid special case, where the start value is an imm(0).
861   if (Start->isImm() && StartV == 0) {
862     DistR = End->getReg();
863     DistSR = End->getSubReg();
864   } else {
865     const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
866                               (RegToImm ? TII->get(Hexagon::A2_subri) :
867                                           TII->get(Hexagon::A2_addi));
868     if (RegToReg || RegToImm) {
869       unsigned SubR = MRI->createVirtualRegister(IntRC);
870       MachineInstrBuilder SubIB =
871         BuildMI(*PH, InsertPos, DL, SubD, SubR);
872 
873       if (RegToReg)
874         SubIB.addReg(End->getReg(), 0, End->getSubReg())
875           .addReg(Start->getReg(), 0, Start->getSubReg());
876       else
877         SubIB.addImm(EndV)
878           .addReg(Start->getReg(), 0, Start->getSubReg());
879       DistR = SubR;
880     } else {
881       // If the loop has been unrolled, we should use the original loop count
882       // instead of recalculating the value. This will avoid additional
883       // 'Add' instruction.
884       const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
885       if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
886           EndValInstr->getOperand(2).getImm() == StartV) {
887         DistR = EndValInstr->getOperand(1).getReg();
888       } else {
889         unsigned SubR = MRI->createVirtualRegister(IntRC);
890         MachineInstrBuilder SubIB =
891           BuildMI(*PH, InsertPos, DL, SubD, SubR);
892         SubIB.addReg(End->getReg(), 0, End->getSubReg())
893              .addImm(-StartV);
894         DistR = SubR;
895       }
896     }
897     DistSR = 0;
898   }
899 
900   // From DistR, compute AdjR (register with the adjusted distance).
901   unsigned AdjR, AdjSR;
902 
903   if (AdjV == 0) {
904     AdjR = DistR;
905     AdjSR = DistSR;
906   } else {
907     // Generate CountR = ADD DistR, AdjVal
908     unsigned AddR = MRI->createVirtualRegister(IntRC);
909     MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
910     BuildMI(*PH, InsertPos, DL, AddD, AddR)
911       .addReg(DistR, 0, DistSR)
912       .addImm(AdjV);
913 
914     AdjR = AddR;
915     AdjSR = 0;
916   }
917 
918   // From AdjR, compute CountR (register with the final count).
919   unsigned CountR, CountSR;
920 
921   if (IVBump == 1) {
922     CountR = AdjR;
923     CountSR = AdjSR;
924   } else {
925     // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
926     unsigned Shift = Log2_32(IVBump);
927 
928     // Generate NormR = LSR DistR, Shift.
929     unsigned LsrR = MRI->createVirtualRegister(IntRC);
930     const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
931     BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
932       .addReg(AdjR, 0, AdjSR)
933       .addImm(Shift);
934 
935     CountR = LsrR;
936     CountSR = 0;
937   }
938 
939   return new CountValue(CountValue::CV_Register, CountR, CountSR);
940 }
941 
942 /// \brief Return true if the operation is invalid within hardware loop.
943 bool HexagonHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI,
944                                                   bool IsInnerHWLoop) const {
945 
946   // Call is not allowed because the callee may use a hardware loop except for
947   // the case when the call never returns.
948   if (MI->getDesc().isCall())
949     return !TII->doesNotReturn(*MI);
950 
951   // Check if the instruction defines a hardware loop register.
952   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
953     const MachineOperand &MO = MI->getOperand(i);
954     if (!MO.isReg() || !MO.isDef())
955       continue;
956     unsigned R = MO.getReg();
957     if (IsInnerHWLoop && (R == Hexagon::LC0 || R == Hexagon::SA0 ||
958                           R == Hexagon::LC1 || R == Hexagon::SA1))
959       return true;
960     if (!IsInnerHWLoop && (R == Hexagon::LC1 || R == Hexagon::SA1))
961       return true;
962   }
963   return false;
964 }
965 
966 /// \brief Return true if the loop contains an instruction that inhibits
967 /// the use of the hardware loop instruction.
968 bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
969     bool IsInnerHWLoop) const {
970   const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
971   DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
972   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
973     MachineBasicBlock *MBB = Blocks[i];
974     for (MachineBasicBlock::iterator
975            MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
976       const MachineInstr *MI = &*MII;
977       if (isInvalidLoopOperation(MI, IsInnerHWLoop)) {
978         DEBUG(dbgs()<< "\nCannot convert to hw_loop due to:"; MI->dump(););
979         return true;
980       }
981     }
982   }
983   return false;
984 }
985 
986 /// \brief Returns true if the instruction is dead.  This was essentially
987 /// copied from DeadMachineInstructionElim::isDead, but with special cases
988 /// for inline asm, physical registers and instructions with side effects
989 /// removed.
990 bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
991                               SmallVectorImpl<MachineInstr *> &DeadPhis) const {
992   // Examine each operand.
993   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
994     const MachineOperand &MO = MI->getOperand(i);
995     if (!MO.isReg() || !MO.isDef())
996       continue;
997 
998     unsigned Reg = MO.getReg();
999     if (MRI->use_nodbg_empty(Reg))
1000       continue;
1001 
1002     typedef MachineRegisterInfo::use_nodbg_iterator use_nodbg_iterator;
1003 
1004     // This instruction has users, but if the only user is the phi node for the
1005     // parent block, and the only use of that phi node is this instruction, then
1006     // this instruction is dead: both it (and the phi node) can be removed.
1007     use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
1008     use_nodbg_iterator End = MRI->use_nodbg_end();
1009     if (std::next(I) != End || !I->getParent()->isPHI())
1010       return false;
1011 
1012     MachineInstr *OnePhi = I->getParent();
1013     for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
1014       const MachineOperand &OPO = OnePhi->getOperand(j);
1015       if (!OPO.isReg() || !OPO.isDef())
1016         continue;
1017 
1018       unsigned OPReg = OPO.getReg();
1019       use_nodbg_iterator nextJ;
1020       for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
1021            J != End; J = nextJ) {
1022         nextJ = std::next(J);
1023         MachineOperand &Use = *J;
1024         MachineInstr *UseMI = Use.getParent();
1025 
1026         // If the phi node has a user that is not MI, bail.
1027         if (MI != UseMI)
1028           return false;
1029       }
1030     }
1031     DeadPhis.push_back(OnePhi);
1032   }
1033 
1034   // If there are no defs with uses, the instruction is dead.
1035   return true;
1036 }
1037 
1038 void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
1039   // This procedure was essentially copied from DeadMachineInstructionElim.
1040 
1041   SmallVector<MachineInstr*, 1> DeadPhis;
1042   if (isDead(MI, DeadPhis)) {
1043     DEBUG(dbgs() << "HW looping will remove: " << *MI);
1044 
1045     // It is possible that some DBG_VALUE instructions refer to this
1046     // instruction.  Examine each def operand for such references;
1047     // if found, mark the DBG_VALUE as undef (but don't delete it).
1048     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1049       const MachineOperand &MO = MI->getOperand(i);
1050       if (!MO.isReg() || !MO.isDef())
1051         continue;
1052       unsigned Reg = MO.getReg();
1053       MachineRegisterInfo::use_iterator nextI;
1054       for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
1055            E = MRI->use_end(); I != E; I = nextI) {
1056         nextI = std::next(I);  // I is invalidated by the setReg
1057         MachineOperand &Use = *I;
1058         MachineInstr *UseMI = I->getParent();
1059         if (UseMI == MI)
1060           continue;
1061         if (Use.isDebug())
1062           UseMI->getOperand(0).setReg(0U);
1063       }
1064     }
1065 
1066     MI->eraseFromParent();
1067     for (unsigned i = 0; i < DeadPhis.size(); ++i)
1068       DeadPhis[i]->eraseFromParent();
1069   }
1070 }
1071 
1072 /// \brief Check if the loop is a candidate for converting to a hardware
1073 /// loop.  If so, then perform the transformation.
1074 ///
1075 /// This function works on innermost loops first.  A loop can be converted
1076 /// if it is a counting loop; either a register value or an immediate.
1077 ///
1078 /// The code makes several assumptions about the representation of the loop
1079 /// in llvm.
1080 bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
1081                                                  bool &RecL0used,
1082                                                  bool &RecL1used) {
1083   // This is just for sanity.
1084   assert(L->getHeader() && "Loop without a header?");
1085 
1086   bool Changed = false;
1087   bool L0Used = false;
1088   bool L1Used = false;
1089 
1090   // Process nested loops first.
1091   for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
1092     Changed |= convertToHardwareLoop(*I, RecL0used, RecL1used);
1093     L0Used |= RecL0used;
1094     L1Used |= RecL1used;
1095   }
1096 
1097   // If a nested loop has been converted, then we can't convert this loop.
1098   if (Changed && L0Used && L1Used)
1099     return Changed;
1100 
1101   unsigned LOOP_i;
1102   unsigned LOOP_r;
1103   unsigned ENDLOOP;
1104 
1105   // Flag used to track loopN instruction:
1106   // 1 - Hardware loop is being generated for the inner most loop.
1107   // 0 - Hardware loop is being generated for the outer loop.
1108   unsigned IsInnerHWLoop = 1;
1109 
1110   if (L0Used) {
1111     LOOP_i = Hexagon::J2_loop1i;
1112     LOOP_r = Hexagon::J2_loop1r;
1113     ENDLOOP = Hexagon::ENDLOOP1;
1114     IsInnerHWLoop = 0;
1115   } else {
1116     LOOP_i = Hexagon::J2_loop0i;
1117     LOOP_r = Hexagon::J2_loop0r;
1118     ENDLOOP = Hexagon::ENDLOOP0;
1119   }
1120 
1121 #ifndef NDEBUG
1122   // Stop trying after reaching the limit (if any).
1123   int Limit = HWLoopLimit;
1124   if (Limit >= 0) {
1125     if (Counter >= HWLoopLimit)
1126       return false;
1127     Counter++;
1128   }
1129 #endif
1130 
1131   // Does the loop contain any invalid instructions?
1132   if (containsInvalidInstruction(L, IsInnerHWLoop))
1133     return false;
1134 
1135   MachineBasicBlock *LastMBB = L->findLoopControlBlock();
1136   // Don't generate hw loop if the loop has more than one exit.
1137   if (!LastMBB)
1138     return false;
1139 
1140   MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
1141   if (LastI == LastMBB->end())
1142     return false;
1143 
1144   // Is the induction variable bump feeding the latch condition?
1145   if (!fixupInductionVariable(L))
1146     return false;
1147 
1148   // Ensure the loop has a preheader: the loop instruction will be
1149   // placed there.
1150   MachineBasicBlock *Preheader = MLI->findLoopPreheader(L, SpecPreheader);
1151   if (!Preheader) {
1152     Preheader = createPreheaderForLoop(L);
1153     if (!Preheader)
1154       return false;
1155   }
1156 
1157   MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1158 
1159   SmallVector<MachineInstr*, 2> OldInsts;
1160   // Are we able to determine the trip count for the loop?
1161   CountValue *TripCount = getLoopTripCount(L, OldInsts);
1162   if (!TripCount)
1163     return false;
1164 
1165   // Is the trip count available in the preheader?
1166   if (TripCount->isReg()) {
1167     // There will be a use of the register inserted into the preheader,
1168     // so make sure that the register is actually defined at that point.
1169     MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1170     MachineBasicBlock *BBDef = TCDef->getParent();
1171     if (!MDT->dominates(BBDef, Preheader))
1172       return false;
1173   }
1174 
1175   // Determine the loop start.
1176   MachineBasicBlock *TopBlock = L->getTopBlock();
1177   MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
1178   MachineBasicBlock *LoopStart = 0;
1179   if (ExitingBlock !=  L->getLoopLatch()) {
1180     MachineBasicBlock *TB = 0, *FB = 0;
1181     SmallVector<MachineOperand, 2> Cond;
1182 
1183     if (TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false))
1184       return false;
1185 
1186     if (L->contains(TB))
1187       LoopStart = TB;
1188     else if (L->contains(FB))
1189       LoopStart = FB;
1190     else
1191       return false;
1192   }
1193   else
1194     LoopStart = TopBlock;
1195 
1196   // Convert the loop to a hardware loop.
1197   DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
1198   DebugLoc DL;
1199   if (InsertPos != Preheader->end())
1200     DL = InsertPos->getDebugLoc();
1201 
1202   if (TripCount->isReg()) {
1203     // Create a copy of the loop count register.
1204     unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1205     BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1206       .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
1207     // Add the Loop instruction to the beginning of the loop.
1208     BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r)).addMBB(LoopStart)
1209       .addReg(CountReg);
1210   } else {
1211     assert(TripCount->isImm() && "Expecting immediate value for trip count");
1212     // Add the Loop immediate instruction to the beginning of the loop,
1213     // if the immediate fits in the instructions.  Otherwise, we need to
1214     // create a new virtual register.
1215     int64_t CountImm = TripCount->getImm();
1216     if (!TII->isValidOffset(LOOP_i, CountImm)) {
1217       unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1218       BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
1219         .addImm(CountImm);
1220       BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r))
1221         .addMBB(LoopStart).addReg(CountReg);
1222     } else
1223       BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_i))
1224         .addMBB(LoopStart).addImm(CountImm);
1225   }
1226 
1227   // Make sure the loop start always has a reference in the CFG.  We need
1228   // to create a BlockAddress operand to get this mechanism to work both the
1229   // MachineBasicBlock and BasicBlock objects need the flag set.
1230   LoopStart->setHasAddressTaken();
1231   // This line is needed to set the hasAddressTaken flag on the BasicBlock
1232   // object.
1233   BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
1234 
1235   // Replace the loop branch with an endloop instruction.
1236   DebugLoc LastIDL = LastI->getDebugLoc();
1237   BuildMI(*LastMBB, LastI, LastIDL, TII->get(ENDLOOP)).addMBB(LoopStart);
1238 
1239   // The loop ends with either:
1240   //  - a conditional branch followed by an unconditional branch, or
1241   //  - a conditional branch to the loop start.
1242   if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1243       LastI->getOpcode() == Hexagon::J2_jumpf) {
1244     // Delete one and change/add an uncond. branch to out of the loop.
1245     MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1246     LastI = LastMBB->erase(LastI);
1247     if (!L->contains(BranchTarget)) {
1248       if (LastI != LastMBB->end())
1249         LastI = LastMBB->erase(LastI);
1250       SmallVector<MachineOperand, 0> Cond;
1251       TII->InsertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
1252     }
1253   } else {
1254     // Conditional branch to loop start; just delete it.
1255     LastMBB->erase(LastI);
1256   }
1257   delete TripCount;
1258 
1259   // The induction operation and the comparison may now be
1260   // unneeded. If these are unneeded, then remove them.
1261   for (unsigned i = 0; i < OldInsts.size(); ++i)
1262     removeIfDead(OldInsts[i]);
1263 
1264   ++NumHWLoops;
1265 
1266   // Set RecL1used and RecL0used only after hardware loop has been
1267   // successfully generated. Doing it earlier can cause wrong loop instruction
1268   // to be used.
1269   if (L0Used) // Loop0 was already used. So, the correct loop must be loop1.
1270     RecL1used = true;
1271   else
1272     RecL0used = true;
1273 
1274   return true;
1275 }
1276 
1277 bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1278                                             MachineInstr *CmpI) {
1279   assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1280 
1281   MachineBasicBlock *BB = BumpI->getParent();
1282   if (CmpI->getParent() != BB)
1283     return false;
1284 
1285   typedef MachineBasicBlock::instr_iterator instr_iterator;
1286   // Check if things are in order to begin with.
1287   for (instr_iterator I(BumpI), E = BB->instr_end(); I != E; ++I)
1288     if (&*I == CmpI)
1289       return true;
1290 
1291   // Out of order.
1292   unsigned PredR = CmpI->getOperand(0).getReg();
1293   bool FoundBump = false;
1294   instr_iterator CmpIt = CmpI->getIterator(), NextIt = std::next(CmpIt);
1295   for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1296     MachineInstr *In = &*I;
1297     for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1298       MachineOperand &MO = In->getOperand(i);
1299       if (MO.isReg() && MO.isUse()) {
1300         if (MO.getReg() == PredR)  // Found an intervening use of PredR.
1301           return false;
1302       }
1303     }
1304 
1305     if (In == BumpI) {
1306       BB->splice(++BumpI->getIterator(), BB, CmpI->getIterator());
1307       FoundBump = true;
1308       break;
1309     }
1310   }
1311   assert (FoundBump && "Cannot determine instruction order");
1312   return FoundBump;
1313 }
1314 
1315 /// This function is required to break recursion. Visiting phis in a loop may
1316 /// result in recursion during compilation. We break the recursion by making
1317 /// sure that we visit a MachineOperand and its definition in a
1318 /// MachineInstruction only once. If we attempt to visit more than once, then
1319 /// there is recursion, and will return false.
1320 bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
1321                                         MachineInstr *MI,
1322                                         const MachineOperand *MO,
1323                                         LoopFeederMap &LoopFeederPhi) const {
1324   if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
1325     const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
1326     DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
1327     // Ignore all BBs that form Loop.
1328     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1329       MachineBasicBlock *MBB = Blocks[i];
1330       if (A == MBB)
1331         return false;
1332     }
1333     MachineInstr *Def = MRI->getVRegDef(MO->getReg());
1334     LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
1335     return true;
1336   } else
1337     // Already visited node.
1338     return false;
1339 }
1340 
1341 /// Return true if a Phi may generate a value that can underflow.
1342 /// This function calls loopCountMayWrapOrUnderFlow for each Phi operand.
1343 bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1344     MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
1345     MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
1346   assert(Phi->isPHI() && "Expecting a Phi.");
1347   // Walk through each Phi, and its used operands. Make sure that
1348   // if there is recursion in Phi, we won't generate hardware loops.
1349   for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
1350     if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
1351       if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
1352                                       Phi->getParent(), L, LoopFeederPhi))
1353         return true;
1354   return false;
1355 }
1356 
1357 /// Return true if the induction variable can underflow in the first iteration.
1358 /// An example, is an initial unsigned value that is 0 and is decrement in the
1359 /// first itertion of a do-while loop.  In this case, we cannot generate a
1360 /// hardware loop because the endloop instruction does not decrement the loop
1361 /// counter if it is <= 1. We only need to perform this analysis if the
1362 /// initial value is a register.
1363 ///
1364 /// This function assumes the initial value may underfow unless proven
1365 /// otherwise. If the type is signed, then we don't care because signed
1366 /// underflow is undefined. We attempt to prove the initial value is not
1367 /// zero by perfoming a crude analysis of the loop counter. This function
1368 /// checks if the initial value is used in any comparison prior to the loop
1369 /// and, if so, assumes the comparison is a range check. This is inexact,
1370 /// but will catch the simple cases.
1371 bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1372     const MachineOperand *InitVal, const MachineOperand *EndVal,
1373     MachineBasicBlock *MBB, MachineLoop *L,
1374     LoopFeederMap &LoopFeederPhi) const {
1375   // Only check register values since they are unknown.
1376   if (!InitVal->isReg())
1377     return false;
1378 
1379   if (!EndVal->isImm())
1380     return false;
1381 
1382   // A register value that is assigned an immediate is a known value, and it
1383   // won't underflow in the first iteration.
1384   int64_t Imm;
1385   if (checkForImmediate(*InitVal, Imm))
1386     return (EndVal->getImm() == Imm);
1387 
1388   unsigned Reg = InitVal->getReg();
1389 
1390   // We don't know the value of a physical register.
1391   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1392     return true;
1393 
1394   MachineInstr *Def = MRI->getVRegDef(Reg);
1395   if (!Def)
1396     return true;
1397 
1398   // If the initial value is a Phi or copy and the operands may not underflow,
1399   // then the definition cannot be underflow either.
1400   if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
1401                                              L, LoopFeederPhi))
1402     return false;
1403   if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
1404                                                     EndVal, Def->getParent(),
1405                                                     L, LoopFeederPhi))
1406     return false;
1407 
1408   // Iterate over the uses of the initial value. If the initial value is used
1409   // in a compare, then we assume this is a range check that ensures the loop
1410   // doesn't underflow. This is not an exact test and should be improved.
1411   for (MachineRegisterInfo::use_instr_nodbg_iterator I = MRI->use_instr_nodbg_begin(Reg),
1412          E = MRI->use_instr_nodbg_end(); I != E; ++I) {
1413     MachineInstr *MI = &*I;
1414     unsigned CmpReg1 = 0, CmpReg2 = 0;
1415     int CmpMask = 0, CmpValue = 0;
1416 
1417     if (!TII->analyzeCompare(*MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
1418       continue;
1419 
1420     MachineBasicBlock *TBB = 0, *FBB = 0;
1421     SmallVector<MachineOperand, 2> Cond;
1422     if (TII->analyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
1423       continue;
1424 
1425     Comparison::Kind Cmp = getComparisonKind(MI->getOpcode(), 0, 0, 0);
1426     if (Cmp == 0)
1427       continue;
1428     if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
1429       Cmp = Comparison::getNegatedComparison(Cmp);
1430     if (CmpReg2 != 0 && CmpReg2 == Reg)
1431       Cmp = Comparison::getSwappedComparison(Cmp);
1432 
1433     // Signed underflow is undefined.
1434     if (Comparison::isSigned(Cmp))
1435       return false;
1436 
1437     // Check if there is a comparison of the initial value. If the initial value
1438     // is greater than or not equal to another value, then assume this is a
1439     // range check.
1440     if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1441       return false;
1442   }
1443 
1444   // OK - this is a hack that needs to be improved. We really need to analyze
1445   // the instructions performed on the initial value. This works on the simplest
1446   // cases only.
1447   if (!Def->isCopy() && !Def->isPHI())
1448     return false;
1449 
1450   return true;
1451 }
1452 
1453 bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
1454                                              int64_t &Val) const {
1455   if (MO.isImm()) {
1456     Val = MO.getImm();
1457     return true;
1458   }
1459   if (!MO.isReg())
1460     return false;
1461 
1462   // MO is a register. Check whether it is defined as an immediate value,
1463   // and if so, get the value of it in TV. That value will then need to be
1464   // processed to handle potential subregisters in MO.
1465   int64_t TV;
1466 
1467   unsigned R = MO.getReg();
1468   if (!TargetRegisterInfo::isVirtualRegister(R))
1469     return false;
1470   MachineInstr *DI = MRI->getVRegDef(R);
1471   unsigned DOpc = DI->getOpcode();
1472   switch (DOpc) {
1473     case TargetOpcode::COPY:
1474     case Hexagon::A2_tfrsi:
1475     case Hexagon::A2_tfrpi:
1476     case Hexagon::CONST32:
1477     case Hexagon::CONST64: {
1478       // Call recursively to avoid an extra check whether operand(1) is
1479       // indeed an immediate (it could be a global address, for example),
1480       // plus we can handle COPY at the same time.
1481       if (!checkForImmediate(DI->getOperand(1), TV))
1482         return false;
1483       break;
1484     }
1485     case Hexagon::A2_combineii:
1486     case Hexagon::A4_combineir:
1487     case Hexagon::A4_combineii:
1488     case Hexagon::A4_combineri:
1489     case Hexagon::A2_combinew: {
1490       const MachineOperand &S1 = DI->getOperand(1);
1491       const MachineOperand &S2 = DI->getOperand(2);
1492       int64_t V1, V2;
1493       if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
1494         return false;
1495       TV = V2 | (V1 << 32);
1496       break;
1497     }
1498     case TargetOpcode::REG_SEQUENCE: {
1499       const MachineOperand &S1 = DI->getOperand(1);
1500       const MachineOperand &S3 = DI->getOperand(3);
1501       int64_t V1, V3;
1502       if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
1503         return false;
1504       unsigned Sub2 = DI->getOperand(2).getImm();
1505       unsigned Sub4 = DI->getOperand(4).getImm();
1506       if (Sub2 == Hexagon::subreg_loreg && Sub4 == Hexagon::subreg_hireg)
1507         TV = V1 | (V3 << 32);
1508       else if (Sub2 == Hexagon::subreg_hireg && Sub4 == Hexagon::subreg_loreg)
1509         TV = V3 | (V1 << 32);
1510       else
1511         llvm_unreachable("Unexpected form of REG_SEQUENCE");
1512       break;
1513     }
1514 
1515     default:
1516       return false;
1517   }
1518 
1519   // By now, we should have successfuly obtained the immediate value defining
1520   // the register referenced in MO. Handle a potential use of a subregister.
1521   switch (MO.getSubReg()) {
1522     case Hexagon::subreg_loreg:
1523       Val = TV & 0xFFFFFFFFULL;
1524       break;
1525     case Hexagon::subreg_hireg:
1526       Val = (TV >> 32) & 0xFFFFFFFFULL;
1527       break;
1528     default:
1529       Val = TV;
1530       break;
1531   }
1532   return true;
1533 }
1534 
1535 void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1536   if (MO.isImm()) {
1537     MO.setImm(Val);
1538     return;
1539   }
1540 
1541   assert(MO.isReg());
1542   unsigned R = MO.getReg();
1543   MachineInstr *DI = MRI->getVRegDef(R);
1544 
1545   const TargetRegisterClass *RC = MRI->getRegClass(R);
1546   unsigned NewR = MRI->createVirtualRegister(RC);
1547   MachineBasicBlock &B = *DI->getParent();
1548   DebugLoc DL = DI->getDebugLoc();
1549   BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
1550   MO.setReg(NewR);
1551 }
1552 
1553 static bool isImmValidForOpcode(unsigned CmpOpc, int64_t Imm) {
1554   // These two instructions are not extendable.
1555   if (CmpOpc == Hexagon::A4_cmpbeqi)
1556     return isUInt<8>(Imm);
1557   if (CmpOpc == Hexagon::A4_cmpbgti)
1558     return isInt<8>(Imm);
1559   // The rest of the comparison-with-immediate instructions are extendable.
1560   return true;
1561 }
1562 
1563 bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1564   MachineBasicBlock *Header = L->getHeader();
1565   MachineBasicBlock *Latch = L->getLoopLatch();
1566   MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
1567 
1568   if (!(Header && Latch && ExitingBlock))
1569     return false;
1570 
1571   // These data structures follow the same concept as the corresponding
1572   // ones in findInductionRegister (where some comments are).
1573   typedef std::pair<unsigned,int64_t> RegisterBump;
1574   typedef std::pair<unsigned,RegisterBump> RegisterInduction;
1575   typedef std::set<RegisterInduction> RegisterInductionSet;
1576 
1577   // Register candidates for induction variables, with their associated bumps.
1578   RegisterInductionSet IndRegs;
1579 
1580   // Look for induction patterns:
1581   //   vreg1 = PHI ..., [ latch, vreg2 ]
1582   //   vreg2 = ADD vreg1, imm
1583   typedef MachineBasicBlock::instr_iterator instr_iterator;
1584   for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1585        I != E && I->isPHI(); ++I) {
1586     MachineInstr *Phi = &*I;
1587 
1588     // Have a PHI instruction.
1589     for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1590       if (Phi->getOperand(i+1).getMBB() != Latch)
1591         continue;
1592 
1593       unsigned PhiReg = Phi->getOperand(i).getReg();
1594       MachineInstr *DI = MRI->getVRegDef(PhiReg);
1595       unsigned UpdOpc = DI->getOpcode();
1596       bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
1597 
1598       if (isAdd) {
1599         // If the register operand to the add/sub is the PHI we are looking
1600         // at, this meets the induction pattern.
1601         unsigned IndReg = DI->getOperand(1).getReg();
1602         MachineOperand &Opnd2 = DI->getOperand(2);
1603         int64_t V;
1604         if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
1605           unsigned UpdReg = DI->getOperand(0).getReg();
1606           IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
1607         }
1608       }
1609     }  // for (i)
1610   }  // for (instr)
1611 
1612   if (IndRegs.empty())
1613     return false;
1614 
1615   MachineBasicBlock *TB = nullptr, *FB = nullptr;
1616   SmallVector<MachineOperand,2> Cond;
1617   // AnalyzeBranch returns true if it fails to analyze branch.
1618   bool NotAnalyzed = TII->analyzeBranch(*ExitingBlock, TB, FB, Cond, false);
1619   if (NotAnalyzed || Cond.empty())
1620     return false;
1621 
1622   if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
1623     MachineBasicBlock *LTB = 0, *LFB = 0;
1624     SmallVector<MachineOperand,2> LCond;
1625     bool NotAnalyzed = TII->analyzeBranch(*Latch, LTB, LFB, LCond, false);
1626     if (NotAnalyzed)
1627       return false;
1628 
1629     // Since latch is not the exiting block, the latch branch should be an
1630     // unconditional branch to the loop header.
1631     if (TB == Latch)
1632       TB = (LTB == Header) ? LTB : LFB;
1633     else
1634       FB = (LTB == Header) ? LTB : LFB;
1635   }
1636   if (TB != Header) {
1637     if (FB != Header) {
1638       // The latch/exit block does not go back to the header.
1639       return false;
1640     }
1641     // FB is the header (i.e., uncond. jump to branch header)
1642     // In this case, the LoopBody -> TB should not be a back edge otherwise
1643     // it could result in an infinite loop after conversion to hw_loop.
1644     // This case can happen when the Latch has two jumps like this:
1645     // Jmp_c OuterLoopHeader <-- TB
1646     // Jmp   InnerLoopHeader <-- FB
1647     if (MDT->dominates(TB, FB))
1648       return false;
1649   }
1650 
1651   // Expecting a predicate register as a condition.  It won't be a hardware
1652   // predicate register at this point yet, just a vreg.
1653   // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1654   // into Cond, followed by the predicate register.  For non-negated branches
1655   // it's just the register.
1656   unsigned CSz = Cond.size();
1657   if (CSz != 1 && CSz != 2)
1658     return false;
1659 
1660   if (!Cond[CSz-1].isReg())
1661     return false;
1662 
1663   unsigned P = Cond[CSz-1].getReg();
1664   MachineInstr *PredDef = MRI->getVRegDef(P);
1665 
1666   if (!PredDef->isCompare())
1667     return false;
1668 
1669   SmallSet<unsigned,2> CmpRegs;
1670   MachineOperand *CmpImmOp = nullptr;
1671 
1672   // Go over all operands to the compare and look for immediate and register
1673   // operands.  Assume that if the compare has a single register use and a
1674   // single immediate operand, then the register is being compared with the
1675   // immediate value.
1676   for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1677     MachineOperand &MO = PredDef->getOperand(i);
1678     if (MO.isReg()) {
1679       // Skip all implicit references.  In one case there was:
1680       //   %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1681       if (MO.isImplicit())
1682         continue;
1683       if (MO.isUse()) {
1684         if (!isImmediate(MO)) {
1685           CmpRegs.insert(MO.getReg());
1686           continue;
1687         }
1688         // Consider the register to be the "immediate" operand.
1689         if (CmpImmOp)
1690           return false;
1691         CmpImmOp = &MO;
1692       }
1693     } else if (MO.isImm()) {
1694       if (CmpImmOp)    // A second immediate argument?  Confusing.  Bail out.
1695         return false;
1696       CmpImmOp = &MO;
1697     }
1698   }
1699 
1700   if (CmpRegs.empty())
1701     return false;
1702 
1703   // Check if the compared register follows the order we want.  Fix if needed.
1704   for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1705        I != E; ++I) {
1706     // This is a success.  If the register used in the comparison is one that
1707     // we have identified as a bumped (updated) induction register, there is
1708     // nothing to do.
1709     if (CmpRegs.count(I->first))
1710       return true;
1711 
1712     // Otherwise, if the register being compared comes out of a PHI node,
1713     // and has been recognized as following the induction pattern, and is
1714     // compared against an immediate, we can fix it.
1715     const RegisterBump &RB = I->second;
1716     if (CmpRegs.count(RB.first)) {
1717       if (!CmpImmOp) {
1718         // If both operands to the compare instruction are registers, see if
1719         // it can be changed to use induction register as one of the operands.
1720         MachineInstr *IndI = nullptr;
1721         MachineInstr *nonIndI = nullptr;
1722         MachineOperand *IndMO = nullptr;
1723         MachineOperand *nonIndMO = nullptr;
1724 
1725         for (unsigned i = 1, n = PredDef->getNumOperands(); i < n; ++i) {
1726           MachineOperand &MO = PredDef->getOperand(i);
1727           if (MO.isReg() && MO.getReg() == RB.first) {
1728             DEBUG(dbgs() << "\n DefMI(" << i << ") = "
1729                          << *(MRI->getVRegDef(I->first)));
1730             if (IndI)
1731               return false;
1732 
1733             IndI = MRI->getVRegDef(I->first);
1734             IndMO = &MO;
1735           } else if (MO.isReg()) {
1736             DEBUG(dbgs() << "\n DefMI(" << i << ") = "
1737                          << *(MRI->getVRegDef(MO.getReg())));
1738             if (nonIndI)
1739               return false;
1740 
1741             nonIndI = MRI->getVRegDef(MO.getReg());
1742             nonIndMO = &MO;
1743           }
1744         }
1745         if (IndI && nonIndI &&
1746             nonIndI->getOpcode() == Hexagon::A2_addi &&
1747             nonIndI->getOperand(2).isImm() &&
1748             nonIndI->getOperand(2).getImm() == - RB.second) {
1749           bool Order = orderBumpCompare(IndI, PredDef);
1750           if (Order) {
1751             IndMO->setReg(I->first);
1752             nonIndMO->setReg(nonIndI->getOperand(1).getReg());
1753             return true;
1754           }
1755         }
1756         return false;
1757       }
1758 
1759       // It is not valid to do this transformation on an unsigned comparison
1760       // because it may underflow.
1761       Comparison::Kind Cmp = getComparisonKind(PredDef->getOpcode(), 0, 0, 0);
1762       if (!Cmp || Comparison::isUnsigned(Cmp))
1763         return false;
1764 
1765       // If the register is being compared against an immediate, try changing
1766       // the compare instruction to use induction register and adjust the
1767       // immediate operand.
1768       int64_t CmpImm = getImmediate(*CmpImmOp);
1769       int64_t V = RB.second;
1770       // Handle Overflow (64-bit).
1771       if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
1772           ((V < 0) && (CmpImm < INT64_MIN - V)))
1773         return false;
1774       CmpImm += V;
1775       // Most comparisons of register against an immediate value allow
1776       // the immediate to be constant-extended. There are some exceptions
1777       // though. Make sure the new combination will work.
1778       if (CmpImmOp->isImm())
1779         if (!isImmValidForOpcode(PredDef->getOpcode(), CmpImm))
1780           return false;
1781 
1782       // Make sure that the compare happens after the bump.  Otherwise,
1783       // after the fixup, the compare would use a yet-undefined register.
1784       MachineInstr *BumpI = MRI->getVRegDef(I->first);
1785       bool Order = orderBumpCompare(BumpI, PredDef);
1786       if (!Order)
1787         return false;
1788 
1789       // Finally, fix the compare instruction.
1790       setImmediate(*CmpImmOp, CmpImm);
1791       for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1792         MachineOperand &MO = PredDef->getOperand(i);
1793         if (MO.isReg() && MO.getReg() == RB.first) {
1794           MO.setReg(I->first);
1795           return true;
1796         }
1797       }
1798     }
1799   }
1800 
1801   return false;
1802 }
1803 
1804 /// createPreheaderForLoop - Create a preheader for a given loop.
1805 MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1806       MachineLoop *L) {
1807   if (MachineBasicBlock *TmpPH = MLI->findLoopPreheader(L, SpecPreheader))
1808     return TmpPH;
1809   if (!HWCreatePreheader)
1810     return nullptr;
1811 
1812   MachineBasicBlock *Header = L->getHeader();
1813   MachineBasicBlock *Latch = L->getLoopLatch();
1814   MachineBasicBlock *ExitingBlock = L->findLoopControlBlock();
1815   MachineFunction *MF = Header->getParent();
1816   DebugLoc DL;
1817 
1818 #ifndef NDEBUG
1819   if ((PHFn != "") && (PHFn != MF->getName()))
1820     return nullptr;
1821 #endif
1822 
1823   if (!Latch || !ExitingBlock || Header->hasAddressTaken())
1824     return nullptr;
1825 
1826   typedef MachineBasicBlock::instr_iterator instr_iterator;
1827 
1828   // Verify that all existing predecessors have analyzable branches
1829   // (or no branches at all).
1830   typedef std::vector<MachineBasicBlock*> MBBVector;
1831   MBBVector Preds(Header->pred_begin(), Header->pred_end());
1832   SmallVector<MachineOperand,2> Tmp1;
1833   MachineBasicBlock *TB = nullptr, *FB = nullptr;
1834 
1835   if (TII->analyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
1836     return nullptr;
1837 
1838   for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1839     MachineBasicBlock *PB = *I;
1840     bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp1, false);
1841     if (NotAnalyzed)
1842       return nullptr;
1843   }
1844 
1845   MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
1846   MF->insert(Header->getIterator(), NewPH);
1847 
1848   if (Header->pred_size() > 2) {
1849     // Ensure that the header has only two predecessors: the preheader and
1850     // the loop latch.  Any additional predecessors of the header should
1851     // join at the newly created preheader. Inspect all PHI nodes from the
1852     // header and create appropriate corresponding PHI nodes in the preheader.
1853 
1854     for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1855          I != E && I->isPHI(); ++I) {
1856       MachineInstr *PN = &*I;
1857 
1858       const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1859       MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1860       NewPH->insert(NewPH->end(), NewPN);
1861 
1862       unsigned PR = PN->getOperand(0).getReg();
1863       const TargetRegisterClass *RC = MRI->getRegClass(PR);
1864       unsigned NewPR = MRI->createVirtualRegister(RC);
1865       NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1866 
1867       // Copy all non-latch operands of a header's PHI node to the newly
1868       // created PHI node in the preheader.
1869       for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1870         unsigned PredR = PN->getOperand(i).getReg();
1871         unsigned PredRSub = PN->getOperand(i).getSubReg();
1872         MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1873         if (PredB == Latch)
1874           continue;
1875 
1876         MachineOperand MO = MachineOperand::CreateReg(PredR, false);
1877         MO.setSubReg(PredRSub);
1878         NewPN->addOperand(MO);
1879         NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1880       }
1881 
1882       // Remove copied operands from the old PHI node and add the value
1883       // coming from the preheader's PHI.
1884       for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1885         MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1886         if (PredB != Latch) {
1887           PN->RemoveOperand(i+1);
1888           PN->RemoveOperand(i);
1889         }
1890       }
1891       PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1892       PN->addOperand(MachineOperand::CreateMBB(NewPH));
1893     }
1894 
1895   } else {
1896     assert(Header->pred_size() == 2);
1897 
1898     // The header has only two predecessors, but the non-latch predecessor
1899     // is not a preheader (e.g. it has other successors, etc.)
1900     // In such a case we don't need any extra PHI nodes in the new preheader,
1901     // all we need is to adjust existing PHIs in the header to now refer to
1902     // the new preheader.
1903     for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1904          I != E && I->isPHI(); ++I) {
1905       MachineInstr *PN = &*I;
1906       for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1907         MachineOperand &MO = PN->getOperand(i+1);
1908         if (MO.getMBB() != Latch)
1909           MO.setMBB(NewPH);
1910       }
1911     }
1912   }
1913 
1914   // "Reroute" the CFG edges to link in the new preheader.
1915   // If any of the predecessors falls through to the header, insert a branch
1916   // to the new preheader in that place.
1917   SmallVector<MachineOperand,1> Tmp2;
1918   SmallVector<MachineOperand,1> EmptyCond;
1919 
1920   TB = FB = nullptr;
1921 
1922   for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1923     MachineBasicBlock *PB = *I;
1924     if (PB != Latch) {
1925       Tmp2.clear();
1926       bool NotAnalyzed = TII->analyzeBranch(*PB, TB, FB, Tmp2, false);
1927       (void)NotAnalyzed; // suppress compiler warning
1928       assert (!NotAnalyzed && "Should be analyzable!");
1929       if (TB != Header && (Tmp2.empty() || FB != Header))
1930         TII->InsertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
1931       PB->ReplaceUsesOfBlockWith(Header, NewPH);
1932     }
1933   }
1934 
1935   // It can happen that the latch block will fall through into the header.
1936   // Insert an unconditional branch to the header.
1937   TB = FB = nullptr;
1938   bool LatchNotAnalyzed = TII->analyzeBranch(*Latch, TB, FB, Tmp2, false);
1939   (void)LatchNotAnalyzed; // suppress compiler warning
1940   assert (!LatchNotAnalyzed && "Should be analyzable!");
1941   if (!TB && !FB)
1942     TII->InsertBranch(*Latch, Header, nullptr, EmptyCond, DL);
1943 
1944   // Finally, the branch from the preheader to the header.
1945   TII->InsertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
1946   NewPH->addSuccessor(Header);
1947 
1948   MachineLoop *ParentLoop = L->getParentLoop();
1949   if (ParentLoop)
1950     ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
1951 
1952   // Update the dominator information with the new preheader.
1953   if (MDT) {
1954     if (MachineDomTreeNode *HN = MDT->getNode(Header)) {
1955       if (MachineDomTreeNode *DHN = HN->getIDom()) {
1956         MDT->addNewBlock(NewPH, DHN->getBlock());
1957         MDT->changeImmediateDominator(Header, NewPH);
1958       }
1959     }
1960   }
1961 
1962   return NewPH;
1963 }
1964