1 //===- HexagonInstrInfo.cpp - Hexagon Instruction Information -------------===//
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 file contains the Hexagon implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "HexagonInstrInfo.h"
15 #include "Hexagon.h"
16 #include "HexagonFrameLowering.h"
17 #include "HexagonHazardRecognizer.h"
18 #include "HexagonRegisterInfo.h"
19 #include "HexagonSubtarget.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/CodeGen/DFAPacketizer.h"
25 #include "llvm/CodeGen/LivePhysRegs.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineInstrBundle.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineOperand.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/MachineValueType.h"
38 #include "llvm/CodeGen/ScheduleDAG.h"
39 #include "llvm/IR/DebugLoc.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCInstrDesc.h"
42 #include "llvm/MC/MCInstrItineraries.h"
43 #include "llvm/MC/MCRegisterInfo.h"
44 #include "llvm/Support/BranchProbability.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetOpcodes.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
55 #include <cassert>
56 #include <cctype>
57 #include <cstdint>
58 #include <cstring>
59 #include <iterator>
60 #include <string>
61 #include <utility>
62 
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "hexagon-instrinfo"
66 
67 #define GET_INSTRINFO_CTOR_DTOR
68 #define GET_INSTRMAP_INFO
69 #include "HexagonDepTimingClasses.h"
70 #include "HexagonGenDFAPacketizer.inc"
71 #include "HexagonGenInstrInfo.inc"
72 
73 cl::opt<bool> ScheduleInlineAsm("hexagon-sched-inline-asm", cl::Hidden,
74   cl::init(false), cl::desc("Do not consider inline-asm a scheduling/"
75                             "packetization boundary."));
76 
77 static cl::opt<bool> EnableBranchPrediction("hexagon-enable-branch-prediction",
78   cl::Hidden, cl::init(true), cl::desc("Enable branch prediction"));
79 
80 static cl::opt<bool> DisableNVSchedule("disable-hexagon-nv-schedule",
81   cl::Hidden, cl::ZeroOrMore, cl::init(false),
82   cl::desc("Disable schedule adjustment for new value stores."));
83 
84 static cl::opt<bool> EnableTimingClassLatency(
85   "enable-timing-class-latency", cl::Hidden, cl::init(false),
86   cl::desc("Enable timing class latency"));
87 
88 static cl::opt<bool> EnableALUForwarding(
89   "enable-alu-forwarding", cl::Hidden, cl::init(true),
90   cl::desc("Enable vec alu forwarding"));
91 
92 static cl::opt<bool> EnableACCForwarding(
93   "enable-acc-forwarding", cl::Hidden, cl::init(true),
94   cl::desc("Enable vec acc forwarding"));
95 
96 static cl::opt<bool> BranchRelaxAsmLarge("branch-relax-asm-large",
97   cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("branch relax asm"));
98 
99 static cl::opt<bool> UseDFAHazardRec("dfa-hazard-rec",
100   cl::init(true), cl::Hidden, cl::ZeroOrMore,
101   cl::desc("Use the DFA based hazard recognizer."));
102 
103 /// Constants for Hexagon instructions.
104 const int Hexagon_MEMW_OFFSET_MAX = 4095;
105 const int Hexagon_MEMW_OFFSET_MIN = -4096;
106 const int Hexagon_MEMD_OFFSET_MAX = 8191;
107 const int Hexagon_MEMD_OFFSET_MIN = -8192;
108 const int Hexagon_MEMH_OFFSET_MAX = 2047;
109 const int Hexagon_MEMH_OFFSET_MIN = -2048;
110 const int Hexagon_MEMB_OFFSET_MAX = 1023;
111 const int Hexagon_MEMB_OFFSET_MIN = -1024;
112 const int Hexagon_ADDI_OFFSET_MAX = 32767;
113 const int Hexagon_ADDI_OFFSET_MIN = -32768;
114 
115 // Pin the vtable to this file.
116 void HexagonInstrInfo::anchor() {}
117 
118 HexagonInstrInfo::HexagonInstrInfo(HexagonSubtarget &ST)
119   : HexagonGenInstrInfo(Hexagon::ADJCALLSTACKDOWN, Hexagon::ADJCALLSTACKUP),
120     Subtarget(ST) {}
121 
122 static bool isIntRegForSubInst(unsigned Reg) {
123   return (Reg >= Hexagon::R0 && Reg <= Hexagon::R7) ||
124          (Reg >= Hexagon::R16 && Reg <= Hexagon::R23);
125 }
126 
127 static bool isDblRegForSubInst(unsigned Reg, const HexagonRegisterInfo &HRI) {
128   return isIntRegForSubInst(HRI.getSubReg(Reg, Hexagon::isub_lo)) &&
129          isIntRegForSubInst(HRI.getSubReg(Reg, Hexagon::isub_hi));
130 }
131 
132 /// Calculate number of instructions excluding the debug instructions.
133 static unsigned nonDbgMICount(MachineBasicBlock::const_instr_iterator MIB,
134                               MachineBasicBlock::const_instr_iterator MIE) {
135   unsigned Count = 0;
136   for (; MIB != MIE; ++MIB) {
137     if (!MIB->isDebugValue())
138       ++Count;
139   }
140   return Count;
141 }
142 
143 /// Find the hardware loop instruction used to set-up the specified loop.
144 /// On Hexagon, we have two instructions used to set-up the hardware loop
145 /// (LOOP0, LOOP1) with corresponding endloop (ENDLOOP0, ENDLOOP1) instructions
146 /// to indicate the end of a loop.
147 static MachineInstr *findLoopInstr(MachineBasicBlock *BB, unsigned EndLoopOp,
148       MachineBasicBlock *TargetBB,
149       SmallPtrSet<MachineBasicBlock *, 8> &Visited) {
150   unsigned LOOPi;
151   unsigned LOOPr;
152   if (EndLoopOp == Hexagon::ENDLOOP0) {
153     LOOPi = Hexagon::J2_loop0i;
154     LOOPr = Hexagon::J2_loop0r;
155   } else { // EndLoopOp == Hexagon::EndLOOP1
156     LOOPi = Hexagon::J2_loop1i;
157     LOOPr = Hexagon::J2_loop1r;
158   }
159 
160   // The loop set-up instruction will be in a predecessor block
161   for (MachineBasicBlock *PB : BB->predecessors()) {
162     // If this has been visited, already skip it.
163     if (!Visited.insert(PB).second)
164       continue;
165     if (PB == BB)
166       continue;
167     for (auto I = PB->instr_rbegin(), E = PB->instr_rend(); I != E; ++I) {
168       unsigned Opc = I->getOpcode();
169       if (Opc == LOOPi || Opc == LOOPr)
170         return &*I;
171       // We've reached a different loop, which means the loop01 has been
172       // removed.
173       if (Opc == EndLoopOp && I->getOperand(0).getMBB() != TargetBB)
174         return nullptr;
175     }
176     // Check the predecessors for the LOOP instruction.
177     if (MachineInstr *Loop = findLoopInstr(PB, EndLoopOp, TargetBB, Visited))
178       return Loop;
179   }
180   return nullptr;
181 }
182 
183 /// Gather register def/uses from MI.
184 /// This treats possible (predicated) defs as actually happening ones
185 /// (conservatively).
186 static inline void parseOperands(const MachineInstr &MI,
187       SmallVector<unsigned, 4> &Defs, SmallVector<unsigned, 8> &Uses) {
188   Defs.clear();
189   Uses.clear();
190 
191   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
192     const MachineOperand &MO = MI.getOperand(i);
193 
194     if (!MO.isReg())
195       continue;
196 
197     unsigned Reg = MO.getReg();
198     if (!Reg)
199       continue;
200 
201     if (MO.isUse())
202       Uses.push_back(MO.getReg());
203 
204     if (MO.isDef())
205       Defs.push_back(MO.getReg());
206   }
207 }
208 
209 // Position dependent, so check twice for swap.
210 static bool isDuplexPairMatch(unsigned Ga, unsigned Gb) {
211   switch (Ga) {
212   case HexagonII::HSIG_None:
213   default:
214     return false;
215   case HexagonII::HSIG_L1:
216     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_A);
217   case HexagonII::HSIG_L2:
218     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
219             Gb == HexagonII::HSIG_A);
220   case HexagonII::HSIG_S1:
221     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
222             Gb == HexagonII::HSIG_S1 || Gb == HexagonII::HSIG_A);
223   case HexagonII::HSIG_S2:
224     return (Gb == HexagonII::HSIG_L1 || Gb == HexagonII::HSIG_L2 ||
225             Gb == HexagonII::HSIG_S1 || Gb == HexagonII::HSIG_S2 ||
226             Gb == HexagonII::HSIG_A);
227   case HexagonII::HSIG_A:
228     return (Gb == HexagonII::HSIG_A);
229   case HexagonII::HSIG_Compound:
230     return (Gb == HexagonII::HSIG_Compound);
231   }
232   return false;
233 }
234 
235 /// isLoadFromStackSlot - If the specified machine instruction is a direct
236 /// load from a stack slot, return the virtual or physical register number of
237 /// the destination along with the FrameIndex of the loaded stack slot.  If
238 /// not, return 0.  This predicate must return 0 if the instruction has
239 /// any side effects other than loading from the stack slot.
240 unsigned HexagonInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
241                                                int &FrameIndex) const {
242   switch (MI.getOpcode()) {
243   default:
244     break;
245   case Hexagon::L2_loadri_io:
246   case Hexagon::L2_loadrd_io:
247   case Hexagon::V6_vL32b_ai:
248   case Hexagon::V6_vL32b_nt_ai:
249   case Hexagon::V6_vL32Ub_ai:
250   case Hexagon::LDriw_pred:
251   case Hexagon::LDriw_mod:
252   case Hexagon::PS_vloadrq_ai:
253   case Hexagon::PS_vloadrw_ai:
254   case Hexagon::PS_vloadrw_nt_ai: {
255     const MachineOperand OpFI = MI.getOperand(1);
256     if (!OpFI.isFI())
257       return 0;
258     const MachineOperand OpOff = MI.getOperand(2);
259     if (!OpOff.isImm() || OpOff.getImm() != 0)
260       return 0;
261     FrameIndex = OpFI.getIndex();
262     return MI.getOperand(0).getReg();
263   }
264 
265   case Hexagon::L2_ploadrit_io:
266   case Hexagon::L2_ploadrif_io:
267   case Hexagon::L2_ploadrdt_io:
268   case Hexagon::L2_ploadrdf_io: {
269     const MachineOperand OpFI = MI.getOperand(2);
270     if (!OpFI.isFI())
271       return 0;
272     const MachineOperand OpOff = MI.getOperand(3);
273     if (!OpOff.isImm() || OpOff.getImm() != 0)
274       return 0;
275     FrameIndex = OpFI.getIndex();
276     return MI.getOperand(0).getReg();
277   }
278   }
279 
280   return 0;
281 }
282 
283 /// isStoreToStackSlot - If the specified machine instruction is a direct
284 /// store to a stack slot, return the virtual or physical register number of
285 /// the source reg along with the FrameIndex of the loaded stack slot.  If
286 /// not, return 0.  This predicate must return 0 if the instruction has
287 /// any side effects other than storing to the stack slot.
288 unsigned HexagonInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
289                                               int &FrameIndex) const {
290   switch (MI.getOpcode()) {
291   default:
292     break;
293   case Hexagon::S2_storerb_io:
294   case Hexagon::S2_storerh_io:
295   case Hexagon::S2_storeri_io:
296   case Hexagon::S2_storerd_io:
297   case Hexagon::V6_vS32b_ai:
298   case Hexagon::V6_vS32Ub_ai:
299   case Hexagon::STriw_pred:
300   case Hexagon::STriw_mod:
301   case Hexagon::PS_vstorerq_ai:
302   case Hexagon::PS_vstorerw_ai: {
303     const MachineOperand &OpFI = MI.getOperand(0);
304     if (!OpFI.isFI())
305       return 0;
306     const MachineOperand &OpOff = MI.getOperand(1);
307     if (!OpOff.isImm() || OpOff.getImm() != 0)
308       return 0;
309     FrameIndex = OpFI.getIndex();
310     return MI.getOperand(2).getReg();
311   }
312 
313   case Hexagon::S2_pstorerbt_io:
314   case Hexagon::S2_pstorerbf_io:
315   case Hexagon::S2_pstorerht_io:
316   case Hexagon::S2_pstorerhf_io:
317   case Hexagon::S2_pstorerit_io:
318   case Hexagon::S2_pstorerif_io:
319   case Hexagon::S2_pstorerdt_io:
320   case Hexagon::S2_pstorerdf_io: {
321     const MachineOperand &OpFI = MI.getOperand(1);
322     if (!OpFI.isFI())
323       return 0;
324     const MachineOperand &OpOff = MI.getOperand(2);
325     if (!OpOff.isImm() || OpOff.getImm() != 0)
326       return 0;
327     FrameIndex = OpFI.getIndex();
328     return MI.getOperand(3).getReg();
329   }
330   }
331 
332   return 0;
333 }
334 
335 /// This function can analyze one/two way branching only and should (mostly) be
336 /// called by target independent side.
337 /// First entry is always the opcode of the branching instruction, except when
338 /// the Cond vector is supposed to be empty, e.g., when AnalyzeBranch fails, a
339 /// BB with only unconditional jump. Subsequent entries depend upon the opcode,
340 /// e.g. Jump_c p will have
341 /// Cond[0] = Jump_c
342 /// Cond[1] = p
343 /// HW-loop ENDLOOP:
344 /// Cond[0] = ENDLOOP
345 /// Cond[1] = MBB
346 /// New value jump:
347 /// Cond[0] = Hexagon::CMPEQri_f_Jumpnv_t_V4 -- specific opcode
348 /// Cond[1] = R
349 /// Cond[2] = Imm
350 bool HexagonInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
351                                      MachineBasicBlock *&TBB,
352                                      MachineBasicBlock *&FBB,
353                                      SmallVectorImpl<MachineOperand> &Cond,
354                                      bool AllowModify) const {
355   TBB = nullptr;
356   FBB = nullptr;
357   Cond.clear();
358 
359   // If the block has no terminators, it just falls into the block after it.
360   MachineBasicBlock::instr_iterator I = MBB.instr_end();
361   if (I == MBB.instr_begin())
362     return false;
363 
364   // A basic block may looks like this:
365   //
366   //  [   insn
367   //     EH_LABEL
368   //      insn
369   //      insn
370   //      insn
371   //     EH_LABEL
372   //      insn     ]
373   //
374   // It has two succs but does not have a terminator
375   // Don't know how to handle it.
376   do {
377     --I;
378     if (I->isEHLabel())
379       // Don't analyze EH branches.
380       return true;
381   } while (I != MBB.instr_begin());
382 
383   I = MBB.instr_end();
384   --I;
385 
386   while (I->isDebugValue()) {
387     if (I == MBB.instr_begin())
388       return false;
389     --I;
390   }
391 
392   bool JumpToBlock = I->getOpcode() == Hexagon::J2_jump &&
393                      I->getOperand(0).isMBB();
394   // Delete the J2_jump if it's equivalent to a fall-through.
395   if (AllowModify && JumpToBlock &&
396       MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
397     DEBUG(dbgs() << "\nErasing the jump to successor block\n";);
398     I->eraseFromParent();
399     I = MBB.instr_end();
400     if (I == MBB.instr_begin())
401       return false;
402     --I;
403   }
404   if (!isUnpredicatedTerminator(*I))
405     return false;
406 
407   // Get the last instruction in the block.
408   MachineInstr *LastInst = &*I;
409   MachineInstr *SecondLastInst = nullptr;
410   // Find one more terminator if present.
411   while (true) {
412     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(*I)) {
413       if (!SecondLastInst)
414         SecondLastInst = &*I;
415       else
416         // This is a third branch.
417         return true;
418     }
419     if (I == MBB.instr_begin())
420       break;
421     --I;
422   }
423 
424   int LastOpcode = LastInst->getOpcode();
425   int SecLastOpcode = SecondLastInst ? SecondLastInst->getOpcode() : 0;
426   // If the branch target is not a basic block, it could be a tail call.
427   // (It is, if the target is a function.)
428   if (LastOpcode == Hexagon::J2_jump && !LastInst->getOperand(0).isMBB())
429     return true;
430   if (SecLastOpcode == Hexagon::J2_jump &&
431       !SecondLastInst->getOperand(0).isMBB())
432     return true;
433 
434   bool LastOpcodeHasJMP_c = PredOpcodeHasJMP_c(LastOpcode);
435   bool LastOpcodeHasNVJump = isNewValueJump(*LastInst);
436 
437   if (LastOpcodeHasJMP_c && !LastInst->getOperand(1).isMBB())
438     return true;
439 
440   // If there is only one terminator instruction, process it.
441   if (LastInst && !SecondLastInst) {
442     if (LastOpcode == Hexagon::J2_jump) {
443       TBB = LastInst->getOperand(0).getMBB();
444       return false;
445     }
446     if (isEndLoopN(LastOpcode)) {
447       TBB = LastInst->getOperand(0).getMBB();
448       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
449       Cond.push_back(LastInst->getOperand(0));
450       return false;
451     }
452     if (LastOpcodeHasJMP_c) {
453       TBB = LastInst->getOperand(1).getMBB();
454       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
455       Cond.push_back(LastInst->getOperand(0));
456       return false;
457     }
458     // Only supporting rr/ri versions of new-value jumps.
459     if (LastOpcodeHasNVJump && (LastInst->getNumExplicitOperands() == 3)) {
460       TBB = LastInst->getOperand(2).getMBB();
461       Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
462       Cond.push_back(LastInst->getOperand(0));
463       Cond.push_back(LastInst->getOperand(1));
464       return false;
465     }
466     DEBUG(dbgs() << "\nCant analyze BB#" << MBB.getNumber()
467                  << " with one jump\n";);
468     // Otherwise, don't know what this is.
469     return true;
470   }
471 
472   bool SecLastOpcodeHasJMP_c = PredOpcodeHasJMP_c(SecLastOpcode);
473   bool SecLastOpcodeHasNVJump = isNewValueJump(*SecondLastInst);
474   if (SecLastOpcodeHasJMP_c && (LastOpcode == Hexagon::J2_jump)) {
475     if (!SecondLastInst->getOperand(1).isMBB())
476       return true;
477     TBB =  SecondLastInst->getOperand(1).getMBB();
478     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
479     Cond.push_back(SecondLastInst->getOperand(0));
480     FBB = LastInst->getOperand(0).getMBB();
481     return false;
482   }
483 
484   // Only supporting rr/ri versions of new-value jumps.
485   if (SecLastOpcodeHasNVJump &&
486       (SecondLastInst->getNumExplicitOperands() == 3) &&
487       (LastOpcode == Hexagon::J2_jump)) {
488     TBB = SecondLastInst->getOperand(2).getMBB();
489     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
490     Cond.push_back(SecondLastInst->getOperand(0));
491     Cond.push_back(SecondLastInst->getOperand(1));
492     FBB = LastInst->getOperand(0).getMBB();
493     return false;
494   }
495 
496   // If the block ends with two Hexagon:JMPs, handle it.  The second one is not
497   // executed, so remove it.
498   if (SecLastOpcode == Hexagon::J2_jump && LastOpcode == Hexagon::J2_jump) {
499     TBB = SecondLastInst->getOperand(0).getMBB();
500     I = LastInst->getIterator();
501     if (AllowModify)
502       I->eraseFromParent();
503     return false;
504   }
505 
506   // If the block ends with an ENDLOOP, and J2_jump, handle it.
507   if (isEndLoopN(SecLastOpcode) && LastOpcode == Hexagon::J2_jump) {
508     TBB = SecondLastInst->getOperand(0).getMBB();
509     Cond.push_back(MachineOperand::CreateImm(SecondLastInst->getOpcode()));
510     Cond.push_back(SecondLastInst->getOperand(0));
511     FBB = LastInst->getOperand(0).getMBB();
512     return false;
513   }
514   DEBUG(dbgs() << "\nCant analyze BB#" << MBB.getNumber()
515                << " with two jumps";);
516   // Otherwise, can't handle this.
517   return true;
518 }
519 
520 unsigned HexagonInstrInfo::removeBranch(MachineBasicBlock &MBB,
521                                         int *BytesRemoved) const {
522   assert(!BytesRemoved && "code size not handled");
523 
524   DEBUG(dbgs() << "\nRemoving branches out of BB#" << MBB.getNumber());
525   MachineBasicBlock::iterator I = MBB.end();
526   unsigned Count = 0;
527   while (I != MBB.begin()) {
528     --I;
529     if (I->isDebugValue())
530       continue;
531     // Only removing branches from end of MBB.
532     if (!I->isBranch())
533       return Count;
534     if (Count && (I->getOpcode() == Hexagon::J2_jump))
535       llvm_unreachable("Malformed basic block: unconditional branch not last");
536     MBB.erase(&MBB.back());
537     I = MBB.end();
538     ++Count;
539   }
540   return Count;
541 }
542 
543 unsigned HexagonInstrInfo::insertBranch(MachineBasicBlock &MBB,
544                                         MachineBasicBlock *TBB,
545                                         MachineBasicBlock *FBB,
546                                         ArrayRef<MachineOperand> Cond,
547                                         const DebugLoc &DL,
548                                         int *BytesAdded) const {
549   unsigned BOpc   = Hexagon::J2_jump;
550   unsigned BccOpc = Hexagon::J2_jumpt;
551   assert(validateBranchCond(Cond) && "Invalid branching condition");
552   assert(TBB && "insertBranch must not be told to insert a fallthrough");
553   assert(!BytesAdded && "code size not handled");
554 
555   // Check if reverseBranchCondition has asked to reverse this branch
556   // If we want to reverse the branch an odd number of times, we want
557   // J2_jumpf.
558   if (!Cond.empty() && Cond[0].isImm())
559     BccOpc = Cond[0].getImm();
560 
561   if (!FBB) {
562     if (Cond.empty()) {
563       // Due to a bug in TailMerging/CFG Optimization, we need to add a
564       // special case handling of a predicated jump followed by an
565       // unconditional jump. If not, Tail Merging and CFG Optimization go
566       // into an infinite loop.
567       MachineBasicBlock *NewTBB, *NewFBB;
568       SmallVector<MachineOperand, 4> Cond;
569       auto Term = MBB.getFirstTerminator();
570       if (Term != MBB.end() && isPredicated(*Term) &&
571           !analyzeBranch(MBB, NewTBB, NewFBB, Cond, false) &&
572           MachineFunction::iterator(NewTBB) == ++MBB.getIterator()) {
573         reverseBranchCondition(Cond);
574         removeBranch(MBB);
575         return insertBranch(MBB, TBB, nullptr, Cond, DL);
576       }
577       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
578     } else if (isEndLoopN(Cond[0].getImm())) {
579       int EndLoopOp = Cond[0].getImm();
580       assert(Cond[1].isMBB());
581       // Since we're adding an ENDLOOP, there better be a LOOP instruction.
582       // Check for it, and change the BB target if needed.
583       SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
584       MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, Cond[1].getMBB(),
585                                          VisitedBBs);
586       assert(Loop != nullptr && "Inserting an ENDLOOP without a LOOP");
587       Loop->getOperand(0).setMBB(TBB);
588       // Add the ENDLOOP after the finding the LOOP0.
589       BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
590     } else if (isNewValueJump(Cond[0].getImm())) {
591       assert((Cond.size() == 3) && "Only supporting rr/ri version of nvjump");
592       // New value jump
593       // (ins IntRegs:$src1, IntRegs:$src2, brtarget:$offset)
594       // (ins IntRegs:$src1, u5Imm:$src2, brtarget:$offset)
595       unsigned Flags1 = getUndefRegState(Cond[1].isUndef());
596       DEBUG(dbgs() << "\nInserting NVJump for BB#" << MBB.getNumber(););
597       if (Cond[2].isReg()) {
598         unsigned Flags2 = getUndefRegState(Cond[2].isUndef());
599         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
600           addReg(Cond[2].getReg(), Flags2).addMBB(TBB);
601       } else if(Cond[2].isImm()) {
602         BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[1].getReg(), Flags1).
603           addImm(Cond[2].getImm()).addMBB(TBB);
604       } else
605         llvm_unreachable("Invalid condition for branching");
606     } else {
607       assert((Cond.size() == 2) && "Malformed cond vector");
608       const MachineOperand &RO = Cond[1];
609       unsigned Flags = getUndefRegState(RO.isUndef());
610       BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
611     }
612     return 1;
613   }
614   assert((!Cond.empty()) &&
615          "Cond. cannot be empty when multiple branchings are required");
616   assert((!isNewValueJump(Cond[0].getImm())) &&
617          "NV-jump cannot be inserted with another branch");
618   // Special case for hardware loops.  The condition is a basic block.
619   if (isEndLoopN(Cond[0].getImm())) {
620     int EndLoopOp = Cond[0].getImm();
621     assert(Cond[1].isMBB());
622     // Since we're adding an ENDLOOP, there better be a LOOP instruction.
623     // Check for it, and change the BB target if needed.
624     SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
625     MachineInstr *Loop = findLoopInstr(TBB, EndLoopOp, Cond[1].getMBB(),
626                                        VisitedBBs);
627     assert(Loop != nullptr && "Inserting an ENDLOOP without a LOOP");
628     Loop->getOperand(0).setMBB(TBB);
629     // Add the ENDLOOP after the finding the LOOP0.
630     BuildMI(&MBB, DL, get(EndLoopOp)).addMBB(TBB);
631   } else {
632     const MachineOperand &RO = Cond[1];
633     unsigned Flags = getUndefRegState(RO.isUndef());
634     BuildMI(&MBB, DL, get(BccOpc)).addReg(RO.getReg(), Flags).addMBB(TBB);
635   }
636   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
637 
638   return 2;
639 }
640 
641 /// Analyze the loop code to find the loop induction variable and compare used
642 /// to compute the number of iterations. Currently, we analyze loop that are
643 /// controlled using hardware loops.  In this case, the induction variable
644 /// instruction is null.  For all other cases, this function returns true, which
645 /// means we're unable to analyze it.
646 bool HexagonInstrInfo::analyzeLoop(MachineLoop &L,
647                                    MachineInstr *&IndVarInst,
648                                    MachineInstr *&CmpInst) const {
649 
650   MachineBasicBlock *LoopEnd = L.getBottomBlock();
651   MachineBasicBlock::iterator I = LoopEnd->getFirstTerminator();
652   // We really "analyze" only hardware loops right now.
653   if (I != LoopEnd->end() && isEndLoopN(I->getOpcode())) {
654     IndVarInst = nullptr;
655     CmpInst = &*I;
656     return false;
657   }
658   return true;
659 }
660 
661 /// Generate code to reduce the loop iteration by one and check if the loop is
662 /// finished. Return the value/register of the new loop count. this function
663 /// assumes the nth iteration is peeled first.
664 unsigned HexagonInstrInfo::reduceLoopCount(MachineBasicBlock &MBB,
665       MachineInstr *IndVar, MachineInstr &Cmp,
666       SmallVectorImpl<MachineOperand> &Cond,
667       SmallVectorImpl<MachineInstr *> &PrevInsts,
668       unsigned Iter, unsigned MaxIter) const {
669   // We expect a hardware loop currently. This means that IndVar is set
670   // to null, and the compare is the ENDLOOP instruction.
671   assert((!IndVar) && isEndLoopN(Cmp.getOpcode())
672                    && "Expecting a hardware loop");
673   MachineFunction *MF = MBB.getParent();
674   DebugLoc DL = Cmp.getDebugLoc();
675   SmallPtrSet<MachineBasicBlock *, 8> VisitedBBs;
676   MachineInstr *Loop = findLoopInstr(&MBB, Cmp.getOpcode(),
677                                      Cmp.getOperand(0).getMBB(), VisitedBBs);
678   if (!Loop)
679     return 0;
680   // If the loop trip count is a compile-time value, then just change the
681   // value.
682   if (Loop->getOpcode() == Hexagon::J2_loop0i ||
683       Loop->getOpcode() == Hexagon::J2_loop1i) {
684     int64_t Offset = Loop->getOperand(1).getImm();
685     if (Offset <= 1)
686       Loop->eraseFromParent();
687     else
688       Loop->getOperand(1).setImm(Offset - 1);
689     return Offset - 1;
690   }
691   // The loop trip count is a run-time value. We generate code to subtract
692   // one from the trip count, and update the loop instruction.
693   assert(Loop->getOpcode() == Hexagon::J2_loop0r && "Unexpected instruction");
694   unsigned LoopCount = Loop->getOperand(1).getReg();
695   // Check if we're done with the loop.
696   unsigned LoopEnd = createVR(MF, MVT::i1);
697   MachineInstr *NewCmp = BuildMI(&MBB, DL, get(Hexagon::C2_cmpgtui), LoopEnd).
698     addReg(LoopCount).addImm(1);
699   unsigned NewLoopCount = createVR(MF, MVT::i32);
700   MachineInstr *NewAdd = BuildMI(&MBB, DL, get(Hexagon::A2_addi), NewLoopCount).
701     addReg(LoopCount).addImm(-1);
702   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
703   // Update the previously generated instructions with the new loop counter.
704   for (SmallVectorImpl<MachineInstr *>::iterator I = PrevInsts.begin(),
705          E = PrevInsts.end(); I != E; ++I)
706     (*I)->substituteRegister(LoopCount, NewLoopCount, 0, HRI);
707   PrevInsts.clear();
708   PrevInsts.push_back(NewCmp);
709   PrevInsts.push_back(NewAdd);
710   // Insert the new loop instruction if this is the last time the loop is
711   // decremented.
712   if (Iter == MaxIter)
713     BuildMI(&MBB, DL, get(Hexagon::J2_loop0r)).
714       addMBB(Loop->getOperand(0).getMBB()).addReg(NewLoopCount);
715   // Delete the old loop instruction.
716   if (Iter == 0)
717     Loop->eraseFromParent();
718   Cond.push_back(MachineOperand::CreateImm(Hexagon::J2_jumpf));
719   Cond.push_back(NewCmp->getOperand(0));
720   return NewLoopCount;
721 }
722 
723 bool HexagonInstrInfo::isProfitableToIfCvt(MachineBasicBlock &MBB,
724       unsigned NumCycles, unsigned ExtraPredCycles,
725       BranchProbability Probability) const {
726   return nonDbgBBSize(&MBB) <= 3;
727 }
728 
729 bool HexagonInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
730       unsigned NumTCycles, unsigned ExtraTCycles, MachineBasicBlock &FMBB,
731       unsigned NumFCycles, unsigned ExtraFCycles, BranchProbability Probability)
732       const {
733   return nonDbgBBSize(&TMBB) <= 3 && nonDbgBBSize(&FMBB) <= 3;
734 }
735 
736 bool HexagonInstrInfo::isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
737       unsigned NumInstrs, BranchProbability Probability) const {
738   return NumInstrs <= 4;
739 }
740 
741 void HexagonInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
742                                    MachineBasicBlock::iterator I,
743                                    const DebugLoc &DL, unsigned DestReg,
744                                    unsigned SrcReg, bool KillSrc) const {
745   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
746   unsigned KillFlag = getKillRegState(KillSrc);
747 
748   if (Hexagon::IntRegsRegClass.contains(SrcReg, DestReg)) {
749     BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), DestReg)
750       .addReg(SrcReg, KillFlag);
751     return;
752   }
753   if (Hexagon::DoubleRegsRegClass.contains(SrcReg, DestReg)) {
754     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrp), DestReg)
755       .addReg(SrcReg, KillFlag);
756     return;
757   }
758   if (Hexagon::PredRegsRegClass.contains(SrcReg, DestReg)) {
759     // Map Pd = Ps to Pd = or(Ps, Ps).
760     BuildMI(MBB, I, DL, get(Hexagon::C2_or), DestReg)
761       .addReg(SrcReg).addReg(SrcReg, KillFlag);
762     return;
763   }
764   if (Hexagon::CtrRegsRegClass.contains(DestReg) &&
765       Hexagon::IntRegsRegClass.contains(SrcReg)) {
766     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg)
767       .addReg(SrcReg, KillFlag);
768     return;
769   }
770   if (Hexagon::IntRegsRegClass.contains(DestReg) &&
771       Hexagon::CtrRegsRegClass.contains(SrcReg)) {
772     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrcrr), DestReg)
773       .addReg(SrcReg, KillFlag);
774     return;
775   }
776   if (Hexagon::ModRegsRegClass.contains(DestReg) &&
777       Hexagon::IntRegsRegClass.contains(SrcReg)) {
778     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg)
779       .addReg(SrcReg, KillFlag);
780     return;
781   }
782   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
783       Hexagon::IntRegsRegClass.contains(DestReg)) {
784     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg)
785       .addReg(SrcReg, KillFlag);
786     return;
787   }
788   if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
789       Hexagon::PredRegsRegClass.contains(DestReg)) {
790     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrrp), DestReg)
791       .addReg(SrcReg, KillFlag);
792     return;
793   }
794   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
795       Hexagon::IntRegsRegClass.contains(DestReg)) {
796     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg)
797       .addReg(SrcReg, KillFlag);
798     return;
799   }
800   if (Hexagon::HvxVRRegClass.contains(SrcReg, DestReg)) {
801     BuildMI(MBB, I, DL, get(Hexagon::V6_vassign), DestReg).
802       addReg(SrcReg, KillFlag);
803     return;
804   }
805   if (Hexagon::HvxWRRegClass.contains(SrcReg, DestReg)) {
806     unsigned LoSrc = HRI.getSubReg(SrcReg, Hexagon::vsub_lo);
807     unsigned HiSrc = HRI.getSubReg(SrcReg, Hexagon::vsub_hi);
808     BuildMI(MBB, I, DL, get(Hexagon::V6_vcombine), DestReg)
809       .addReg(HiSrc, KillFlag)
810       .addReg(LoSrc, KillFlag);
811     return;
812   }
813   if (Hexagon::HvxQRRegClass.contains(SrcReg, DestReg)) {
814     BuildMI(MBB, I, DL, get(Hexagon::V6_pred_and), DestReg)
815       .addReg(SrcReg)
816       .addReg(SrcReg, KillFlag);
817     return;
818   }
819   if (Hexagon::HvxQRRegClass.contains(SrcReg) &&
820       Hexagon::HvxVRRegClass.contains(DestReg)) {
821     llvm_unreachable("Unimplemented pred to vec");
822     return;
823   }
824   if (Hexagon::HvxQRRegClass.contains(DestReg) &&
825       Hexagon::HvxVRRegClass.contains(SrcReg)) {
826     llvm_unreachable("Unimplemented vec to pred");
827     return;
828   }
829 
830 #ifndef NDEBUG
831   // Show the invalid registers to ease debugging.
832   dbgs() << "Invalid registers for copy in BB#" << MBB.getNumber()
833          << ": " << PrintReg(DestReg, &HRI)
834          << " = " << PrintReg(SrcReg, &HRI) << '\n';
835 #endif
836   llvm_unreachable("Unimplemented");
837 }
838 
839 void HexagonInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
840       MachineBasicBlock::iterator I, unsigned SrcReg, bool isKill, int FI,
841       const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const {
842   DebugLoc DL = MBB.findDebugLoc(I);
843   MachineFunction &MF = *MBB.getParent();
844   MachineFrameInfo &MFI = MF.getFrameInfo();
845   unsigned SlotAlign = MFI.getObjectAlignment(FI);
846   unsigned RegAlign = TRI->getSpillAlignment(*RC);
847   unsigned KillFlag = getKillRegState(isKill);
848   bool HasAlloca = MFI.hasVarSizedObjects();
849   const HexagonFrameLowering &HFI = *Subtarget.getFrameLowering();
850 
851   MachineMemOperand *MMO = MF.getMachineMemOperand(
852       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
853       MFI.getObjectSize(FI), SlotAlign);
854 
855   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
856     BuildMI(MBB, I, DL, get(Hexagon::S2_storeri_io))
857       .addFrameIndex(FI).addImm(0)
858       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
859   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
860     BuildMI(MBB, I, DL, get(Hexagon::S2_storerd_io))
861       .addFrameIndex(FI).addImm(0)
862       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
863   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
864     BuildMI(MBB, I, DL, get(Hexagon::STriw_pred))
865       .addFrameIndex(FI).addImm(0)
866       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
867   } else if (Hexagon::ModRegsRegClass.hasSubClassEq(RC)) {
868     BuildMI(MBB, I, DL, get(Hexagon::STriw_mod))
869       .addFrameIndex(FI).addImm(0)
870       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
871   } else if (Hexagon::HvxQRRegClass.hasSubClassEq(RC)) {
872     BuildMI(MBB, I, DL, get(Hexagon::PS_vstorerq_ai))
873       .addFrameIndex(FI).addImm(0)
874       .addReg(SrcReg, KillFlag).addMemOperand(MMO);
875   } else if (Hexagon::HvxVRRegClass.hasSubClassEq(RC)) {
876     // If there are variable-sized objects, spills will not be aligned.
877     if (HasAlloca)
878       SlotAlign = HFI.getStackAlignment();
879     unsigned Opc = SlotAlign < RegAlign ? Hexagon::V6_vS32Ub_ai
880                                         : Hexagon::V6_vS32b_ai;
881     MachineMemOperand *MMOA = MF.getMachineMemOperand(
882         MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
883         MFI.getObjectSize(FI), SlotAlign);
884     BuildMI(MBB, I, DL, get(Opc))
885       .addFrameIndex(FI).addImm(0)
886       .addReg(SrcReg, KillFlag).addMemOperand(MMOA);
887   } else if (Hexagon::HvxWRRegClass.hasSubClassEq(RC)) {
888     // If there are variable-sized objects, spills will not be aligned.
889     if (HasAlloca)
890       SlotAlign = HFI.getStackAlignment();
891     unsigned Opc = SlotAlign < RegAlign ? Hexagon::PS_vstorerwu_ai
892                                         : Hexagon::PS_vstorerw_ai;
893     MachineMemOperand *MMOA = MF.getMachineMemOperand(
894         MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
895         MFI.getObjectSize(FI), SlotAlign);
896     BuildMI(MBB, I, DL, get(Opc))
897       .addFrameIndex(FI).addImm(0)
898       .addReg(SrcReg, KillFlag).addMemOperand(MMOA);
899   } else {
900     llvm_unreachable("Unimplemented");
901   }
902 }
903 
904 void HexagonInstrInfo::loadRegFromStackSlot(
905     MachineBasicBlock &MBB, MachineBasicBlock::iterator I, unsigned DestReg,
906     int FI, const TargetRegisterClass *RC,
907     const TargetRegisterInfo *TRI) const {
908   DebugLoc DL = MBB.findDebugLoc(I);
909   MachineFunction &MF = *MBB.getParent();
910   MachineFrameInfo &MFI = MF.getFrameInfo();
911   unsigned SlotAlign = MFI.getObjectAlignment(FI);
912   unsigned RegAlign = TRI->getSpillAlignment(*RC);
913   bool HasAlloca = MFI.hasVarSizedObjects();
914   const HexagonFrameLowering &HFI = *Subtarget.getFrameLowering();
915 
916   MachineMemOperand *MMO = MF.getMachineMemOperand(
917       MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
918       MFI.getObjectSize(FI), SlotAlign);
919 
920   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
921     BuildMI(MBB, I, DL, get(Hexagon::L2_loadri_io), DestReg)
922       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
923   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
924     BuildMI(MBB, I, DL, get(Hexagon::L2_loadrd_io), DestReg)
925       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
926   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
927     BuildMI(MBB, I, DL, get(Hexagon::LDriw_pred), DestReg)
928       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
929   } else if (Hexagon::ModRegsRegClass.hasSubClassEq(RC)) {
930     BuildMI(MBB, I, DL, get(Hexagon::LDriw_mod), DestReg)
931       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
932   } else if (Hexagon::HvxQRRegClass.hasSubClassEq(RC)) {
933     BuildMI(MBB, I, DL, get(Hexagon::PS_vloadrq_ai), DestReg)
934       .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
935   } else if (Hexagon::HvxVRRegClass.hasSubClassEq(RC)) {
936     // If there are variable-sized objects, spills will not be aligned.
937     if (HasAlloca)
938       SlotAlign = HFI.getStackAlignment();
939     unsigned Opc = SlotAlign < RegAlign ? Hexagon::V6_vL32Ub_ai
940                                         : Hexagon::V6_vL32b_ai;
941     MachineMemOperand *MMOA = MF.getMachineMemOperand(
942         MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
943         MFI.getObjectSize(FI), SlotAlign);
944     BuildMI(MBB, I, DL, get(Opc), DestReg)
945       .addFrameIndex(FI).addImm(0).addMemOperand(MMOA);
946   } else if (Hexagon::HvxWRRegClass.hasSubClassEq(RC)) {
947     // If there are variable-sized objects, spills will not be aligned.
948     if (HasAlloca)
949       SlotAlign = HFI.getStackAlignment();
950     unsigned Opc = SlotAlign < RegAlign ? Hexagon::PS_vloadrwu_ai
951                                         : Hexagon::PS_vloadrw_ai;
952     MachineMemOperand *MMOA = MF.getMachineMemOperand(
953         MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
954         MFI.getObjectSize(FI), SlotAlign);
955     BuildMI(MBB, I, DL, get(Opc), DestReg)
956       .addFrameIndex(FI).addImm(0).addMemOperand(MMOA);
957   } else {
958     llvm_unreachable("Can't store this register to stack slot");
959   }
960 }
961 
962 static void getLiveRegsAt(LivePhysRegs &Regs, const MachineInstr &MI) {
963   const MachineBasicBlock &B = *MI.getParent();
964   Regs.addLiveOuts(B);
965   auto E = ++MachineBasicBlock::const_iterator(MI.getIterator()).getReverse();
966   for (auto I = B.rbegin(); I != E; ++I)
967     Regs.stepBackward(*I);
968 }
969 
970 /// expandPostRAPseudo - This function is called for all pseudo instructions
971 /// that remain after register allocation. Many pseudo instructions are
972 /// created to help register allocation. This is the place to convert them
973 /// into real instructions. The target can edit MI in place, or it can insert
974 /// new instructions and erase MI. The function should return true if
975 /// anything was changed.
976 bool HexagonInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
977   MachineBasicBlock &MBB = *MI.getParent();
978   MachineFunction &MF = *MBB.getParent();
979   MachineRegisterInfo &MRI = MF.getRegInfo();
980   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
981   DebugLoc DL = MI.getDebugLoc();
982   unsigned Opc = MI.getOpcode();
983 
984   switch (Opc) {
985     case TargetOpcode::COPY: {
986       MachineOperand &MD = MI.getOperand(0);
987       MachineOperand &MS = MI.getOperand(1);
988       MachineBasicBlock::iterator MBBI = MI.getIterator();
989       if (MD.getReg() != MS.getReg() && !MS.isUndef()) {
990         copyPhysReg(MBB, MI, DL, MD.getReg(), MS.getReg(), MS.isKill());
991         std::prev(MBBI)->copyImplicitOps(*MBB.getParent(), MI);
992       }
993       MBB.erase(MBBI);
994       return true;
995     }
996     case Hexagon::PS_aligna:
997       BuildMI(MBB, MI, DL, get(Hexagon::A2_andir), MI.getOperand(0).getReg())
998           .addReg(HRI.getFrameRegister())
999           .addImm(-MI.getOperand(1).getImm());
1000       MBB.erase(MI);
1001       return true;
1002     case Hexagon::V6_vassignp: {
1003       unsigned SrcReg = MI.getOperand(1).getReg();
1004       unsigned DstReg = MI.getOperand(0).getReg();
1005       unsigned Kill = getKillRegState(MI.getOperand(1).isKill());
1006       BuildMI(MBB, MI, DL, get(Hexagon::V6_vcombine), DstReg)
1007         .addReg(HRI.getSubReg(SrcReg, Hexagon::vsub_hi), Kill)
1008         .addReg(HRI.getSubReg(SrcReg, Hexagon::vsub_lo), Kill);
1009       MBB.erase(MI);
1010       return true;
1011     }
1012     case Hexagon::V6_lo: {
1013       unsigned SrcReg = MI.getOperand(1).getReg();
1014       unsigned DstReg = MI.getOperand(0).getReg();
1015       unsigned SrcSubLo = HRI.getSubReg(SrcReg, Hexagon::vsub_lo);
1016       copyPhysReg(MBB, MI, DL, DstReg, SrcSubLo, MI.getOperand(1).isKill());
1017       MBB.erase(MI);
1018       MRI.clearKillFlags(SrcSubLo);
1019       return true;
1020     }
1021     case Hexagon::V6_hi: {
1022       unsigned SrcReg = MI.getOperand(1).getReg();
1023       unsigned DstReg = MI.getOperand(0).getReg();
1024       unsigned SrcSubHi = HRI.getSubReg(SrcReg, Hexagon::vsub_hi);
1025       copyPhysReg(MBB, MI, DL, DstReg, SrcSubHi, MI.getOperand(1).isKill());
1026       MBB.erase(MI);
1027       MRI.clearKillFlags(SrcSubHi);
1028       return true;
1029     }
1030     case Hexagon::PS_vstorerw_ai:
1031     case Hexagon::PS_vstorerwu_ai: {
1032       bool Aligned = Opc == Hexagon::PS_vstorerw_ai;
1033       unsigned SrcReg = MI.getOperand(2).getReg();
1034       unsigned SrcSubHi = HRI.getSubReg(SrcReg, Hexagon::vsub_hi);
1035       unsigned SrcSubLo = HRI.getSubReg(SrcReg, Hexagon::vsub_lo);
1036       unsigned NewOpc = Aligned ? Hexagon::V6_vS32b_ai : Hexagon::V6_vS32Ub_ai;
1037       unsigned Offset = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1038 
1039       MachineInstr *MI1New =
1040           BuildMI(MBB, MI, DL, get(NewOpc))
1041               .add(MI.getOperand(0))
1042               .addImm(MI.getOperand(1).getImm())
1043               .addReg(SrcSubLo)
1044               .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1045       MI1New->getOperand(0).setIsKill(false);
1046       BuildMI(MBB, MI, DL, get(NewOpc))
1047           .add(MI.getOperand(0))
1048           // The Vectors are indexed in multiples of vector size.
1049           .addImm(MI.getOperand(1).getImm() + Offset)
1050           .addReg(SrcSubHi)
1051           .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1052       MBB.erase(MI);
1053       return true;
1054     }
1055     case Hexagon::PS_vloadrw_ai:
1056     case Hexagon::PS_vloadrwu_ai: {
1057       bool Aligned = Opc == Hexagon::PS_vloadrw_ai;
1058       unsigned DstReg = MI.getOperand(0).getReg();
1059       unsigned NewOpc = Aligned ? Hexagon::V6_vL32b_ai : Hexagon::V6_vL32Ub_ai;
1060       unsigned Offset = HRI.getSpillSize(Hexagon::HvxVRRegClass);
1061 
1062       MachineInstr *MI1New = BuildMI(MBB, MI, DL, get(NewOpc),
1063                                      HRI.getSubReg(DstReg, Hexagon::vsub_lo))
1064               .add(MI.getOperand(1))
1065               .addImm(MI.getOperand(2).getImm())
1066               .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1067       MI1New->getOperand(1).setIsKill(false);
1068       BuildMI(MBB, MI, DL, get(NewOpc), HRI.getSubReg(DstReg, Hexagon::vsub_hi))
1069           .add(MI.getOperand(1))
1070           // The Vectors are indexed in multiples of vector size.
1071           .addImm(MI.getOperand(2).getImm() + Offset)
1072           .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
1073       MBB.erase(MI);
1074       return true;
1075     }
1076     case Hexagon::PS_true: {
1077       unsigned Reg = MI.getOperand(0).getReg();
1078       BuildMI(MBB, MI, DL, get(Hexagon::C2_orn), Reg)
1079         .addReg(Reg, RegState::Undef)
1080         .addReg(Reg, RegState::Undef);
1081       MBB.erase(MI);
1082       return true;
1083     }
1084     case Hexagon::PS_false: {
1085       unsigned Reg = MI.getOperand(0).getReg();
1086       BuildMI(MBB, MI, DL, get(Hexagon::C2_andn), Reg)
1087         .addReg(Reg, RegState::Undef)
1088         .addReg(Reg, RegState::Undef);
1089       MBB.erase(MI);
1090       return true;
1091     }
1092     case Hexagon::PS_vmulw: {
1093       // Expand a 64-bit vector multiply into 2 32-bit scalar multiplies.
1094       unsigned DstReg = MI.getOperand(0).getReg();
1095       unsigned Src1Reg = MI.getOperand(1).getReg();
1096       unsigned Src2Reg = MI.getOperand(2).getReg();
1097       unsigned Src1SubHi = HRI.getSubReg(Src1Reg, Hexagon::isub_hi);
1098       unsigned Src1SubLo = HRI.getSubReg(Src1Reg, Hexagon::isub_lo);
1099       unsigned Src2SubHi = HRI.getSubReg(Src2Reg, Hexagon::isub_hi);
1100       unsigned Src2SubLo = HRI.getSubReg(Src2Reg, Hexagon::isub_lo);
1101       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_mpyi),
1102               HRI.getSubReg(DstReg, Hexagon::isub_hi))
1103           .addReg(Src1SubHi)
1104           .addReg(Src2SubHi);
1105       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_mpyi),
1106               HRI.getSubReg(DstReg, Hexagon::isub_lo))
1107           .addReg(Src1SubLo)
1108           .addReg(Src2SubLo);
1109       MBB.erase(MI);
1110       MRI.clearKillFlags(Src1SubHi);
1111       MRI.clearKillFlags(Src1SubLo);
1112       MRI.clearKillFlags(Src2SubHi);
1113       MRI.clearKillFlags(Src2SubLo);
1114       return true;
1115     }
1116     case Hexagon::PS_vmulw_acc: {
1117       // Expand 64-bit vector multiply with addition into 2 scalar multiplies.
1118       unsigned DstReg = MI.getOperand(0).getReg();
1119       unsigned Src1Reg = MI.getOperand(1).getReg();
1120       unsigned Src2Reg = MI.getOperand(2).getReg();
1121       unsigned Src3Reg = MI.getOperand(3).getReg();
1122       unsigned Src1SubHi = HRI.getSubReg(Src1Reg, Hexagon::isub_hi);
1123       unsigned Src1SubLo = HRI.getSubReg(Src1Reg, Hexagon::isub_lo);
1124       unsigned Src2SubHi = HRI.getSubReg(Src2Reg, Hexagon::isub_hi);
1125       unsigned Src2SubLo = HRI.getSubReg(Src2Reg, Hexagon::isub_lo);
1126       unsigned Src3SubHi = HRI.getSubReg(Src3Reg, Hexagon::isub_hi);
1127       unsigned Src3SubLo = HRI.getSubReg(Src3Reg, Hexagon::isub_lo);
1128       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_maci),
1129               HRI.getSubReg(DstReg, Hexagon::isub_hi))
1130           .addReg(Src1SubHi)
1131           .addReg(Src2SubHi)
1132           .addReg(Src3SubHi);
1133       BuildMI(MBB, MI, MI.getDebugLoc(), get(Hexagon::M2_maci),
1134               HRI.getSubReg(DstReg, Hexagon::isub_lo))
1135           .addReg(Src1SubLo)
1136           .addReg(Src2SubLo)
1137           .addReg(Src3SubLo);
1138       MBB.erase(MI);
1139       MRI.clearKillFlags(Src1SubHi);
1140       MRI.clearKillFlags(Src1SubLo);
1141       MRI.clearKillFlags(Src2SubHi);
1142       MRI.clearKillFlags(Src2SubLo);
1143       MRI.clearKillFlags(Src3SubHi);
1144       MRI.clearKillFlags(Src3SubLo);
1145       return true;
1146     }
1147     case Hexagon::PS_pselect: {
1148       const MachineOperand &Op0 = MI.getOperand(0);
1149       const MachineOperand &Op1 = MI.getOperand(1);
1150       const MachineOperand &Op2 = MI.getOperand(2);
1151       const MachineOperand &Op3 = MI.getOperand(3);
1152       unsigned Rd = Op0.getReg();
1153       unsigned Pu = Op1.getReg();
1154       unsigned Rs = Op2.getReg();
1155       unsigned Rt = Op3.getReg();
1156       DebugLoc DL = MI.getDebugLoc();
1157       unsigned K1 = getKillRegState(Op1.isKill());
1158       unsigned K2 = getKillRegState(Op2.isKill());
1159       unsigned K3 = getKillRegState(Op3.isKill());
1160       if (Rd != Rs)
1161         BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrpt), Rd)
1162           .addReg(Pu, (Rd == Rt) ? K1 : 0)
1163           .addReg(Rs, K2);
1164       if (Rd != Rt)
1165         BuildMI(MBB, MI, DL, get(Hexagon::A2_tfrpf), Rd)
1166           .addReg(Pu, K1)
1167           .addReg(Rt, K3);
1168       MBB.erase(MI);
1169       return true;
1170     }
1171     case Hexagon::PS_vselect: {
1172       const MachineOperand &Op0 = MI.getOperand(0);
1173       const MachineOperand &Op1 = MI.getOperand(1);
1174       const MachineOperand &Op2 = MI.getOperand(2);
1175       const MachineOperand &Op3 = MI.getOperand(3);
1176       LivePhysRegs LiveAtMI(HRI);
1177       getLiveRegsAt(LiveAtMI, MI);
1178       bool IsDestLive = !LiveAtMI.available(MRI, Op0.getReg());
1179       unsigned PReg = Op1.getReg();
1180       assert(Op1.getSubReg() == 0);
1181       unsigned PState = getRegState(Op1);
1182 
1183       if (Op0.getReg() != Op2.getReg()) {
1184         unsigned S = Op0.getReg() != Op3.getReg() ? PState & ~RegState::Kill
1185                                                   : PState;
1186         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vcmov))
1187                      .add(Op0)
1188                      .addReg(PReg, S)
1189                      .add(Op2);
1190         if (IsDestLive)
1191           T.addReg(Op0.getReg(), RegState::Implicit);
1192         IsDestLive = true;
1193       }
1194       if (Op0.getReg() != Op3.getReg()) {
1195         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vncmov))
1196                      .add(Op0)
1197                      .addReg(PReg, PState)
1198                      .add(Op3);
1199         if (IsDestLive)
1200           T.addReg(Op0.getReg(), RegState::Implicit);
1201       }
1202       MBB.erase(MI);
1203       return true;
1204     }
1205     case Hexagon::PS_wselect: {
1206       MachineOperand &Op0 = MI.getOperand(0);
1207       MachineOperand &Op1 = MI.getOperand(1);
1208       MachineOperand &Op2 = MI.getOperand(2);
1209       MachineOperand &Op3 = MI.getOperand(3);
1210       LivePhysRegs LiveAtMI(HRI);
1211       getLiveRegsAt(LiveAtMI, MI);
1212       bool IsDestLive = !LiveAtMI.available(MRI, Op0.getReg());
1213       unsigned PReg = Op1.getReg();
1214       assert(Op1.getSubReg() == 0);
1215       unsigned PState = getRegState(Op1);
1216 
1217       if (Op0.getReg() != Op2.getReg()) {
1218         unsigned S = Op0.getReg() != Op3.getReg() ? PState & ~RegState::Kill
1219                                                   : PState;
1220         unsigned SrcLo = HRI.getSubReg(Op2.getReg(), Hexagon::vsub_lo);
1221         unsigned SrcHi = HRI.getSubReg(Op2.getReg(), Hexagon::vsub_hi);
1222         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vccombine))
1223                      .add(Op0)
1224                      .addReg(PReg, S)
1225                      .add(Op1)
1226                      .addReg(SrcHi)
1227                      .addReg(SrcLo);
1228         if (IsDestLive)
1229           T.addReg(Op0.getReg(), RegState::Implicit);
1230         IsDestLive = true;
1231       }
1232       if (Op0.getReg() != Op3.getReg()) {
1233         unsigned SrcLo = HRI.getSubReg(Op3.getReg(), Hexagon::vsub_lo);
1234         unsigned SrcHi = HRI.getSubReg(Op3.getReg(), Hexagon::vsub_hi);
1235         auto T = BuildMI(MBB, MI, DL, get(Hexagon::V6_vnccombine))
1236                      .add(Op0)
1237                      .addReg(PReg, PState)
1238                      .addReg(SrcHi)
1239                      .addReg(SrcLo);
1240         if (IsDestLive)
1241           T.addReg(Op0.getReg(), RegState::Implicit);
1242       }
1243       MBB.erase(MI);
1244       return true;
1245     }
1246     case Hexagon::PS_tailcall_i:
1247       MI.setDesc(get(Hexagon::J2_jump));
1248       return true;
1249     case Hexagon::PS_tailcall_r:
1250     case Hexagon::PS_jmpret:
1251       MI.setDesc(get(Hexagon::J2_jumpr));
1252       return true;
1253     case Hexagon::PS_jmprett:
1254       MI.setDesc(get(Hexagon::J2_jumprt));
1255       return true;
1256     case Hexagon::PS_jmpretf:
1257       MI.setDesc(get(Hexagon::J2_jumprf));
1258       return true;
1259     case Hexagon::PS_jmprettnewpt:
1260       MI.setDesc(get(Hexagon::J2_jumprtnewpt));
1261       return true;
1262     case Hexagon::PS_jmpretfnewpt:
1263       MI.setDesc(get(Hexagon::J2_jumprfnewpt));
1264       return true;
1265     case Hexagon::PS_jmprettnew:
1266       MI.setDesc(get(Hexagon::J2_jumprtnew));
1267       return true;
1268     case Hexagon::PS_jmpretfnew:
1269       MI.setDesc(get(Hexagon::J2_jumprfnew));
1270       return true;
1271   }
1272 
1273   return false;
1274 }
1275 
1276 // We indicate that we want to reverse the branch by
1277 // inserting the reversed branching opcode.
1278 bool HexagonInstrInfo::reverseBranchCondition(
1279       SmallVectorImpl<MachineOperand> &Cond) const {
1280   if (Cond.empty())
1281     return true;
1282   assert(Cond[0].isImm() && "First entry in the cond vector not imm-val");
1283   unsigned opcode = Cond[0].getImm();
1284   //unsigned temp;
1285   assert(get(opcode).isBranch() && "Should be a branching condition.");
1286   if (isEndLoopN(opcode))
1287     return true;
1288   unsigned NewOpcode = getInvertedPredicatedOpcode(opcode);
1289   Cond[0].setImm(NewOpcode);
1290   return false;
1291 }
1292 
1293 void HexagonInstrInfo::insertNoop(MachineBasicBlock &MBB,
1294       MachineBasicBlock::iterator MI) const {
1295   DebugLoc DL;
1296   BuildMI(MBB, MI, DL, get(Hexagon::A2_nop));
1297 }
1298 
1299 bool HexagonInstrInfo::isPostIncrement(const MachineInstr &MI) const {
1300   return getAddrMode(MI) == HexagonII::PostInc;
1301 }
1302 
1303 // Returns true if an instruction is predicated irrespective of the predicate
1304 // sense. For example, all of the following will return true.
1305 // if (p0) R1 = add(R2, R3)
1306 // if (!p0) R1 = add(R2, R3)
1307 // if (p0.new) R1 = add(R2, R3)
1308 // if (!p0.new) R1 = add(R2, R3)
1309 // Note: New-value stores are not included here as in the current
1310 // implementation, we don't need to check their predicate sense.
1311 bool HexagonInstrInfo::isPredicated(const MachineInstr &MI) const {
1312   const uint64_t F = MI.getDesc().TSFlags;
1313   return (F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask;
1314 }
1315 
1316 bool HexagonInstrInfo::PredicateInstruction(
1317     MachineInstr &MI, ArrayRef<MachineOperand> Cond) const {
1318   if (Cond.empty() || isNewValueJump(Cond[0].getImm()) ||
1319       isEndLoopN(Cond[0].getImm())) {
1320     DEBUG(dbgs() << "\nCannot predicate:"; MI.dump(););
1321     return false;
1322   }
1323   int Opc = MI.getOpcode();
1324   assert (isPredicable(MI) && "Expected predicable instruction");
1325   bool invertJump = predOpcodeHasNot(Cond);
1326 
1327   // We have to predicate MI "in place", i.e. after this function returns,
1328   // MI will need to be transformed into a predicated form. To avoid com-
1329   // plicated manipulations with the operands (handling tied operands,
1330   // etc.), build a new temporary instruction, then overwrite MI with it.
1331 
1332   MachineBasicBlock &B = *MI.getParent();
1333   DebugLoc DL = MI.getDebugLoc();
1334   unsigned PredOpc = getCondOpcode(Opc, invertJump);
1335   MachineInstrBuilder T = BuildMI(B, MI, DL, get(PredOpc));
1336   unsigned NOp = 0, NumOps = MI.getNumOperands();
1337   while (NOp < NumOps) {
1338     MachineOperand &Op = MI.getOperand(NOp);
1339     if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1340       break;
1341     T.add(Op);
1342     NOp++;
1343   }
1344 
1345   unsigned PredReg, PredRegPos, PredRegFlags;
1346   bool GotPredReg = getPredReg(Cond, PredReg, PredRegPos, PredRegFlags);
1347   (void)GotPredReg;
1348   assert(GotPredReg);
1349   T.addReg(PredReg, PredRegFlags);
1350   while (NOp < NumOps)
1351     T.add(MI.getOperand(NOp++));
1352 
1353   MI.setDesc(get(PredOpc));
1354   while (unsigned n = MI.getNumOperands())
1355     MI.RemoveOperand(n-1);
1356   for (unsigned i = 0, n = T->getNumOperands(); i < n; ++i)
1357     MI.addOperand(T->getOperand(i));
1358 
1359   MachineBasicBlock::instr_iterator TI = T->getIterator();
1360   B.erase(TI);
1361 
1362   MachineRegisterInfo &MRI = B.getParent()->getRegInfo();
1363   MRI.clearKillFlags(PredReg);
1364   return true;
1365 }
1366 
1367 bool HexagonInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1368       ArrayRef<MachineOperand> Pred2) const {
1369   // TODO: Fix this
1370   return false;
1371 }
1372 
1373 bool HexagonInstrInfo::DefinesPredicate(MachineInstr &MI,
1374       std::vector<MachineOperand> &Pred) const {
1375   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1376 
1377   for (unsigned oper = 0; oper < MI.getNumOperands(); ++oper) {
1378     MachineOperand MO = MI.getOperand(oper);
1379     if (MO.isReg()) {
1380       if (!MO.isDef())
1381         continue;
1382       const TargetRegisterClass* RC = HRI.getMinimalPhysRegClass(MO.getReg());
1383       if (RC == &Hexagon::PredRegsRegClass) {
1384         Pred.push_back(MO);
1385         return true;
1386       }
1387       continue;
1388     } else if (MO.isRegMask()) {
1389       for (unsigned PR : Hexagon::PredRegsRegClass) {
1390         if (!MI.modifiesRegister(PR, &HRI))
1391           continue;
1392         Pred.push_back(MO);
1393         return true;
1394       }
1395     }
1396   }
1397   return false;
1398 }
1399 
1400 bool HexagonInstrInfo::isPredicable(const MachineInstr &MI) const {
1401   if (!MI.getDesc().isPredicable())
1402     return false;
1403 
1404   if (MI.isCall() || isTailCall(MI)) {
1405     if (!Subtarget.usePredicatedCalls())
1406       return false;
1407   }
1408   return true;
1409 }
1410 
1411 bool HexagonInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1412                                             const MachineBasicBlock *MBB,
1413                                             const MachineFunction &MF) const {
1414   // Debug info is never a scheduling boundary. It's necessary to be explicit
1415   // due to the special treatment of IT instructions below, otherwise a
1416   // dbg_value followed by an IT will result in the IT instruction being
1417   // considered a scheduling hazard, which is wrong. It should be the actual
1418   // instruction preceding the dbg_value instruction(s), just like it is
1419   // when debug info is not present.
1420   if (MI.isDebugValue())
1421     return false;
1422 
1423   // Throwing call is a boundary.
1424   if (MI.isCall()) {
1425     // Don't mess around with no return calls.
1426     if (doesNotReturn(MI))
1427       return true;
1428     // If any of the block's successors is a landing pad, this could be a
1429     // throwing call.
1430     for (auto I : MBB->successors())
1431       if (I->isEHPad())
1432         return true;
1433   }
1434 
1435   // Terminators and labels can't be scheduled around.
1436   if (MI.getDesc().isTerminator() || MI.isPosition())
1437     return true;
1438 
1439   if (MI.isInlineAsm() && !ScheduleInlineAsm)
1440     return true;
1441 
1442   return false;
1443 }
1444 
1445 /// Measure the specified inline asm to determine an approximation of its
1446 /// length.
1447 /// Comments (which run till the next SeparatorString or newline) do not
1448 /// count as an instruction.
1449 /// Any other non-whitespace text is considered an instruction, with
1450 /// multiple instructions separated by SeparatorString or newlines.
1451 /// Variable-length instructions are not handled here; this function
1452 /// may be overloaded in the target code to do that.
1453 /// Hexagon counts the number of ##'s and adjust for that many
1454 /// constant exenders.
1455 unsigned HexagonInstrInfo::getInlineAsmLength(const char *Str,
1456       const MCAsmInfo &MAI) const {
1457   StringRef AStr(Str);
1458   // Count the number of instructions in the asm.
1459   bool atInsnStart = true;
1460   unsigned Length = 0;
1461   for (; *Str; ++Str) {
1462     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
1463                                 strlen(MAI.getSeparatorString())) == 0)
1464       atInsnStart = true;
1465     if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
1466       Length += MAI.getMaxInstLength();
1467       atInsnStart = false;
1468     }
1469     if (atInsnStart && strncmp(Str, MAI.getCommentString().data(),
1470                                MAI.getCommentString().size()) == 0)
1471       atInsnStart = false;
1472   }
1473 
1474   // Add to size number of constant extenders seen * 4.
1475   StringRef Occ("##");
1476   Length += AStr.count(Occ)*4;
1477   return Length;
1478 }
1479 
1480 ScheduleHazardRecognizer*
1481 HexagonInstrInfo::CreateTargetPostRAHazardRecognizer(
1482       const InstrItineraryData *II, const ScheduleDAG *DAG) const {
1483   if (UseDFAHazardRec)
1484     return new HexagonHazardRecognizer(II, this, Subtarget);
1485   return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
1486 }
1487 
1488 /// \brief For a comparison instruction, return the source registers in
1489 /// \p SrcReg and \p SrcReg2 if having two register operands, and the value it
1490 /// compares against in CmpValue. Return true if the comparison instruction
1491 /// can be analyzed.
1492 bool HexagonInstrInfo::analyzeCompare(const MachineInstr &MI, unsigned &SrcReg,
1493                                       unsigned &SrcReg2, int &Mask,
1494                                       int &Value) const {
1495   unsigned Opc = MI.getOpcode();
1496 
1497   // Set mask and the first source register.
1498   switch (Opc) {
1499     case Hexagon::C2_cmpeq:
1500     case Hexagon::C2_cmpeqp:
1501     case Hexagon::C2_cmpgt:
1502     case Hexagon::C2_cmpgtp:
1503     case Hexagon::C2_cmpgtu:
1504     case Hexagon::C2_cmpgtup:
1505     case Hexagon::C4_cmpneq:
1506     case Hexagon::C4_cmplte:
1507     case Hexagon::C4_cmplteu:
1508     case Hexagon::C2_cmpeqi:
1509     case Hexagon::C2_cmpgti:
1510     case Hexagon::C2_cmpgtui:
1511     case Hexagon::C4_cmpneqi:
1512     case Hexagon::C4_cmplteui:
1513     case Hexagon::C4_cmpltei:
1514       SrcReg = MI.getOperand(1).getReg();
1515       Mask = ~0;
1516       break;
1517     case Hexagon::A4_cmpbeq:
1518     case Hexagon::A4_cmpbgt:
1519     case Hexagon::A4_cmpbgtu:
1520     case Hexagon::A4_cmpbeqi:
1521     case Hexagon::A4_cmpbgti:
1522     case Hexagon::A4_cmpbgtui:
1523       SrcReg = MI.getOperand(1).getReg();
1524       Mask = 0xFF;
1525       break;
1526     case Hexagon::A4_cmpheq:
1527     case Hexagon::A4_cmphgt:
1528     case Hexagon::A4_cmphgtu:
1529     case Hexagon::A4_cmpheqi:
1530     case Hexagon::A4_cmphgti:
1531     case Hexagon::A4_cmphgtui:
1532       SrcReg = MI.getOperand(1).getReg();
1533       Mask = 0xFFFF;
1534       break;
1535   }
1536 
1537   // Set the value/second source register.
1538   switch (Opc) {
1539     case Hexagon::C2_cmpeq:
1540     case Hexagon::C2_cmpeqp:
1541     case Hexagon::C2_cmpgt:
1542     case Hexagon::C2_cmpgtp:
1543     case Hexagon::C2_cmpgtu:
1544     case Hexagon::C2_cmpgtup:
1545     case Hexagon::A4_cmpbeq:
1546     case Hexagon::A4_cmpbgt:
1547     case Hexagon::A4_cmpbgtu:
1548     case Hexagon::A4_cmpheq:
1549     case Hexagon::A4_cmphgt:
1550     case Hexagon::A4_cmphgtu:
1551     case Hexagon::C4_cmpneq:
1552     case Hexagon::C4_cmplte:
1553     case Hexagon::C4_cmplteu:
1554       SrcReg2 = MI.getOperand(2).getReg();
1555       return true;
1556 
1557     case Hexagon::C2_cmpeqi:
1558     case Hexagon::C2_cmpgtui:
1559     case Hexagon::C2_cmpgti:
1560     case Hexagon::C4_cmpneqi:
1561     case Hexagon::C4_cmplteui:
1562     case Hexagon::C4_cmpltei:
1563     case Hexagon::A4_cmpbeqi:
1564     case Hexagon::A4_cmpbgti:
1565     case Hexagon::A4_cmpbgtui:
1566     case Hexagon::A4_cmpheqi:
1567     case Hexagon::A4_cmphgti:
1568     case Hexagon::A4_cmphgtui:
1569       SrcReg2 = 0;
1570       Value = MI.getOperand(2).getImm();
1571       return true;
1572   }
1573 
1574   return false;
1575 }
1576 
1577 unsigned HexagonInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1578                                            const MachineInstr &MI,
1579                                            unsigned *PredCost) const {
1580   return getInstrTimingClassLatency(ItinData, MI);
1581 }
1582 
1583 DFAPacketizer *HexagonInstrInfo::CreateTargetScheduleState(
1584     const TargetSubtargetInfo &STI) const {
1585   const InstrItineraryData *II = STI.getInstrItineraryData();
1586   return static_cast<const HexagonSubtarget&>(STI).createDFAPacketizer(II);
1587 }
1588 
1589 // Inspired by this pair:
1590 //  %R13<def> = L2_loadri_io %R29, 136; mem:LD4[FixedStack0]
1591 //  S2_storeri_io %R29, 132, %R1<kill>; flags:  mem:ST4[FixedStack1]
1592 // Currently AA considers the addresses in these instructions to be aliasing.
1593 bool HexagonInstrInfo::areMemAccessesTriviallyDisjoint(
1594     MachineInstr &MIa, MachineInstr &MIb, AliasAnalysis *AA) const {
1595   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
1596       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1597     return false;
1598 
1599   // Instructions that are pure loads, not loads and stores like memops are not
1600   // dependent.
1601   if (MIa.mayLoad() && !isMemOp(MIa) && MIb.mayLoad() && !isMemOp(MIb))
1602     return true;
1603 
1604   // Get the base register in MIa.
1605   unsigned BasePosA, OffsetPosA;
1606   if (!getBaseAndOffsetPosition(MIa, BasePosA, OffsetPosA))
1607     return false;
1608   const MachineOperand &BaseA = MIa.getOperand(BasePosA);
1609   unsigned BaseRegA = BaseA.getReg();
1610   unsigned BaseSubA = BaseA.getSubReg();
1611 
1612   // Get the base register in MIb.
1613   unsigned BasePosB, OffsetPosB;
1614   if (!getBaseAndOffsetPosition(MIb, BasePosB, OffsetPosB))
1615     return false;
1616   const MachineOperand &BaseB = MIb.getOperand(BasePosB);
1617   unsigned BaseRegB = BaseB.getReg();
1618   unsigned BaseSubB = BaseB.getSubReg();
1619 
1620   if (BaseRegA != BaseRegB || BaseSubA != BaseSubB)
1621     return false;
1622 
1623   // Get the access sizes.
1624   unsigned SizeA = getMemAccessSize(MIa);
1625   unsigned SizeB = getMemAccessSize(MIb);
1626 
1627   // Get the offsets. Handle immediates only for now.
1628   const MachineOperand &OffA = MIa.getOperand(OffsetPosA);
1629   const MachineOperand &OffB = MIb.getOperand(OffsetPosB);
1630   if (!MIa.getOperand(OffsetPosA).isImm() ||
1631       !MIb.getOperand(OffsetPosB).isImm())
1632     return false;
1633   int OffsetA = isPostIncrement(MIa) ? 0 : OffA.getImm();
1634   int OffsetB = isPostIncrement(MIb) ? 0 : OffB.getImm();
1635 
1636   // This is a mem access with the same base register and known offsets from it.
1637   // Reason about it.
1638   if (OffsetA > OffsetB) {
1639     uint64_t OffDiff = (uint64_t)((int64_t)OffsetA - (int64_t)OffsetB);
1640     return SizeB <= OffDiff;
1641   }
1642   if (OffsetA < OffsetB) {
1643     uint64_t OffDiff = (uint64_t)((int64_t)OffsetB - (int64_t)OffsetA);
1644     return SizeA <= OffDiff;
1645   }
1646 
1647   return false;
1648 }
1649 
1650 /// If the instruction is an increment of a constant value, return the amount.
1651 bool HexagonInstrInfo::getIncrementValue(const MachineInstr &MI,
1652       int &Value) const {
1653   if (isPostIncrement(MI)) {
1654     unsigned AccessSize;
1655     return getBaseAndOffset(MI, Value, AccessSize);
1656   }
1657   if (MI.getOpcode() == Hexagon::A2_addi) {
1658     Value = MI.getOperand(2).getImm();
1659     return true;
1660   }
1661 
1662   return false;
1663 }
1664 
1665 std::pair<unsigned, unsigned>
1666 HexagonInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
1667   return std::make_pair(TF & ~HexagonII::MO_Bitmasks,
1668                         TF & HexagonII::MO_Bitmasks);
1669 }
1670 
1671 ArrayRef<std::pair<unsigned, const char*>>
1672 HexagonInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
1673   using namespace HexagonII;
1674 
1675   static const std::pair<unsigned, const char*> Flags[] = {
1676     {MO_PCREL,  "hexagon-pcrel"},
1677     {MO_GOT,    "hexagon-got"},
1678     {MO_LO16,   "hexagon-lo16"},
1679     {MO_HI16,   "hexagon-hi16"},
1680     {MO_GPREL,  "hexagon-gprel"},
1681     {MO_GDGOT,  "hexagon-gdgot"},
1682     {MO_GDPLT,  "hexagon-gdplt"},
1683     {MO_IE,     "hexagon-ie"},
1684     {MO_IEGOT,  "hexagon-iegot"},
1685     {MO_TPREL,  "hexagon-tprel"}
1686   };
1687   return makeArrayRef(Flags);
1688 }
1689 
1690 ArrayRef<std::pair<unsigned, const char*>>
1691 HexagonInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
1692   using namespace HexagonII;
1693 
1694   static const std::pair<unsigned, const char*> Flags[] = {
1695     {HMOTF_ConstExtended, "hexagon-ext"}
1696   };
1697   return makeArrayRef(Flags);
1698 }
1699 
1700 unsigned HexagonInstrInfo::createVR(MachineFunction *MF, MVT VT) const {
1701   MachineRegisterInfo &MRI = MF->getRegInfo();
1702   const TargetRegisterClass *TRC;
1703   if (VT == MVT::i1) {
1704     TRC = &Hexagon::PredRegsRegClass;
1705   } else if (VT == MVT::i32 || VT == MVT::f32) {
1706     TRC = &Hexagon::IntRegsRegClass;
1707   } else if (VT == MVT::i64 || VT == MVT::f64) {
1708     TRC = &Hexagon::DoubleRegsRegClass;
1709   } else {
1710     llvm_unreachable("Cannot handle this register class");
1711   }
1712 
1713   unsigned NewReg = MRI.createVirtualRegister(TRC);
1714   return NewReg;
1715 }
1716 
1717 bool HexagonInstrInfo::isAbsoluteSet(const MachineInstr &MI) const {
1718   return (getAddrMode(MI) == HexagonII::AbsoluteSet);
1719 }
1720 
1721 bool HexagonInstrInfo::isAccumulator(const MachineInstr &MI) const {
1722   const uint64_t F = MI.getDesc().TSFlags;
1723   return((F >> HexagonII::AccumulatorPos) & HexagonII::AccumulatorMask);
1724 }
1725 
1726 bool HexagonInstrInfo::isComplex(const MachineInstr &MI) const {
1727   return !isTC1(MI) && !isTC2Early(MI) && !MI.getDesc().mayLoad() &&
1728          !MI.getDesc().mayStore() &&
1729          MI.getDesc().getOpcode() != Hexagon::S2_allocframe &&
1730          MI.getDesc().getOpcode() != Hexagon::L2_deallocframe &&
1731          !isMemOp(MI) && !MI.isBranch() && !MI.isReturn() && !MI.isCall();
1732 }
1733 
1734 // Return true if the instruction is a compund branch instruction.
1735 bool HexagonInstrInfo::isCompoundBranchInstr(const MachineInstr &MI) const {
1736   return getType(MI) == HexagonII::TypeCJ && MI.isBranch();
1737 }
1738 
1739 // TODO: In order to have isExtendable for fpimm/f32Ext, we need to handle
1740 // isFPImm and later getFPImm as well.
1741 bool HexagonInstrInfo::isConstExtended(const MachineInstr &MI) const {
1742   const uint64_t F = MI.getDesc().TSFlags;
1743   unsigned isExtended = (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
1744   if (isExtended) // Instruction must be extended.
1745     return true;
1746 
1747   unsigned isExtendable =
1748     (F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask;
1749   if (!isExtendable)
1750     return false;
1751 
1752   if (MI.isCall())
1753     return false;
1754 
1755   short ExtOpNum = getCExtOpNum(MI);
1756   const MachineOperand &MO = MI.getOperand(ExtOpNum);
1757   // Use MO operand flags to determine if MO
1758   // has the HMOTF_ConstExtended flag set.
1759   if (MO.getTargetFlags() & HexagonII::HMOTF_ConstExtended)
1760     return true;
1761   // If this is a Machine BB address we are talking about, and it is
1762   // not marked as extended, say so.
1763   if (MO.isMBB())
1764     return false;
1765 
1766   // We could be using an instruction with an extendable immediate and shoehorn
1767   // a global address into it. If it is a global address it will be constant
1768   // extended. We do this for COMBINE.
1769   if (MO.isGlobal() || MO.isSymbol() || MO.isBlockAddress() ||
1770       MO.isJTI() || MO.isCPI() || MO.isFPImm())
1771     return true;
1772 
1773   // If the extendable operand is not 'Immediate' type, the instruction should
1774   // have 'isExtended' flag set.
1775   assert(MO.isImm() && "Extendable operand must be Immediate type");
1776 
1777   int MinValue = getMinValue(MI);
1778   int MaxValue = getMaxValue(MI);
1779   int ImmValue = MO.getImm();
1780 
1781   return (ImmValue < MinValue || ImmValue > MaxValue);
1782 }
1783 
1784 bool HexagonInstrInfo::isDeallocRet(const MachineInstr &MI) const {
1785   switch (MI.getOpcode()) {
1786   case Hexagon::L4_return:
1787   case Hexagon::L4_return_t:
1788   case Hexagon::L4_return_f:
1789   case Hexagon::L4_return_tnew_pnt:
1790   case Hexagon::L4_return_fnew_pnt:
1791   case Hexagon::L4_return_tnew_pt:
1792   case Hexagon::L4_return_fnew_pt:
1793     return true;
1794   }
1795   return false;
1796 }
1797 
1798 // Return true when ConsMI uses a register defined by ProdMI.
1799 bool HexagonInstrInfo::isDependent(const MachineInstr &ProdMI,
1800       const MachineInstr &ConsMI) const {
1801   if (!ProdMI.getDesc().getNumDefs())
1802     return false;
1803   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
1804 
1805   SmallVector<unsigned, 4> DefsA;
1806   SmallVector<unsigned, 4> DefsB;
1807   SmallVector<unsigned, 8> UsesA;
1808   SmallVector<unsigned, 8> UsesB;
1809 
1810   parseOperands(ProdMI, DefsA, UsesA);
1811   parseOperands(ConsMI, DefsB, UsesB);
1812 
1813   for (auto &RegA : DefsA)
1814     for (auto &RegB : UsesB) {
1815       // True data dependency.
1816       if (RegA == RegB)
1817         return true;
1818 
1819       if (TargetRegisterInfo::isPhysicalRegister(RegA))
1820         for (MCSubRegIterator SubRegs(RegA, &HRI); SubRegs.isValid(); ++SubRegs)
1821           if (RegB == *SubRegs)
1822             return true;
1823 
1824       if (TargetRegisterInfo::isPhysicalRegister(RegB))
1825         for (MCSubRegIterator SubRegs(RegB, &HRI); SubRegs.isValid(); ++SubRegs)
1826           if (RegA == *SubRegs)
1827             return true;
1828     }
1829 
1830   return false;
1831 }
1832 
1833 // Returns true if the instruction is alread a .cur.
1834 bool HexagonInstrInfo::isDotCurInst(const MachineInstr &MI) const {
1835   switch (MI.getOpcode()) {
1836   case Hexagon::V6_vL32b_cur_pi:
1837   case Hexagon::V6_vL32b_cur_ai:
1838     return true;
1839   }
1840   return false;
1841 }
1842 
1843 // Returns true, if any one of the operands is a dot new
1844 // insn, whether it is predicated dot new or register dot new.
1845 bool HexagonInstrInfo::isDotNewInst(const MachineInstr &MI) const {
1846   if (isNewValueInst(MI) || (isPredicated(MI) && isPredicatedNew(MI)))
1847     return true;
1848 
1849   return false;
1850 }
1851 
1852 /// Symmetrical. See if these two instructions are fit for duplex pair.
1853 bool HexagonInstrInfo::isDuplexPair(const MachineInstr &MIa,
1854       const MachineInstr &MIb) const {
1855   HexagonII::SubInstructionGroup MIaG = getDuplexCandidateGroup(MIa);
1856   HexagonII::SubInstructionGroup MIbG = getDuplexCandidateGroup(MIb);
1857   return (isDuplexPairMatch(MIaG, MIbG) || isDuplexPairMatch(MIbG, MIaG));
1858 }
1859 
1860 bool HexagonInstrInfo::isEarlySourceInstr(const MachineInstr &MI) const {
1861   if (MI.mayLoad() || MI.mayStore() || MI.isCompare())
1862     return true;
1863 
1864   // Multiply
1865   unsigned SchedClass = MI.getDesc().getSchedClass();
1866   return is_TC4x(SchedClass) || is_TC3x(SchedClass);
1867 }
1868 
1869 bool HexagonInstrInfo::isEndLoopN(unsigned Opcode) const {
1870   return (Opcode == Hexagon::ENDLOOP0 ||
1871           Opcode == Hexagon::ENDLOOP1);
1872 }
1873 
1874 bool HexagonInstrInfo::isExpr(unsigned OpType) const {
1875   switch(OpType) {
1876   case MachineOperand::MO_MachineBasicBlock:
1877   case MachineOperand::MO_GlobalAddress:
1878   case MachineOperand::MO_ExternalSymbol:
1879   case MachineOperand::MO_JumpTableIndex:
1880   case MachineOperand::MO_ConstantPoolIndex:
1881   case MachineOperand::MO_BlockAddress:
1882     return true;
1883   default:
1884     return false;
1885   }
1886 }
1887 
1888 bool HexagonInstrInfo::isExtendable(const MachineInstr &MI) const {
1889   const MCInstrDesc &MID = MI.getDesc();
1890   const uint64_t F = MID.TSFlags;
1891   if ((F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask)
1892     return true;
1893 
1894   // TODO: This is largely obsolete now. Will need to be removed
1895   // in consecutive patches.
1896   switch (MI.getOpcode()) {
1897     // PS_fi and PS_fia remain special cases.
1898     case Hexagon::PS_fi:
1899     case Hexagon::PS_fia:
1900       return true;
1901     default:
1902       return false;
1903   }
1904   return  false;
1905 }
1906 
1907 // This returns true in two cases:
1908 // - The OP code itself indicates that this is an extended instruction.
1909 // - One of MOs has been marked with HMOTF_ConstExtended flag.
1910 bool HexagonInstrInfo::isExtended(const MachineInstr &MI) const {
1911   // First check if this is permanently extended op code.
1912   const uint64_t F = MI.getDesc().TSFlags;
1913   if ((F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask)
1914     return true;
1915   // Use MO operand flags to determine if one of MI's operands
1916   // has HMOTF_ConstExtended flag set.
1917   for (const MachineOperand &MO : MI.operands())
1918     if (MO.getTargetFlags() & HexagonII::HMOTF_ConstExtended)
1919       return true;
1920   return  false;
1921 }
1922 
1923 bool HexagonInstrInfo::isFloat(const MachineInstr &MI) const {
1924   unsigned Opcode = MI.getOpcode();
1925   const uint64_t F = get(Opcode).TSFlags;
1926   return (F >> HexagonII::FPPos) & HexagonII::FPMask;
1927 }
1928 
1929 // No V60 HVX VMEM with A_INDIRECT.
1930 bool HexagonInstrInfo::isHVXMemWithAIndirect(const MachineInstr &I,
1931       const MachineInstr &J) const {
1932   if (!isHVXVec(I))
1933     return false;
1934   if (!I.mayLoad() && !I.mayStore())
1935     return false;
1936   return J.isIndirectBranch() || isIndirectCall(J) || isIndirectL4Return(J);
1937 }
1938 
1939 bool HexagonInstrInfo::isIndirectCall(const MachineInstr &MI) const {
1940   switch (MI.getOpcode()) {
1941   case Hexagon::J2_callr:
1942   case Hexagon::J2_callrf:
1943   case Hexagon::J2_callrt:
1944   case Hexagon::PS_call_nr:
1945     return true;
1946   }
1947   return false;
1948 }
1949 
1950 bool HexagonInstrInfo::isIndirectL4Return(const MachineInstr &MI) const {
1951   switch (MI.getOpcode()) {
1952   case Hexagon::L4_return:
1953   case Hexagon::L4_return_t:
1954   case Hexagon::L4_return_f:
1955   case Hexagon::L4_return_fnew_pnt:
1956   case Hexagon::L4_return_fnew_pt:
1957   case Hexagon::L4_return_tnew_pnt:
1958   case Hexagon::L4_return_tnew_pt:
1959     return true;
1960   }
1961   return false;
1962 }
1963 
1964 bool HexagonInstrInfo::isJumpR(const MachineInstr &MI) const {
1965   switch (MI.getOpcode()) {
1966   case Hexagon::J2_jumpr:
1967   case Hexagon::J2_jumprt:
1968   case Hexagon::J2_jumprf:
1969   case Hexagon::J2_jumprtnewpt:
1970   case Hexagon::J2_jumprfnewpt:
1971   case Hexagon::J2_jumprtnew:
1972   case Hexagon::J2_jumprfnew:
1973     return true;
1974   }
1975   return false;
1976 }
1977 
1978 // Return true if a given MI can accommodate given offset.
1979 // Use abs estimate as oppose to the exact number.
1980 // TODO: This will need to be changed to use MC level
1981 // definition of instruction extendable field size.
1982 bool HexagonInstrInfo::isJumpWithinBranchRange(const MachineInstr &MI,
1983       unsigned offset) const {
1984   // This selection of jump instructions matches to that what
1985   // analyzeBranch can parse, plus NVJ.
1986   if (isNewValueJump(MI)) // r9:2
1987     return isInt<11>(offset);
1988 
1989   switch (MI.getOpcode()) {
1990   // Still missing Jump to address condition on register value.
1991   default:
1992     return false;
1993   case Hexagon::J2_jump: // bits<24> dst; // r22:2
1994   case Hexagon::J2_call:
1995   case Hexagon::PS_call_nr:
1996     return isInt<24>(offset);
1997   case Hexagon::J2_jumpt: //bits<17> dst; // r15:2
1998   case Hexagon::J2_jumpf:
1999   case Hexagon::J2_jumptnew:
2000   case Hexagon::J2_jumptnewpt:
2001   case Hexagon::J2_jumpfnew:
2002   case Hexagon::J2_jumpfnewpt:
2003   case Hexagon::J2_callt:
2004   case Hexagon::J2_callf:
2005     return isInt<17>(offset);
2006   case Hexagon::J2_loop0i:
2007   case Hexagon::J2_loop0iext:
2008   case Hexagon::J2_loop0r:
2009   case Hexagon::J2_loop0rext:
2010   case Hexagon::J2_loop1i:
2011   case Hexagon::J2_loop1iext:
2012   case Hexagon::J2_loop1r:
2013   case Hexagon::J2_loop1rext:
2014     return isInt<9>(offset);
2015   // TODO: Add all the compound branches here. Can we do this in Relation model?
2016   case Hexagon::J4_cmpeqi_tp0_jump_nt:
2017   case Hexagon::J4_cmpeqi_tp1_jump_nt:
2018     return isInt<11>(offset);
2019   }
2020 }
2021 
2022 bool HexagonInstrInfo::isLateInstrFeedsEarlyInstr(const MachineInstr &LRMI,
2023       const MachineInstr &ESMI) const {
2024   bool isLate = isLateResultInstr(LRMI);
2025   bool isEarly = isEarlySourceInstr(ESMI);
2026 
2027   DEBUG(dbgs() << "V60" <<  (isLate ? "-LR  " : " --  "));
2028   DEBUG(LRMI.dump());
2029   DEBUG(dbgs() << "V60" <<  (isEarly ? "-ES  " : " --  "));
2030   DEBUG(ESMI.dump());
2031 
2032   if (isLate && isEarly) {
2033     DEBUG(dbgs() << "++Is Late Result feeding Early Source\n");
2034     return true;
2035   }
2036 
2037   return false;
2038 }
2039 
2040 bool HexagonInstrInfo::isLateResultInstr(const MachineInstr &MI) const {
2041   switch (MI.getOpcode()) {
2042   case TargetOpcode::EXTRACT_SUBREG:
2043   case TargetOpcode::INSERT_SUBREG:
2044   case TargetOpcode::SUBREG_TO_REG:
2045   case TargetOpcode::REG_SEQUENCE:
2046   case TargetOpcode::IMPLICIT_DEF:
2047   case TargetOpcode::COPY:
2048   case TargetOpcode::INLINEASM:
2049   case TargetOpcode::PHI:
2050     return false;
2051   default:
2052     break;
2053   }
2054 
2055   unsigned SchedClass = MI.getDesc().getSchedClass();
2056   return !is_TC1(SchedClass);
2057 }
2058 
2059 bool HexagonInstrInfo::isLateSourceInstr(const MachineInstr &MI) const {
2060   // Instructions with iclass A_CVI_VX and attribute A_CVI_LATE uses a multiply
2061   // resource, but all operands can be received late like an ALU instruction.
2062   return getType(MI) == HexagonII::TypeCVI_VX_LATE;
2063 }
2064 
2065 bool HexagonInstrInfo::isLoopN(const MachineInstr &MI) const {
2066   unsigned Opcode = MI.getOpcode();
2067   return Opcode == Hexagon::J2_loop0i    ||
2068          Opcode == Hexagon::J2_loop0r    ||
2069          Opcode == Hexagon::J2_loop0iext ||
2070          Opcode == Hexagon::J2_loop0rext ||
2071          Opcode == Hexagon::J2_loop1i    ||
2072          Opcode == Hexagon::J2_loop1r    ||
2073          Opcode == Hexagon::J2_loop1iext ||
2074          Opcode == Hexagon::J2_loop1rext;
2075 }
2076 
2077 bool HexagonInstrInfo::isMemOp(const MachineInstr &MI) const {
2078   switch (MI.getOpcode()) {
2079     default: return false;
2080     case Hexagon::L4_iadd_memopw_io:
2081     case Hexagon::L4_isub_memopw_io:
2082     case Hexagon::L4_add_memopw_io:
2083     case Hexagon::L4_sub_memopw_io:
2084     case Hexagon::L4_and_memopw_io:
2085     case Hexagon::L4_or_memopw_io:
2086     case Hexagon::L4_iadd_memoph_io:
2087     case Hexagon::L4_isub_memoph_io:
2088     case Hexagon::L4_add_memoph_io:
2089     case Hexagon::L4_sub_memoph_io:
2090     case Hexagon::L4_and_memoph_io:
2091     case Hexagon::L4_or_memoph_io:
2092     case Hexagon::L4_iadd_memopb_io:
2093     case Hexagon::L4_isub_memopb_io:
2094     case Hexagon::L4_add_memopb_io:
2095     case Hexagon::L4_sub_memopb_io:
2096     case Hexagon::L4_and_memopb_io:
2097     case Hexagon::L4_or_memopb_io:
2098     case Hexagon::L4_ior_memopb_io:
2099     case Hexagon::L4_ior_memoph_io:
2100     case Hexagon::L4_ior_memopw_io:
2101     case Hexagon::L4_iand_memopb_io:
2102     case Hexagon::L4_iand_memoph_io:
2103     case Hexagon::L4_iand_memopw_io:
2104     return true;
2105   }
2106   return false;
2107 }
2108 
2109 bool HexagonInstrInfo::isNewValue(const MachineInstr &MI) const {
2110   const uint64_t F = MI.getDesc().TSFlags;
2111   return (F >> HexagonII::NewValuePos) & HexagonII::NewValueMask;
2112 }
2113 
2114 bool HexagonInstrInfo::isNewValue(unsigned Opcode) const {
2115   const uint64_t F = get(Opcode).TSFlags;
2116   return (F >> HexagonII::NewValuePos) & HexagonII::NewValueMask;
2117 }
2118 
2119 bool HexagonInstrInfo::isNewValueInst(const MachineInstr &MI) const {
2120   return isNewValueJump(MI) || isNewValueStore(MI);
2121 }
2122 
2123 bool HexagonInstrInfo::isNewValueJump(const MachineInstr &MI) const {
2124   return isNewValue(MI) && MI.isBranch();
2125 }
2126 
2127 bool HexagonInstrInfo::isNewValueJump(unsigned Opcode) const {
2128   return isNewValue(Opcode) && get(Opcode).isBranch() && isPredicated(Opcode);
2129 }
2130 
2131 bool HexagonInstrInfo::isNewValueStore(const MachineInstr &MI) const {
2132   const uint64_t F = MI.getDesc().TSFlags;
2133   return (F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask;
2134 }
2135 
2136 bool HexagonInstrInfo::isNewValueStore(unsigned Opcode) const {
2137   const uint64_t F = get(Opcode).TSFlags;
2138   return (F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask;
2139 }
2140 
2141 // Returns true if a particular operand is extendable for an instruction.
2142 bool HexagonInstrInfo::isOperandExtended(const MachineInstr &MI,
2143     unsigned OperandNum) const {
2144   const uint64_t F = MI.getDesc().TSFlags;
2145   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask)
2146           == OperandNum;
2147 }
2148 
2149 bool HexagonInstrInfo::isPredicatedNew(const MachineInstr &MI) const {
2150   const uint64_t F = MI.getDesc().TSFlags;
2151   assert(isPredicated(MI));
2152   return (F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask;
2153 }
2154 
2155 bool HexagonInstrInfo::isPredicatedNew(unsigned Opcode) const {
2156   const uint64_t F = get(Opcode).TSFlags;
2157   assert(isPredicated(Opcode));
2158   return (F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask;
2159 }
2160 
2161 bool HexagonInstrInfo::isPredicatedTrue(const MachineInstr &MI) const {
2162   const uint64_t F = MI.getDesc().TSFlags;
2163   return !((F >> HexagonII::PredicatedFalsePos) &
2164            HexagonII::PredicatedFalseMask);
2165 }
2166 
2167 bool HexagonInstrInfo::isPredicatedTrue(unsigned Opcode) const {
2168   const uint64_t F = get(Opcode).TSFlags;
2169   // Make sure that the instruction is predicated.
2170   assert((F>> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
2171   return !((F >> HexagonII::PredicatedFalsePos) &
2172            HexagonII::PredicatedFalseMask);
2173 }
2174 
2175 bool HexagonInstrInfo::isPredicated(unsigned Opcode) const {
2176   const uint64_t F = get(Opcode).TSFlags;
2177   return (F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask;
2178 }
2179 
2180 bool HexagonInstrInfo::isPredicateLate(unsigned Opcode) const {
2181   const uint64_t F = get(Opcode).TSFlags;
2182   return ~(F >> HexagonII::PredicateLatePos) & HexagonII::PredicateLateMask;
2183 }
2184 
2185 bool HexagonInstrInfo::isPredictedTaken(unsigned Opcode) const {
2186   const uint64_t F = get(Opcode).TSFlags;
2187   assert(get(Opcode).isBranch() &&
2188          (isPredicatedNew(Opcode) || isNewValue(Opcode)));
2189   return (F >> HexagonII::TakenPos) & HexagonII::TakenMask;
2190 }
2191 
2192 bool HexagonInstrInfo::isSaveCalleeSavedRegsCall(const MachineInstr &MI) const {
2193   return MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4 ||
2194          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_EXT ||
2195          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_PIC ||
2196          MI.getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4_EXT_PIC;
2197 }
2198 
2199 bool HexagonInstrInfo::isSignExtendingLoad(const MachineInstr &MI) const {
2200   switch (MI.getOpcode()) {
2201   // Byte
2202   case Hexagon::L2_loadrb_io:
2203   case Hexagon::L4_loadrb_ur:
2204   case Hexagon::L4_loadrb_ap:
2205   case Hexagon::L2_loadrb_pr:
2206   case Hexagon::L2_loadrb_pbr:
2207   case Hexagon::L2_loadrb_pi:
2208   case Hexagon::L2_loadrb_pci:
2209   case Hexagon::L2_loadrb_pcr:
2210   case Hexagon::L2_loadbsw2_io:
2211   case Hexagon::L4_loadbsw2_ur:
2212   case Hexagon::L4_loadbsw2_ap:
2213   case Hexagon::L2_loadbsw2_pr:
2214   case Hexagon::L2_loadbsw2_pbr:
2215   case Hexagon::L2_loadbsw2_pi:
2216   case Hexagon::L2_loadbsw2_pci:
2217   case Hexagon::L2_loadbsw2_pcr:
2218   case Hexagon::L2_loadbsw4_io:
2219   case Hexagon::L4_loadbsw4_ur:
2220   case Hexagon::L4_loadbsw4_ap:
2221   case Hexagon::L2_loadbsw4_pr:
2222   case Hexagon::L2_loadbsw4_pbr:
2223   case Hexagon::L2_loadbsw4_pi:
2224   case Hexagon::L2_loadbsw4_pci:
2225   case Hexagon::L2_loadbsw4_pcr:
2226   case Hexagon::L4_loadrb_rr:
2227   case Hexagon::L2_ploadrbt_io:
2228   case Hexagon::L2_ploadrbt_pi:
2229   case Hexagon::L2_ploadrbf_io:
2230   case Hexagon::L2_ploadrbf_pi:
2231   case Hexagon::L2_ploadrbtnew_io:
2232   case Hexagon::L2_ploadrbfnew_io:
2233   case Hexagon::L4_ploadrbt_rr:
2234   case Hexagon::L4_ploadrbf_rr:
2235   case Hexagon::L4_ploadrbtnew_rr:
2236   case Hexagon::L4_ploadrbfnew_rr:
2237   case Hexagon::L2_ploadrbtnew_pi:
2238   case Hexagon::L2_ploadrbfnew_pi:
2239   case Hexagon::L4_ploadrbt_abs:
2240   case Hexagon::L4_ploadrbf_abs:
2241   case Hexagon::L4_ploadrbtnew_abs:
2242   case Hexagon::L4_ploadrbfnew_abs:
2243   case Hexagon::L2_loadrbgp:
2244   // Half
2245   case Hexagon::L2_loadrh_io:
2246   case Hexagon::L4_loadrh_ur:
2247   case Hexagon::L4_loadrh_ap:
2248   case Hexagon::L2_loadrh_pr:
2249   case Hexagon::L2_loadrh_pbr:
2250   case Hexagon::L2_loadrh_pi:
2251   case Hexagon::L2_loadrh_pci:
2252   case Hexagon::L2_loadrh_pcr:
2253   case Hexagon::L4_loadrh_rr:
2254   case Hexagon::L2_ploadrht_io:
2255   case Hexagon::L2_ploadrht_pi:
2256   case Hexagon::L2_ploadrhf_io:
2257   case Hexagon::L2_ploadrhf_pi:
2258   case Hexagon::L2_ploadrhtnew_io:
2259   case Hexagon::L2_ploadrhfnew_io:
2260   case Hexagon::L4_ploadrht_rr:
2261   case Hexagon::L4_ploadrhf_rr:
2262   case Hexagon::L4_ploadrhtnew_rr:
2263   case Hexagon::L4_ploadrhfnew_rr:
2264   case Hexagon::L2_ploadrhtnew_pi:
2265   case Hexagon::L2_ploadrhfnew_pi:
2266   case Hexagon::L4_ploadrht_abs:
2267   case Hexagon::L4_ploadrhf_abs:
2268   case Hexagon::L4_ploadrhtnew_abs:
2269   case Hexagon::L4_ploadrhfnew_abs:
2270   case Hexagon::L2_loadrhgp:
2271     return true;
2272   default:
2273     return false;
2274   }
2275 }
2276 
2277 bool HexagonInstrInfo::isSolo(const MachineInstr &MI) const {
2278   const uint64_t F = MI.getDesc().TSFlags;
2279   return (F >> HexagonII::SoloPos) & HexagonII::SoloMask;
2280 }
2281 
2282 bool HexagonInstrInfo::isSpillPredRegOp(const MachineInstr &MI) const {
2283   switch (MI.getOpcode()) {
2284   case Hexagon::STriw_pred:
2285   case Hexagon::LDriw_pred:
2286     return true;
2287   default:
2288     return false;
2289   }
2290 }
2291 
2292 bool HexagonInstrInfo::isTailCall(const MachineInstr &MI) const {
2293   if (!MI.isBranch())
2294     return false;
2295 
2296   for (auto &Op : MI.operands())
2297     if (Op.isGlobal() || Op.isSymbol())
2298       return true;
2299   return false;
2300 }
2301 
2302 // Returns true when SU has a timing class TC1.
2303 bool HexagonInstrInfo::isTC1(const MachineInstr &MI) const {
2304   unsigned SchedClass = MI.getDesc().getSchedClass();
2305   return is_TC1(SchedClass);
2306 }
2307 
2308 bool HexagonInstrInfo::isTC2(const MachineInstr &MI) const {
2309   unsigned SchedClass = MI.getDesc().getSchedClass();
2310   return is_TC2(SchedClass);
2311 }
2312 
2313 bool HexagonInstrInfo::isTC2Early(const MachineInstr &MI) const {
2314   unsigned SchedClass = MI.getDesc().getSchedClass();
2315   return is_TC2early(SchedClass);
2316 }
2317 
2318 bool HexagonInstrInfo::isTC4x(const MachineInstr &MI) const {
2319   unsigned SchedClass = MI.getDesc().getSchedClass();
2320   return is_TC4x(SchedClass);
2321 }
2322 
2323 // Schedule this ASAP.
2324 bool HexagonInstrInfo::isToBeScheduledASAP(const MachineInstr &MI1,
2325       const MachineInstr &MI2) const {
2326   if (mayBeCurLoad(MI1)) {
2327     // if (result of SU is used in Next) return true;
2328     unsigned DstReg = MI1.getOperand(0).getReg();
2329     int N = MI2.getNumOperands();
2330     for (int I = 0; I < N; I++)
2331       if (MI2.getOperand(I).isReg() && DstReg == MI2.getOperand(I).getReg())
2332         return true;
2333   }
2334   if (mayBeNewStore(MI2))
2335     if (MI2.getOpcode() == Hexagon::V6_vS32b_pi)
2336       if (MI1.getOperand(0).isReg() && MI2.getOperand(3).isReg() &&
2337           MI1.getOperand(0).getReg() == MI2.getOperand(3).getReg())
2338         return true;
2339   return false;
2340 }
2341 
2342 bool HexagonInstrInfo::isHVXVec(const MachineInstr &MI) const {
2343   const uint64_t V = getType(MI);
2344   return HexagonII::TypeCVI_FIRST <= V && V <= HexagonII::TypeCVI_LAST;
2345 }
2346 
2347 // Check if the Offset is a valid auto-inc imm by Load/Store Type.
2348 bool HexagonInstrInfo::isValidAutoIncImm(const EVT VT, int Offset) const {
2349   int Size = VT.getSizeInBits() / 8;
2350   if (Offset % Size != 0)
2351     return false;
2352   int Count = Offset / Size;
2353 
2354   switch (VT.getSimpleVT().SimpleTy) {
2355     // For scalars the auto-inc is s4
2356     case MVT::i8:
2357     case MVT::i16:
2358     case MVT::i32:
2359     case MVT::i64:
2360       return isInt<4>(Count);
2361     // For HVX vectors the auto-inc is s3
2362     case MVT::v64i8:
2363     case MVT::v32i16:
2364     case MVT::v16i32:
2365     case MVT::v8i64:
2366     case MVT::v128i8:
2367     case MVT::v64i16:
2368     case MVT::v32i32:
2369     case MVT::v16i64:
2370       return isInt<3>(Count);
2371     default:
2372       break;
2373   }
2374 
2375   llvm_unreachable("Not an valid type!");
2376 }
2377 
2378 bool HexagonInstrInfo::isValidOffset(unsigned Opcode, int Offset,
2379       const TargetRegisterInfo *TRI, bool Extend) const {
2380   // This function is to check whether the "Offset" is in the correct range of
2381   // the given "Opcode". If "Offset" is not in the correct range, "A2_addi" is
2382   // inserted to calculate the final address. Due to this reason, the function
2383   // assumes that the "Offset" has correct alignment.
2384   // We used to assert if the offset was not properly aligned, however,
2385   // there are cases where a misaligned pointer recast can cause this
2386   // problem, and we need to allow for it. The front end warns of such
2387   // misaligns with respect to load size.
2388   switch (Opcode) {
2389   case Hexagon::PS_vstorerq_ai:
2390   case Hexagon::PS_vstorerw_ai:
2391   case Hexagon::PS_vstorerw_nt_ai:
2392   case Hexagon::PS_vloadrq_ai:
2393   case Hexagon::PS_vloadrw_ai:
2394   case Hexagon::PS_vloadrw_nt_ai:
2395   case Hexagon::V6_vL32b_ai:
2396   case Hexagon::V6_vS32b_ai:
2397   case Hexagon::V6_vL32b_nt_ai:
2398   case Hexagon::V6_vS32b_nt_ai:
2399   case Hexagon::V6_vL32Ub_ai:
2400   case Hexagon::V6_vS32Ub_ai: {
2401     unsigned VectorSize = TRI->getSpillSize(Hexagon::HvxVRRegClass);
2402     assert(isPowerOf2_32(VectorSize));
2403     if (Offset & (VectorSize-1))
2404       return false;
2405     return isInt<4>(Offset >> Log2_32(VectorSize));
2406   }
2407 
2408   case Hexagon::J2_loop0i:
2409   case Hexagon::J2_loop1i:
2410     return isUInt<10>(Offset);
2411 
2412   case Hexagon::S4_storeirb_io:
2413   case Hexagon::S4_storeirbt_io:
2414   case Hexagon::S4_storeirbf_io:
2415     return isUInt<6>(Offset);
2416 
2417   case Hexagon::S4_storeirh_io:
2418   case Hexagon::S4_storeirht_io:
2419   case Hexagon::S4_storeirhf_io:
2420     return isShiftedUInt<6,1>(Offset);
2421 
2422   case Hexagon::S4_storeiri_io:
2423   case Hexagon::S4_storeirit_io:
2424   case Hexagon::S4_storeirif_io:
2425     return isShiftedUInt<6,2>(Offset);
2426   }
2427 
2428   if (Extend)
2429     return true;
2430 
2431   switch (Opcode) {
2432   case Hexagon::L2_loadri_io:
2433   case Hexagon::S2_storeri_io:
2434     return (Offset >= Hexagon_MEMW_OFFSET_MIN) &&
2435       (Offset <= Hexagon_MEMW_OFFSET_MAX);
2436 
2437   case Hexagon::L2_loadrd_io:
2438   case Hexagon::S2_storerd_io:
2439     return (Offset >= Hexagon_MEMD_OFFSET_MIN) &&
2440       (Offset <= Hexagon_MEMD_OFFSET_MAX);
2441 
2442   case Hexagon::L2_loadrh_io:
2443   case Hexagon::L2_loadruh_io:
2444   case Hexagon::S2_storerh_io:
2445   case Hexagon::S2_storerf_io:
2446     return (Offset >= Hexagon_MEMH_OFFSET_MIN) &&
2447       (Offset <= Hexagon_MEMH_OFFSET_MAX);
2448 
2449   case Hexagon::L2_loadrb_io:
2450   case Hexagon::L2_loadrub_io:
2451   case Hexagon::S2_storerb_io:
2452     return (Offset >= Hexagon_MEMB_OFFSET_MIN) &&
2453       (Offset <= Hexagon_MEMB_OFFSET_MAX);
2454 
2455   case Hexagon::A2_addi:
2456     return (Offset >= Hexagon_ADDI_OFFSET_MIN) &&
2457       (Offset <= Hexagon_ADDI_OFFSET_MAX);
2458 
2459   case Hexagon::L4_iadd_memopw_io:
2460   case Hexagon::L4_isub_memopw_io:
2461   case Hexagon::L4_add_memopw_io:
2462   case Hexagon::L4_sub_memopw_io:
2463   case Hexagon::L4_and_memopw_io:
2464   case Hexagon::L4_or_memopw_io:
2465     return (0 <= Offset && Offset <= 255);
2466 
2467   case Hexagon::L4_iadd_memoph_io:
2468   case Hexagon::L4_isub_memoph_io:
2469   case Hexagon::L4_add_memoph_io:
2470   case Hexagon::L4_sub_memoph_io:
2471   case Hexagon::L4_and_memoph_io:
2472   case Hexagon::L4_or_memoph_io:
2473     return (0 <= Offset && Offset <= 127);
2474 
2475   case Hexagon::L4_iadd_memopb_io:
2476   case Hexagon::L4_isub_memopb_io:
2477   case Hexagon::L4_add_memopb_io:
2478   case Hexagon::L4_sub_memopb_io:
2479   case Hexagon::L4_and_memopb_io:
2480   case Hexagon::L4_or_memopb_io:
2481     return (0 <= Offset && Offset <= 63);
2482 
2483   // LDriw_xxx and STriw_xxx are pseudo operations, so it has to take offset of
2484   // any size. Later pass knows how to handle it.
2485   case Hexagon::STriw_pred:
2486   case Hexagon::LDriw_pred:
2487   case Hexagon::STriw_mod:
2488   case Hexagon::LDriw_mod:
2489     return true;
2490 
2491   case Hexagon::PS_fi:
2492   case Hexagon::PS_fia:
2493   case Hexagon::INLINEASM:
2494     return true;
2495 
2496   case Hexagon::L2_ploadrbt_io:
2497   case Hexagon::L2_ploadrbf_io:
2498   case Hexagon::L2_ploadrubt_io:
2499   case Hexagon::L2_ploadrubf_io:
2500   case Hexagon::S2_pstorerbt_io:
2501   case Hexagon::S2_pstorerbf_io:
2502     return isUInt<6>(Offset);
2503 
2504   case Hexagon::L2_ploadrht_io:
2505   case Hexagon::L2_ploadrhf_io:
2506   case Hexagon::L2_ploadruht_io:
2507   case Hexagon::L2_ploadruhf_io:
2508   case Hexagon::S2_pstorerht_io:
2509   case Hexagon::S2_pstorerhf_io:
2510     return isShiftedUInt<6,1>(Offset);
2511 
2512   case Hexagon::L2_ploadrit_io:
2513   case Hexagon::L2_ploadrif_io:
2514   case Hexagon::S2_pstorerit_io:
2515   case Hexagon::S2_pstorerif_io:
2516     return isShiftedUInt<6,2>(Offset);
2517 
2518   case Hexagon::L2_ploadrdt_io:
2519   case Hexagon::L2_ploadrdf_io:
2520   case Hexagon::S2_pstorerdt_io:
2521   case Hexagon::S2_pstorerdf_io:
2522     return isShiftedUInt<6,3>(Offset);
2523   } // switch
2524 
2525   llvm_unreachable("No offset range is defined for this opcode. "
2526                    "Please define it in the above switch statement!");
2527 }
2528 
2529 bool HexagonInstrInfo::isVecAcc(const MachineInstr &MI) const {
2530   return isHVXVec(MI) && isAccumulator(MI);
2531 }
2532 
2533 bool HexagonInstrInfo::isVecALU(const MachineInstr &MI) const {
2534   const uint64_t F = get(MI.getOpcode()).TSFlags;
2535   const uint64_t V = ((F >> HexagonII::TypePos) & HexagonII::TypeMask);
2536   return
2537     V == HexagonII::TypeCVI_VA         ||
2538     V == HexagonII::TypeCVI_VA_DV;
2539 }
2540 
2541 bool HexagonInstrInfo::isVecUsableNextPacket(const MachineInstr &ProdMI,
2542       const MachineInstr &ConsMI) const {
2543   if (EnableACCForwarding && isVecAcc(ProdMI) && isVecAcc(ConsMI))
2544     return true;
2545 
2546   if (EnableALUForwarding && (isVecALU(ConsMI) || isLateSourceInstr(ConsMI)))
2547     return true;
2548 
2549   if (mayBeNewStore(ConsMI))
2550     return true;
2551 
2552   return false;
2553 }
2554 
2555 bool HexagonInstrInfo::isZeroExtendingLoad(const MachineInstr &MI) const {
2556   switch (MI.getOpcode()) {
2557   // Byte
2558   case Hexagon::L2_loadrub_io:
2559   case Hexagon::L4_loadrub_ur:
2560   case Hexagon::L4_loadrub_ap:
2561   case Hexagon::L2_loadrub_pr:
2562   case Hexagon::L2_loadrub_pbr:
2563   case Hexagon::L2_loadrub_pi:
2564   case Hexagon::L2_loadrub_pci:
2565   case Hexagon::L2_loadrub_pcr:
2566   case Hexagon::L2_loadbzw2_io:
2567   case Hexagon::L4_loadbzw2_ur:
2568   case Hexagon::L4_loadbzw2_ap:
2569   case Hexagon::L2_loadbzw2_pr:
2570   case Hexagon::L2_loadbzw2_pbr:
2571   case Hexagon::L2_loadbzw2_pi:
2572   case Hexagon::L2_loadbzw2_pci:
2573   case Hexagon::L2_loadbzw2_pcr:
2574   case Hexagon::L2_loadbzw4_io:
2575   case Hexagon::L4_loadbzw4_ur:
2576   case Hexagon::L4_loadbzw4_ap:
2577   case Hexagon::L2_loadbzw4_pr:
2578   case Hexagon::L2_loadbzw4_pbr:
2579   case Hexagon::L2_loadbzw4_pi:
2580   case Hexagon::L2_loadbzw4_pci:
2581   case Hexagon::L2_loadbzw4_pcr:
2582   case Hexagon::L4_loadrub_rr:
2583   case Hexagon::L2_ploadrubt_io:
2584   case Hexagon::L2_ploadrubt_pi:
2585   case Hexagon::L2_ploadrubf_io:
2586   case Hexagon::L2_ploadrubf_pi:
2587   case Hexagon::L2_ploadrubtnew_io:
2588   case Hexagon::L2_ploadrubfnew_io:
2589   case Hexagon::L4_ploadrubt_rr:
2590   case Hexagon::L4_ploadrubf_rr:
2591   case Hexagon::L4_ploadrubtnew_rr:
2592   case Hexagon::L4_ploadrubfnew_rr:
2593   case Hexagon::L2_ploadrubtnew_pi:
2594   case Hexagon::L2_ploadrubfnew_pi:
2595   case Hexagon::L4_ploadrubt_abs:
2596   case Hexagon::L4_ploadrubf_abs:
2597   case Hexagon::L4_ploadrubtnew_abs:
2598   case Hexagon::L4_ploadrubfnew_abs:
2599   case Hexagon::L2_loadrubgp:
2600   // Half
2601   case Hexagon::L2_loadruh_io:
2602   case Hexagon::L4_loadruh_ur:
2603   case Hexagon::L4_loadruh_ap:
2604   case Hexagon::L2_loadruh_pr:
2605   case Hexagon::L2_loadruh_pbr:
2606   case Hexagon::L2_loadruh_pi:
2607   case Hexagon::L2_loadruh_pci:
2608   case Hexagon::L2_loadruh_pcr:
2609   case Hexagon::L4_loadruh_rr:
2610   case Hexagon::L2_ploadruht_io:
2611   case Hexagon::L2_ploadruht_pi:
2612   case Hexagon::L2_ploadruhf_io:
2613   case Hexagon::L2_ploadruhf_pi:
2614   case Hexagon::L2_ploadruhtnew_io:
2615   case Hexagon::L2_ploadruhfnew_io:
2616   case Hexagon::L4_ploadruht_rr:
2617   case Hexagon::L4_ploadruhf_rr:
2618   case Hexagon::L4_ploadruhtnew_rr:
2619   case Hexagon::L4_ploadruhfnew_rr:
2620   case Hexagon::L2_ploadruhtnew_pi:
2621   case Hexagon::L2_ploadruhfnew_pi:
2622   case Hexagon::L4_ploadruht_abs:
2623   case Hexagon::L4_ploadruhf_abs:
2624   case Hexagon::L4_ploadruhtnew_abs:
2625   case Hexagon::L4_ploadruhfnew_abs:
2626   case Hexagon::L2_loadruhgp:
2627     return true;
2628   default:
2629     return false;
2630   }
2631 }
2632 
2633 // Add latency to instruction.
2634 bool HexagonInstrInfo::addLatencyToSchedule(const MachineInstr &MI1,
2635       const MachineInstr &MI2) const {
2636   if (isHVXVec(MI1) && isHVXVec(MI2))
2637     if (!isVecUsableNextPacket(MI1, MI2))
2638       return true;
2639   return false;
2640 }
2641 
2642 /// \brief Get the base register and byte offset of a load/store instr.
2643 bool HexagonInstrInfo::getMemOpBaseRegImmOfs(MachineInstr &LdSt,
2644       unsigned &BaseReg, int64_t &Offset, const TargetRegisterInfo *TRI)
2645       const {
2646   unsigned AccessSize = 0;
2647   int OffsetVal = 0;
2648   BaseReg = getBaseAndOffset(LdSt, OffsetVal, AccessSize);
2649   Offset = OffsetVal;
2650   return BaseReg != 0;
2651 }
2652 
2653 /// \brief Can these instructions execute at the same time in a bundle.
2654 bool HexagonInstrInfo::canExecuteInBundle(const MachineInstr &First,
2655       const MachineInstr &Second) const {
2656   if (Second.mayStore() && First.getOpcode() == Hexagon::S2_allocframe) {
2657     const MachineOperand &Op = Second.getOperand(0);
2658     if (Op.isReg() && Op.isUse() && Op.getReg() == Hexagon::R29)
2659       return true;
2660   }
2661   if (DisableNVSchedule)
2662     return false;
2663   if (mayBeNewStore(Second)) {
2664     // Make sure the definition of the first instruction is the value being
2665     // stored.
2666     const MachineOperand &Stored =
2667       Second.getOperand(Second.getNumOperands() - 1);
2668     if (!Stored.isReg())
2669       return false;
2670     for (unsigned i = 0, e = First.getNumOperands(); i < e; ++i) {
2671       const MachineOperand &Op = First.getOperand(i);
2672       if (Op.isReg() && Op.isDef() && Op.getReg() == Stored.getReg())
2673         return true;
2674     }
2675   }
2676   return false;
2677 }
2678 
2679 bool HexagonInstrInfo::doesNotReturn(const MachineInstr &CallMI) const {
2680   unsigned Opc = CallMI.getOpcode();
2681   return Opc == Hexagon::PS_call_nr || Opc == Hexagon::PS_callr_nr;
2682 }
2683 
2684 bool HexagonInstrInfo::hasEHLabel(const MachineBasicBlock *B) const {
2685   for (auto &I : *B)
2686     if (I.isEHLabel())
2687       return true;
2688   return false;
2689 }
2690 
2691 // Returns true if an instruction can be converted into a non-extended
2692 // equivalent instruction.
2693 bool HexagonInstrInfo::hasNonExtEquivalent(const MachineInstr &MI) const {
2694   short NonExtOpcode;
2695   // Check if the instruction has a register form that uses register in place
2696   // of the extended operand, if so return that as the non-extended form.
2697   if (Hexagon::getRegForm(MI.getOpcode()) >= 0)
2698     return true;
2699 
2700   if (MI.getDesc().mayLoad() || MI.getDesc().mayStore()) {
2701     // Check addressing mode and retrieve non-ext equivalent instruction.
2702 
2703     switch (getAddrMode(MI)) {
2704     case HexagonII::Absolute:
2705       // Load/store with absolute addressing mode can be converted into
2706       // base+offset mode.
2707       NonExtOpcode = Hexagon::changeAddrMode_abs_io(MI.getOpcode());
2708       break;
2709     case HexagonII::BaseImmOffset:
2710       // Load/store with base+offset addressing mode can be converted into
2711       // base+register offset addressing mode. However left shift operand should
2712       // be set to 0.
2713       NonExtOpcode = Hexagon::changeAddrMode_io_rr(MI.getOpcode());
2714       break;
2715     case HexagonII::BaseLongOffset:
2716       NonExtOpcode = Hexagon::changeAddrMode_ur_rr(MI.getOpcode());
2717       break;
2718     default:
2719       return false;
2720     }
2721     if (NonExtOpcode < 0)
2722       return false;
2723     return true;
2724   }
2725   return false;
2726 }
2727 
2728 bool HexagonInstrInfo::hasPseudoInstrPair(const MachineInstr &MI) const {
2729   return Hexagon::getRealHWInstr(MI.getOpcode(),
2730                                  Hexagon::InstrType_Pseudo) >= 0;
2731 }
2732 
2733 bool HexagonInstrInfo::hasUncondBranch(const MachineBasicBlock *B)
2734       const {
2735   MachineBasicBlock::const_iterator I = B->getFirstTerminator(), E = B->end();
2736   while (I != E) {
2737     if (I->isBarrier())
2738       return true;
2739     ++I;
2740   }
2741   return false;
2742 }
2743 
2744 // Returns true, if a LD insn can be promoted to a cur load.
2745 bool HexagonInstrInfo::mayBeCurLoad(const MachineInstr &MI) const {
2746   const uint64_t F = MI.getDesc().TSFlags;
2747   return ((F >> HexagonII::mayCVLoadPos) & HexagonII::mayCVLoadMask) &&
2748          Subtarget.hasV60TOps();
2749 }
2750 
2751 // Returns true, if a ST insn can be promoted to a new-value store.
2752 bool HexagonInstrInfo::mayBeNewStore(const MachineInstr &MI) const {
2753   const uint64_t F = MI.getDesc().TSFlags;
2754   return (F >> HexagonII::mayNVStorePos) & HexagonII::mayNVStoreMask;
2755 }
2756 
2757 bool HexagonInstrInfo::producesStall(const MachineInstr &ProdMI,
2758       const MachineInstr &ConsMI) const {
2759   // There is no stall when ProdMI is not a V60 vector.
2760   if (!isHVXVec(ProdMI))
2761     return false;
2762 
2763   // There is no stall when ProdMI and ConsMI are not dependent.
2764   if (!isDependent(ProdMI, ConsMI))
2765     return false;
2766 
2767   // When Forward Scheduling is enabled, there is no stall if ProdMI and ConsMI
2768   // are scheduled in consecutive packets.
2769   if (isVecUsableNextPacket(ProdMI, ConsMI))
2770     return false;
2771 
2772   return true;
2773 }
2774 
2775 bool HexagonInstrInfo::producesStall(const MachineInstr &MI,
2776       MachineBasicBlock::const_instr_iterator BII) const {
2777   // There is no stall when I is not a V60 vector.
2778   if (!isHVXVec(MI))
2779     return false;
2780 
2781   MachineBasicBlock::const_instr_iterator MII = BII;
2782   MachineBasicBlock::const_instr_iterator MIE = MII->getParent()->instr_end();
2783 
2784   if (!(*MII).isBundle()) {
2785     const MachineInstr &J = *MII;
2786     return producesStall(J, MI);
2787   }
2788 
2789   for (++MII; MII != MIE && MII->isInsideBundle(); ++MII) {
2790     const MachineInstr &J = *MII;
2791     if (producesStall(J, MI))
2792       return true;
2793   }
2794   return false;
2795 }
2796 
2797 bool HexagonInstrInfo::predCanBeUsedAsDotNew(const MachineInstr &MI,
2798       unsigned PredReg) const {
2799   for (const MachineOperand &MO : MI.operands()) {
2800     // Predicate register must be explicitly defined.
2801     if (MO.isRegMask() && MO.clobbersPhysReg(PredReg))
2802       return false;
2803     if (MO.isReg() && MO.isDef() && MO.isImplicit() && (MO.getReg() == PredReg))
2804       return false;
2805   }
2806 
2807   // Hexagon Programmer's Reference says that decbin, memw_locked, and
2808   // memd_locked cannot be used as .new as well,
2809   // but we don't seem to have these instructions defined.
2810   return MI.getOpcode() != Hexagon::A4_tlbmatch;
2811 }
2812 
2813 bool HexagonInstrInfo::PredOpcodeHasJMP_c(unsigned Opcode) const {
2814   return Opcode == Hexagon::J2_jumpt      ||
2815          Opcode == Hexagon::J2_jumptpt    ||
2816          Opcode == Hexagon::J2_jumpf      ||
2817          Opcode == Hexagon::J2_jumpfpt    ||
2818          Opcode == Hexagon::J2_jumptnew   ||
2819          Opcode == Hexagon::J2_jumpfnew   ||
2820          Opcode == Hexagon::J2_jumptnewpt ||
2821          Opcode == Hexagon::J2_jumpfnewpt;
2822 }
2823 
2824 bool HexagonInstrInfo::predOpcodeHasNot(ArrayRef<MachineOperand> Cond) const {
2825   if (Cond.empty() || !isPredicated(Cond[0].getImm()))
2826     return false;
2827   return !isPredicatedTrue(Cond[0].getImm());
2828 }
2829 
2830 unsigned HexagonInstrInfo::getAddrMode(const MachineInstr &MI) const {
2831   const uint64_t F = MI.getDesc().TSFlags;
2832   return (F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask;
2833 }
2834 
2835 // Returns the base register in a memory access (load/store). The offset is
2836 // returned in Offset and the access size is returned in AccessSize.
2837 // If the base register has a subregister or the offset field does not contain
2838 // an immediate value, return 0.
2839 unsigned HexagonInstrInfo::getBaseAndOffset(const MachineInstr &MI,
2840       int &Offset, unsigned &AccessSize) const {
2841   // Return if it is not a base+offset type instruction or a MemOp.
2842   if (getAddrMode(MI) != HexagonII::BaseImmOffset &&
2843       getAddrMode(MI) != HexagonII::BaseLongOffset &&
2844       !isMemOp(MI) && !isPostIncrement(MI))
2845     return 0;
2846 
2847   AccessSize = getMemAccessSize(MI);
2848 
2849   unsigned BasePos = 0, OffsetPos = 0;
2850   if (!getBaseAndOffsetPosition(MI, BasePos, OffsetPos))
2851     return 0;
2852 
2853   // Post increment updates its EA after the mem access,
2854   // so we need to treat its offset as zero.
2855   if (isPostIncrement(MI)) {
2856     Offset = 0;
2857   } else {
2858     const MachineOperand &OffsetOp = MI.getOperand(OffsetPos);
2859     if (!OffsetOp.isImm())
2860       return 0;
2861     Offset = OffsetOp.getImm();
2862   }
2863 
2864   const MachineOperand &BaseOp = MI.getOperand(BasePos);
2865   if (BaseOp.getSubReg() != 0)
2866     return 0;
2867   return BaseOp.getReg();
2868 }
2869 
2870 /// Return the position of the base and offset operands for this instruction.
2871 bool HexagonInstrInfo::getBaseAndOffsetPosition(const MachineInstr &MI,
2872       unsigned &BasePos, unsigned &OffsetPos) const {
2873   // Deal with memops first.
2874   if (isMemOp(MI)) {
2875     BasePos = 0;
2876     OffsetPos = 1;
2877   } else if (MI.mayStore()) {
2878     BasePos = 0;
2879     OffsetPos = 1;
2880   } else if (MI.mayLoad()) {
2881     BasePos = 1;
2882     OffsetPos = 2;
2883   } else
2884     return false;
2885 
2886   if (isPredicated(MI)) {
2887     BasePos++;
2888     OffsetPos++;
2889   }
2890   if (isPostIncrement(MI)) {
2891     BasePos++;
2892     OffsetPos++;
2893   }
2894 
2895   if (!MI.getOperand(BasePos).isReg() || !MI.getOperand(OffsetPos).isImm())
2896     return false;
2897 
2898   return true;
2899 }
2900 
2901 // Inserts branching instructions in reverse order of their occurrence.
2902 // e.g. jump_t t1 (i1)
2903 // jump t2        (i2)
2904 // Jumpers = {i2, i1}
2905 SmallVector<MachineInstr*, 2> HexagonInstrInfo::getBranchingInstrs(
2906       MachineBasicBlock& MBB) const {
2907   SmallVector<MachineInstr*, 2> Jumpers;
2908   // If the block has no terminators, it just falls into the block after it.
2909   MachineBasicBlock::instr_iterator I = MBB.instr_end();
2910   if (I == MBB.instr_begin())
2911     return Jumpers;
2912 
2913   // A basic block may looks like this:
2914   //
2915   //  [   insn
2916   //     EH_LABEL
2917   //      insn
2918   //      insn
2919   //      insn
2920   //     EH_LABEL
2921   //      insn     ]
2922   //
2923   // It has two succs but does not have a terminator
2924   // Don't know how to handle it.
2925   do {
2926     --I;
2927     if (I->isEHLabel())
2928       return Jumpers;
2929   } while (I != MBB.instr_begin());
2930 
2931   I = MBB.instr_end();
2932   --I;
2933 
2934   while (I->isDebugValue()) {
2935     if (I == MBB.instr_begin())
2936       return Jumpers;
2937     --I;
2938   }
2939   if (!isUnpredicatedTerminator(*I))
2940     return Jumpers;
2941 
2942   // Get the last instruction in the block.
2943   MachineInstr *LastInst = &*I;
2944   Jumpers.push_back(LastInst);
2945   MachineInstr *SecondLastInst = nullptr;
2946   // Find one more terminator if present.
2947   do {
2948     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(*I)) {
2949       if (!SecondLastInst) {
2950         SecondLastInst = &*I;
2951         Jumpers.push_back(SecondLastInst);
2952       } else // This is a third branch.
2953         return Jumpers;
2954     }
2955     if (I == MBB.instr_begin())
2956       break;
2957     --I;
2958   } while (true);
2959   return Jumpers;
2960 }
2961 
2962 // Returns Operand Index for the constant extended instruction.
2963 unsigned HexagonInstrInfo::getCExtOpNum(const MachineInstr &MI) const {
2964   const uint64_t F = MI.getDesc().TSFlags;
2965   return (F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask;
2966 }
2967 
2968 // See if instruction could potentially be a duplex candidate.
2969 // If so, return its group. Zero otherwise.
2970 HexagonII::CompoundGroup HexagonInstrInfo::getCompoundCandidateGroup(
2971       const MachineInstr &MI) const {
2972   unsigned DstReg, SrcReg, Src1Reg, Src2Reg;
2973 
2974   switch (MI.getOpcode()) {
2975   default:
2976     return HexagonII::HCG_None;
2977   //
2978   // Compound pairs.
2979   // "p0=cmp.eq(Rs16,Rt16); if (p0.new) jump:nt #r9:2"
2980   // "Rd16=#U6 ; jump #r9:2"
2981   // "Rd16=Rs16 ; jump #r9:2"
2982   //
2983   case Hexagon::C2_cmpeq:
2984   case Hexagon::C2_cmpgt:
2985   case Hexagon::C2_cmpgtu:
2986     DstReg = MI.getOperand(0).getReg();
2987     Src1Reg = MI.getOperand(1).getReg();
2988     Src2Reg = MI.getOperand(2).getReg();
2989     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
2990         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
2991         isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg))
2992       return HexagonII::HCG_A;
2993     break;
2994   case Hexagon::C2_cmpeqi:
2995   case Hexagon::C2_cmpgti:
2996   case Hexagon::C2_cmpgtui:
2997     // P0 = cmp.eq(Rs,#u2)
2998     DstReg = MI.getOperand(0).getReg();
2999     SrcReg = MI.getOperand(1).getReg();
3000     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3001         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3002         isIntRegForSubInst(SrcReg) && MI.getOperand(2).isImm() &&
3003         ((isUInt<5>(MI.getOperand(2).getImm())) ||
3004          (MI.getOperand(2).getImm() == -1)))
3005       return HexagonII::HCG_A;
3006     break;
3007   case Hexagon::A2_tfr:
3008     // Rd = Rs
3009     DstReg = MI.getOperand(0).getReg();
3010     SrcReg = MI.getOperand(1).getReg();
3011     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
3012       return HexagonII::HCG_A;
3013     break;
3014   case Hexagon::A2_tfrsi:
3015     // Rd = #u6
3016     // Do not test for #u6 size since the const is getting extended
3017     // regardless and compound could be formed.
3018     DstReg = MI.getOperand(0).getReg();
3019     if (isIntRegForSubInst(DstReg))
3020       return HexagonII::HCG_A;
3021     break;
3022   case Hexagon::S2_tstbit_i:
3023     DstReg = MI.getOperand(0).getReg();
3024     Src1Reg = MI.getOperand(1).getReg();
3025     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3026         (Hexagon::P0 == DstReg || Hexagon::P1 == DstReg) &&
3027         MI.getOperand(2).isImm() &&
3028         isIntRegForSubInst(Src1Reg) && (MI.getOperand(2).getImm() == 0))
3029       return HexagonII::HCG_A;
3030     break;
3031   // The fact that .new form is used pretty much guarantees
3032   // that predicate register will match. Nevertheless,
3033   // there could be some false positives without additional
3034   // checking.
3035   case Hexagon::J2_jumptnew:
3036   case Hexagon::J2_jumpfnew:
3037   case Hexagon::J2_jumptnewpt:
3038   case Hexagon::J2_jumpfnewpt:
3039     Src1Reg = MI.getOperand(0).getReg();
3040     if (Hexagon::PredRegsRegClass.contains(Src1Reg) &&
3041         (Hexagon::P0 == Src1Reg || Hexagon::P1 == Src1Reg))
3042       return HexagonII::HCG_B;
3043     break;
3044   // Transfer and jump:
3045   // Rd=#U6 ; jump #r9:2
3046   // Rd=Rs ; jump #r9:2
3047   // Do not test for jump range here.
3048   case Hexagon::J2_jump:
3049   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
3050   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
3051     return HexagonII::HCG_C;
3052   }
3053 
3054   return HexagonII::HCG_None;
3055 }
3056 
3057 // Returns -1 when there is no opcode found.
3058 unsigned HexagonInstrInfo::getCompoundOpcode(const MachineInstr &GA,
3059       const MachineInstr &GB) const {
3060   assert(getCompoundCandidateGroup(GA) == HexagonII::HCG_A);
3061   assert(getCompoundCandidateGroup(GB) == HexagonII::HCG_B);
3062   if ((GA.getOpcode() != Hexagon::C2_cmpeqi) ||
3063       (GB.getOpcode() != Hexagon::J2_jumptnew))
3064     return -1;
3065   unsigned DestReg = GA.getOperand(0).getReg();
3066   if (!GB.readsRegister(DestReg))
3067     return -1;
3068   if (DestReg == Hexagon::P0)
3069     return Hexagon::J4_cmpeqi_tp0_jump_nt;
3070   if (DestReg == Hexagon::P1)
3071     return Hexagon::J4_cmpeqi_tp1_jump_nt;
3072   return -1;
3073 }
3074 
3075 int HexagonInstrInfo::getCondOpcode(int Opc, bool invertPredicate) const {
3076   enum Hexagon::PredSense inPredSense;
3077   inPredSense = invertPredicate ? Hexagon::PredSense_false :
3078                                   Hexagon::PredSense_true;
3079   int CondOpcode = Hexagon::getPredOpcode(Opc, inPredSense);
3080   if (CondOpcode >= 0) // Valid Conditional opcode/instruction
3081     return CondOpcode;
3082 
3083   llvm_unreachable("Unexpected predicable instruction");
3084 }
3085 
3086 // Return the cur value instruction for a given store.
3087 int HexagonInstrInfo::getDotCurOp(const MachineInstr &MI) const {
3088   switch (MI.getOpcode()) {
3089   default: llvm_unreachable("Unknown .cur type");
3090   case Hexagon::V6_vL32b_pi:
3091     return Hexagon::V6_vL32b_cur_pi;
3092   case Hexagon::V6_vL32b_ai:
3093     return Hexagon::V6_vL32b_cur_ai;
3094   case Hexagon::V6_vL32b_nt_pi:
3095     return Hexagon::V6_vL32b_nt_cur_pi;
3096   case Hexagon::V6_vL32b_nt_ai:
3097     return Hexagon::V6_vL32b_nt_cur_ai;
3098   }
3099   return 0;
3100 }
3101 
3102 // Return the regular version of the .cur instruction.
3103 int HexagonInstrInfo::getNonDotCurOp(const MachineInstr &MI) const {
3104   switch (MI.getOpcode()) {
3105   default: llvm_unreachable("Unknown .cur type");
3106   case Hexagon::V6_vL32b_cur_pi:
3107     return Hexagon::V6_vL32b_pi;
3108   case Hexagon::V6_vL32b_cur_ai:
3109     return Hexagon::V6_vL32b_ai;
3110   case Hexagon::V6_vL32b_nt_cur_pi:
3111     return Hexagon::V6_vL32b_nt_pi;
3112   case Hexagon::V6_vL32b_nt_cur_ai:
3113     return Hexagon::V6_vL32b_nt_ai;
3114   }
3115   return 0;
3116 }
3117 
3118 // The diagram below shows the steps involved in the conversion of a predicated
3119 // store instruction to its .new predicated new-value form.
3120 //
3121 // Note: It doesn't include conditional new-value stores as they can't be
3122 // converted to .new predicate.
3123 //
3124 //               p.new NV store [ if(p0.new)memw(R0+#0)=R2.new ]
3125 //                ^           ^
3126 //               /             \ (not OK. it will cause new-value store to be
3127 //              /               X conditional on p0.new while R2 producer is
3128 //             /                 \ on p0)
3129 //            /                   \.
3130 //     p.new store                 p.old NV store
3131 // [if(p0.new)memw(R0+#0)=R2]    [if(p0)memw(R0+#0)=R2.new]
3132 //            ^                  ^
3133 //             \                /
3134 //              \              /
3135 //               \            /
3136 //                 p.old store
3137 //             [if (p0)memw(R0+#0)=R2]
3138 //
3139 // The following set of instructions further explains the scenario where
3140 // conditional new-value store becomes invalid when promoted to .new predicate
3141 // form.
3142 //
3143 // { 1) if (p0) r0 = add(r1, r2)
3144 //   2) p0 = cmp.eq(r3, #0) }
3145 //
3146 //   3) if (p0) memb(r1+#0) = r0  --> this instruction can't be grouped with
3147 // the first two instructions because in instr 1, r0 is conditional on old value
3148 // of p0 but its use in instr 3 is conditional on p0 modified by instr 2 which
3149 // is not valid for new-value stores.
3150 // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
3151 // from the "Conditional Store" list. Because a predicated new value store
3152 // would NOT be promoted to a double dot new store. See diagram below:
3153 // This function returns yes for those stores that are predicated but not
3154 // yet promoted to predicate dot new instructions.
3155 //
3156 //                          +---------------------+
3157 //                    /-----| if (p0) memw(..)=r0 |---------\~
3158 //                   ||     +---------------------+         ||
3159 //          promote  ||       /\       /\                   ||  promote
3160 //                   ||      /||\     /||\                  ||
3161 //                  \||/    demote     ||                  \||/
3162 //                   \/       ||       ||                   \/
3163 //       +-------------------------+   ||   +-------------------------+
3164 //       | if (p0.new) memw(..)=r0 |   ||   | if (p0) memw(..)=r0.new |
3165 //       +-------------------------+   ||   +-------------------------+
3166 //                        ||           ||         ||
3167 //                        ||         demote      \||/
3168 //                      promote        ||         \/ NOT possible
3169 //                        ||           ||         /\~
3170 //                       \||/          ||        /||\~
3171 //                        \/           ||         ||
3172 //                      +-----------------------------+
3173 //                      | if (p0.new) memw(..)=r0.new |
3174 //                      +-----------------------------+
3175 //                           Double Dot New Store
3176 //
3177 // Returns the most basic instruction for the .new predicated instructions and
3178 // new-value stores.
3179 // For example, all of the following instructions will be converted back to the
3180 // same instruction:
3181 // 1) if (p0.new) memw(R0+#0) = R1.new  --->
3182 // 2) if (p0) memw(R0+#0)= R1.new      -------> if (p0) memw(R0+#0) = R1
3183 // 3) if (p0.new) memw(R0+#0) = R1      --->
3184 //
3185 // To understand the translation of instruction 1 to its original form, consider
3186 // a packet with 3 instructions.
3187 // { p0 = cmp.eq(R0,R1)
3188 //   if (p0.new) R2 = add(R3, R4)
3189 //   R5 = add (R3, R1)
3190 // }
3191 // if (p0) memw(R5+#0) = R2 <--- trying to include it in the previous packet
3192 //
3193 // This instruction can be part of the previous packet only if both p0 and R2
3194 // are promoted to .new values. This promotion happens in steps, first
3195 // predicate register is promoted to .new and in the next iteration R2 is
3196 // promoted. Therefore, in case of dependence check failure (due to R5) during
3197 // next iteration, it should be converted back to its most basic form.
3198 
3199 // Return the new value instruction for a given store.
3200 int HexagonInstrInfo::getDotNewOp(const MachineInstr &MI) const {
3201   int NVOpcode = Hexagon::getNewValueOpcode(MI.getOpcode());
3202   if (NVOpcode >= 0) // Valid new-value store instruction.
3203     return NVOpcode;
3204 
3205   switch (MI.getOpcode()) {
3206   default:
3207     report_fatal_error(std::string("Unknown .new type: ") +
3208       std::to_string(MI.getOpcode()));
3209   case Hexagon::S4_storerb_ur:
3210     return Hexagon::S4_storerbnew_ur;
3211 
3212   case Hexagon::S2_storerb_pci:
3213     return Hexagon::S2_storerb_pci;
3214 
3215   case Hexagon::S2_storeri_pci:
3216     return Hexagon::S2_storeri_pci;
3217 
3218   case Hexagon::S2_storerh_pci:
3219     return Hexagon::S2_storerh_pci;
3220 
3221   case Hexagon::S2_storerd_pci:
3222     return Hexagon::S2_storerd_pci;
3223 
3224   case Hexagon::S2_storerf_pci:
3225     return Hexagon::S2_storerf_pci;
3226 
3227   case Hexagon::V6_vS32b_ai:
3228     return Hexagon::V6_vS32b_new_ai;
3229 
3230   case Hexagon::V6_vS32b_pi:
3231     return Hexagon::V6_vS32b_new_pi;
3232   }
3233   return 0;
3234 }
3235 
3236 // Returns the opcode to use when converting MI, which is a conditional jump,
3237 // into a conditional instruction which uses the .new value of the predicate.
3238 // We also use branch probabilities to add a hint to the jump.
3239 // If MBPI is null, all edges will be treated as equally likely for the
3240 // purposes of establishing a predication hint.
3241 int HexagonInstrInfo::getDotNewPredJumpOp(const MachineInstr &MI,
3242       const MachineBranchProbabilityInfo *MBPI) const {
3243   // We assume that block can have at most two successors.
3244   const MachineBasicBlock *Src = MI.getParent();
3245   const MachineOperand &BrTarget = MI.getOperand(1);
3246   bool Taken = false;
3247   const BranchProbability OneHalf(1, 2);
3248 
3249   auto getEdgeProbability = [MBPI] (const MachineBasicBlock *Src,
3250                                     const MachineBasicBlock *Dst) {
3251     if (MBPI)
3252       return MBPI->getEdgeProbability(Src, Dst);
3253     return BranchProbability(1, Src->succ_size());
3254   };
3255 
3256   if (BrTarget.isMBB()) {
3257     const MachineBasicBlock *Dst = BrTarget.getMBB();
3258     Taken = getEdgeProbability(Src, Dst) >= OneHalf;
3259   } else {
3260     // The branch target is not a basic block (most likely a function).
3261     // Since BPI only gives probabilities for targets that are basic blocks,
3262     // try to identify another target of this branch (potentially a fall-
3263     // -through) and check the probability of that target.
3264     //
3265     // The only handled branch combinations are:
3266     // - one conditional branch,
3267     // - one conditional branch followed by one unconditional branch.
3268     // Otherwise, assume not-taken.
3269     assert(MI.isConditionalBranch());
3270     const MachineBasicBlock &B = *MI.getParent();
3271     bool SawCond = false, Bad = false;
3272     for (const MachineInstr &I : B) {
3273       if (!I.isBranch())
3274         continue;
3275       if (I.isConditionalBranch()) {
3276         SawCond = true;
3277         if (&I != &MI) {
3278           Bad = true;
3279           break;
3280         }
3281       }
3282       if (I.isUnconditionalBranch() && !SawCond) {
3283         Bad = true;
3284         break;
3285       }
3286     }
3287     if (!Bad) {
3288       MachineBasicBlock::const_instr_iterator It(MI);
3289       MachineBasicBlock::const_instr_iterator NextIt = std::next(It);
3290       if (NextIt == B.instr_end()) {
3291         // If this branch is the last, look for the fall-through block.
3292         for (const MachineBasicBlock *SB : B.successors()) {
3293           if (!B.isLayoutSuccessor(SB))
3294             continue;
3295           Taken = getEdgeProbability(Src, SB) < OneHalf;
3296           break;
3297         }
3298       } else {
3299         assert(NextIt->isUnconditionalBranch());
3300         // Find the first MBB operand and assume it's the target.
3301         const MachineBasicBlock *BT = nullptr;
3302         for (const MachineOperand &Op : NextIt->operands()) {
3303           if (!Op.isMBB())
3304             continue;
3305           BT = Op.getMBB();
3306           break;
3307         }
3308         Taken = BT && getEdgeProbability(Src, BT) < OneHalf;
3309       }
3310     } // if (!Bad)
3311   }
3312 
3313   // The Taken flag should be set to something reasonable by this point.
3314 
3315   switch (MI.getOpcode()) {
3316   case Hexagon::J2_jumpt:
3317     return Taken ? Hexagon::J2_jumptnewpt : Hexagon::J2_jumptnew;
3318   case Hexagon::J2_jumpf:
3319     return Taken ? Hexagon::J2_jumpfnewpt : Hexagon::J2_jumpfnew;
3320 
3321   default:
3322     llvm_unreachable("Unexpected jump instruction.");
3323   }
3324 }
3325 
3326 // Return .new predicate version for an instruction.
3327 int HexagonInstrInfo::getDotNewPredOp(const MachineInstr &MI,
3328       const MachineBranchProbabilityInfo *MBPI) const {
3329   switch (MI.getOpcode()) {
3330   // Condtional Jumps
3331   case Hexagon::J2_jumpt:
3332   case Hexagon::J2_jumpf:
3333     return getDotNewPredJumpOp(MI, MBPI);
3334   }
3335 
3336   int NewOpcode = Hexagon::getPredNewOpcode(MI.getOpcode());
3337   if (NewOpcode >= 0)
3338     return NewOpcode;
3339   return 0;
3340 }
3341 
3342 int HexagonInstrInfo::getDotOldOp(const MachineInstr &MI) const {
3343   int NewOp = MI.getOpcode();
3344   if (isPredicated(NewOp) && isPredicatedNew(NewOp)) { // Get predicate old form
3345     NewOp = Hexagon::getPredOldOpcode(NewOp);
3346     // All Hexagon architectures have prediction bits on dot-new branches,
3347     // but only Hexagon V60+ has prediction bits on dot-old ones. Make sure
3348     // to pick the right opcode when converting back to dot-old.
3349     if (!Subtarget.getFeatureBits()[Hexagon::ArchV60]) {
3350       switch (NewOp) {
3351       case Hexagon::J2_jumptpt:
3352         NewOp = Hexagon::J2_jumpt;
3353         break;
3354       case Hexagon::J2_jumpfpt:
3355         NewOp = Hexagon::J2_jumpf;
3356         break;
3357       case Hexagon::J2_jumprtpt:
3358         NewOp = Hexagon::J2_jumprt;
3359         break;
3360       case Hexagon::J2_jumprfpt:
3361         NewOp = Hexagon::J2_jumprf;
3362         break;
3363       }
3364     }
3365     assert(NewOp >= 0 &&
3366            "Couldn't change predicate new instruction to its old form.");
3367   }
3368 
3369   if (isNewValueStore(NewOp)) { // Convert into non-new-value format
3370     NewOp = Hexagon::getNonNVStore(NewOp);
3371     assert(NewOp >= 0 && "Couldn't change new-value store to its old form.");
3372   }
3373 
3374   if (Subtarget.hasV60TOps())
3375     return NewOp;
3376 
3377   // Subtargets prior to V60 didn't support 'taken' forms of predicated jumps.
3378   switch (NewOp) {
3379   case Hexagon::J2_jumpfpt:
3380     return Hexagon::J2_jumpf;
3381   case Hexagon::J2_jumptpt:
3382     return Hexagon::J2_jumpt;
3383   case Hexagon::J2_jumprfpt:
3384     return Hexagon::J2_jumprf;
3385   case Hexagon::J2_jumprtpt:
3386     return Hexagon::J2_jumprt;
3387   }
3388   return NewOp;
3389 }
3390 
3391 // See if instruction could potentially be a duplex candidate.
3392 // If so, return its group. Zero otherwise.
3393 HexagonII::SubInstructionGroup HexagonInstrInfo::getDuplexCandidateGroup(
3394       const MachineInstr &MI) const {
3395   unsigned DstReg, SrcReg, Src1Reg, Src2Reg;
3396   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
3397 
3398   switch (MI.getOpcode()) {
3399   default:
3400     return HexagonII::HSIG_None;
3401   //
3402   // Group L1:
3403   //
3404   // Rd = memw(Rs+#u4:2)
3405   // Rd = memub(Rs+#u4:0)
3406   case Hexagon::L2_loadri_io:
3407     DstReg = MI.getOperand(0).getReg();
3408     SrcReg = MI.getOperand(1).getReg();
3409     // Special case this one from Group L2.
3410     // Rd = memw(r29+#u5:2)
3411     if (isIntRegForSubInst(DstReg)) {
3412       if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
3413           HRI.getStackRegister() == SrcReg &&
3414           MI.getOperand(2).isImm() &&
3415           isShiftedUInt<5,2>(MI.getOperand(2).getImm()))
3416         return HexagonII::HSIG_L2;
3417       // Rd = memw(Rs+#u4:2)
3418       if (isIntRegForSubInst(SrcReg) &&
3419           (MI.getOperand(2).isImm() &&
3420           isShiftedUInt<4,2>(MI.getOperand(2).getImm())))
3421         return HexagonII::HSIG_L1;
3422     }
3423     break;
3424   case Hexagon::L2_loadrub_io:
3425     // Rd = memub(Rs+#u4:0)
3426     DstReg = MI.getOperand(0).getReg();
3427     SrcReg = MI.getOperand(1).getReg();
3428     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3429         MI.getOperand(2).isImm() && isUInt<4>(MI.getOperand(2).getImm()))
3430       return HexagonII::HSIG_L1;
3431     break;
3432   //
3433   // Group L2:
3434   //
3435   // Rd = memh/memuh(Rs+#u3:1)
3436   // Rd = memb(Rs+#u3:0)
3437   // Rd = memw(r29+#u5:2) - Handled above.
3438   // Rdd = memd(r29+#u5:3)
3439   // deallocframe
3440   // [if ([!]p0[.new])] dealloc_return
3441   // [if ([!]p0[.new])] jumpr r31
3442   case Hexagon::L2_loadrh_io:
3443   case Hexagon::L2_loadruh_io:
3444     // Rd = memh/memuh(Rs+#u3:1)
3445     DstReg = MI.getOperand(0).getReg();
3446     SrcReg = MI.getOperand(1).getReg();
3447     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3448         MI.getOperand(2).isImm() &&
3449         isShiftedUInt<3,1>(MI.getOperand(2).getImm()))
3450       return HexagonII::HSIG_L2;
3451     break;
3452   case Hexagon::L2_loadrb_io:
3453     // Rd = memb(Rs+#u3:0)
3454     DstReg = MI.getOperand(0).getReg();
3455     SrcReg = MI.getOperand(1).getReg();
3456     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3457         MI.getOperand(2).isImm() &&
3458         isUInt<3>(MI.getOperand(2).getImm()))
3459       return HexagonII::HSIG_L2;
3460     break;
3461   case Hexagon::L2_loadrd_io:
3462     // Rdd = memd(r29+#u5:3)
3463     DstReg = MI.getOperand(0).getReg();
3464     SrcReg = MI.getOperand(1).getReg();
3465     if (isDblRegForSubInst(DstReg, HRI) &&
3466         Hexagon::IntRegsRegClass.contains(SrcReg) &&
3467         HRI.getStackRegister() == SrcReg &&
3468         MI.getOperand(2).isImm() &&
3469         isShiftedUInt<5,3>(MI.getOperand(2).getImm()))
3470       return HexagonII::HSIG_L2;
3471     break;
3472   // dealloc_return is not documented in Hexagon Manual, but marked
3473   // with A_SUBINSN attribute in iset_v4classic.py.
3474   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4:
3475   case Hexagon::RESTORE_DEALLOC_RET_JMP_V4_PIC:
3476   case Hexagon::L4_return:
3477   case Hexagon::L2_deallocframe:
3478     return HexagonII::HSIG_L2;
3479   case Hexagon::EH_RETURN_JMPR:
3480   case Hexagon::PS_jmpret:
3481     // jumpr r31
3482     // Actual form JMPR %PC<imp-def>, %R31<imp-use>, %R0<imp-use,internal>.
3483     DstReg = MI.getOperand(0).getReg();
3484     if (Hexagon::IntRegsRegClass.contains(DstReg) && (Hexagon::R31 == DstReg))
3485       return HexagonII::HSIG_L2;
3486     break;
3487   case Hexagon::PS_jmprett:
3488   case Hexagon::PS_jmpretf:
3489   case Hexagon::PS_jmprettnewpt:
3490   case Hexagon::PS_jmpretfnewpt:
3491   case Hexagon::PS_jmprettnew:
3492   case Hexagon::PS_jmpretfnew:
3493     DstReg = MI.getOperand(1).getReg();
3494     SrcReg = MI.getOperand(0).getReg();
3495     // [if ([!]p0[.new])] jumpr r31
3496     if ((Hexagon::PredRegsRegClass.contains(SrcReg) &&
3497         (Hexagon::P0 == SrcReg)) &&
3498         (Hexagon::IntRegsRegClass.contains(DstReg) && (Hexagon::R31 == DstReg)))
3499       return HexagonII::HSIG_L2;
3500     break;
3501   case Hexagon::L4_return_t:
3502   case Hexagon::L4_return_f:
3503   case Hexagon::L4_return_tnew_pnt:
3504   case Hexagon::L4_return_fnew_pnt:
3505   case Hexagon::L4_return_tnew_pt:
3506   case Hexagon::L4_return_fnew_pt:
3507     // [if ([!]p0[.new])] dealloc_return
3508     SrcReg = MI.getOperand(0).getReg();
3509     if (Hexagon::PredRegsRegClass.contains(SrcReg) && (Hexagon::P0 == SrcReg))
3510       return HexagonII::HSIG_L2;
3511     break;
3512   //
3513   // Group S1:
3514   //
3515   // memw(Rs+#u4:2) = Rt
3516   // memb(Rs+#u4:0) = Rt
3517   case Hexagon::S2_storeri_io:
3518     // Special case this one from Group S2.
3519     // memw(r29+#u5:2) = Rt
3520     Src1Reg = MI.getOperand(0).getReg();
3521     Src2Reg = MI.getOperand(2).getReg();
3522     if (Hexagon::IntRegsRegClass.contains(Src1Reg) &&
3523         isIntRegForSubInst(Src2Reg) &&
3524         HRI.getStackRegister() == Src1Reg && MI.getOperand(1).isImm() &&
3525         isShiftedUInt<5,2>(MI.getOperand(1).getImm()))
3526       return HexagonII::HSIG_S2;
3527     // memw(Rs+#u4:2) = Rt
3528     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3529         MI.getOperand(1).isImm() &&
3530         isShiftedUInt<4,2>(MI.getOperand(1).getImm()))
3531       return HexagonII::HSIG_S1;
3532     break;
3533   case Hexagon::S2_storerb_io:
3534     // memb(Rs+#u4:0) = Rt
3535     Src1Reg = MI.getOperand(0).getReg();
3536     Src2Reg = MI.getOperand(2).getReg();
3537     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3538         MI.getOperand(1).isImm() && isUInt<4>(MI.getOperand(1).getImm()))
3539       return HexagonII::HSIG_S1;
3540     break;
3541   //
3542   // Group S2:
3543   //
3544   // memh(Rs+#u3:1) = Rt
3545   // memw(r29+#u5:2) = Rt
3546   // memd(r29+#s6:3) = Rtt
3547   // memw(Rs+#u4:2) = #U1
3548   // memb(Rs+#u4) = #U1
3549   // allocframe(#u5:3)
3550   case Hexagon::S2_storerh_io:
3551     // memh(Rs+#u3:1) = Rt
3552     Src1Reg = MI.getOperand(0).getReg();
3553     Src2Reg = MI.getOperand(2).getReg();
3554     if (isIntRegForSubInst(Src1Reg) && isIntRegForSubInst(Src2Reg) &&
3555         MI.getOperand(1).isImm() &&
3556         isShiftedUInt<3,1>(MI.getOperand(1).getImm()))
3557       return HexagonII::HSIG_S1;
3558     break;
3559   case Hexagon::S2_storerd_io:
3560     // memd(r29+#s6:3) = Rtt
3561     Src1Reg = MI.getOperand(0).getReg();
3562     Src2Reg = MI.getOperand(2).getReg();
3563     if (isDblRegForSubInst(Src2Reg, HRI) &&
3564         Hexagon::IntRegsRegClass.contains(Src1Reg) &&
3565         HRI.getStackRegister() == Src1Reg && MI.getOperand(1).isImm() &&
3566         isShiftedInt<6,3>(MI.getOperand(1).getImm()))
3567       return HexagonII::HSIG_S2;
3568     break;
3569   case Hexagon::S4_storeiri_io:
3570     // memw(Rs+#u4:2) = #U1
3571     Src1Reg = MI.getOperand(0).getReg();
3572     if (isIntRegForSubInst(Src1Reg) && MI.getOperand(1).isImm() &&
3573         isShiftedUInt<4,2>(MI.getOperand(1).getImm()) &&
3574         MI.getOperand(2).isImm() && isUInt<1>(MI.getOperand(2).getImm()))
3575       return HexagonII::HSIG_S2;
3576     break;
3577   case Hexagon::S4_storeirb_io:
3578     // memb(Rs+#u4) = #U1
3579     Src1Reg = MI.getOperand(0).getReg();
3580     if (isIntRegForSubInst(Src1Reg) &&
3581         MI.getOperand(1).isImm() && isUInt<4>(MI.getOperand(1).getImm()) &&
3582         MI.getOperand(2).isImm() && isUInt<1>(MI.getOperand(2).getImm()))
3583       return HexagonII::HSIG_S2;
3584     break;
3585   case Hexagon::S2_allocframe:
3586     if (MI.getOperand(0).isImm() &&
3587         isShiftedUInt<5,3>(MI.getOperand(0).getImm()))
3588       return HexagonII::HSIG_S1;
3589     break;
3590   //
3591   // Group A:
3592   //
3593   // Rx = add(Rx,#s7)
3594   // Rd = Rs
3595   // Rd = #u6
3596   // Rd = #-1
3597   // if ([!]P0[.new]) Rd = #0
3598   // Rd = add(r29,#u6:2)
3599   // Rx = add(Rx,Rs)
3600   // P0 = cmp.eq(Rs,#u2)
3601   // Rdd = combine(#0,Rs)
3602   // Rdd = combine(Rs,#0)
3603   // Rdd = combine(#u2,#U2)
3604   // Rd = add(Rs,#1)
3605   // Rd = add(Rs,#-1)
3606   // Rd = sxth/sxtb/zxtb/zxth(Rs)
3607   // Rd = and(Rs,#1)
3608   case Hexagon::A2_addi:
3609     DstReg = MI.getOperand(0).getReg();
3610     SrcReg = MI.getOperand(1).getReg();
3611     if (isIntRegForSubInst(DstReg)) {
3612       // Rd = add(r29,#u6:2)
3613       if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
3614         HRI.getStackRegister() == SrcReg && MI.getOperand(2).isImm() &&
3615         isShiftedUInt<6,2>(MI.getOperand(2).getImm()))
3616         return HexagonII::HSIG_A;
3617       // Rx = add(Rx,#s7)
3618       if ((DstReg == SrcReg) && MI.getOperand(2).isImm() &&
3619           isInt<7>(MI.getOperand(2).getImm()))
3620         return HexagonII::HSIG_A;
3621       // Rd = add(Rs,#1)
3622       // Rd = add(Rs,#-1)
3623       if (isIntRegForSubInst(SrcReg) && MI.getOperand(2).isImm() &&
3624           ((MI.getOperand(2).getImm() == 1) ||
3625           (MI.getOperand(2).getImm() == -1)))
3626         return HexagonII::HSIG_A;
3627     }
3628     break;
3629   case Hexagon::A2_add:
3630     // Rx = add(Rx,Rs)
3631     DstReg = MI.getOperand(0).getReg();
3632     Src1Reg = MI.getOperand(1).getReg();
3633     Src2Reg = MI.getOperand(2).getReg();
3634     if (isIntRegForSubInst(DstReg) && (DstReg == Src1Reg) &&
3635         isIntRegForSubInst(Src2Reg))
3636       return HexagonII::HSIG_A;
3637     break;
3638   case Hexagon::A2_andir:
3639     // Same as zxtb.
3640     // Rd16=and(Rs16,#255)
3641     // Rd16=and(Rs16,#1)
3642     DstReg = MI.getOperand(0).getReg();
3643     SrcReg = MI.getOperand(1).getReg();
3644     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg) &&
3645         MI.getOperand(2).isImm() &&
3646         ((MI.getOperand(2).getImm() == 1) ||
3647         (MI.getOperand(2).getImm() == 255)))
3648       return HexagonII::HSIG_A;
3649     break;
3650   case Hexagon::A2_tfr:
3651     // Rd = Rs
3652     DstReg = MI.getOperand(0).getReg();
3653     SrcReg = MI.getOperand(1).getReg();
3654     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
3655       return HexagonII::HSIG_A;
3656     break;
3657   case Hexagon::A2_tfrsi:
3658     // Rd = #u6
3659     // Do not test for #u6 size since the const is getting extended
3660     // regardless and compound could be formed.
3661     // Rd = #-1
3662     DstReg = MI.getOperand(0).getReg();
3663     if (isIntRegForSubInst(DstReg))
3664       return HexagonII::HSIG_A;
3665     break;
3666   case Hexagon::C2_cmoveit:
3667   case Hexagon::C2_cmovenewit:
3668   case Hexagon::C2_cmoveif:
3669   case Hexagon::C2_cmovenewif:
3670     // if ([!]P0[.new]) Rd = #0
3671     // Actual form:
3672     // %R16<def> = C2_cmovenewit %P0<internal>, 0, %R16<imp-use,undef>;
3673     DstReg = MI.getOperand(0).getReg();
3674     SrcReg = MI.getOperand(1).getReg();
3675     if (isIntRegForSubInst(DstReg) &&
3676         Hexagon::PredRegsRegClass.contains(SrcReg) && Hexagon::P0 == SrcReg &&
3677         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0)
3678       return HexagonII::HSIG_A;
3679     break;
3680   case Hexagon::C2_cmpeqi:
3681     // P0 = cmp.eq(Rs,#u2)
3682     DstReg = MI.getOperand(0).getReg();
3683     SrcReg = MI.getOperand(1).getReg();
3684     if (Hexagon::PredRegsRegClass.contains(DstReg) &&
3685         Hexagon::P0 == DstReg && isIntRegForSubInst(SrcReg) &&
3686         MI.getOperand(2).isImm() && isUInt<2>(MI.getOperand(2).getImm()))
3687       return HexagonII::HSIG_A;
3688     break;
3689   case Hexagon::A2_combineii:
3690   case Hexagon::A4_combineii:
3691     // Rdd = combine(#u2,#U2)
3692     DstReg = MI.getOperand(0).getReg();
3693     if (isDblRegForSubInst(DstReg, HRI) &&
3694         ((MI.getOperand(1).isImm() && isUInt<2>(MI.getOperand(1).getImm())) ||
3695         (MI.getOperand(1).isGlobal() &&
3696         isUInt<2>(MI.getOperand(1).getOffset()))) &&
3697         ((MI.getOperand(2).isImm() && isUInt<2>(MI.getOperand(2).getImm())) ||
3698         (MI.getOperand(2).isGlobal() &&
3699         isUInt<2>(MI.getOperand(2).getOffset()))))
3700       return HexagonII::HSIG_A;
3701     break;
3702   case Hexagon::A4_combineri:
3703     // Rdd = combine(Rs,#0)
3704     DstReg = MI.getOperand(0).getReg();
3705     SrcReg = MI.getOperand(1).getReg();
3706     if (isDblRegForSubInst(DstReg, HRI) && isIntRegForSubInst(SrcReg) &&
3707         ((MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) ||
3708         (MI.getOperand(2).isGlobal() && MI.getOperand(2).getOffset() == 0)))
3709       return HexagonII::HSIG_A;
3710     break;
3711   case Hexagon::A4_combineir:
3712     // Rdd = combine(#0,Rs)
3713     DstReg = MI.getOperand(0).getReg();
3714     SrcReg = MI.getOperand(2).getReg();
3715     if (isDblRegForSubInst(DstReg, HRI) && isIntRegForSubInst(SrcReg) &&
3716         ((MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) ||
3717         (MI.getOperand(1).isGlobal() && MI.getOperand(1).getOffset() == 0)))
3718       return HexagonII::HSIG_A;
3719     break;
3720   case Hexagon::A2_sxtb:
3721   case Hexagon::A2_sxth:
3722   case Hexagon::A2_zxtb:
3723   case Hexagon::A2_zxth:
3724     // Rd = sxth/sxtb/zxtb/zxth(Rs)
3725     DstReg = MI.getOperand(0).getReg();
3726     SrcReg = MI.getOperand(1).getReg();
3727     if (isIntRegForSubInst(DstReg) && isIntRegForSubInst(SrcReg))
3728       return HexagonII::HSIG_A;
3729     break;
3730   }
3731 
3732   return HexagonII::HSIG_None;
3733 }
3734 
3735 short HexagonInstrInfo::getEquivalentHWInstr(const MachineInstr &MI) const {
3736   return Hexagon::getRealHWInstr(MI.getOpcode(), Hexagon::InstrType_Real);
3737 }
3738 
3739 unsigned HexagonInstrInfo::getInstrTimingClassLatency(
3740       const InstrItineraryData *ItinData, const MachineInstr &MI) const {
3741   // Default to one cycle for no itinerary. However, an "empty" itinerary may
3742   // still have a MinLatency property, which getStageLatency checks.
3743   if (!ItinData)
3744     return getInstrLatency(ItinData, MI);
3745 
3746   if (MI.isTransient())
3747     return 0;
3748   return ItinData->getStageLatency(MI.getDesc().getSchedClass());
3749 }
3750 
3751 /// getOperandLatency - Compute and return the use operand latency of a given
3752 /// pair of def and use.
3753 /// In most cases, the static scheduling itinerary was enough to determine the
3754 /// operand latency. But it may not be possible for instructions with variable
3755 /// number of defs / uses.
3756 ///
3757 /// This is a raw interface to the itinerary that may be directly overriden by
3758 /// a target. Use computeOperandLatency to get the best estimate of latency.
3759 int HexagonInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3760                                         const MachineInstr &DefMI,
3761                                         unsigned DefIdx,
3762                                         const MachineInstr &UseMI,
3763                                         unsigned UseIdx) const {
3764   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
3765 
3766   // Get DefIdx and UseIdx for super registers.
3767   MachineOperand DefMO = DefMI.getOperand(DefIdx);
3768 
3769   if (HRI.isPhysicalRegister(DefMO.getReg())) {
3770     if (DefMO.isImplicit()) {
3771       for (MCSuperRegIterator SR(DefMO.getReg(), &HRI); SR.isValid(); ++SR) {
3772         int Idx = DefMI.findRegisterDefOperandIdx(*SR, false, false, &HRI);
3773         if (Idx != -1) {
3774           DefIdx = Idx;
3775           break;
3776         }
3777       }
3778     }
3779 
3780     MachineOperand UseMO = UseMI.getOperand(UseIdx);
3781     if (UseMO.isImplicit()) {
3782       for (MCSuperRegIterator SR(UseMO.getReg(), &HRI); SR.isValid(); ++SR) {
3783         int Idx = UseMI.findRegisterUseOperandIdx(*SR, false, &HRI);
3784         if (Idx != -1) {
3785           UseIdx = Idx;
3786           break;
3787         }
3788       }
3789     }
3790   }
3791 
3792   return TargetInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
3793                                             UseMI, UseIdx);
3794 }
3795 
3796 // inverts the predication logic.
3797 // p -> NotP
3798 // NotP -> P
3799 bool HexagonInstrInfo::getInvertedPredSense(
3800       SmallVectorImpl<MachineOperand> &Cond) const {
3801   if (Cond.empty())
3802     return false;
3803   unsigned Opc = getInvertedPredicatedOpcode(Cond[0].getImm());
3804   Cond[0].setImm(Opc);
3805   return true;
3806 }
3807 
3808 unsigned HexagonInstrInfo::getInvertedPredicatedOpcode(const int Opc) const {
3809   int InvPredOpcode;
3810   InvPredOpcode = isPredicatedTrue(Opc) ? Hexagon::getFalsePredOpcode(Opc)
3811                                         : Hexagon::getTruePredOpcode(Opc);
3812   if (InvPredOpcode >= 0) // Valid instruction with the inverted predicate.
3813     return InvPredOpcode;
3814 
3815   llvm_unreachable("Unexpected predicated instruction");
3816 }
3817 
3818 // Returns the max value that doesn't need to be extended.
3819 int HexagonInstrInfo::getMaxValue(const MachineInstr &MI) const {
3820   const uint64_t F = MI.getDesc().TSFlags;
3821   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
3822                     & HexagonII::ExtentSignedMask;
3823   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
3824                     & HexagonII::ExtentBitsMask;
3825 
3826   if (isSigned) // if value is signed
3827     return ~(-1U << (bits - 1));
3828   else
3829     return ~(-1U << bits);
3830 }
3831 
3832 unsigned HexagonInstrInfo::getMemAccessSize(const MachineInstr &MI) const {
3833   using namespace HexagonII;
3834 
3835   const uint64_t F = MI.getDesc().TSFlags;
3836   unsigned S = (F >> MemAccessSizePos) & MemAccesSizeMask;
3837   unsigned Size = getMemAccessSizeInBytes(MemAccessSize(S));
3838   if (Size != 0)
3839     return Size;
3840 
3841   // Handle vector access sizes.
3842   const HexagonRegisterInfo &HRI = *Subtarget.getRegisterInfo();
3843   switch (S) {
3844     case HexagonII::HVXVectorAccess:
3845       return HRI.getSpillSize(Hexagon::HvxVRRegClass);
3846     default:
3847       llvm_unreachable("Unexpected instruction");
3848   }
3849 }
3850 
3851 // Returns the min value that doesn't need to be extended.
3852 int HexagonInstrInfo::getMinValue(const MachineInstr &MI) const {
3853   const uint64_t F = MI.getDesc().TSFlags;
3854   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
3855                     & HexagonII::ExtentSignedMask;
3856   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
3857                     & HexagonII::ExtentBitsMask;
3858 
3859   if (isSigned) // if value is signed
3860     return -1U << (bits - 1);
3861   else
3862     return 0;
3863 }
3864 
3865 // Returns opcode of the non-extended equivalent instruction.
3866 short HexagonInstrInfo::getNonExtOpcode(const MachineInstr &MI) const {
3867   // Check if the instruction has a register form that uses register in place
3868   // of the extended operand, if so return that as the non-extended form.
3869   short NonExtOpcode = Hexagon::getRegForm(MI.getOpcode());
3870     if (NonExtOpcode >= 0)
3871       return NonExtOpcode;
3872 
3873   if (MI.getDesc().mayLoad() || MI.getDesc().mayStore()) {
3874     // Check addressing mode and retrieve non-ext equivalent instruction.
3875     switch (getAddrMode(MI)) {
3876     case HexagonII::Absolute:
3877       return Hexagon::changeAddrMode_abs_io(MI.getOpcode());
3878     case HexagonII::BaseImmOffset:
3879       return Hexagon::changeAddrMode_io_rr(MI.getOpcode());
3880     case HexagonII::BaseLongOffset:
3881       return Hexagon::changeAddrMode_ur_rr(MI.getOpcode());
3882 
3883     default:
3884       return -1;
3885     }
3886   }
3887   return -1;
3888 }
3889 
3890 bool HexagonInstrInfo::getPredReg(ArrayRef<MachineOperand> Cond,
3891       unsigned &PredReg, unsigned &PredRegPos, unsigned &PredRegFlags) const {
3892   if (Cond.empty())
3893     return false;
3894   assert(Cond.size() == 2);
3895   if (isNewValueJump(Cond[0].getImm()) || Cond[1].isMBB()) {
3896     DEBUG(dbgs() << "No predregs for new-value jumps/endloop");
3897     return false;
3898   }
3899   PredReg = Cond[1].getReg();
3900   PredRegPos = 1;
3901   // See IfConversion.cpp why we add RegState::Implicit | RegState::Undef
3902   PredRegFlags = 0;
3903   if (Cond[1].isImplicit())
3904     PredRegFlags = RegState::Implicit;
3905   if (Cond[1].isUndef())
3906     PredRegFlags |= RegState::Undef;
3907   return true;
3908 }
3909 
3910 short HexagonInstrInfo::getPseudoInstrPair(const MachineInstr &MI) const {
3911   return Hexagon::getRealHWInstr(MI.getOpcode(), Hexagon::InstrType_Pseudo);
3912 }
3913 
3914 short HexagonInstrInfo::getRegForm(const MachineInstr &MI) const {
3915   return Hexagon::getRegForm(MI.getOpcode());
3916 }
3917 
3918 // Return the number of bytes required to encode the instruction.
3919 // Hexagon instructions are fixed length, 4 bytes, unless they
3920 // use a constant extender, which requires another 4 bytes.
3921 // For debug instructions and prolog labels, return 0.
3922 unsigned HexagonInstrInfo::getSize(const MachineInstr &MI) const {
3923   if (MI.isDebugValue() || MI.isPosition())
3924     return 0;
3925 
3926   unsigned Size = MI.getDesc().getSize();
3927   if (!Size)
3928     // Assume the default insn size in case it cannot be determined
3929     // for whatever reason.
3930     Size = HEXAGON_INSTR_SIZE;
3931 
3932   if (isConstExtended(MI) || isExtended(MI))
3933     Size += HEXAGON_INSTR_SIZE;
3934 
3935   // Try and compute number of instructions in asm.
3936   if (BranchRelaxAsmLarge && MI.getOpcode() == Hexagon::INLINEASM) {
3937     const MachineBasicBlock &MBB = *MI.getParent();
3938     const MachineFunction *MF = MBB.getParent();
3939     const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
3940 
3941     // Count the number of register definitions to find the asm string.
3942     unsigned NumDefs = 0;
3943     for (; MI.getOperand(NumDefs).isReg() && MI.getOperand(NumDefs).isDef();
3944          ++NumDefs)
3945       assert(NumDefs != MI.getNumOperands()-2 && "No asm string?");
3946 
3947     assert(MI.getOperand(NumDefs).isSymbol() && "No asm string?");
3948     // Disassemble the AsmStr and approximate number of instructions.
3949     const char *AsmStr = MI.getOperand(NumDefs).getSymbolName();
3950     Size = getInlineAsmLength(AsmStr, *MAI);
3951   }
3952 
3953   return Size;
3954 }
3955 
3956 uint64_t HexagonInstrInfo::getType(const MachineInstr &MI) const {
3957   const uint64_t F = MI.getDesc().TSFlags;
3958   return (F >> HexagonII::TypePos) & HexagonII::TypeMask;
3959 }
3960 
3961 unsigned HexagonInstrInfo::getUnits(const MachineInstr &MI) const {
3962   const InstrItineraryData &II = *Subtarget.getInstrItineraryData();
3963   const InstrStage &IS = *II.beginStage(MI.getDesc().getSchedClass());
3964 
3965   return IS.getUnits();
3966 }
3967 
3968 // Calculate size of the basic block without debug instructions.
3969 unsigned HexagonInstrInfo::nonDbgBBSize(const MachineBasicBlock *BB) const {
3970   return nonDbgMICount(BB->instr_begin(), BB->instr_end());
3971 }
3972 
3973 unsigned HexagonInstrInfo::nonDbgBundleSize(
3974       MachineBasicBlock::const_iterator BundleHead) const {
3975   assert(BundleHead->isBundle() && "Not a bundle header");
3976   auto MII = BundleHead.getInstrIterator();
3977   // Skip the bundle header.
3978   return nonDbgMICount(++MII, getBundleEnd(BundleHead.getInstrIterator()));
3979 }
3980 
3981 /// immediateExtend - Changes the instruction in place to one using an immediate
3982 /// extender.
3983 void HexagonInstrInfo::immediateExtend(MachineInstr &MI) const {
3984   assert((isExtendable(MI)||isConstExtended(MI)) &&
3985                                "Instruction must be extendable");
3986   // Find which operand is extendable.
3987   short ExtOpNum = getCExtOpNum(MI);
3988   MachineOperand &MO = MI.getOperand(ExtOpNum);
3989   // This needs to be something we understand.
3990   assert((MO.isMBB() || MO.isImm()) &&
3991          "Branch with unknown extendable field type");
3992   // Mark given operand as extended.
3993   MO.addTargetFlag(HexagonII::HMOTF_ConstExtended);
3994 }
3995 
3996 bool HexagonInstrInfo::invertAndChangeJumpTarget(
3997       MachineInstr &MI, MachineBasicBlock *NewTarget) const {
3998   DEBUG(dbgs() << "\n[invertAndChangeJumpTarget] to BB#"
3999                << NewTarget->getNumber(); MI.dump(););
4000   assert(MI.isBranch());
4001   unsigned NewOpcode = getInvertedPredicatedOpcode(MI.getOpcode());
4002   int TargetPos = MI.getNumOperands() - 1;
4003   // In general branch target is the last operand,
4004   // but some implicit defs added at the end might change it.
4005   while ((TargetPos > -1) && !MI.getOperand(TargetPos).isMBB())
4006     --TargetPos;
4007   assert((TargetPos >= 0) && MI.getOperand(TargetPos).isMBB());
4008   MI.getOperand(TargetPos).setMBB(NewTarget);
4009   if (EnableBranchPrediction && isPredicatedNew(MI)) {
4010     NewOpcode = reversePrediction(NewOpcode);
4011   }
4012   MI.setDesc(get(NewOpcode));
4013   return true;
4014 }
4015 
4016 void HexagonInstrInfo::genAllInsnTimingClasses(MachineFunction &MF) const {
4017   /* +++ The code below is used to generate complete set of Hexagon Insn +++ */
4018   MachineFunction::iterator A = MF.begin();
4019   MachineBasicBlock &B = *A;
4020   MachineBasicBlock::iterator I = B.begin();
4021   DebugLoc DL = I->getDebugLoc();
4022   MachineInstr *NewMI;
4023 
4024   for (unsigned insn = TargetOpcode::GENERIC_OP_END+1;
4025        insn < Hexagon::INSTRUCTION_LIST_END; ++insn) {
4026     NewMI = BuildMI(B, I, DL, get(insn));
4027     DEBUG(dbgs() << "\n" << getName(NewMI->getOpcode()) <<
4028           "  Class: " << NewMI->getDesc().getSchedClass());
4029     NewMI->eraseFromParent();
4030   }
4031   /* --- The code above is used to generate complete set of Hexagon Insn --- */
4032 }
4033 
4034 // inverts the predication logic.
4035 // p -> NotP
4036 // NotP -> P
4037 bool HexagonInstrInfo::reversePredSense(MachineInstr &MI) const {
4038   DEBUG(dbgs() << "\nTrying to reverse pred. sense of:"; MI.dump());
4039   MI.setDesc(get(getInvertedPredicatedOpcode(MI.getOpcode())));
4040   return true;
4041 }
4042 
4043 // Reverse the branch prediction.
4044 unsigned HexagonInstrInfo::reversePrediction(unsigned Opcode) const {
4045   int PredRevOpcode = -1;
4046   if (isPredictedTaken(Opcode))
4047     PredRevOpcode = Hexagon::notTakenBranchPrediction(Opcode);
4048   else
4049     PredRevOpcode = Hexagon::takenBranchPrediction(Opcode);
4050   assert(PredRevOpcode > 0);
4051   return PredRevOpcode;
4052 }
4053 
4054 // TODO: Add more rigorous validation.
4055 bool HexagonInstrInfo::validateBranchCond(const ArrayRef<MachineOperand> &Cond)
4056       const {
4057   return Cond.empty() || (Cond[0].isImm() && (Cond.size() != 1));
4058 }
4059 
4060 // Addressing mode relations.
4061 short HexagonInstrInfo::changeAddrMode_abs_io(short Opc) const {
4062   return Opc >= 0 ? Hexagon::changeAddrMode_abs_io(Opc) : Opc;
4063 }
4064 
4065 short HexagonInstrInfo::changeAddrMode_io_abs(short Opc) const {
4066   return Opc >= 0 ? Hexagon::changeAddrMode_io_abs(Opc) : Opc;
4067 }
4068 
4069 short HexagonInstrInfo::changeAddrMode_io_rr(short Opc) const {
4070   return Opc >= 0 ? Hexagon::changeAddrMode_io_rr(Opc) : Opc;
4071 }
4072 
4073 short HexagonInstrInfo::changeAddrMode_rr_io(short Opc) const {
4074   return Opc >= 0 ? Hexagon::changeAddrMode_rr_io(Opc) : Opc;
4075 }
4076 
4077 short HexagonInstrInfo::changeAddrMode_rr_ur(short Opc) const {
4078   return Opc >= 0 ? Hexagon::changeAddrMode_rr_ur(Opc) : Opc;
4079 }
4080 
4081 short HexagonInstrInfo::changeAddrMode_ur_rr(short Opc) const {
4082   return Opc >= 0 ? Hexagon::changeAddrMode_ur_rr(Opc) : Opc;
4083 }
4084