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