xref: /llvm-project/llvm/lib/Target/Hexagon/HexagonHardwareLoops.cpp (revision 9376e9998e554dbe171eba409eabdc2dddae16f0)
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 STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
64 
65 namespace llvm {
66   void initializeHexagonHardwareLoopsPass(PassRegistry&);
67 }
68 
69 namespace {
70   class CountValue;
71   struct HexagonHardwareLoops : public MachineFunctionPass {
72     MachineLoopInfo            *MLI;
73     MachineRegisterInfo        *MRI;
74     MachineDominatorTree       *MDT;
75     const HexagonInstrInfo     *TII;
76 #ifndef NDEBUG
77     static int Counter;
78 #endif
79 
80   public:
81     static char ID;
82 
83     HexagonHardwareLoops() : MachineFunctionPass(ID) {
84       initializeHexagonHardwareLoopsPass(*PassRegistry::getPassRegistry());
85     }
86 
87     bool runOnMachineFunction(MachineFunction &MF) override;
88 
89     const char *getPassName() const override { return "Hexagon Hardware Loops"; }
90 
91     void getAnalysisUsage(AnalysisUsage &AU) const override {
92       AU.addRequired<MachineDominatorTree>();
93       AU.addRequired<MachineLoopInfo>();
94       MachineFunctionPass::getAnalysisUsage(AU);
95     }
96 
97   private:
98     typedef std::map<unsigned, MachineInstr *> LoopFeederMap;
99 
100     /// Kinds of comparisons in the compare instructions.
101     struct Comparison {
102       enum Kind {
103         EQ  = 0x01,
104         NE  = 0x02,
105         L   = 0x04,
106         G   = 0x08,
107         U   = 0x40,
108         LTs = L,
109         LEs = L | EQ,
110         GTs = G,
111         GEs = G | EQ,
112         LTu = L      | U,
113         LEu = L | EQ | U,
114         GTu = G      | U,
115         GEu = G | EQ | U
116       };
117 
118       static Kind getSwappedComparison(Kind Cmp) {
119         assert ((!((Cmp & L) && (Cmp & G))) && "Malformed comparison operator");
120         if ((Cmp & L) || (Cmp & G))
121           return (Kind)(Cmp ^ (L|G));
122         return Cmp;
123       }
124 
125       static Kind getNegatedComparison(Kind Cmp) {
126         if ((Cmp & L) || (Cmp & G))
127           return (Kind)((Cmp ^ (L | G)) ^ EQ);
128         if ((Cmp & NE) || (Cmp & EQ))
129           return (Kind)(Cmp ^ (EQ | NE));
130         return (Kind)0;
131       }
132 
133       static bool isSigned(Kind Cmp) {
134         return (Cmp & (L | G) && !(Cmp & U));
135       }
136 
137       static bool isUnsigned(Kind Cmp) {
138         return (Cmp & U);
139       }
140 
141     };
142 
143     /// \brief Find the register that contains the loop controlling
144     /// induction variable.
145     /// If successful, it will return true and set the \p Reg, \p IVBump
146     /// and \p IVOp arguments.  Otherwise it will return false.
147     /// The returned induction register is the register R that follows the
148     /// following induction pattern:
149     /// loop:
150     ///   R = phi ..., [ R.next, LatchBlock ]
151     ///   R.next = R + #bump
152     ///   if (R.next < #N) goto loop
153     /// IVBump is the immediate value added to R, and IVOp is the instruction
154     /// "R.next = R + #bump".
155     bool findInductionRegister(MachineLoop *L, unsigned &Reg,
156                                int64_t &IVBump, MachineInstr *&IVOp) const;
157 
158     /// \brief Return the comparison kind for the specified opcode.
159     Comparison::Kind getComparisonKind(unsigned CondOpc,
160                                        MachineOperand *InitialValue,
161                                        const MachineOperand *Endvalue,
162                                        int64_t IVBump) const;
163 
164     /// \brief Analyze the statements in a loop to determine if the loop
165     /// has a computable trip count and, if so, return a value that represents
166     /// the trip count expression.
167     CountValue *getLoopTripCount(MachineLoop *L,
168                                  SmallVectorImpl<MachineInstr *> &OldInsts);
169 
170     /// \brief Return the expression that represents the number of times
171     /// a loop iterates.  The function takes the operands that represent the
172     /// loop start value, loop end value, and induction value.  Based upon
173     /// these operands, the function attempts to compute the trip count.
174     /// If the trip count is not directly available (as an immediate value,
175     /// or a register), the function will attempt to insert computation of it
176     /// to the loop's preheader.
177     CountValue *computeCount(MachineLoop *Loop, const MachineOperand *Start,
178                              const MachineOperand *End, unsigned IVReg,
179                              int64_t IVBump, Comparison::Kind Cmp) const;
180 
181     /// \brief Return true if the instruction is not valid within a hardware
182     /// loop.
183     bool isInvalidLoopOperation(const MachineInstr *MI,
184                                 bool IsInnerHWLoop) const;
185 
186     /// \brief Return true if the loop contains an instruction that inhibits
187     /// using the hardware loop.
188     bool containsInvalidInstruction(MachineLoop *L, bool IsInnerHWLoop) const;
189 
190     /// \brief Given a loop, check if we can convert it to a hardware loop.
191     /// If so, then perform the conversion and return true.
192     bool convertToHardwareLoop(MachineLoop *L, bool &L0used, bool &L1used);
193 
194     /// \brief Return true if the instruction is now dead.
195     bool isDead(const MachineInstr *MI,
196                 SmallVectorImpl<MachineInstr *> &DeadPhis) const;
197 
198     /// \brief Remove the instruction if it is now dead.
199     void removeIfDead(MachineInstr *MI);
200 
201     /// \brief Make sure that the "bump" instruction executes before the
202     /// compare.  We need that for the IV fixup, so that the compare
203     /// instruction would not use a bumped value that has not yet been
204     /// defined.  If the instructions are out of order, try to reorder them.
205     bool orderBumpCompare(MachineInstr *BumpI, MachineInstr *CmpI);
206 
207     /// \brief Return true if MO and MI pair is visited only once. If visited
208     /// more than once, this indicates there is recursion. In such a case,
209     /// return false.
210     bool isLoopFeeder(MachineLoop *L, MachineBasicBlock *A, MachineInstr *MI,
211                       const MachineOperand *MO,
212                       LoopFeederMap &LoopFeederPhi) const;
213 
214     /// \brief Return true if the Phi may generate a value that may underflow,
215     /// or may wrap.
216     bool phiMayWrapOrUnderflow(MachineInstr *Phi, const MachineOperand *EndVal,
217                                MachineBasicBlock *MBB, MachineLoop *L,
218                                LoopFeederMap &LoopFeederPhi) const;
219 
220     /// \brief Return true if the induction variable may underflow an unsigned
221     /// value in the first iteration.
222     bool loopCountMayWrapOrUnderFlow(const MachineOperand *InitVal,
223                                      const MachineOperand *EndVal,
224                                      MachineBasicBlock *MBB, MachineLoop *L,
225                                      LoopFeederMap &LoopFeederPhi) const;
226 
227     /// \brief Check if the given operand has a compile-time known constant
228     /// value. Return true if yes, and false otherwise. When returning true, set
229     /// Val to the corresponding constant value.
230     bool checkForImmediate(const MachineOperand &MO, int64_t &Val) const;
231 
232     /// \brief Check if the operand has a compile-time known constant value.
233     bool isImmediate(const MachineOperand &MO) const {
234       int64_t V;
235       return checkForImmediate(MO, V);
236     }
237 
238     /// \brief Return the immediate for the specified operand.
239     int64_t getImmediate(const MachineOperand &MO) const {
240       int64_t V;
241       if (!checkForImmediate(MO, V))
242         llvm_unreachable("Invalid operand");
243       return V;
244     }
245 
246     /// \brief Reset the given machine operand to now refer to a new immediate
247     /// value.  Assumes that the operand was already referencing an immediate
248     /// value, either directly, or via a register.
249     void setImmediate(MachineOperand &MO, int64_t Val);
250 
251     /// \brief Fix the data flow of the induction varible.
252     /// The desired flow is: phi ---> bump -+-> comparison-in-latch.
253     ///                                     |
254     ///                                     +-> back to phi
255     /// where "bump" is the increment of the induction variable:
256     ///   iv = iv + #const.
257     /// Due to some prior code transformations, the actual flow may look
258     /// like this:
259     ///   phi -+-> bump ---> back to phi
260     ///        |
261     ///        +-> comparison-in-latch (against upper_bound-bump),
262     /// i.e. the comparison that controls the loop execution may be using
263     /// the value of the induction variable from before the increment.
264     ///
265     /// Return true if the loop's flow is the desired one (i.e. it's
266     /// either been fixed, or no fixing was necessary).
267     /// Otherwise, return false.  This can happen if the induction variable
268     /// couldn't be identified, or if the value in the latch's comparison
269     /// cannot be adjusted to reflect the post-bump value.
270     bool fixupInductionVariable(MachineLoop *L);
271 
272     /// \brief Given a loop, if it does not have a preheader, create one.
273     /// Return the block that is the preheader.
274     MachineBasicBlock *createPreheaderForLoop(MachineLoop *L);
275   };
276 
277   char HexagonHardwareLoops::ID = 0;
278 #ifndef NDEBUG
279   int HexagonHardwareLoops::Counter = 0;
280 #endif
281 
282   /// \brief Abstraction for a trip count of a loop. A smaller version
283   /// of the MachineOperand class without the concerns of changing the
284   /// operand representation.
285   class CountValue {
286   public:
287     enum CountValueType {
288       CV_Register,
289       CV_Immediate
290     };
291   private:
292     CountValueType Kind;
293     union Values {
294       struct {
295         unsigned Reg;
296         unsigned Sub;
297       } R;
298       unsigned ImmVal;
299     } Contents;
300 
301   public:
302     explicit CountValue(CountValueType t, unsigned v, unsigned u = 0) {
303       Kind = t;
304       if (Kind == CV_Register) {
305         Contents.R.Reg = v;
306         Contents.R.Sub = u;
307       } else {
308         Contents.ImmVal = v;
309       }
310     }
311     bool isReg() const { return Kind == CV_Register; }
312     bool isImm() const { return Kind == CV_Immediate; }
313 
314     unsigned getReg() const {
315       assert(isReg() && "Wrong CountValue accessor");
316       return Contents.R.Reg;
317     }
318     unsigned getSubReg() const {
319       assert(isReg() && "Wrong CountValue accessor");
320       return Contents.R.Sub;
321     }
322     unsigned getImm() const {
323       assert(isImm() && "Wrong CountValue accessor");
324       return Contents.ImmVal;
325     }
326 
327     void print(raw_ostream &OS, const TargetRegisterInfo *TRI = nullptr) const {
328       if (isReg()) { OS << PrintReg(Contents.R.Reg, TRI, Contents.R.Sub); }
329       if (isImm()) { OS << Contents.ImmVal; }
330     }
331   };
332 } // end anonymous namespace
333 
334 
335 INITIALIZE_PASS_BEGIN(HexagonHardwareLoops, "hwloops",
336                       "Hexagon Hardware Loops", false, false)
337 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
338 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
339 INITIALIZE_PASS_END(HexagonHardwareLoops, "hwloops",
340                     "Hexagon Hardware Loops", false, false)
341 
342 FunctionPass *llvm::createHexagonHardwareLoops() {
343   return new HexagonHardwareLoops();
344 }
345 
346 bool HexagonHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
347   DEBUG(dbgs() << "********* Hexagon Hardware Loops *********\n");
348 
349   bool Changed = false;
350 
351   MLI = &getAnalysis<MachineLoopInfo>();
352   MRI = &MF.getRegInfo();
353   MDT = &getAnalysis<MachineDominatorTree>();
354   TII = MF.getSubtarget<HexagonSubtarget>().getInstrInfo();
355 
356   for (auto &L : *MLI)
357     if (!L->getParentLoop()) {
358       bool L0Used = false;
359       bool L1Used = false;
360       Changed |= convertToHardwareLoop(L, L0Used, L1Used);
361     }
362 
363   return Changed;
364 }
365 
366 /// \brief Return the latch block if it's one of the exiting blocks. Otherwise,
367 /// return the exiting block. Return 'null' when multiple exiting blocks are
368 /// present.
369 static MachineBasicBlock* getExitingBlock(MachineLoop *L) {
370   if (MachineBasicBlock *Latch = L->getLoopLatch()) {
371     if (L->isLoopExiting(Latch))
372       return Latch;
373     else
374       return L->getExitingBlock();
375   }
376   return nullptr;
377 }
378 
379 bool HexagonHardwareLoops::findInductionRegister(MachineLoop *L,
380                                                  unsigned &Reg,
381                                                  int64_t &IVBump,
382                                                  MachineInstr *&IVOp
383                                                  ) const {
384   MachineBasicBlock *Header = L->getHeader();
385   MachineBasicBlock *Preheader = L->getLoopPreheader();
386   MachineBasicBlock *Latch = L->getLoopLatch();
387   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
388   if (!Header || !Preheader || !Latch || !ExitingBlock)
389     return false;
390 
391   // This pair represents an induction register together with an immediate
392   // value that will be added to it in each loop iteration.
393   typedef std::pair<unsigned,int64_t> RegisterBump;
394 
395   // Mapping:  R.next -> (R, bump), where R, R.next and bump are derived
396   // from an induction operation
397   //   R.next = R + bump
398   // where bump is an immediate value.
399   typedef std::map<unsigned,RegisterBump> InductionMap;
400 
401   InductionMap IndMap;
402 
403   typedef MachineBasicBlock::instr_iterator instr_iterator;
404   for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
405        I != E && I->isPHI(); ++I) {
406     MachineInstr *Phi = &*I;
407 
408     // Have a PHI instruction.  Get the operand that corresponds to the
409     // latch block, and see if is a result of an addition of form "reg+imm",
410     // where the "reg" is defined by the PHI node we are looking at.
411     for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
412       if (Phi->getOperand(i+1).getMBB() != Latch)
413         continue;
414 
415       unsigned PhiOpReg = Phi->getOperand(i).getReg();
416       MachineInstr *DI = MRI->getVRegDef(PhiOpReg);
417       unsigned UpdOpc = DI->getOpcode();
418       bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
419 
420       if (isAdd) {
421         // If the register operand to the add is the PHI we're looking at, this
422         // meets the induction pattern.
423         unsigned IndReg = DI->getOperand(1).getReg();
424         MachineOperand &Opnd2 = DI->getOperand(2);
425         int64_t V;
426         if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
427           unsigned UpdReg = DI->getOperand(0).getReg();
428           IndMap.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
429         }
430       }
431     }  // for (i)
432   }  // for (instr)
433 
434   SmallVector<MachineOperand,2> Cond;
435   MachineBasicBlock *TB = nullptr, *FB = nullptr;
436   bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
437   if (NotAnalyzed)
438     return false;
439 
440   unsigned PredR, PredPos, PredRegFlags;
441   if (!TII->getPredReg(Cond, PredR, PredPos, PredRegFlags))
442     return false;
443 
444   MachineInstr *PredI = MRI->getVRegDef(PredR);
445   if (!PredI->isCompare())
446     return false;
447 
448   unsigned CmpReg1 = 0, CmpReg2 = 0;
449   int CmpImm = 0, CmpMask = 0;
450   bool CmpAnalyzed = TII->analyzeCompare(PredI, CmpReg1, CmpReg2,
451                                          CmpMask, CmpImm);
452   // Fail if the compare was not analyzed, or it's not comparing a register
453   // with an immediate value.  Not checking the mask here, since we handle
454   // the individual compare opcodes (including A4_cmpb*) later on.
455   if (!CmpAnalyzed)
456     return false;
457 
458   // Exactly one of the input registers to the comparison should be among
459   // the induction registers.
460   InductionMap::iterator IndMapEnd = IndMap.end();
461   InductionMap::iterator F = IndMapEnd;
462   if (CmpReg1 != 0) {
463     InductionMap::iterator F1 = IndMap.find(CmpReg1);
464     if (F1 != IndMapEnd)
465       F = F1;
466   }
467   if (CmpReg2 != 0) {
468     InductionMap::iterator F2 = IndMap.find(CmpReg2);
469     if (F2 != IndMapEnd) {
470       if (F != IndMapEnd)
471         return false;
472       F = F2;
473     }
474   }
475   if (F == IndMapEnd)
476     return false;
477 
478   Reg = F->second.first;
479   IVBump = F->second.second;
480   IVOp = MRI->getVRegDef(F->first);
481   return true;
482 }
483 
484 // Return the comparison kind for the specified opcode.
485 HexagonHardwareLoops::Comparison::Kind
486 HexagonHardwareLoops::getComparisonKind(unsigned CondOpc,
487                                         MachineOperand *InitialValue,
488                                         const MachineOperand *EndValue,
489                                         int64_t IVBump) const {
490   Comparison::Kind Cmp = (Comparison::Kind)0;
491   switch (CondOpc) {
492   case Hexagon::C2_cmpeqi:
493   case Hexagon::C2_cmpeq:
494   case Hexagon::C2_cmpeqp:
495     Cmp = Comparison::EQ;
496     break;
497   case Hexagon::C4_cmpneq:
498   case Hexagon::C4_cmpneqi:
499     Cmp = Comparison::NE;
500     break;
501   case Hexagon::C4_cmplte:
502     Cmp = Comparison::LEs;
503     break;
504   case Hexagon::C4_cmplteu:
505     Cmp = Comparison::LEu;
506     break;
507   case Hexagon::C2_cmpgtui:
508   case Hexagon::C2_cmpgtu:
509   case Hexagon::C2_cmpgtup:
510     Cmp = Comparison::GTu;
511     break;
512   case Hexagon::C2_cmpgti:
513   case Hexagon::C2_cmpgt:
514   case Hexagon::C2_cmpgtp:
515     Cmp = Comparison::GTs;
516     break;
517   default:
518     return (Comparison::Kind)0;
519   }
520   return Cmp;
521 }
522 
523 /// \brief Analyze the statements in a loop to determine if the loop has
524 /// a computable trip count and, if so, return a value that represents
525 /// the trip count expression.
526 ///
527 /// This function iterates over the phi nodes in the loop to check for
528 /// induction variable patterns that are used in the calculation for
529 /// the number of time the loop is executed.
530 CountValue *HexagonHardwareLoops::getLoopTripCount(MachineLoop *L,
531     SmallVectorImpl<MachineInstr *> &OldInsts) {
532   MachineBasicBlock *TopMBB = L->getTopBlock();
533   MachineBasicBlock::pred_iterator PI = TopMBB->pred_begin();
534   assert(PI != TopMBB->pred_end() &&
535          "Loop must have more than one incoming edge!");
536   MachineBasicBlock *Backedge = *PI++;
537   if (PI == TopMBB->pred_end())  // dead loop?
538     return nullptr;
539   MachineBasicBlock *Incoming = *PI++;
540   if (PI != TopMBB->pred_end())  // multiple backedges?
541     return nullptr;
542 
543   // Make sure there is one incoming and one backedge and determine which
544   // is which.
545   if (L->contains(Incoming)) {
546     if (L->contains(Backedge))
547       return nullptr;
548     std::swap(Incoming, Backedge);
549   } else if (!L->contains(Backedge))
550     return nullptr;
551 
552   // Look for the cmp instruction to determine if we can get a useful trip
553   // count.  The trip count can be either a register or an immediate.  The
554   // location of the value depends upon the type (reg or imm).
555   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
556   if (!ExitingBlock)
557     return nullptr;
558 
559   unsigned IVReg = 0;
560   int64_t IVBump = 0;
561   MachineInstr *IVOp;
562   bool FoundIV = findInductionRegister(L, IVReg, IVBump, IVOp);
563   if (!FoundIV)
564     return nullptr;
565 
566   MachineBasicBlock *Preheader = L->getLoopPreheader();
567 
568   MachineOperand *InitialValue = nullptr;
569   MachineInstr *IV_Phi = MRI->getVRegDef(IVReg);
570   MachineBasicBlock *Latch = L->getLoopLatch();
571   for (unsigned i = 1, n = IV_Phi->getNumOperands(); i < n; i += 2) {
572     MachineBasicBlock *MBB = IV_Phi->getOperand(i+1).getMBB();
573     if (MBB == Preheader)
574       InitialValue = &IV_Phi->getOperand(i);
575     else if (MBB == Latch)
576       IVReg = IV_Phi->getOperand(i).getReg();  // Want IV reg after bump.
577   }
578   if (!InitialValue)
579     return nullptr;
580 
581   SmallVector<MachineOperand,2> Cond;
582   MachineBasicBlock *TB = nullptr, *FB = nullptr;
583   bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
584   if (NotAnalyzed)
585     return nullptr;
586 
587   MachineBasicBlock *Header = L->getHeader();
588   // TB must be non-null.  If FB is also non-null, one of them must be
589   // the header.  Otherwise, branch to TB could be exiting the loop, and
590   // the fall through can go to the header.
591   assert (TB && "Exit block without a branch?");
592   if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
593     MachineBasicBlock *LTB = 0, *LFB = 0;
594     SmallVector<MachineOperand,2> LCond;
595     bool NotAnalyzed = TII->AnalyzeBranch(*Latch, LTB, LFB, LCond, false);
596     if (NotAnalyzed)
597       return nullptr;
598     if (TB == Latch)
599       TB = (LTB == Header) ? LTB : LFB;
600     else
601       FB = (LTB == Header) ? LTB: LFB;
602   }
603   assert ((!FB || TB == Header || FB == Header) && "Branches not to header?");
604   if (!TB || (FB && TB != Header && FB != Header))
605     return nullptr;
606 
607   // Branches of form "if (!P) ..." cause HexagonInstrInfo::AnalyzeBranch
608   // to put imm(0), followed by P in the vector Cond.
609   // If TB is not the header, it means that the "not-taken" path must lead
610   // to the header.
611   bool Negated = TII->predOpcodeHasNot(Cond) ^ (TB != Header);
612   unsigned PredReg, PredPos, PredRegFlags;
613   if (!TII->getPredReg(Cond, PredReg, PredPos, PredRegFlags))
614     return nullptr;
615   MachineInstr *CondI = MRI->getVRegDef(PredReg);
616   unsigned CondOpc = CondI->getOpcode();
617 
618   unsigned CmpReg1 = 0, CmpReg2 = 0;
619   int Mask = 0, ImmValue = 0;
620   bool AnalyzedCmp = TII->analyzeCompare(CondI, CmpReg1, CmpReg2,
621                                          Mask, ImmValue);
622   if (!AnalyzedCmp)
623     return nullptr;
624 
625   // The comparison operator type determines how we compute the loop
626   // trip count.
627   OldInsts.push_back(CondI);
628   OldInsts.push_back(IVOp);
629 
630   // Sadly, the following code gets information based on the position
631   // of the operands in the compare instruction.  This has to be done
632   // this way, because the comparisons check for a specific relationship
633   // between the operands (e.g. is-less-than), rather than to find out
634   // what relationship the operands are in (as on PPC).
635   Comparison::Kind Cmp;
636   bool isSwapped = false;
637   const MachineOperand &Op1 = CondI->getOperand(1);
638   const MachineOperand &Op2 = CondI->getOperand(2);
639   const MachineOperand *EndValue = nullptr;
640 
641   if (Op1.isReg()) {
642     if (Op2.isImm() || Op1.getReg() == IVReg)
643       EndValue = &Op2;
644     else {
645       EndValue = &Op1;
646       isSwapped = true;
647     }
648   }
649 
650   if (!EndValue)
651     return nullptr;
652 
653   Cmp = getComparisonKind(CondOpc, InitialValue, EndValue, IVBump);
654   if (!Cmp)
655     return nullptr;
656   if (Negated)
657     Cmp = Comparison::getNegatedComparison(Cmp);
658   if (isSwapped)
659     Cmp = Comparison::getSwappedComparison(Cmp);
660 
661   if (InitialValue->isReg()) {
662     unsigned R = InitialValue->getReg();
663     MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
664     if (!MDT->properlyDominates(DefBB, Header))
665       return nullptr;
666     OldInsts.push_back(MRI->getVRegDef(R));
667   }
668   if (EndValue->isReg()) {
669     unsigned R = EndValue->getReg();
670     MachineBasicBlock *DefBB = MRI->getVRegDef(R)->getParent();
671     if (!MDT->properlyDominates(DefBB, Header))
672       return nullptr;
673   }
674 
675   return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
676 }
677 
678 /// \brief Helper function that returns the expression that represents the
679 /// number of times a loop iterates.  The function takes the operands that
680 /// represent the loop start value, loop end value, and induction value.
681 /// Based upon these operands, the function attempts to compute the trip count.
682 CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
683                                                const MachineOperand *Start,
684                                                const MachineOperand *End,
685                                                unsigned IVReg,
686                                                int64_t IVBump,
687                                                Comparison::Kind Cmp) const {
688   // Cannot handle comparison EQ, i.e. while (A == B).
689   if (Cmp == Comparison::EQ)
690     return nullptr;
691 
692   // Check if either the start or end values are an assignment of an immediate.
693   // If so, use the immediate value rather than the register.
694   if (Start->isReg()) {
695     const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
696     if (StartValInstr && StartValInstr->getOpcode() == Hexagon::A2_tfrsi)
697       Start = &StartValInstr->getOperand(1);
698   }
699   if (End->isReg()) {
700     const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
701     if (EndValInstr && EndValInstr->getOpcode() == Hexagon::A2_tfrsi)
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 inital 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 shoudn'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 = Loop->getLoopPreheader();
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() && MI->getOpcode() != Hexagon::CALLv3nr)
949     return true;
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 = getExitingBlock(L);
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 = L->getLoopPreheader();
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 = getExitingBlock(L);
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, 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       instr_iterator After = BumpI;
1307       instr_iterator From = CmpI;
1308       BB->splice(std::next(After), BB, From);
1309       FoundBump = true;
1310       break;
1311     }
1312   }
1313   assert (FoundBump && "Cannot determine instruction order");
1314   return FoundBump;
1315 }
1316 
1317 /// This function is required to break recursion. Visiting phis in a loop may
1318 /// result in recursion during compilation. We break the recursion by making
1319 /// sure that we visit a MachineOperand and its definition in a
1320 /// MachineInstruction only once. If we attempt to visit more than once, then
1321 /// there is recursion, and will return false.
1322 bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
1323                                         MachineInstr *MI,
1324                                         const MachineOperand *MO,
1325                                         LoopFeederMap &LoopFeederPhi) const {
1326   if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
1327     const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
1328     DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
1329     // Ignore all BBs that form Loop.
1330     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1331       MachineBasicBlock *MBB = Blocks[i];
1332       if (A == MBB)
1333         return false;
1334     }
1335     MachineInstr *Def = MRI->getVRegDef(MO->getReg());
1336     LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
1337     return true;
1338   } else
1339     // Already visited node.
1340     return false;
1341 }
1342 
1343 /// Return true if a Phi may generate a value that can underflow.
1344 /// This function calls loopCountMayWrapOrUnderFlow for each Phi operand.
1345 bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1346     MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
1347     MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
1348   assert(Phi->isPHI() && "Expecting a Phi.");
1349   // Walk through each Phi, and its used operands. Make sure that
1350   // if there is recursion in Phi, we won't generate hardware loops.
1351   for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
1352     if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
1353       if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
1354                                       Phi->getParent(), L, LoopFeederPhi))
1355         return true;
1356   return false;
1357 }
1358 
1359 /// Return true if the induction variable can underflow in the first iteration.
1360 /// An example, is an initial unsigned value that is 0 and is decrement in the
1361 /// first itertion of a do-while loop.  In this case, we cannot generate a
1362 /// hardware loop because the endloop instruction does not decrement the loop
1363 /// counter if it is <= 1. We only need to perform this analysis if the
1364 /// initial value is a register.
1365 ///
1366 /// This function assumes the initial value may underfow unless proven
1367 /// otherwise. If the type is signed, then we don't care because signed
1368 /// underflow is undefined. We attempt to prove the initial value is not
1369 /// zero by perfoming a crude analysis of the loop counter. This function
1370 /// checks if the initial value is used in any comparison prior to the loop
1371 /// and, if so, assumes the comparison is a range check. This is inexact,
1372 /// but will catch the simple cases.
1373 bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1374     const MachineOperand *InitVal, const MachineOperand *EndVal,
1375     MachineBasicBlock *MBB, MachineLoop *L,
1376     LoopFeederMap &LoopFeederPhi) const {
1377   // Only check register values since they are unknown.
1378   if (!InitVal->isReg())
1379     return false;
1380 
1381   if (!EndVal->isImm())
1382     return false;
1383 
1384   // A register value that is assigned an immediate is a known value, and it
1385   // won't underflow in the first iteration.
1386   int64_t Imm;
1387   if (checkForImmediate(*InitVal, Imm))
1388     return (EndVal->getImm() == Imm);
1389 
1390   unsigned Reg = InitVal->getReg();
1391 
1392   // We don't know the value of a physical register.
1393   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1394     return true;
1395 
1396   MachineInstr *Def = MRI->getVRegDef(Reg);
1397   if (!Def)
1398     return true;
1399 
1400   // If the initial value is a Phi or copy and the operands may not underflow,
1401   // then the definition cannot be underflow either.
1402   if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
1403                                              L, LoopFeederPhi))
1404     return false;
1405   if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
1406                                                     EndVal, Def->getParent(),
1407                                                     L, LoopFeederPhi))
1408     return false;
1409 
1410   // Iterate over the uses of the initial value. If the initial value is used
1411   // in a compare, then we assume this is a range check that ensures the loop
1412   // doesn't underflow. This is not an exact test and should be improved.
1413   for (MachineRegisterInfo::use_instr_nodbg_iterator I = MRI->use_instr_nodbg_begin(Reg),
1414          E = MRI->use_instr_nodbg_end(); I != E; ++I) {
1415     MachineInstr *MI = &*I;
1416     unsigned CmpReg1 = 0, CmpReg2 = 0;
1417     int CmpMask = 0, CmpValue = 0;
1418 
1419     if (!TII->analyzeCompare(MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
1420       continue;
1421 
1422     MachineBasicBlock *TBB = 0, *FBB = 0;
1423     SmallVector<MachineOperand, 2> Cond;
1424     if (TII->AnalyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
1425       continue;
1426 
1427     Comparison::Kind Cmp = getComparisonKind(MI->getOpcode(), 0, 0, 0);
1428     if (Cmp == 0)
1429       continue;
1430     if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
1431       Cmp = Comparison::getNegatedComparison(Cmp);
1432     if (CmpReg2 != 0 && CmpReg2 == Reg)
1433       Cmp = Comparison::getSwappedComparison(Cmp);
1434 
1435     // Signed underflow is undefined.
1436     if (Comparison::isSigned(Cmp))
1437       return false;
1438 
1439     // Check if there is a comparison of the inital value. If the initial value
1440     // is greater than or not equal to another value, then assume this is a
1441     // range check.
1442     if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1443       return false;
1444   }
1445 
1446   // OK - this is a hack that needs to be improved. We really need to analyze
1447   // the instructions performed on the initial value. This works on the simplest
1448   // cases only.
1449   if (!Def->isCopy() && !Def->isPHI())
1450     return false;
1451 
1452   return true;
1453 }
1454 
1455 bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
1456                                              int64_t &Val) const {
1457   if (MO.isImm()) {
1458     Val = MO.getImm();
1459     return true;
1460   }
1461   if (!MO.isReg())
1462     return false;
1463 
1464   // MO is a register. Check whether it is defined as an immediate value,
1465   // and if so, get the value of it in TV. That value will then need to be
1466   // processed to handle potential subregisters in MO.
1467   int64_t TV;
1468 
1469   unsigned R = MO.getReg();
1470   if (!TargetRegisterInfo::isVirtualRegister(R))
1471     return false;
1472   MachineInstr *DI = MRI->getVRegDef(R);
1473   unsigned DOpc = DI->getOpcode();
1474   switch (DOpc) {
1475     case TargetOpcode::COPY:
1476     case Hexagon::A2_tfrsi:
1477     case Hexagon::A2_tfrpi:
1478     case Hexagon::CONST32_Int_Real:
1479     case Hexagon::CONST64_Int_Real: {
1480       // Call recursively to avoid an extra check whether operand(1) is
1481       // indeed an immediate (it could be a global address, for example),
1482       // plus we can handle COPY at the same time.
1483       if (!checkForImmediate(DI->getOperand(1), TV))
1484         return false;
1485       break;
1486     }
1487     case Hexagon::A2_combineii:
1488     case Hexagon::A4_combineir:
1489     case Hexagon::A4_combineii:
1490     case Hexagon::A4_combineri:
1491     case Hexagon::A2_combinew: {
1492       const MachineOperand &S1 = DI->getOperand(1);
1493       const MachineOperand &S2 = DI->getOperand(2);
1494       int64_t V1, V2;
1495       if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
1496         return false;
1497       TV = V2 | (V1 << 32);
1498       break;
1499     }
1500     case TargetOpcode::REG_SEQUENCE: {
1501       const MachineOperand &S1 = DI->getOperand(1);
1502       const MachineOperand &S3 = DI->getOperand(3);
1503       int64_t V1, V3;
1504       if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
1505         return false;
1506       unsigned Sub2 = DI->getOperand(2).getImm();
1507       unsigned Sub4 = DI->getOperand(4).getImm();
1508       if (Sub2 == Hexagon::subreg_loreg && Sub4 == Hexagon::subreg_hireg)
1509         TV = V1 | (V3 << 32);
1510       else if (Sub2 == Hexagon::subreg_hireg && Sub4 == Hexagon::subreg_loreg)
1511         TV = V3 | (V1 << 32);
1512       else
1513         llvm_unreachable("Unexpected form of REG_SEQUENCE");
1514       break;
1515     }
1516 
1517     default:
1518       return false;
1519   }
1520 
1521   // By now, we should have successfuly obtained the immediate value defining
1522   // the register referenced in MO. Handle a potential use of a subregister.
1523   switch (MO.getSubReg()) {
1524     case Hexagon::subreg_loreg:
1525       Val = TV & 0xFFFFFFFFULL;
1526       break;
1527     case Hexagon::subreg_hireg:
1528       Val = (TV >> 32) & 0xFFFFFFFFULL;
1529       break;
1530     default:
1531       Val = TV;
1532       break;
1533   }
1534   return true;
1535 }
1536 
1537 void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1538   if (MO.isImm()) {
1539     MO.setImm(Val);
1540     return;
1541   }
1542 
1543   assert(MO.isReg());
1544   unsigned R = MO.getReg();
1545   MachineInstr *DI = MRI->getVRegDef(R);
1546 
1547   const TargetRegisterClass *RC = MRI->getRegClass(R);
1548   unsigned NewR = MRI->createVirtualRegister(RC);
1549   MachineBasicBlock &B = *DI->getParent();
1550   DebugLoc DL = DI->getDebugLoc();
1551   BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
1552   MO.setReg(NewR);
1553 }
1554 
1555 static bool isImmValidForOpcode(unsigned CmpOpc, int64_t Imm) {
1556   // These two instructions are not extendable.
1557   if (CmpOpc == Hexagon::A4_cmpbeqi)
1558     return isUInt<8>(Imm);
1559   if (CmpOpc == Hexagon::A4_cmpbgti)
1560     return isInt<8>(Imm);
1561   // The rest of the comparison-with-immediate instructions are extendable.
1562   return true;
1563 }
1564 
1565 bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1566   MachineBasicBlock *Header = L->getHeader();
1567   MachineBasicBlock *Latch = L->getLoopLatch();
1568   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1569 
1570   if (!(Header && Latch && ExitingBlock))
1571     return false;
1572 
1573   // These data structures follow the same concept as the corresponding
1574   // ones in findInductionRegister (where some comments are).
1575   typedef std::pair<unsigned,int64_t> RegisterBump;
1576   typedef std::pair<unsigned,RegisterBump> RegisterInduction;
1577   typedef std::set<RegisterInduction> RegisterInductionSet;
1578 
1579   // Register candidates for induction variables, with their associated bumps.
1580   RegisterInductionSet IndRegs;
1581 
1582   // Look for induction patterns:
1583   //   vreg1 = PHI ..., [ latch, vreg2 ]
1584   //   vreg2 = ADD vreg1, imm
1585   typedef MachineBasicBlock::instr_iterator instr_iterator;
1586   for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1587        I != E && I->isPHI(); ++I) {
1588     MachineInstr *Phi = &*I;
1589 
1590     // Have a PHI instruction.
1591     for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1592       if (Phi->getOperand(i+1).getMBB() != Latch)
1593         continue;
1594 
1595       unsigned PhiReg = Phi->getOperand(i).getReg();
1596       MachineInstr *DI = MRI->getVRegDef(PhiReg);
1597       unsigned UpdOpc = DI->getOpcode();
1598       bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
1599 
1600       if (isAdd) {
1601         // If the register operand to the add/sub is the PHI we are looking
1602         // at, this meets the induction pattern.
1603         unsigned IndReg = DI->getOperand(1).getReg();
1604         MachineOperand &Opnd2 = DI->getOperand(2);
1605         int64_t V;
1606         if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
1607           unsigned UpdReg = DI->getOperand(0).getReg();
1608           IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
1609         }
1610       }
1611     }  // for (i)
1612   }  // for (instr)
1613 
1614   if (IndRegs.empty())
1615     return false;
1616 
1617   MachineBasicBlock *TB = nullptr, *FB = nullptr;
1618   SmallVector<MachineOperand,2> Cond;
1619   // AnalyzeBranch returns true if it fails to analyze branch.
1620   bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
1621   if (NotAnalyzed || Cond.empty())
1622     return false;
1623 
1624   if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
1625     MachineBasicBlock *LTB = 0, *LFB = 0;
1626     SmallVector<MachineOperand,2> LCond;
1627     bool NotAnalyzed = TII->AnalyzeBranch(*Latch, LTB, LFB, LCond, false);
1628     if (NotAnalyzed)
1629       return false;
1630 
1631     // Since latch is not the exiting block, the latch branch should be an
1632     // unconditional branch to the loop header.
1633     if (TB == Latch)
1634       TB = (LTB == Header) ? LTB : LFB;
1635     else
1636       FB = (LTB == Header) ? LTB : LFB;
1637   }
1638   if (TB != Header) {
1639     if (FB != Header) {
1640       // The latch/exit block does not go back to the header.
1641       return false;
1642     }
1643     // FB is the header (i.e., uncond. jump to branch header)
1644     // In this case, the LoopBody -> TB should not be a back edge otherwise
1645     // it could result in an infinite loop after conversion to hw_loop.
1646     // This case can happen when the Latch has two jumps like this:
1647     // Jmp_c OuterLoopHeader <-- TB
1648     // Jmp   InnerLoopHeader <-- FB
1649     if (MDT->dominates(TB, FB))
1650       return false;
1651   }
1652 
1653   // Expecting a predicate register as a condition.  It won't be a hardware
1654   // predicate register at this point yet, just a vreg.
1655   // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1656   // into Cond, followed by the predicate register.  For non-negated branches
1657   // it's just the register.
1658   unsigned CSz = Cond.size();
1659   if (CSz != 1 && CSz != 2)
1660     return false;
1661 
1662   if (!Cond[CSz-1].isReg())
1663     return false;
1664 
1665   unsigned P = Cond[CSz-1].getReg();
1666   MachineInstr *PredDef = MRI->getVRegDef(P);
1667 
1668   if (!PredDef->isCompare())
1669     return false;
1670 
1671   SmallSet<unsigned,2> CmpRegs;
1672   MachineOperand *CmpImmOp = nullptr;
1673 
1674   // Go over all operands to the compare and look for immediate and register
1675   // operands.  Assume that if the compare has a single register use and a
1676   // single immediate operand, then the register is being compared with the
1677   // immediate value.
1678   for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1679     MachineOperand &MO = PredDef->getOperand(i);
1680     if (MO.isReg()) {
1681       // Skip all implicit references.  In one case there was:
1682       //   %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1683       if (MO.isImplicit())
1684         continue;
1685       if (MO.isUse()) {
1686         if (!isImmediate(MO)) {
1687           CmpRegs.insert(MO.getReg());
1688           continue;
1689         }
1690         // Consider the register to be the "immediate" operand.
1691         if (CmpImmOp)
1692           return false;
1693         CmpImmOp = &MO;
1694       }
1695     } else if (MO.isImm()) {
1696       if (CmpImmOp)    // A second immediate argument?  Confusing.  Bail out.
1697         return false;
1698       CmpImmOp = &MO;
1699     }
1700   }
1701 
1702   if (CmpRegs.empty())
1703     return false;
1704 
1705   // Check if the compared register follows the order we want.  Fix if needed.
1706   for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1707        I != E; ++I) {
1708     // This is a success.  If the register used in the comparison is one that
1709     // we have identified as a bumped (updated) induction register, there is
1710     // nothing to do.
1711     if (CmpRegs.count(I->first))
1712       return true;
1713 
1714     // Otherwise, if the register being compared comes out of a PHI node,
1715     // and has been recognized as following the induction pattern, and is
1716     // compared against an immediate, we can fix it.
1717     const RegisterBump &RB = I->second;
1718     if (CmpRegs.count(RB.first)) {
1719       if (!CmpImmOp)
1720         return false;
1721 
1722       // If the register is being compared against an immediate, try changing
1723       // the compare instruction to use induction register and adjust the
1724       // immediate operand.
1725       int64_t CmpImm = getImmediate(*CmpImmOp);
1726       int64_t V = RB.second;
1727       // Handle Overflow (64-bit).
1728       if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
1729           ((V < 0) && (CmpImm < INT64_MIN - V)))
1730         return false;
1731       CmpImm += V;
1732       // Most comparisons of register against an immediate value allow
1733       // the immediate to be constant-extended. There are some exceptions
1734       // though. Make sure the new combination will work.
1735       if (CmpImmOp->isImm())
1736         if (!isImmValidForOpcode(PredDef->getOpcode(), CmpImm))
1737           return false;
1738 
1739       // It is not valid to do this transformation on an unsigned comparison
1740       // because it may underflow.
1741       Comparison::Kind Cmp = getComparisonKind(PredDef->getOpcode(), 0, 0, 0);
1742       if (!Cmp || Comparison::isUnsigned(Cmp))
1743         return false;
1744 
1745       // Make sure that the compare happens after the bump.  Otherwise,
1746       // after the fixup, the compare would use a yet-undefined register.
1747       MachineInstr *BumpI = MRI->getVRegDef(I->first);
1748       bool Order = orderBumpCompare(BumpI, PredDef);
1749       if (!Order)
1750         return false;
1751 
1752       // Finally, fix the compare instruction.
1753       setImmediate(*CmpImmOp, CmpImm);
1754       for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1755         MachineOperand &MO = PredDef->getOperand(i);
1756         if (MO.isReg() && MO.getReg() == RB.first) {
1757           MO.setReg(I->first);
1758           return true;
1759         }
1760       }
1761     }
1762   }
1763 
1764   return false;
1765 }
1766 
1767 /// \brief Create a preheader for a given loop.
1768 MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1769       MachineLoop *L) {
1770   if (MachineBasicBlock *TmpPH = L->getLoopPreheader())
1771     return TmpPH;
1772 
1773   if (!HWCreatePreheader)
1774     return nullptr;
1775 
1776   MachineBasicBlock *Header = L->getHeader();
1777   MachineBasicBlock *Latch = L->getLoopLatch();
1778   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1779   MachineFunction *MF = Header->getParent();
1780   DebugLoc DL;
1781 
1782 #ifndef NDEBUG
1783   if ((PHFn != "") && (PHFn != MF->getName()))
1784     return nullptr;
1785 #endif
1786 
1787   if (!Latch || !ExitingBlock || Header->hasAddressTaken())
1788     return nullptr;
1789 
1790   typedef MachineBasicBlock::instr_iterator instr_iterator;
1791 
1792   // Verify that all existing predecessors have analyzable branches
1793   // (or no branches at all).
1794   typedef std::vector<MachineBasicBlock*> MBBVector;
1795   MBBVector Preds(Header->pred_begin(), Header->pred_end());
1796   SmallVector<MachineOperand,2> Tmp1;
1797   MachineBasicBlock *TB = nullptr, *FB = nullptr;
1798 
1799   if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
1800     return nullptr;
1801 
1802   for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1803     MachineBasicBlock *PB = *I;
1804     bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp1, false);
1805     if (NotAnalyzed)
1806       return nullptr;
1807   }
1808 
1809   MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
1810   MF->insert(Header, NewPH);
1811 
1812   if (Header->pred_size() > 2) {
1813     // Ensure that the header has only two predecessors: the preheader and
1814     // the loop latch.  Any additional predecessors of the header should
1815     // join at the newly created preheader. Inspect all PHI nodes from the
1816     // header and create appropriate corresponding PHI nodes in the preheader.
1817 
1818     for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1819          I != E && I->isPHI(); ++I) {
1820       MachineInstr *PN = &*I;
1821 
1822       const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1823       MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1824       NewPH->insert(NewPH->end(), NewPN);
1825 
1826       unsigned PR = PN->getOperand(0).getReg();
1827       const TargetRegisterClass *RC = MRI->getRegClass(PR);
1828       unsigned NewPR = MRI->createVirtualRegister(RC);
1829       NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1830 
1831       // Copy all non-latch operands of a header's PHI node to the newly
1832       // created PHI node in the preheader.
1833       for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1834         unsigned PredR = PN->getOperand(i).getReg();
1835         MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1836         if (PredB == Latch)
1837           continue;
1838 
1839         NewPN->addOperand(MachineOperand::CreateReg(PredR, false));
1840         NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1841       }
1842 
1843       // Remove copied operands from the old PHI node and add the value
1844       // coming from the preheader's PHI.
1845       for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1846         MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1847         if (PredB != Latch) {
1848           PN->RemoveOperand(i+1);
1849           PN->RemoveOperand(i);
1850         }
1851       }
1852       PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1853       PN->addOperand(MachineOperand::CreateMBB(NewPH));
1854     }
1855 
1856   } else {
1857     assert(Header->pred_size() == 2);
1858 
1859     // The header has only two predecessors, but the non-latch predecessor
1860     // is not a preheader (e.g. it has other successors, etc.)
1861     // In such a case we don't need any extra PHI nodes in the new preheader,
1862     // all we need is to adjust existing PHIs in the header to now refer to
1863     // the new preheader.
1864     for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1865          I != E && I->isPHI(); ++I) {
1866       MachineInstr *PN = &*I;
1867       for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1868         MachineOperand &MO = PN->getOperand(i+1);
1869         if (MO.getMBB() != Latch)
1870           MO.setMBB(NewPH);
1871       }
1872     }
1873   }
1874 
1875   // "Reroute" the CFG edges to link in the new preheader.
1876   // If any of the predecessors falls through to the header, insert a branch
1877   // to the new preheader in that place.
1878   SmallVector<MachineOperand,1> Tmp2;
1879   SmallVector<MachineOperand,1> EmptyCond;
1880 
1881   TB = FB = nullptr;
1882 
1883   for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1884     MachineBasicBlock *PB = *I;
1885     if (PB != Latch) {
1886       Tmp2.clear();
1887       bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp2, false);
1888       (void)NotAnalyzed; // suppress compiler warning
1889       assert (!NotAnalyzed && "Should be analyzable!");
1890       if (TB != Header && (Tmp2.empty() || FB != Header))
1891         TII->InsertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
1892       PB->ReplaceUsesOfBlockWith(Header, NewPH);
1893     }
1894   }
1895 
1896   // It can happen that the latch block will fall through into the header.
1897   // Insert an unconditional branch to the header.
1898   TB = FB = nullptr;
1899   bool LatchNotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Tmp2, false);
1900   (void)LatchNotAnalyzed; // suppress compiler warning
1901   assert (!LatchNotAnalyzed && "Should be analyzable!");
1902   if (!TB && !FB)
1903     TII->InsertBranch(*Latch, Header, nullptr, EmptyCond, DL);
1904 
1905   // Finally, the branch from the preheader to the header.
1906   TII->InsertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
1907   NewPH->addSuccessor(Header);
1908 
1909   MachineLoop *ParentLoop = L->getParentLoop();
1910   if (ParentLoop)
1911     ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
1912 
1913   // Update the dominator information with the new preheader.
1914   if (MDT) {
1915     MachineDomTreeNode *HDom = MDT->getNode(Header);
1916     MDT->addNewBlock(NewPH, HDom->getIDom()->getBlock());
1917     MDT->changeImmediateDominator(Header, NewPH);
1918   }
1919 
1920   return NewPH;
1921 }
1922