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