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