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