[Hexagon] Adding decoders for signed operands and ensuring all signed operand types...
[oota-llvm.git] / lib / Target / Hexagon / HexagonHardwareLoops.cpp
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     OldInsts.push_back(MRI->getVRegDef(R));
674   }
675
676   return computeCount(L, InitialValue, EndValue, IVReg, IVBump, Cmp);
677 }
678
679 /// \brief Helper function that returns the expression that represents the
680 /// number of times a loop iterates.  The function takes the operands that
681 /// represent the loop start value, loop end value, and induction value.
682 /// Based upon these operands, the function attempts to compute the trip count.
683 CountValue *HexagonHardwareLoops::computeCount(MachineLoop *Loop,
684                                                const MachineOperand *Start,
685                                                const MachineOperand *End,
686                                                unsigned IVReg,
687                                                int64_t IVBump,
688                                                Comparison::Kind Cmp) const {
689   // Cannot handle comparison EQ, i.e. while (A == B).
690   if (Cmp == Comparison::EQ)
691     return nullptr;
692
693   // Check if either the start or end values are an assignment of an immediate.
694   // If so, use the immediate value rather than the register.
695   if (Start->isReg()) {
696     const MachineInstr *StartValInstr = MRI->getVRegDef(Start->getReg());
697     if (StartValInstr && (StartValInstr->getOpcode() == Hexagon::A2_tfrsi ||
698                           StartValInstr->getOpcode() == Hexagon::A2_tfrpi))
699       Start = &StartValInstr->getOperand(1);
700   }
701   if (End->isReg()) {
702     const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
703     if (EndValInstr && (EndValInstr->getOpcode() == Hexagon::A2_tfrsi ||
704                         EndValInstr->getOpcode() == Hexagon::A2_tfrpi))
705       End = &EndValInstr->getOperand(1);
706   }
707
708   if (!Start->isReg() && !Start->isImm())
709     return nullptr;
710   if (!End->isReg() && !End->isImm())
711     return nullptr;
712
713   bool CmpLess =     Cmp & Comparison::L;
714   bool CmpGreater =  Cmp & Comparison::G;
715   bool CmpHasEqual = Cmp & Comparison::EQ;
716
717   // Avoid certain wrap-arounds.  This doesn't detect all wrap-arounds.
718   if (CmpLess && IVBump < 0)
719     // Loop going while iv is "less" with the iv value going down.  Must wrap.
720     return nullptr;
721
722   if (CmpGreater && IVBump > 0)
723     // Loop going while iv is "greater" with the iv value going up.  Must wrap.
724     return nullptr;
725
726   // Phis that may feed into the loop.
727   LoopFeederMap LoopFeederPhi;
728
729   // Check if the inital value may be zero and can be decremented in the first
730   // iteration. If the value is zero, the endloop instruction will not decrement
731   // the loop counter, so we shoudn't generate a hardware loop in this case.
732   if (loopCountMayWrapOrUnderFlow(Start, End, Loop->getLoopPreheader(), Loop,
733                                   LoopFeederPhi))
734       return nullptr;
735
736   if (Start->isImm() && End->isImm()) {
737     // Both, start and end are immediates.
738     int64_t StartV = Start->getImm();
739     int64_t EndV = End->getImm();
740     int64_t Dist = EndV - StartV;
741     if (Dist == 0)
742       return nullptr;
743
744     bool Exact = (Dist % IVBump) == 0;
745
746     if (Cmp == Comparison::NE) {
747       if (!Exact)
748         return nullptr;
749       if ((Dist < 0) ^ (IVBump < 0))
750         return nullptr;
751     }
752
753     // For comparisons that include the final value (i.e. include equality
754     // with the final value), we need to increase the distance by 1.
755     if (CmpHasEqual)
756       Dist = Dist > 0 ? Dist+1 : Dist-1;
757
758     // For the loop to iterate, CmpLess should imply Dist > 0.  Similarly,
759     // CmpGreater should imply Dist < 0.  These conditions could actually
760     // fail, for example, in unreachable code (which may still appear to be
761     // reachable in the CFG).
762     if ((CmpLess && Dist < 0) || (CmpGreater && Dist > 0))
763       return nullptr;
764
765     // "Normalized" distance, i.e. with the bump set to +-1.
766     int64_t Dist1 = (IVBump > 0) ? (Dist +  (IVBump - 1)) / IVBump
767                                  : (-Dist + (-IVBump - 1)) / (-IVBump);
768     assert (Dist1 > 0 && "Fishy thing.  Both operands have the same sign.");
769
770     uint64_t Count = Dist1;
771
772     if (Count > 0xFFFFFFFFULL)
773       return nullptr;
774
775     return new CountValue(CountValue::CV_Immediate, Count);
776   }
777
778   // A general case: Start and End are some values, but the actual
779   // iteration count may not be available.  If it is not, insert
780   // a computation of it into the preheader.
781
782   // If the induction variable bump is not a power of 2, quit.
783   // Othwerise we'd need a general integer division.
784   if (!isPowerOf2_64(std::abs(IVBump)))
785     return nullptr;
786
787   MachineBasicBlock *PH = Loop->getLoopPreheader();
788   assert (PH && "Should have a preheader by now");
789   MachineBasicBlock::iterator InsertPos = PH->getFirstTerminator();
790   DebugLoc DL;
791   if (InsertPos != PH->end())
792     DL = InsertPos->getDebugLoc();
793
794   // If Start is an immediate and End is a register, the trip count
795   // will be "reg - imm".  Hexagon's "subtract immediate" instruction
796   // is actually "reg + -imm".
797
798   // If the loop IV is going downwards, i.e. if the bump is negative,
799   // then the iteration count (computed as End-Start) will need to be
800   // negated.  To avoid the negation, just swap Start and End.
801   if (IVBump < 0) {
802     std::swap(Start, End);
803     IVBump = -IVBump;
804   }
805   // Cmp may now have a wrong direction, e.g.  LEs may now be GEs.
806   // Signedness, and "including equality" are preserved.
807
808   bool RegToImm = Start->isReg() && End->isImm(); // for (reg..imm)
809   bool RegToReg = Start->isReg() && End->isReg(); // for (reg..reg)
810
811   int64_t StartV = 0, EndV = 0;
812   if (Start->isImm())
813     StartV = Start->getImm();
814   if (End->isImm())
815     EndV = End->getImm();
816
817   int64_t AdjV = 0;
818   // To compute the iteration count, we would need this computation:
819   //   Count = (End - Start + (IVBump-1)) / IVBump
820   // or, when CmpHasEqual:
821   //   Count = (End - Start + (IVBump-1)+1) / IVBump
822   // The "IVBump-1" part is the adjustment (AdjV).  We can avoid
823   // generating an instruction specifically to add it if we can adjust
824   // the immediate values for Start or End.
825
826   if (CmpHasEqual) {
827     // Need to add 1 to the total iteration count.
828     if (Start->isImm())
829       StartV--;
830     else if (End->isImm())
831       EndV++;
832     else
833       AdjV += 1;
834   }
835
836   if (Cmp != Comparison::NE) {
837     if (Start->isImm())
838       StartV -= (IVBump-1);
839     else if (End->isImm())
840       EndV += (IVBump-1);
841     else
842       AdjV += (IVBump-1);
843   }
844
845   unsigned R = 0, SR = 0;
846   if (Start->isReg()) {
847     R = Start->getReg();
848     SR = Start->getSubReg();
849   } else {
850     R = End->getReg();
851     SR = End->getSubReg();
852   }
853   const TargetRegisterClass *RC = MRI->getRegClass(R);
854   // Hardware loops cannot handle 64-bit registers.  If it's a double
855   // register, it has to have a subregister.
856   if (!SR && RC == &Hexagon::DoubleRegsRegClass)
857     return nullptr;
858   const TargetRegisterClass *IntRC = &Hexagon::IntRegsRegClass;
859
860   // Compute DistR (register with the distance between Start and End).
861   unsigned DistR, DistSR;
862
863   // Avoid special case, where the start value is an imm(0).
864   if (Start->isImm() && StartV == 0) {
865     DistR = End->getReg();
866     DistSR = End->getSubReg();
867   } else {
868     const MCInstrDesc &SubD = RegToReg ? TII->get(Hexagon::A2_sub) :
869                               (RegToImm ? TII->get(Hexagon::A2_subri) :
870                                           TII->get(Hexagon::A2_addi));
871     if (RegToReg || RegToImm) {
872       unsigned SubR = MRI->createVirtualRegister(IntRC);
873       MachineInstrBuilder SubIB =
874         BuildMI(*PH, InsertPos, DL, SubD, SubR);
875
876       if (RegToReg)
877         SubIB.addReg(End->getReg(), 0, End->getSubReg())
878           .addReg(Start->getReg(), 0, Start->getSubReg());
879       else
880         SubIB.addImm(EndV)
881           .addReg(Start->getReg(), 0, Start->getSubReg());
882       DistR = SubR;
883     } else {
884       // If the loop has been unrolled, we should use the original loop count
885       // instead of recalculating the value. This will avoid additional
886       // 'Add' instruction.
887       const MachineInstr *EndValInstr = MRI->getVRegDef(End->getReg());
888       if (EndValInstr->getOpcode() == Hexagon::A2_addi &&
889           EndValInstr->getOperand(2).getImm() == StartV) {
890         DistR = EndValInstr->getOperand(1).getReg();
891       } else {
892         unsigned SubR = MRI->createVirtualRegister(IntRC);
893         MachineInstrBuilder SubIB =
894           BuildMI(*PH, InsertPos, DL, SubD, SubR);
895         SubIB.addReg(End->getReg(), 0, End->getSubReg())
896              .addImm(-StartV);
897         DistR = SubR;
898       }
899     }
900     DistSR = 0;
901   }
902
903   // From DistR, compute AdjR (register with the adjusted distance).
904   unsigned AdjR, AdjSR;
905
906   if (AdjV == 0) {
907     AdjR = DistR;
908     AdjSR = DistSR;
909   } else {
910     // Generate CountR = ADD DistR, AdjVal
911     unsigned AddR = MRI->createVirtualRegister(IntRC);
912     MCInstrDesc const &AddD = TII->get(Hexagon::A2_addi);
913     BuildMI(*PH, InsertPos, DL, AddD, AddR)
914       .addReg(DistR, 0, DistSR)
915       .addImm(AdjV);
916
917     AdjR = AddR;
918     AdjSR = 0;
919   }
920
921   // From AdjR, compute CountR (register with the final count).
922   unsigned CountR, CountSR;
923
924   if (IVBump == 1) {
925     CountR = AdjR;
926     CountSR = AdjSR;
927   } else {
928     // The IV bump is a power of two. Log_2(IV bump) is the shift amount.
929     unsigned Shift = Log2_32(IVBump);
930
931     // Generate NormR = LSR DistR, Shift.
932     unsigned LsrR = MRI->createVirtualRegister(IntRC);
933     const MCInstrDesc &LsrD = TII->get(Hexagon::S2_lsr_i_r);
934     BuildMI(*PH, InsertPos, DL, LsrD, LsrR)
935       .addReg(AdjR, 0, AdjSR)
936       .addImm(Shift);
937
938     CountR = LsrR;
939     CountSR = 0;
940   }
941
942   return new CountValue(CountValue::CV_Register, CountR, CountSR);
943 }
944
945 /// \brief Return true if the operation is invalid within hardware loop.
946 bool HexagonHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI,
947                                                   bool IsInnerHWLoop) const {
948
949   // Call is not allowed because the callee may use a hardware loop except for
950   // the case when the call never returns.
951   if (MI->getDesc().isCall() && MI->getOpcode() != Hexagon::CALLv3nr)
952     return true;
953
954   // Check if the instruction defines a hardware loop register.
955   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
956     const MachineOperand &MO = MI->getOperand(i);
957     if (!MO.isReg() || !MO.isDef())
958       continue;
959     unsigned R = MO.getReg();
960     if (IsInnerHWLoop && (R == Hexagon::LC0 || R == Hexagon::SA0 ||
961                           R == Hexagon::LC1 || R == Hexagon::SA1))
962       return true;
963     if (!IsInnerHWLoop && (R == Hexagon::LC1 || R == Hexagon::SA1))
964       return true;
965   }
966   return false;
967 }
968
969 /// \brief Return true if the loop contains an instruction that inhibits
970 /// the use of the hardware loop instruction.
971 bool HexagonHardwareLoops::containsInvalidInstruction(MachineLoop *L,
972     bool IsInnerHWLoop) const {
973   const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
974   DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
975   for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
976     MachineBasicBlock *MBB = Blocks[i];
977     for (MachineBasicBlock::iterator
978            MII = MBB->begin(), E = MBB->end(); MII != E; ++MII) {
979       const MachineInstr *MI = &*MII;
980       if (isInvalidLoopOperation(MI, IsInnerHWLoop)) {
981         DEBUG(dbgs()<< "\nCannot convert to hw_loop due to:"; MI->dump(););
982         return true;
983       }
984     }
985   }
986   return false;
987 }
988
989 /// \brief Returns true if the instruction is dead.  This was essentially
990 /// copied from DeadMachineInstructionElim::isDead, but with special cases
991 /// for inline asm, physical registers and instructions with side effects
992 /// removed.
993 bool HexagonHardwareLoops::isDead(const MachineInstr *MI,
994                               SmallVectorImpl<MachineInstr *> &DeadPhis) const {
995   // Examine each operand.
996   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
997     const MachineOperand &MO = MI->getOperand(i);
998     if (!MO.isReg() || !MO.isDef())
999       continue;
1000
1001     unsigned Reg = MO.getReg();
1002     if (MRI->use_nodbg_empty(Reg))
1003       continue;
1004
1005     typedef MachineRegisterInfo::use_nodbg_iterator use_nodbg_iterator;
1006
1007     // This instruction has users, but if the only user is the phi node for the
1008     // parent block, and the only use of that phi node is this instruction, then
1009     // this instruction is dead: both it (and the phi node) can be removed.
1010     use_nodbg_iterator I = MRI->use_nodbg_begin(Reg);
1011     use_nodbg_iterator End = MRI->use_nodbg_end();
1012     if (std::next(I) != End || !I->getParent()->isPHI())
1013       return false;
1014
1015     MachineInstr *OnePhi = I->getParent();
1016     for (unsigned j = 0, f = OnePhi->getNumOperands(); j != f; ++j) {
1017       const MachineOperand &OPO = OnePhi->getOperand(j);
1018       if (!OPO.isReg() || !OPO.isDef())
1019         continue;
1020
1021       unsigned OPReg = OPO.getReg();
1022       use_nodbg_iterator nextJ;
1023       for (use_nodbg_iterator J = MRI->use_nodbg_begin(OPReg);
1024            J != End; J = nextJ) {
1025         nextJ = std::next(J);
1026         MachineOperand &Use = *J;
1027         MachineInstr *UseMI = Use.getParent();
1028
1029         // If the phi node has a user that is not MI, bail.
1030         if (MI != UseMI)
1031           return false;
1032       }
1033     }
1034     DeadPhis.push_back(OnePhi);
1035   }
1036
1037   // If there are no defs with uses, the instruction is dead.
1038   return true;
1039 }
1040
1041 void HexagonHardwareLoops::removeIfDead(MachineInstr *MI) {
1042   // This procedure was essentially copied from DeadMachineInstructionElim.
1043
1044   SmallVector<MachineInstr*, 1> DeadPhis;
1045   if (isDead(MI, DeadPhis)) {
1046     DEBUG(dbgs() << "HW looping will remove: " << *MI);
1047
1048     // It is possible that some DBG_VALUE instructions refer to this
1049     // instruction.  Examine each def operand for such references;
1050     // if found, mark the DBG_VALUE as undef (but don't delete it).
1051     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1052       const MachineOperand &MO = MI->getOperand(i);
1053       if (!MO.isReg() || !MO.isDef())
1054         continue;
1055       unsigned Reg = MO.getReg();
1056       MachineRegisterInfo::use_iterator nextI;
1057       for (MachineRegisterInfo::use_iterator I = MRI->use_begin(Reg),
1058            E = MRI->use_end(); I != E; I = nextI) {
1059         nextI = std::next(I);  // I is invalidated by the setReg
1060         MachineOperand &Use = *I;
1061         MachineInstr *UseMI = I->getParent();
1062         if (UseMI == MI)
1063           continue;
1064         if (Use.isDebug())
1065           UseMI->getOperand(0).setReg(0U);
1066       }
1067     }
1068
1069     MI->eraseFromParent();
1070     for (unsigned i = 0; i < DeadPhis.size(); ++i)
1071       DeadPhis[i]->eraseFromParent();
1072   }
1073 }
1074
1075 /// \brief Check if the loop is a candidate for converting to a hardware
1076 /// loop.  If so, then perform the transformation.
1077 ///
1078 /// This function works on innermost loops first.  A loop can be converted
1079 /// if it is a counting loop; either a register value or an immediate.
1080 ///
1081 /// The code makes several assumptions about the representation of the loop
1082 /// in llvm.
1083 bool HexagonHardwareLoops::convertToHardwareLoop(MachineLoop *L,
1084                                                  bool &RecL0used,
1085                                                  bool &RecL1used) {
1086   // This is just for sanity.
1087   assert(L->getHeader() && "Loop without a header?");
1088
1089   bool Changed = false;
1090   bool L0Used = false;
1091   bool L1Used = false;
1092
1093   // Process nested loops first.
1094   for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
1095     Changed |= convertToHardwareLoop(*I, RecL0used, RecL1used);
1096     L0Used |= RecL0used;
1097     L1Used |= RecL1used;
1098   }
1099
1100   // If a nested loop has been converted, then we can't convert this loop.
1101   if (Changed && L0Used && L1Used)
1102     return Changed;
1103
1104   unsigned LOOP_i;
1105   unsigned LOOP_r;
1106   unsigned ENDLOOP;
1107
1108   // Flag used to track loopN instruction:
1109   // 1 - Hardware loop is being generated for the inner most loop.
1110   // 0 - Hardware loop is being generated for the outer loop.
1111   unsigned IsInnerHWLoop = 1;
1112
1113   if (L0Used) {
1114     LOOP_i = Hexagon::J2_loop1i;
1115     LOOP_r = Hexagon::J2_loop1r;
1116     ENDLOOP = Hexagon::ENDLOOP1;
1117     IsInnerHWLoop = 0;
1118   } else {
1119     LOOP_i = Hexagon::J2_loop0i;
1120     LOOP_r = Hexagon::J2_loop0r;
1121     ENDLOOP = Hexagon::ENDLOOP0;
1122   }
1123
1124 #ifndef NDEBUG
1125   // Stop trying after reaching the limit (if any).
1126   int Limit = HWLoopLimit;
1127   if (Limit >= 0) {
1128     if (Counter >= HWLoopLimit)
1129       return false;
1130     Counter++;
1131   }
1132 #endif
1133
1134   // Does the loop contain any invalid instructions?
1135   if (containsInvalidInstruction(L, IsInnerHWLoop))
1136     return false;
1137
1138   MachineBasicBlock *LastMBB = getExitingBlock(L);
1139   // Don't generate hw loop if the loop has more than one exit.
1140   if (!LastMBB)
1141     return false;
1142
1143   MachineBasicBlock::iterator LastI = LastMBB->getFirstTerminator();
1144   if (LastI == LastMBB->end())
1145     return false;
1146
1147   // Is the induction variable bump feeding the latch condition?
1148   if (!fixupInductionVariable(L))
1149     return false;
1150
1151   // Ensure the loop has a preheader: the loop instruction will be
1152   // placed there.
1153   MachineBasicBlock *Preheader = L->getLoopPreheader();
1154   if (!Preheader) {
1155     Preheader = createPreheaderForLoop(L);
1156     if (!Preheader)
1157       return false;
1158   }
1159
1160   MachineBasicBlock::iterator InsertPos = Preheader->getFirstTerminator();
1161
1162   SmallVector<MachineInstr*, 2> OldInsts;
1163   // Are we able to determine the trip count for the loop?
1164   CountValue *TripCount = getLoopTripCount(L, OldInsts);
1165   if (!TripCount)
1166     return false;
1167
1168   // Is the trip count available in the preheader?
1169   if (TripCount->isReg()) {
1170     // There will be a use of the register inserted into the preheader,
1171     // so make sure that the register is actually defined at that point.
1172     MachineInstr *TCDef = MRI->getVRegDef(TripCount->getReg());
1173     MachineBasicBlock *BBDef = TCDef->getParent();
1174     if (!MDT->dominates(BBDef, Preheader))
1175       return false;
1176   }
1177
1178   // Determine the loop start.
1179   MachineBasicBlock *TopBlock = L->getTopBlock();
1180   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1181   MachineBasicBlock *LoopStart = 0;
1182   if (ExitingBlock !=  L->getLoopLatch()) {
1183     MachineBasicBlock *TB = 0, *FB = 0;
1184     SmallVector<MachineOperand, 2> Cond;
1185
1186     if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false))
1187       return false;
1188
1189     if (L->contains(TB))
1190       LoopStart = TB;
1191     else if (L->contains(FB))
1192       LoopStart = FB;
1193     else
1194       return false;
1195   }
1196   else
1197     LoopStart = TopBlock;
1198
1199   // Convert the loop to a hardware loop.
1200   DEBUG(dbgs() << "Change to hardware loop at "; L->dump());
1201   DebugLoc DL;
1202   if (InsertPos != Preheader->end())
1203     DL = InsertPos->getDebugLoc();
1204
1205   if (TripCount->isReg()) {
1206     // Create a copy of the loop count register.
1207     unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1208     BuildMI(*Preheader, InsertPos, DL, TII->get(TargetOpcode::COPY), CountReg)
1209       .addReg(TripCount->getReg(), 0, TripCount->getSubReg());
1210     // Add the Loop instruction to the beginning of the loop.
1211     BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r)).addMBB(LoopStart)
1212       .addReg(CountReg);
1213   } else {
1214     assert(TripCount->isImm() && "Expecting immediate value for trip count");
1215     // Add the Loop immediate instruction to the beginning of the loop,
1216     // if the immediate fits in the instructions.  Otherwise, we need to
1217     // create a new virtual register.
1218     int64_t CountImm = TripCount->getImm();
1219     if (!TII->isValidOffset(LOOP_i, CountImm)) {
1220       unsigned CountReg = MRI->createVirtualRegister(&Hexagon::IntRegsRegClass);
1221       BuildMI(*Preheader, InsertPos, DL, TII->get(Hexagon::A2_tfrsi), CountReg)
1222         .addImm(CountImm);
1223       BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_r))
1224         .addMBB(LoopStart).addReg(CountReg);
1225     } else
1226       BuildMI(*Preheader, InsertPos, DL, TII->get(LOOP_i))
1227         .addMBB(LoopStart).addImm(CountImm);
1228   }
1229
1230   // Make sure the loop start always has a reference in the CFG.  We need
1231   // to create a BlockAddress operand to get this mechanism to work both the
1232   // MachineBasicBlock and BasicBlock objects need the flag set.
1233   LoopStart->setHasAddressTaken();
1234   // This line is needed to set the hasAddressTaken flag on the BasicBlock
1235   // object.
1236   BlockAddress::get(const_cast<BasicBlock *>(LoopStart->getBasicBlock()));
1237
1238   // Replace the loop branch with an endloop instruction.
1239   DebugLoc LastIDL = LastI->getDebugLoc();
1240   BuildMI(*LastMBB, LastI, LastIDL, TII->get(ENDLOOP)).addMBB(LoopStart);
1241
1242   // The loop ends with either:
1243   //  - a conditional branch followed by an unconditional branch, or
1244   //  - a conditional branch to the loop start.
1245   if (LastI->getOpcode() == Hexagon::J2_jumpt ||
1246       LastI->getOpcode() == Hexagon::J2_jumpf) {
1247     // Delete one and change/add an uncond. branch to out of the loop.
1248     MachineBasicBlock *BranchTarget = LastI->getOperand(1).getMBB();
1249     LastI = LastMBB->erase(LastI);
1250     if (!L->contains(BranchTarget)) {
1251       if (LastI != LastMBB->end())
1252         LastI = LastMBB->erase(LastI);
1253       SmallVector<MachineOperand, 0> Cond;
1254       TII->InsertBranch(*LastMBB, BranchTarget, nullptr, Cond, LastIDL);
1255     }
1256   } else {
1257     // Conditional branch to loop start; just delete it.
1258     LastMBB->erase(LastI);
1259   }
1260   delete TripCount;
1261
1262   // The induction operation and the comparison may now be
1263   // unneeded. If these are unneeded, then remove them.
1264   for (unsigned i = 0; i < OldInsts.size(); ++i)
1265     removeIfDead(OldInsts[i]);
1266
1267   ++NumHWLoops;
1268
1269   // Set RecL1used and RecL0used only after hardware loop has been
1270   // successfully generated. Doing it earlier can cause wrong loop instruction
1271   // to be used.
1272   if (L0Used) // Loop0 was already used. So, the correct loop must be loop1.
1273     RecL1used = true;
1274   else
1275     RecL0used = true;
1276
1277   return true;
1278 }
1279
1280 bool HexagonHardwareLoops::orderBumpCompare(MachineInstr *BumpI,
1281                                             MachineInstr *CmpI) {
1282   assert (BumpI != CmpI && "Bump and compare in the same instruction?");
1283
1284   MachineBasicBlock *BB = BumpI->getParent();
1285   if (CmpI->getParent() != BB)
1286     return false;
1287
1288   typedef MachineBasicBlock::instr_iterator instr_iterator;
1289   // Check if things are in order to begin with.
1290   for (instr_iterator I = BumpI, E = BB->instr_end(); I != E; ++I)
1291     if (&*I == CmpI)
1292       return true;
1293
1294   // Out of order.
1295   unsigned PredR = CmpI->getOperand(0).getReg();
1296   bool FoundBump = false;
1297   instr_iterator CmpIt = CmpI, NextIt = std::next(CmpIt);
1298   for (instr_iterator I = NextIt, E = BB->instr_end(); I != E; ++I) {
1299     MachineInstr *In = &*I;
1300     for (unsigned i = 0, n = In->getNumOperands(); i < n; ++i) {
1301       MachineOperand &MO = In->getOperand(i);
1302       if (MO.isReg() && MO.isUse()) {
1303         if (MO.getReg() == PredR)  // Found an intervening use of PredR.
1304           return false;
1305       }
1306     }
1307
1308     if (In == BumpI) {
1309       instr_iterator After = BumpI;
1310       instr_iterator From = CmpI;
1311       BB->splice(std::next(After), BB, From);
1312       FoundBump = true;
1313       break;
1314     }
1315   }
1316   assert (FoundBump && "Cannot determine instruction order");
1317   return FoundBump;
1318 }
1319
1320 /// This function is required to break recursion. Visiting phis in a loop may
1321 /// result in recursion during compilation. We break the recursion by making
1322 /// sure that we visit a MachineOperand and its definition in a
1323 /// MachineInstruction only once. If we attempt to visit more than once, then
1324 /// there is recursion, and will return false.
1325 bool HexagonHardwareLoops::isLoopFeeder(MachineLoop *L, MachineBasicBlock *A,
1326                                         MachineInstr *MI,
1327                                         const MachineOperand *MO,
1328                                         LoopFeederMap &LoopFeederPhi) const {
1329   if (LoopFeederPhi.find(MO->getReg()) == LoopFeederPhi.end()) {
1330     const std::vector<MachineBasicBlock *> &Blocks = L->getBlocks();
1331     DEBUG(dbgs() << "\nhw_loop head, BB#" << Blocks[0]->getNumber(););
1332     // Ignore all BBs that form Loop.
1333     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1334       MachineBasicBlock *MBB = Blocks[i];
1335       if (A == MBB)
1336         return false;
1337     }
1338     MachineInstr *Def = MRI->getVRegDef(MO->getReg());
1339     LoopFeederPhi.insert(std::make_pair(MO->getReg(), Def));
1340     return true;
1341   } else
1342     // Already visited node.
1343     return false;
1344 }
1345
1346 /// Return true if a Phi may generate a value that can underflow.
1347 /// This function calls loopCountMayWrapOrUnderFlow for each Phi operand.
1348 bool HexagonHardwareLoops::phiMayWrapOrUnderflow(
1349     MachineInstr *Phi, const MachineOperand *EndVal, MachineBasicBlock *MBB,
1350     MachineLoop *L, LoopFeederMap &LoopFeederPhi) const {
1351   assert(Phi->isPHI() && "Expecting a Phi.");
1352   // Walk through each Phi, and its used operands. Make sure that
1353   // if there is recursion in Phi, we won't generate hardware loops.
1354   for (int i = 1, n = Phi->getNumOperands(); i < n; i += 2)
1355     if (isLoopFeeder(L, MBB, Phi, &(Phi->getOperand(i)), LoopFeederPhi))
1356       if (loopCountMayWrapOrUnderFlow(&(Phi->getOperand(i)), EndVal,
1357                                       Phi->getParent(), L, LoopFeederPhi))
1358         return true;
1359   return false;
1360 }
1361
1362 /// Return true if the induction variable can underflow in the first iteration.
1363 /// An example, is an initial unsigned value that is 0 and is decrement in the
1364 /// first itertion of a do-while loop.  In this case, we cannot generate a
1365 /// hardware loop because the endloop instruction does not decrement the loop
1366 /// counter if it is <= 1. We only need to perform this analysis if the
1367 /// initial value is a register.
1368 ///
1369 /// This function assumes the initial value may underfow unless proven
1370 /// otherwise. If the type is signed, then we don't care because signed
1371 /// underflow is undefined. We attempt to prove the initial value is not
1372 /// zero by perfoming a crude analysis of the loop counter. This function
1373 /// checks if the initial value is used in any comparison prior to the loop
1374 /// and, if so, assumes the comparison is a range check. This is inexact,
1375 /// but will catch the simple cases.
1376 bool HexagonHardwareLoops::loopCountMayWrapOrUnderFlow(
1377     const MachineOperand *InitVal, const MachineOperand *EndVal,
1378     MachineBasicBlock *MBB, MachineLoop *L,
1379     LoopFeederMap &LoopFeederPhi) const {
1380   // Only check register values since they are unknown.
1381   if (!InitVal->isReg())
1382     return false;
1383
1384   if (!EndVal->isImm())
1385     return false;
1386
1387   // A register value that is assigned an immediate is a known value, and it
1388   // won't underflow in the first iteration.
1389   int64_t Imm;
1390   if (checkForImmediate(*InitVal, Imm))
1391     return (EndVal->getImm() == Imm);
1392
1393   unsigned Reg = InitVal->getReg();
1394
1395   // We don't know the value of a physical register.
1396   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1397     return true;
1398
1399   MachineInstr *Def = MRI->getVRegDef(Reg);
1400   if (!Def)
1401     return true;
1402
1403   // If the initial value is a Phi or copy and the operands may not underflow,
1404   // then the definition cannot be underflow either.
1405   if (Def->isPHI() && !phiMayWrapOrUnderflow(Def, EndVal, Def->getParent(),
1406                                              L, LoopFeederPhi))
1407     return false;
1408   if (Def->isCopy() && !loopCountMayWrapOrUnderFlow(&(Def->getOperand(1)),
1409                                                     EndVal, Def->getParent(),
1410                                                     L, LoopFeederPhi))
1411     return false;
1412
1413   // Iterate over the uses of the initial value. If the initial value is used
1414   // in a compare, then we assume this is a range check that ensures the loop
1415   // doesn't underflow. This is not an exact test and should be improved.
1416   for (MachineRegisterInfo::use_instr_nodbg_iterator I = MRI->use_instr_nodbg_begin(Reg),
1417          E = MRI->use_instr_nodbg_end(); I != E; ++I) {
1418     MachineInstr *MI = &*I;
1419     unsigned CmpReg1 = 0, CmpReg2 = 0;
1420     int CmpMask = 0, CmpValue = 0;
1421
1422     if (!TII->analyzeCompare(MI, CmpReg1, CmpReg2, CmpMask, CmpValue))
1423       continue;
1424
1425     MachineBasicBlock *TBB = 0, *FBB = 0;
1426     SmallVector<MachineOperand, 2> Cond;
1427     if (TII->AnalyzeBranch(*MI->getParent(), TBB, FBB, Cond, false))
1428       continue;
1429
1430     Comparison::Kind Cmp = getComparisonKind(MI->getOpcode(), 0, 0, 0);
1431     if (Cmp == 0)
1432       continue;
1433     if (TII->predOpcodeHasNot(Cond) ^ (TBB != MBB))
1434       Cmp = Comparison::getNegatedComparison(Cmp);
1435     if (CmpReg2 != 0 && CmpReg2 == Reg)
1436       Cmp = Comparison::getSwappedComparison(Cmp);
1437
1438     // Signed underflow is undefined.
1439     if (Comparison::isSigned(Cmp))
1440       return false;
1441
1442     // Check if there is a comparison of the inital value. If the initial value
1443     // is greater than or not equal to another value, then assume this is a
1444     // range check.
1445     if ((Cmp & Comparison::G) || Cmp == Comparison::NE)
1446       return false;
1447   }
1448
1449   // OK - this is a hack that needs to be improved. We really need to analyze
1450   // the instructions performed on the initial value. This works on the simplest
1451   // cases only.
1452   if (!Def->isCopy() && !Def->isPHI())
1453     return false;
1454
1455   return true;
1456 }
1457
1458 bool HexagonHardwareLoops::checkForImmediate(const MachineOperand &MO,
1459                                              int64_t &Val) const {
1460   if (MO.isImm()) {
1461     Val = MO.getImm();
1462     return true;
1463   }
1464   if (!MO.isReg())
1465     return false;
1466
1467   // MO is a register. Check whether it is defined as an immediate value,
1468   // and if so, get the value of it in TV. That value will then need to be
1469   // processed to handle potential subregisters in MO.
1470   int64_t TV;
1471
1472   unsigned R = MO.getReg();
1473   if (!TargetRegisterInfo::isVirtualRegister(R))
1474     return false;
1475   MachineInstr *DI = MRI->getVRegDef(R);
1476   unsigned DOpc = DI->getOpcode();
1477   switch (DOpc) {
1478     case TargetOpcode::COPY:
1479     case Hexagon::A2_tfrsi:
1480     case Hexagon::A2_tfrpi:
1481     case Hexagon::CONST32_Int_Real:
1482     case Hexagon::CONST64_Int_Real: {
1483       // Call recursively to avoid an extra check whether operand(1) is
1484       // indeed an immediate (it could be a global address, for example),
1485       // plus we can handle COPY at the same time.
1486       if (!checkForImmediate(DI->getOperand(1), TV))
1487         return false;
1488       break;
1489     }
1490     case Hexagon::A2_combineii:
1491     case Hexagon::A4_combineir:
1492     case Hexagon::A4_combineii:
1493     case Hexagon::A4_combineri:
1494     case Hexagon::A2_combinew: {
1495       const MachineOperand &S1 = DI->getOperand(1);
1496       const MachineOperand &S2 = DI->getOperand(2);
1497       int64_t V1, V2;
1498       if (!checkForImmediate(S1, V1) || !checkForImmediate(S2, V2))
1499         return false;
1500       TV = V2 | (V1 << 32);
1501       break;
1502     }
1503     case TargetOpcode::REG_SEQUENCE: {
1504       const MachineOperand &S1 = DI->getOperand(1);
1505       const MachineOperand &S3 = DI->getOperand(3);
1506       int64_t V1, V3;
1507       if (!checkForImmediate(S1, V1) || !checkForImmediate(S3, V3))
1508         return false;
1509       unsigned Sub2 = DI->getOperand(2).getImm();
1510       unsigned Sub4 = DI->getOperand(4).getImm();
1511       if (Sub2 == Hexagon::subreg_loreg && Sub4 == Hexagon::subreg_hireg)
1512         TV = V1 | (V3 << 32);
1513       else if (Sub2 == Hexagon::subreg_hireg && Sub4 == Hexagon::subreg_loreg)
1514         TV = V3 | (V1 << 32);
1515       else
1516         llvm_unreachable("Unexpected form of REG_SEQUENCE");
1517       break;
1518     }
1519
1520     default:
1521       return false;
1522   }
1523
1524   // By now, we should have successfuly obtained the immediate value defining
1525   // the register referenced in MO. Handle a potential use of a subregister.
1526   switch (MO.getSubReg()) {
1527     case Hexagon::subreg_loreg:
1528       Val = TV & 0xFFFFFFFFULL;
1529       break;
1530     case Hexagon::subreg_hireg:
1531       Val = (TV >> 32) & 0xFFFFFFFFULL;
1532       break;
1533     default:
1534       Val = TV;
1535       break;
1536   }
1537   return true;
1538 }
1539
1540 void HexagonHardwareLoops::setImmediate(MachineOperand &MO, int64_t Val) {
1541   if (MO.isImm()) {
1542     MO.setImm(Val);
1543     return;
1544   }
1545
1546   assert(MO.isReg());
1547   unsigned R = MO.getReg();
1548   MachineInstr *DI = MRI->getVRegDef(R);
1549
1550   const TargetRegisterClass *RC = MRI->getRegClass(R);
1551   unsigned NewR = MRI->createVirtualRegister(RC);
1552   MachineBasicBlock &B = *DI->getParent();
1553   DebugLoc DL = DI->getDebugLoc();
1554   BuildMI(B, DI, DL, TII->get(DI->getOpcode()), NewR).addImm(Val);
1555   MO.setReg(NewR);
1556 }
1557
1558 static bool isImmValidForOpcode(unsigned CmpOpc, int64_t Imm) {
1559   // These two instructions are not extendable.
1560   if (CmpOpc == Hexagon::A4_cmpbeqi)
1561     return isUInt<8>(Imm);
1562   if (CmpOpc == Hexagon::A4_cmpbgti)
1563     return isInt<8>(Imm);
1564   // The rest of the comparison-with-immediate instructions are extendable.
1565   return true;
1566 }
1567
1568 bool HexagonHardwareLoops::fixupInductionVariable(MachineLoop *L) {
1569   MachineBasicBlock *Header = L->getHeader();
1570   MachineBasicBlock *Latch = L->getLoopLatch();
1571   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1572
1573   if (!(Header && Latch && ExitingBlock))
1574     return false;
1575
1576   // These data structures follow the same concept as the corresponding
1577   // ones in findInductionRegister (where some comments are).
1578   typedef std::pair<unsigned,int64_t> RegisterBump;
1579   typedef std::pair<unsigned,RegisterBump> RegisterInduction;
1580   typedef std::set<RegisterInduction> RegisterInductionSet;
1581
1582   // Register candidates for induction variables, with their associated bumps.
1583   RegisterInductionSet IndRegs;
1584
1585   // Look for induction patterns:
1586   //   vreg1 = PHI ..., [ latch, vreg2 ]
1587   //   vreg2 = ADD vreg1, imm
1588   typedef MachineBasicBlock::instr_iterator instr_iterator;
1589   for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1590        I != E && I->isPHI(); ++I) {
1591     MachineInstr *Phi = &*I;
1592
1593     // Have a PHI instruction.
1594     for (unsigned i = 1, n = Phi->getNumOperands(); i < n; i += 2) {
1595       if (Phi->getOperand(i+1).getMBB() != Latch)
1596         continue;
1597
1598       unsigned PhiReg = Phi->getOperand(i).getReg();
1599       MachineInstr *DI = MRI->getVRegDef(PhiReg);
1600       unsigned UpdOpc = DI->getOpcode();
1601       bool isAdd = (UpdOpc == Hexagon::A2_addi || UpdOpc == Hexagon::A2_addp);
1602
1603       if (isAdd) {
1604         // If the register operand to the add/sub is the PHI we are looking
1605         // at, this meets the induction pattern.
1606         unsigned IndReg = DI->getOperand(1).getReg();
1607         MachineOperand &Opnd2 = DI->getOperand(2);
1608         int64_t V;
1609         if (MRI->getVRegDef(IndReg) == Phi && checkForImmediate(Opnd2, V)) {
1610           unsigned UpdReg = DI->getOperand(0).getReg();
1611           IndRegs.insert(std::make_pair(UpdReg, std::make_pair(IndReg, V)));
1612         }
1613       }
1614     }  // for (i)
1615   }  // for (instr)
1616
1617   if (IndRegs.empty())
1618     return false;
1619
1620   MachineBasicBlock *TB = nullptr, *FB = nullptr;
1621   SmallVector<MachineOperand,2> Cond;
1622   // AnalyzeBranch returns true if it fails to analyze branch.
1623   bool NotAnalyzed = TII->AnalyzeBranch(*ExitingBlock, TB, FB, Cond, false);
1624   if (NotAnalyzed || Cond.empty())
1625     return false;
1626
1627   if (ExitingBlock != Latch && (TB == Latch || FB == Latch)) {
1628     MachineBasicBlock *LTB = 0, *LFB = 0;
1629     SmallVector<MachineOperand,2> LCond;
1630     bool NotAnalyzed = TII->AnalyzeBranch(*Latch, LTB, LFB, LCond, false);
1631     if (NotAnalyzed)
1632       return false;
1633
1634     // Since latch is not the exiting block, the latch branch should be an
1635     // unconditional branch to the loop header.
1636     if (TB == Latch)
1637       TB = (LTB == Header) ? LTB : LFB;
1638     else
1639       FB = (LTB == Header) ? LTB : LFB;
1640   }
1641   if (TB != Header) {
1642     if (FB != Header) {
1643       // The latch/exit block does not go back to the header.
1644       return false;
1645     }
1646     // FB is the header (i.e., uncond. jump to branch header)
1647     // In this case, the LoopBody -> TB should not be a back edge otherwise
1648     // it could result in an infinite loop after conversion to hw_loop.
1649     // This case can happen when the Latch has two jumps like this:
1650     // Jmp_c OuterLoopHeader <-- TB
1651     // Jmp   InnerLoopHeader <-- FB
1652     if (MDT->dominates(TB, FB))
1653       return false;
1654   }
1655
1656   // Expecting a predicate register as a condition.  It won't be a hardware
1657   // predicate register at this point yet, just a vreg.
1658   // HexagonInstrInfo::AnalyzeBranch for negated branches inserts imm(0)
1659   // into Cond, followed by the predicate register.  For non-negated branches
1660   // it's just the register.
1661   unsigned CSz = Cond.size();
1662   if (CSz != 1 && CSz != 2)
1663     return false;
1664
1665   if (!Cond[CSz-1].isReg())
1666     return false;
1667
1668   unsigned P = Cond[CSz-1].getReg();
1669   MachineInstr *PredDef = MRI->getVRegDef(P);
1670
1671   if (!PredDef->isCompare())
1672     return false;
1673
1674   SmallSet<unsigned,2> CmpRegs;
1675   MachineOperand *CmpImmOp = nullptr;
1676
1677   // Go over all operands to the compare and look for immediate and register
1678   // operands.  Assume that if the compare has a single register use and a
1679   // single immediate operand, then the register is being compared with the
1680   // immediate value.
1681   for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1682     MachineOperand &MO = PredDef->getOperand(i);
1683     if (MO.isReg()) {
1684       // Skip all implicit references.  In one case there was:
1685       //   %vreg140<def> = FCMPUGT32_rr %vreg138, %vreg139, %USR<imp-use>
1686       if (MO.isImplicit())
1687         continue;
1688       if (MO.isUse()) {
1689         if (!isImmediate(MO)) {
1690           CmpRegs.insert(MO.getReg());
1691           continue;
1692         }
1693         // Consider the register to be the "immediate" operand.
1694         if (CmpImmOp)
1695           return false;
1696         CmpImmOp = &MO;
1697       }
1698     } else if (MO.isImm()) {
1699       if (CmpImmOp)    // A second immediate argument?  Confusing.  Bail out.
1700         return false;
1701       CmpImmOp = &MO;
1702     }
1703   }
1704
1705   if (CmpRegs.empty())
1706     return false;
1707
1708   // Check if the compared register follows the order we want.  Fix if needed.
1709   for (RegisterInductionSet::iterator I = IndRegs.begin(), E = IndRegs.end();
1710        I != E; ++I) {
1711     // This is a success.  If the register used in the comparison is one that
1712     // we have identified as a bumped (updated) induction register, there is
1713     // nothing to do.
1714     if (CmpRegs.count(I->first))
1715       return true;
1716
1717     // Otherwise, if the register being compared comes out of a PHI node,
1718     // and has been recognized as following the induction pattern, and is
1719     // compared against an immediate, we can fix it.
1720     const RegisterBump &RB = I->second;
1721     if (CmpRegs.count(RB.first)) {
1722       if (!CmpImmOp) {
1723         // If both operands to the compare instruction are registers, see if
1724         // it can be changed to use induction register as one of the operands.
1725         MachineInstr *IndI = nullptr;
1726         MachineInstr *nonIndI = nullptr;
1727         MachineOperand *IndMO = nullptr;
1728         MachineOperand *nonIndMO = nullptr;
1729
1730         for (unsigned i = 1, n = PredDef->getNumOperands(); i < n; ++i) {
1731           MachineOperand &MO = PredDef->getOperand(i);
1732           if (MO.isReg() && MO.getReg() == RB.first) {
1733             DEBUG(dbgs() << "\n DefMI(" << i << ") = "
1734                          << *(MRI->getVRegDef(I->first)));
1735             if (IndI)
1736               return false;
1737
1738             IndI = MRI->getVRegDef(I->first);
1739             IndMO = &MO;
1740           } else if (MO.isReg()) {
1741             DEBUG(dbgs() << "\n DefMI(" << i << ") = "
1742                          << *(MRI->getVRegDef(MO.getReg())));
1743             if (nonIndI)
1744               return false;
1745
1746             nonIndI = MRI->getVRegDef(MO.getReg());
1747             nonIndMO = &MO;
1748           }
1749         }
1750         if (IndI && nonIndI &&
1751             nonIndI->getOpcode() == Hexagon::A2_addi &&
1752             nonIndI->getOperand(2).isImm() &&
1753             nonIndI->getOperand(2).getImm() == - RB.second) {
1754           bool Order = orderBumpCompare(IndI, PredDef);
1755           if (Order) {
1756             IndMO->setReg(I->first);
1757             nonIndMO->setReg(nonIndI->getOperand(1).getReg());
1758             return true;
1759           }
1760         }
1761         return false;
1762       }
1763
1764       // It is not valid to do this transformation on an unsigned comparison
1765       // because it may underflow.
1766       Comparison::Kind Cmp = getComparisonKind(PredDef->getOpcode(), 0, 0, 0);
1767       if (!Cmp || Comparison::isUnsigned(Cmp))
1768         return false;
1769
1770       // If the register is being compared against an immediate, try changing
1771       // the compare instruction to use induction register and adjust the
1772       // immediate operand.
1773       int64_t CmpImm = getImmediate(*CmpImmOp);
1774       int64_t V = RB.second;
1775       // Handle Overflow (64-bit).
1776       if (((V > 0) && (CmpImm > INT64_MAX - V)) ||
1777           ((V < 0) && (CmpImm < INT64_MIN - V)))
1778         return false;
1779       CmpImm += V;
1780       // Most comparisons of register against an immediate value allow
1781       // the immediate to be constant-extended. There are some exceptions
1782       // though. Make sure the new combination will work.
1783       if (CmpImmOp->isImm())
1784         if (!isImmValidForOpcode(PredDef->getOpcode(), CmpImm))
1785           return false;
1786
1787       // Make sure that the compare happens after the bump.  Otherwise,
1788       // after the fixup, the compare would use a yet-undefined register.
1789       MachineInstr *BumpI = MRI->getVRegDef(I->first);
1790       bool Order = orderBumpCompare(BumpI, PredDef);
1791       if (!Order)
1792         return false;
1793
1794       // Finally, fix the compare instruction.
1795       setImmediate(*CmpImmOp, CmpImm);
1796       for (unsigned i = 0, n = PredDef->getNumOperands(); i < n; ++i) {
1797         MachineOperand &MO = PredDef->getOperand(i);
1798         if (MO.isReg() && MO.getReg() == RB.first) {
1799           MO.setReg(I->first);
1800           return true;
1801         }
1802       }
1803     }
1804   }
1805
1806   return false;
1807 }
1808
1809 /// \brief Create a preheader for a given loop.
1810 MachineBasicBlock *HexagonHardwareLoops::createPreheaderForLoop(
1811       MachineLoop *L) {
1812   if (MachineBasicBlock *TmpPH = L->getLoopPreheader())
1813     return TmpPH;
1814
1815   if (!HWCreatePreheader)
1816     return nullptr;
1817
1818   MachineBasicBlock *Header = L->getHeader();
1819   MachineBasicBlock *Latch = L->getLoopLatch();
1820   MachineBasicBlock *ExitingBlock = getExitingBlock(L);
1821   MachineFunction *MF = Header->getParent();
1822   DebugLoc DL;
1823
1824 #ifndef NDEBUG
1825   if ((PHFn != "") && (PHFn != MF->getName()))
1826     return nullptr;
1827 #endif
1828
1829   if (!Latch || !ExitingBlock || Header->hasAddressTaken())
1830     return nullptr;
1831
1832   typedef MachineBasicBlock::instr_iterator instr_iterator;
1833
1834   // Verify that all existing predecessors have analyzable branches
1835   // (or no branches at all).
1836   typedef std::vector<MachineBasicBlock*> MBBVector;
1837   MBBVector Preds(Header->pred_begin(), Header->pred_end());
1838   SmallVector<MachineOperand,2> Tmp1;
1839   MachineBasicBlock *TB = nullptr, *FB = nullptr;
1840
1841   if (TII->AnalyzeBranch(*ExitingBlock, TB, FB, Tmp1, false))
1842     return nullptr;
1843
1844   for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1845     MachineBasicBlock *PB = *I;
1846     bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp1, false);
1847     if (NotAnalyzed)
1848       return nullptr;
1849   }
1850
1851   MachineBasicBlock *NewPH = MF->CreateMachineBasicBlock();
1852   MF->insert(Header, NewPH);
1853
1854   if (Header->pred_size() > 2) {
1855     // Ensure that the header has only two predecessors: the preheader and
1856     // the loop latch.  Any additional predecessors of the header should
1857     // join at the newly created preheader. Inspect all PHI nodes from the
1858     // header and create appropriate corresponding PHI nodes in the preheader.
1859
1860     for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1861          I != E && I->isPHI(); ++I) {
1862       MachineInstr *PN = &*I;
1863
1864       const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
1865       MachineInstr *NewPN = MF->CreateMachineInstr(PD, DL);
1866       NewPH->insert(NewPH->end(), NewPN);
1867
1868       unsigned PR = PN->getOperand(0).getReg();
1869       const TargetRegisterClass *RC = MRI->getRegClass(PR);
1870       unsigned NewPR = MRI->createVirtualRegister(RC);
1871       NewPN->addOperand(MachineOperand::CreateReg(NewPR, true));
1872
1873       // Copy all non-latch operands of a header's PHI node to the newly
1874       // created PHI node in the preheader.
1875       for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1876         unsigned PredR = PN->getOperand(i).getReg();
1877         unsigned PredRSub = PN->getOperand(i).getSubReg();
1878         MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1879         if (PredB == Latch)
1880           continue;
1881
1882         MachineOperand MO = MachineOperand::CreateReg(PredR, false);
1883         MO.setSubReg(PredRSub);
1884         NewPN->addOperand(MO);
1885         NewPN->addOperand(MachineOperand::CreateMBB(PredB));
1886       }
1887
1888       // Remove copied operands from the old PHI node and add the value
1889       // coming from the preheader's PHI.
1890       for (int i = PN->getNumOperands()-2; i > 0; i -= 2) {
1891         MachineBasicBlock *PredB = PN->getOperand(i+1).getMBB();
1892         if (PredB != Latch) {
1893           PN->RemoveOperand(i+1);
1894           PN->RemoveOperand(i);
1895         }
1896       }
1897       PN->addOperand(MachineOperand::CreateReg(NewPR, false));
1898       PN->addOperand(MachineOperand::CreateMBB(NewPH));
1899     }
1900
1901   } else {
1902     assert(Header->pred_size() == 2);
1903
1904     // The header has only two predecessors, but the non-latch predecessor
1905     // is not a preheader (e.g. it has other successors, etc.)
1906     // In such a case we don't need any extra PHI nodes in the new preheader,
1907     // all we need is to adjust existing PHIs in the header to now refer to
1908     // the new preheader.
1909     for (instr_iterator I = Header->instr_begin(), E = Header->instr_end();
1910          I != E && I->isPHI(); ++I) {
1911       MachineInstr *PN = &*I;
1912       for (unsigned i = 1, n = PN->getNumOperands(); i < n; i += 2) {
1913         MachineOperand &MO = PN->getOperand(i+1);
1914         if (MO.getMBB() != Latch)
1915           MO.setMBB(NewPH);
1916       }
1917     }
1918   }
1919
1920   // "Reroute" the CFG edges to link in the new preheader.
1921   // If any of the predecessors falls through to the header, insert a branch
1922   // to the new preheader in that place.
1923   SmallVector<MachineOperand,1> Tmp2;
1924   SmallVector<MachineOperand,1> EmptyCond;
1925
1926   TB = FB = nullptr;
1927
1928   for (MBBVector::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) {
1929     MachineBasicBlock *PB = *I;
1930     if (PB != Latch) {
1931       Tmp2.clear();
1932       bool NotAnalyzed = TII->AnalyzeBranch(*PB, TB, FB, Tmp2, false);
1933       (void)NotAnalyzed; // suppress compiler warning
1934       assert (!NotAnalyzed && "Should be analyzable!");
1935       if (TB != Header && (Tmp2.empty() || FB != Header))
1936         TII->InsertBranch(*PB, NewPH, nullptr, EmptyCond, DL);
1937       PB->ReplaceUsesOfBlockWith(Header, NewPH);
1938     }
1939   }
1940
1941   // It can happen that the latch block will fall through into the header.
1942   // Insert an unconditional branch to the header.
1943   TB = FB = nullptr;
1944   bool LatchNotAnalyzed = TII->AnalyzeBranch(*Latch, TB, FB, Tmp2, false);
1945   (void)LatchNotAnalyzed; // suppress compiler warning
1946   assert (!LatchNotAnalyzed && "Should be analyzable!");
1947   if (!TB && !FB)
1948     TII->InsertBranch(*Latch, Header, nullptr, EmptyCond, DL);
1949
1950   // Finally, the branch from the preheader to the header.
1951   TII->InsertBranch(*NewPH, Header, nullptr, EmptyCond, DL);
1952   NewPH->addSuccessor(Header);
1953
1954   MachineLoop *ParentLoop = L->getParentLoop();
1955   if (ParentLoop)
1956     ParentLoop->addBasicBlockToLoop(NewPH, MLI->getBase());
1957
1958   // Update the dominator information with the new preheader.
1959   if (MDT) {
1960     MachineDomTreeNode *HDom = MDT->getNode(Header);
1961     MDT->addNewBlock(NewPH, HDom->getIDom()->getBlock());
1962     MDT->changeImmediateDominator(Header, NewPH);
1963   }
1964
1965   return NewPH;
1966 }