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