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