[Hexagon] Reapplying 224775 load words.
[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/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/raw_ostream.h"
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "hexagon-instrinfo"
33
34 #define GET_INSTRINFO_CTOR_DTOR
35 #define GET_INSTRMAP_INFO
36 #include "HexagonGenInstrInfo.inc"
37 #include "HexagonGenDFAPacketizer.inc"
38
39 ///
40 /// Constants for Hexagon instructions.
41 ///
42 const int Hexagon_MEMW_OFFSET_MAX = 4095;
43 const int Hexagon_MEMW_OFFSET_MIN = -4096;
44 const int Hexagon_MEMD_OFFSET_MAX = 8191;
45 const int Hexagon_MEMD_OFFSET_MIN = -8192;
46 const int Hexagon_MEMH_OFFSET_MAX = 2047;
47 const int Hexagon_MEMH_OFFSET_MIN = -2048;
48 const int Hexagon_MEMB_OFFSET_MAX = 1023;
49 const int Hexagon_MEMB_OFFSET_MIN = -1024;
50 const int Hexagon_ADDI_OFFSET_MAX = 32767;
51 const int Hexagon_ADDI_OFFSET_MIN = -32768;
52 const int Hexagon_MEMD_AUTOINC_MAX = 56;
53 const int Hexagon_MEMD_AUTOINC_MIN = -64;
54 const int Hexagon_MEMW_AUTOINC_MAX = 28;
55 const int Hexagon_MEMW_AUTOINC_MIN = -32;
56 const int Hexagon_MEMH_AUTOINC_MAX = 14;
57 const int Hexagon_MEMH_AUTOINC_MIN = -16;
58 const int Hexagon_MEMB_AUTOINC_MAX = 7;
59 const int Hexagon_MEMB_AUTOINC_MIN = -8;
60
61 // Pin the vtable to this file.
62 void HexagonInstrInfo::anchor() {}
63
64 HexagonInstrInfo::HexagonInstrInfo(HexagonSubtarget &ST)
65   : HexagonGenInstrInfo(Hexagon::ADJCALLSTACKDOWN, Hexagon::ADJCALLSTACKUP),
66     RI(ST), Subtarget(ST) {
67 }
68
69
70 /// isLoadFromStackSlot - If the specified machine instruction is a direct
71 /// load from a stack slot, return the virtual or physical register number of
72 /// the destination along with the FrameIndex of the loaded stack slot.  If
73 /// not, return 0.  This predicate must return 0 if the instruction has
74 /// any side effects other than loading from the stack slot.
75 unsigned HexagonInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
76                                              int &FrameIndex) const {
77
78
79   switch (MI->getOpcode()) {
80   default: break;
81   case Hexagon::L2_loadri_io:
82   case Hexagon::LDrid:
83   case Hexagon::L2_loadrh_io:
84   case Hexagon::L2_loadrb_io:
85   case Hexagon::L2_loadrub_io:
86     if (MI->getOperand(2).isFI() &&
87         MI->getOperand(1).isImm() && (MI->getOperand(1).getImm() == 0)) {
88       FrameIndex = MI->getOperand(2).getIndex();
89       return MI->getOperand(0).getReg();
90     }
91     break;
92   }
93   return 0;
94 }
95
96
97 /// isStoreToStackSlot - If the specified machine instruction is a direct
98 /// store to a stack slot, return the virtual or physical register number of
99 /// the source reg along with the FrameIndex of the loaded stack slot.  If
100 /// not, return 0.  This predicate must return 0 if the instruction has
101 /// any side effects other than storing to the stack slot.
102 unsigned HexagonInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
103                                             int &FrameIndex) const {
104   switch (MI->getOpcode()) {
105   default: break;
106   case Hexagon::STriw:
107   case Hexagon::STrid:
108   case Hexagon::STrih:
109   case Hexagon::STrib:
110     if (MI->getOperand(2).isFI() &&
111         MI->getOperand(1).isImm() && (MI->getOperand(1).getImm() == 0)) {
112       FrameIndex = MI->getOperand(0).getIndex();
113       return MI->getOperand(2).getReg();
114     }
115     break;
116   }
117   return 0;
118 }
119
120
121 unsigned
122 HexagonInstrInfo::InsertBranch(MachineBasicBlock &MBB,MachineBasicBlock *TBB,
123                              MachineBasicBlock *FBB,
124                              const SmallVectorImpl<MachineOperand> &Cond,
125                              DebugLoc DL) const{
126
127     int BOpc   = Hexagon::J2_jump;
128     int BccOpc = Hexagon::J2_jumpt;
129
130     assert(TBB && "InsertBranch must not be told to insert a fallthrough");
131
132     int regPos = 0;
133     // Check if ReverseBranchCondition has asked to reverse this branch
134     // If we want to reverse the branch an odd number of times, we want
135     // JMP_f.
136     if (!Cond.empty() && Cond[0].isImm() && Cond[0].getImm() == 0) {
137       BccOpc = Hexagon::J2_jumpf;
138       regPos = 1;
139     }
140
141     if (!FBB) {
142       if (Cond.empty()) {
143         // Due to a bug in TailMerging/CFG Optimization, we need to add a
144         // special case handling of a predicated jump followed by an
145         // unconditional jump. If not, Tail Merging and CFG Optimization go
146         // into an infinite loop.
147         MachineBasicBlock *NewTBB, *NewFBB;
148         SmallVector<MachineOperand, 4> Cond;
149         MachineInstr *Term = MBB.getFirstTerminator();
150         if (isPredicated(Term) && !AnalyzeBranch(MBB, NewTBB, NewFBB, Cond,
151                                                  false)) {
152           MachineBasicBlock *NextBB =
153             std::next(MachineFunction::iterator(&MBB));
154           if (NewTBB == NextBB) {
155             ReverseBranchCondition(Cond);
156             RemoveBranch(MBB);
157             return InsertBranch(MBB, TBB, nullptr, Cond, DL);
158           }
159         }
160         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
161       } else {
162         BuildMI(&MBB, DL,
163                 get(BccOpc)).addReg(Cond[regPos].getReg()).addMBB(TBB);
164       }
165       return 1;
166     }
167
168     BuildMI(&MBB, DL, get(BccOpc)).addReg(Cond[regPos].getReg()).addMBB(TBB);
169     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
170
171     return 2;
172 }
173
174
175 bool HexagonInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
176                                      MachineBasicBlock *&TBB,
177                                  MachineBasicBlock *&FBB,
178                                  SmallVectorImpl<MachineOperand> &Cond,
179                                  bool AllowModify) const {
180   TBB = nullptr;
181   FBB = nullptr;
182
183   // If the block has no terminators, it just falls into the block after it.
184   MachineBasicBlock::instr_iterator I = MBB.instr_end();
185   if (I == MBB.instr_begin())
186     return false;
187
188   // A basic block may looks like this:
189   //
190   //  [   insn
191   //     EH_LABEL
192   //      insn
193   //      insn
194   //      insn
195   //     EH_LABEL
196   //      insn     ]
197   //
198   // It has two succs but does not have a terminator
199   // Don't know how to handle it.
200   do {
201     --I;
202     if (I->isEHLabel())
203       return true;
204   } while (I != MBB.instr_begin());
205
206   I = MBB.instr_end();
207   --I;
208
209   while (I->isDebugValue()) {
210     if (I == MBB.instr_begin())
211       return false;
212     --I;
213   }
214
215   // Delete the JMP if it's equivalent to a fall-through.
216   if (AllowModify && I->getOpcode() == Hexagon::J2_jump &&
217       MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
218     DEBUG(dbgs()<< "\nErasing the jump to successor block\n";);
219     I->eraseFromParent();
220     I = MBB.instr_end();
221     if (I == MBB.instr_begin())
222       return false;
223     --I;
224   }
225   if (!isUnpredicatedTerminator(I))
226     return false;
227
228   // Get the last instruction in the block.
229   MachineInstr *LastInst = I;
230   MachineInstr *SecondLastInst = nullptr;
231   // Find one more terminator if present.
232   do {
233     if (&*I != LastInst && !I->isBundle() && isUnpredicatedTerminator(I)) {
234       if (!SecondLastInst)
235         SecondLastInst = I;
236       else
237         // This is a third branch.
238         return true;
239     }
240     if (I == MBB.instr_begin())
241       break;
242     --I;
243   } while(I);
244
245   int LastOpcode = LastInst->getOpcode();
246
247   bool LastOpcodeHasJMP_c = PredOpcodeHasJMP_c(LastOpcode);
248   bool LastOpcodeHasNot = PredOpcodeHasNot(LastOpcode);
249
250   // If there is only one terminator instruction, process it.
251   if (LastInst && !SecondLastInst) {
252     if (LastOpcode == Hexagon::J2_jump) {
253       TBB = LastInst->getOperand(0).getMBB();
254       return false;
255     }
256     if (LastOpcode == Hexagon::ENDLOOP0) {
257       TBB = LastInst->getOperand(0).getMBB();
258       Cond.push_back(LastInst->getOperand(0));
259       return false;
260     }
261     if (LastOpcodeHasJMP_c) {
262       TBB = LastInst->getOperand(1).getMBB();
263       if (LastOpcodeHasNot) {
264         Cond.push_back(MachineOperand::CreateImm(0));
265       }
266       Cond.push_back(LastInst->getOperand(0));
267       return false;
268     }
269     // Otherwise, don't know what this is.
270     return true;
271   }
272
273   int SecLastOpcode = SecondLastInst->getOpcode();
274
275   bool SecLastOpcodeHasJMP_c = PredOpcodeHasJMP_c(SecLastOpcode);
276   bool SecLastOpcodeHasNot = PredOpcodeHasNot(SecLastOpcode);
277   if (SecLastOpcodeHasJMP_c && (LastOpcode == Hexagon::J2_jump)) {
278     TBB =  SecondLastInst->getOperand(1).getMBB();
279     if (SecLastOpcodeHasNot)
280       Cond.push_back(MachineOperand::CreateImm(0));
281     Cond.push_back(SecondLastInst->getOperand(0));
282     FBB = LastInst->getOperand(0).getMBB();
283     return false;
284   }
285
286   // If the block ends with two Hexagon:JMPs, handle it.  The second one is not
287   // executed, so remove it.
288   if (SecLastOpcode == Hexagon::J2_jump && LastOpcode == Hexagon::J2_jump) {
289     TBB = SecondLastInst->getOperand(0).getMBB();
290     I = LastInst;
291     if (AllowModify)
292       I->eraseFromParent();
293     return false;
294   }
295
296   // If the block ends with an ENDLOOP, and JMP, handle it.
297   if (SecLastOpcode == Hexagon::ENDLOOP0 &&
298       LastOpcode == Hexagon::J2_jump) {
299     TBB = SecondLastInst->getOperand(0).getMBB();
300     Cond.push_back(SecondLastInst->getOperand(0));
301     FBB = LastInst->getOperand(0).getMBB();
302     return false;
303   }
304
305   // Otherwise, can't handle this.
306   return true;
307 }
308
309
310 unsigned HexagonInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
311   int BOpc   = Hexagon::J2_jump;
312   int BccOpc = Hexagon::J2_jumpt;
313   int BccOpcNot = Hexagon::J2_jumpf;
314
315   MachineBasicBlock::iterator I = MBB.end();
316   if (I == MBB.begin()) return 0;
317   --I;
318   if (I->getOpcode() != BOpc && I->getOpcode() != BccOpc &&
319       I->getOpcode() != BccOpcNot)
320     return 0;
321
322   // Remove the branch.
323   I->eraseFromParent();
324
325   I = MBB.end();
326
327   if (I == MBB.begin()) return 1;
328   --I;
329   if (I->getOpcode() != BccOpc && I->getOpcode() != BccOpcNot)
330     return 1;
331
332   // Remove the branch.
333   I->eraseFromParent();
334   return 2;
335 }
336
337
338 /// \brief For a comparison instruction, return the source registers in
339 /// \p SrcReg and \p SrcReg2 if having two register operands, and the value it
340 /// compares against in CmpValue. Return true if the comparison instruction
341 /// can be analyzed.
342 bool HexagonInstrInfo::analyzeCompare(const MachineInstr *MI,
343                                       unsigned &SrcReg, unsigned &SrcReg2,
344                                       int &Mask, int &Value) const {
345   unsigned Opc = MI->getOpcode();
346
347   // Set mask and the first source register.
348   switch (Opc) {
349     case Hexagon::C2_cmpeqp:
350     case Hexagon::C2_cmpeqi:
351     case Hexagon::C2_cmpeq:
352     case Hexagon::C2_cmpgtp:
353     case Hexagon::C2_cmpgtup:
354     case Hexagon::C2_cmpgtui:
355     case Hexagon::C2_cmpgtu:
356     case Hexagon::C2_cmpgti:
357     case Hexagon::C2_cmpgt:
358       SrcReg = MI->getOperand(1).getReg();
359       Mask = ~0;
360       break;
361     case Hexagon::CMPbEQri_V4:
362     case Hexagon::CMPbEQrr_sbsb_V4:
363     case Hexagon::CMPbEQrr_ubub_V4:
364     case Hexagon::CMPbGTUri_V4:
365     case Hexagon::CMPbGTUrr_V4:
366     case Hexagon::CMPbGTrr_V4:
367       SrcReg = MI->getOperand(1).getReg();
368       Mask = 0xFF;
369       break;
370     case Hexagon::CMPhEQri_V4:
371     case Hexagon::CMPhEQrr_shl_V4:
372     case Hexagon::CMPhEQrr_xor_V4:
373     case Hexagon::CMPhGTUri_V4:
374     case Hexagon::CMPhGTUrr_V4:
375     case Hexagon::CMPhGTrr_shl_V4:
376       SrcReg = MI->getOperand(1).getReg();
377       Mask = 0xFFFF;
378       break;
379   }
380
381   // Set the value/second source register.
382   switch (Opc) {
383     case Hexagon::C2_cmpeqp:
384     case Hexagon::C2_cmpeq:
385     case Hexagon::C2_cmpgtp:
386     case Hexagon::C2_cmpgtup:
387     case Hexagon::C2_cmpgtu:
388     case Hexagon::C2_cmpgt:
389     case Hexagon::CMPbEQrr_sbsb_V4:
390     case Hexagon::CMPbEQrr_ubub_V4:
391     case Hexagon::CMPbGTUrr_V4:
392     case Hexagon::CMPbGTrr_V4:
393     case Hexagon::CMPhEQrr_shl_V4:
394     case Hexagon::CMPhEQrr_xor_V4:
395     case Hexagon::CMPhGTUrr_V4:
396     case Hexagon::CMPhGTrr_shl_V4:
397       SrcReg2 = MI->getOperand(2).getReg();
398       return true;
399
400     case Hexagon::C2_cmpeqi:
401     case Hexagon::C2_cmpgtui:
402     case Hexagon::C2_cmpgti:
403     case Hexagon::CMPbEQri_V4:
404     case Hexagon::CMPbGTUri_V4:
405     case Hexagon::CMPhEQri_V4:
406     case Hexagon::CMPhGTUri_V4:
407       SrcReg2 = 0;
408       Value = MI->getOperand(2).getImm();
409       return true;
410   }
411
412   return false;
413 }
414
415
416 void HexagonInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
417                                  MachineBasicBlock::iterator I, DebugLoc DL,
418                                  unsigned DestReg, unsigned SrcReg,
419                                  bool KillSrc) const {
420   if (Hexagon::IntRegsRegClass.contains(SrcReg, DestReg)) {
421     BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), DestReg).addReg(SrcReg);
422     return;
423   }
424   if (Hexagon::DoubleRegsRegClass.contains(SrcReg, DestReg)) {
425     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrp), DestReg).addReg(SrcReg);
426     return;
427   }
428   if (Hexagon::PredRegsRegClass.contains(SrcReg, DestReg)) {
429     // Map Pd = Ps to Pd = or(Ps, Ps).
430     BuildMI(MBB, I, DL, get(Hexagon::C2_or),
431             DestReg).addReg(SrcReg).addReg(SrcReg);
432     return;
433   }
434   if (Hexagon::DoubleRegsRegClass.contains(DestReg) &&
435       Hexagon::IntRegsRegClass.contains(SrcReg)) {
436     // We can have an overlap between single and double reg: r1:0 = r0.
437     if(SrcReg == RI.getSubReg(DestReg, Hexagon::subreg_loreg)) {
438         // r1:0 = r0
439         BuildMI(MBB, I, DL, get(Hexagon::A2_tfrsi), (RI.getSubReg(DestReg,
440                 Hexagon::subreg_hireg))).addImm(0);
441     } else {
442         // r1:0 = r1 or no overlap.
443         BuildMI(MBB, I, DL, get(Hexagon::A2_tfr), (RI.getSubReg(DestReg,
444                 Hexagon::subreg_loreg))).addReg(SrcReg);
445         BuildMI(MBB, I, DL, get(Hexagon::A2_tfrsi), (RI.getSubReg(DestReg,
446                 Hexagon::subreg_hireg))).addImm(0);
447     }
448     return;
449   }
450   if (Hexagon::CtrRegsRegClass.contains(DestReg) &&
451       Hexagon::IntRegsRegClass.contains(SrcReg)) {
452     BuildMI(MBB, I, DL, get(Hexagon::A2_tfrrcr), DestReg).addReg(SrcReg);
453     return;
454   }
455   if (Hexagon::PredRegsRegClass.contains(SrcReg) &&
456       Hexagon::IntRegsRegClass.contains(DestReg)) {
457     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrpr), DestReg).
458       addReg(SrcReg, getKillRegState(KillSrc));
459     return;
460   }
461   if (Hexagon::IntRegsRegClass.contains(SrcReg) &&
462       Hexagon::PredRegsRegClass.contains(DestReg)) {
463     BuildMI(MBB, I, DL, get(Hexagon::C2_tfrrp), DestReg).
464       addReg(SrcReg, getKillRegState(KillSrc));
465     return;
466   }
467
468   llvm_unreachable("Unimplemented");
469 }
470
471
472 void HexagonInstrInfo::
473 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
474                     unsigned SrcReg, bool isKill, int FI,
475                     const TargetRegisterClass *RC,
476                     const TargetRegisterInfo *TRI) const {
477
478   DebugLoc DL = MBB.findDebugLoc(I);
479   MachineFunction &MF = *MBB.getParent();
480   MachineFrameInfo &MFI = *MF.getFrameInfo();
481   unsigned Align = MFI.getObjectAlignment(FI);
482
483   MachineMemOperand *MMO =
484       MF.getMachineMemOperand(
485                       MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
486                       MachineMemOperand::MOStore,
487                       MFI.getObjectSize(FI),
488                       Align);
489
490   if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) {
491     BuildMI(MBB, I, DL, get(Hexagon::STriw))
492           .addFrameIndex(FI).addImm(0)
493           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
494   } else if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) {
495     BuildMI(MBB, I, DL, get(Hexagon::STrid))
496           .addFrameIndex(FI).addImm(0)
497           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
498   } else if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) {
499     BuildMI(MBB, I, DL, get(Hexagon::STriw_pred))
500           .addFrameIndex(FI).addImm(0)
501           .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO);
502   } else {
503     llvm_unreachable("Unimplemented");
504   }
505 }
506
507
508 void HexagonInstrInfo::storeRegToAddr(
509                                  MachineFunction &MF, unsigned SrcReg,
510                                  bool isKill,
511                                  SmallVectorImpl<MachineOperand> &Addr,
512                                  const TargetRegisterClass *RC,
513                                  SmallVectorImpl<MachineInstr*> &NewMIs) const
514 {
515   llvm_unreachable("Unimplemented");
516 }
517
518
519 void HexagonInstrInfo::
520 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
521                      unsigned DestReg, int FI,
522                      const TargetRegisterClass *RC,
523                      const TargetRegisterInfo *TRI) const {
524   DebugLoc DL = MBB.findDebugLoc(I);
525   MachineFunction &MF = *MBB.getParent();
526   MachineFrameInfo &MFI = *MF.getFrameInfo();
527   unsigned Align = MFI.getObjectAlignment(FI);
528
529   MachineMemOperand *MMO =
530       MF.getMachineMemOperand(
531                       MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
532                       MachineMemOperand::MOLoad,
533                       MFI.getObjectSize(FI),
534                       Align);
535   if (RC == &Hexagon::IntRegsRegClass) {
536     BuildMI(MBB, I, DL, get(Hexagon::L2_loadri_io), DestReg)
537           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
538   } else if (RC == &Hexagon::DoubleRegsRegClass) {
539     BuildMI(MBB, I, DL, get(Hexagon::LDrid), DestReg)
540           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
541   } else if (RC == &Hexagon::PredRegsRegClass) {
542     BuildMI(MBB, I, DL, get(Hexagon::LDriw_pred), DestReg)
543           .addFrameIndex(FI).addImm(0).addMemOperand(MMO);
544   } else {
545     llvm_unreachable("Can't store this register to stack slot");
546   }
547 }
548
549
550 void HexagonInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
551                                         SmallVectorImpl<MachineOperand> &Addr,
552                                         const TargetRegisterClass *RC,
553                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
554   llvm_unreachable("Unimplemented");
555 }
556
557
558 MachineInstr *HexagonInstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
559                                                     MachineInstr* MI,
560                                           const SmallVectorImpl<unsigned> &Ops,
561                                                     int FI) const {
562   // Hexagon_TODO: Implement.
563   return nullptr;
564 }
565
566 unsigned HexagonInstrInfo::createVR(MachineFunction* MF, MVT VT) const {
567
568   MachineRegisterInfo &RegInfo = MF->getRegInfo();
569   const TargetRegisterClass *TRC;
570   if (VT == MVT::i1) {
571     TRC = &Hexagon::PredRegsRegClass;
572   } else if (VT == MVT::i32 || VT == MVT::f32) {
573     TRC = &Hexagon::IntRegsRegClass;
574   } else if (VT == MVT::i64 || VT == MVT::f64) {
575     TRC = &Hexagon::DoubleRegsRegClass;
576   } else {
577     llvm_unreachable("Cannot handle this register class");
578   }
579
580   unsigned NewReg = RegInfo.createVirtualRegister(TRC);
581   return NewReg;
582 }
583
584 bool HexagonInstrInfo::isExtendable(const MachineInstr *MI) const {
585   // Constant extenders are allowed only for V4 and above.
586   if (!Subtarget.hasV4TOps())
587     return false;
588
589   const MCInstrDesc &MID = MI->getDesc();
590   const uint64_t F = MID.TSFlags;
591   if ((F >> HexagonII::ExtendablePos) & HexagonII::ExtendableMask)
592     return true;
593
594   // TODO: This is largely obsolete now. Will need to be removed
595   // in consecutive patches.
596   switch(MI->getOpcode()) {
597     // TFR_FI Remains a special case.
598     case Hexagon::TFR_FI:
599       return true;
600     default:
601       return false;
602   }
603   return  false;
604 }
605
606 // This returns true in two cases:
607 // - The OP code itself indicates that this is an extended instruction.
608 // - One of MOs has been marked with HMOTF_ConstExtended flag.
609 bool HexagonInstrInfo::isExtended(const MachineInstr *MI) const {
610   // First check if this is permanently extended op code.
611   const uint64_t F = MI->getDesc().TSFlags;
612   if ((F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask)
613     return true;
614   // Use MO operand flags to determine if one of MI's operands
615   // has HMOTF_ConstExtended flag set.
616   for (MachineInstr::const_mop_iterator I = MI->operands_begin(),
617        E = MI->operands_end(); I != E; ++I) {
618     if (I->getTargetFlags() && HexagonII::HMOTF_ConstExtended)
619       return true;
620   }
621   return  false;
622 }
623
624 bool HexagonInstrInfo::isBranch (const MachineInstr *MI) const {
625   return MI->getDesc().isBranch();
626 }
627
628 bool HexagonInstrInfo::isNewValueInst(const MachineInstr *MI) const {
629   if (isNewValueJump(MI))
630     return true;
631
632   if (isNewValueStore(MI))
633     return true;
634
635   return false;
636 }
637
638 bool HexagonInstrInfo::isSaveCalleeSavedRegsCall(const MachineInstr *MI) const {
639   return MI->getOpcode() == Hexagon::SAVE_REGISTERS_CALL_V4;
640 }
641
642 bool HexagonInstrInfo::isPredicable(MachineInstr *MI) const {
643   bool isPred = MI->getDesc().isPredicable();
644
645   if (!isPred)
646     return false;
647
648   const int Opc = MI->getOpcode();
649
650   switch(Opc) {
651   case Hexagon::A2_tfrsi:
652     return isInt<12>(MI->getOperand(1).getImm());
653
654   case Hexagon::STrid:
655   case Hexagon::STrid_indexed:
656     return isShiftedUInt<6,3>(MI->getOperand(1).getImm());
657
658   case Hexagon::STriw:
659   case Hexagon::STriw_indexed:
660   case Hexagon::STriw_nv_V4:
661     return isShiftedUInt<6,2>(MI->getOperand(1).getImm());
662
663   case Hexagon::STrih:
664   case Hexagon::STrih_indexed:
665   case Hexagon::STrih_nv_V4:
666     return isShiftedUInt<6,1>(MI->getOperand(1).getImm());
667
668   case Hexagon::STrib:
669   case Hexagon::STrib_indexed:
670   case Hexagon::STrib_nv_V4:
671     return isUInt<6>(MI->getOperand(1).getImm());
672
673   case Hexagon::LDrid:
674   case Hexagon::LDrid_indexed:
675     return isShiftedUInt<6,3>(MI->getOperand(2).getImm());
676
677   case Hexagon::L2_loadri_io:
678     return isShiftedUInt<6,2>(MI->getOperand(2).getImm());
679
680   case Hexagon::L2_loadrh_io:
681   case Hexagon::L2_loadruh_io:
682     return isShiftedUInt<6,1>(MI->getOperand(2).getImm());
683
684   case Hexagon::L2_loadrb_io:
685   case Hexagon::L2_loadrub_io:
686     return isUInt<6>(MI->getOperand(2).getImm());
687
688   case Hexagon::POST_LDrid:
689     return isShiftedInt<4,3>(MI->getOperand(3).getImm());
690
691   case Hexagon::POST_LDriw:
692     return isShiftedInt<4,2>(MI->getOperand(3).getImm());
693
694   case Hexagon::POST_LDrih:
695   case Hexagon::POST_LDriuh:
696     return isShiftedInt<4,1>(MI->getOperand(3).getImm());
697
698   case Hexagon::POST_LDrib:
699   case Hexagon::POST_LDriub:
700     return isInt<4>(MI->getOperand(3).getImm());
701
702   case Hexagon::STrib_imm_V4:
703   case Hexagon::STrih_imm_V4:
704   case Hexagon::STriw_imm_V4:
705     return (isUInt<6>(MI->getOperand(1).getImm()) &&
706             isInt<6>(MI->getOperand(2).getImm()));
707
708   case Hexagon::ADD_ri:
709     return isInt<8>(MI->getOperand(2).getImm());
710
711   case Hexagon::A2_aslh:
712   case Hexagon::A2_asrh:
713   case Hexagon::A2_sxtb:
714   case Hexagon::A2_sxth:
715   case Hexagon::A2_zxtb:
716   case Hexagon::A2_zxth:
717     return Subtarget.hasV4TOps();
718   }
719
720   return true;
721 }
722
723 // This function performs the following inversiones:
724 //
725 //  cPt    ---> cNotPt
726 //  cNotPt ---> cPt
727 //
728 unsigned HexagonInstrInfo::getInvertedPredicatedOpcode(const int Opc) const {
729   int InvPredOpcode;
730   InvPredOpcode = isPredicatedTrue(Opc) ? Hexagon::getFalsePredOpcode(Opc)
731                                         : Hexagon::getTruePredOpcode(Opc);
732   if (InvPredOpcode >= 0) // Valid instruction with the inverted predicate.
733     return InvPredOpcode;
734
735   switch(Opc) {
736     default: llvm_unreachable("Unexpected predicated instruction");
737     case Hexagon::C2_ccombinewt:
738       return Hexagon::C2_ccombinewf;
739     case Hexagon::C2_ccombinewf:
740       return Hexagon::C2_ccombinewt;
741
742       // Dealloc_return.
743     case Hexagon::DEALLOC_RET_cPt_V4:
744       return Hexagon::DEALLOC_RET_cNotPt_V4;
745     case Hexagon::DEALLOC_RET_cNotPt_V4:
746       return Hexagon::DEALLOC_RET_cPt_V4;
747   }
748 }
749
750 // New Value Store instructions.
751 bool HexagonInstrInfo::isNewValueStore(const MachineInstr *MI) const {
752   const uint64_t F = MI->getDesc().TSFlags;
753
754   return ((F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask);
755 }
756
757 bool HexagonInstrInfo::isNewValueStore(unsigned Opcode) const {
758   const uint64_t F = get(Opcode).TSFlags;
759
760   return ((F >> HexagonII::NVStorePos) & HexagonII::NVStoreMask);
761 }
762
763 int HexagonInstrInfo::
764 getMatchingCondBranchOpcode(int Opc, bool invertPredicate) const {
765   enum Hexagon::PredSense inPredSense;
766   inPredSense = invertPredicate ? Hexagon::PredSense_false :
767                                   Hexagon::PredSense_true;
768   int CondOpcode = Hexagon::getPredOpcode(Opc, inPredSense);
769   if (CondOpcode >= 0) // Valid Conditional opcode/instruction
770     return CondOpcode;
771
772   // This switch case will be removed once all the instructions have been
773   // modified to use relation maps.
774   switch(Opc) {
775   case Hexagon::TFRI_f:
776     return !invertPredicate ? Hexagon::TFRI_cPt_f :
777                               Hexagon::TFRI_cNotPt_f;
778   case Hexagon::A2_combinew:
779     return !invertPredicate ? Hexagon::C2_ccombinewt :
780                               Hexagon::C2_ccombinewf;
781
782   // Word.
783   case Hexagon::STriw_f:
784     return !invertPredicate ? Hexagon::STriw_cPt :
785                               Hexagon::STriw_cNotPt;
786   case Hexagon::STriw_indexed_f:
787     return !invertPredicate ? Hexagon::STriw_indexed_cPt :
788                               Hexagon::STriw_indexed_cNotPt;
789
790   // DEALLOC_RETURN.
791   case Hexagon::DEALLOC_RET_V4:
792     return !invertPredicate ? Hexagon::DEALLOC_RET_cPt_V4 :
793                               Hexagon::DEALLOC_RET_cNotPt_V4;
794   }
795   llvm_unreachable("Unexpected predicable instruction");
796 }
797
798
799 bool HexagonInstrInfo::
800 PredicateInstruction(MachineInstr *MI,
801                      const SmallVectorImpl<MachineOperand> &Cond) const {
802   int Opc = MI->getOpcode();
803   assert (isPredicable(MI) && "Expected predicable instruction");
804   bool invertJump = (!Cond.empty() && Cond[0].isImm() &&
805                      (Cond[0].getImm() == 0));
806
807   // This will change MI's opcode to its predicate version.
808   // However, its operand list is still the old one, i.e. the
809   // non-predicate one.
810   MI->setDesc(get(getMatchingCondBranchOpcode(Opc, invertJump)));
811
812   int oper = -1;
813   unsigned int GAIdx = 0;
814
815   // Indicates whether the current MI has a GlobalAddress operand
816   bool hasGAOpnd = false;
817   std::vector<MachineOperand> tmpOpnds;
818
819   // Indicates whether we need to shift operands to right.
820   bool needShift = true;
821
822   // The predicate is ALWAYS the FIRST input operand !!!
823   if (MI->getNumOperands() == 0) {
824     // The non-predicate version of MI does not take any operands,
825     // i.e. no outs and no ins. In this condition, the predicate
826     // operand will be directly placed at Operands[0]. No operand
827     // shift is needed.
828     // Example: BARRIER
829     needShift = false;
830     oper = -1;
831   }
832   else if (   MI->getOperand(MI->getNumOperands()-1).isReg()
833            && MI->getOperand(MI->getNumOperands()-1).isDef()
834            && !MI->getOperand(MI->getNumOperands()-1).isImplicit()) {
835     // The non-predicate version of MI does not have any input operands.
836     // In this condition, we extend the length of Operands[] by one and
837     // copy the original last operand to the newly allocated slot.
838     // At this moment, it is just a place holder. Later, we will put
839     // predicate operand directly into it. No operand shift is needed.
840     // Example: r0=BARRIER (this is a faked insn used here for illustration)
841     MI->addOperand(MI->getOperand(MI->getNumOperands()-1));
842     needShift = false;
843     oper = MI->getNumOperands() - 2;
844   }
845   else {
846     // We need to right shift all input operands by one. Duplicate the
847     // last operand into the newly allocated slot.
848     MI->addOperand(MI->getOperand(MI->getNumOperands()-1));
849   }
850
851   if (needShift)
852   {
853     // Operands[ MI->getNumOperands() - 2 ] has been copied into
854     // Operands[ MI->getNumOperands() - 1 ], so we start from
855     // Operands[ MI->getNumOperands() - 3 ].
856     // oper is a signed int.
857     // It is ok if "MI->getNumOperands()-3" is -3, -2, or -1.
858     for (oper = MI->getNumOperands() - 3; oper >= 0; --oper)
859     {
860       MachineOperand &MO = MI->getOperand(oper);
861
862       // Opnd[0] Opnd[1] Opnd[2] Opnd[3] Opnd[4]   Opnd[5]   Opnd[6]   Opnd[7]
863       // <Def0>  <Def1>  <Use0>  <Use1>  <ImpDef0> <ImpDef1> <ImpUse0> <ImpUse1>
864       //               /\~
865       //              /||\~
866       //               ||
867       //        Predicate Operand here
868       if (MO.isReg() && !MO.isUse() && !MO.isImplicit()) {
869         break;
870       }
871       if (MO.isReg()) {
872         MI->getOperand(oper+1).ChangeToRegister(MO.getReg(), MO.isDef(),
873                                                 MO.isImplicit(), MO.isKill(),
874                                                 MO.isDead(), MO.isUndef(),
875                                                 MO.isDebug());
876       }
877       else if (MO.isImm()) {
878         MI->getOperand(oper+1).ChangeToImmediate(MO.getImm());
879       }
880       else if (MO.isGlobal()) {
881         // MI can not have more than one GlobalAddress operand.
882         assert(hasGAOpnd == false && "MI can only have one GlobalAddress opnd");
883
884         // There is no member function called "ChangeToGlobalAddress" in the
885         // MachineOperand class (not like "ChangeToRegister" and
886         // "ChangeToImmediate"). So we have to remove them from Operands[] list
887         // first, and then add them back after we have inserted the predicate
888         // operand. tmpOpnds[] is to remember these operands before we remove
889         // them.
890         tmpOpnds.push_back(MO);
891
892         // Operands[oper] is a GlobalAddress operand;
893         // Operands[oper+1] has been copied into Operands[oper+2];
894         hasGAOpnd = true;
895         GAIdx = oper;
896         continue;
897       }
898       else {
899         assert(false && "Unexpected operand type");
900       }
901     }
902   }
903
904   int regPos = invertJump ? 1 : 0;
905   MachineOperand PredMO = Cond[regPos];
906
907   // [oper] now points to the last explicit Def. Predicate operand must be
908   // located at [oper+1]. See diagram above.
909   // This assumes that the predicate is always the first operand,
910   // i.e. Operands[0+numResults], in the set of inputs
911   // It is better to have an assert here to check this. But I don't know how
912   // to write this assert because findFirstPredOperandIdx() would return -1
913   if (oper < -1) oper = -1;
914
915   MI->getOperand(oper+1).ChangeToRegister(PredMO.getReg(), PredMO.isDef(),
916                                           PredMO.isImplicit(), false,
917                                           PredMO.isDead(), PredMO.isUndef(),
918                                           PredMO.isDebug());
919
920   MachineRegisterInfo &RegInfo = MI->getParent()->getParent()->getRegInfo();
921   RegInfo.clearKillFlags(PredMO.getReg());
922
923   if (hasGAOpnd)
924   {
925     unsigned int i;
926
927     // Operands[GAIdx] is the original GlobalAddress operand, which is
928     // already copied into tmpOpnds[0].
929     // Operands[GAIdx] now stores a copy of Operands[GAIdx-1]
930     // Operands[GAIdx+1] has already been copied into Operands[GAIdx+2],
931     // so we start from [GAIdx+2]
932     for (i = GAIdx + 2; i < MI->getNumOperands(); ++i)
933       tmpOpnds.push_back(MI->getOperand(i));
934
935     // Remove all operands in range [ (GAIdx+1) ... (MI->getNumOperands()-1) ]
936     // It is very important that we always remove from the end of Operands[]
937     // MI->getNumOperands() is at least 2 if program goes to here.
938     for (i = MI->getNumOperands() - 1; i > GAIdx; --i)
939       MI->RemoveOperand(i);
940
941     for (i = 0; i < tmpOpnds.size(); ++i)
942       MI->addOperand(tmpOpnds[i]);
943   }
944
945   return true;
946 }
947
948
949 bool
950 HexagonInstrInfo::
951 isProfitableToIfCvt(MachineBasicBlock &MBB,
952                     unsigned NumCycles,
953                     unsigned ExtraPredCycles,
954                     const BranchProbability &Probability) const {
955   return true;
956 }
957
958
959 bool
960 HexagonInstrInfo::
961 isProfitableToIfCvt(MachineBasicBlock &TMBB,
962                     unsigned NumTCycles,
963                     unsigned ExtraTCycles,
964                     MachineBasicBlock &FMBB,
965                     unsigned NumFCycles,
966                     unsigned ExtraFCycles,
967                     const BranchProbability &Probability) const {
968   return true;
969 }
970
971 // Returns true if an instruction is predicated irrespective of the predicate
972 // sense. For example, all of the following will return true.
973 // if (p0) R1 = add(R2, R3)
974 // if (!p0) R1 = add(R2, R3)
975 // if (p0.new) R1 = add(R2, R3)
976 // if (!p0.new) R1 = add(R2, R3)
977 bool HexagonInstrInfo::isPredicated(const MachineInstr *MI) const {
978   const uint64_t F = MI->getDesc().TSFlags;
979
980   return ((F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
981 }
982
983 bool HexagonInstrInfo::isPredicated(unsigned Opcode) const {
984   const uint64_t F = get(Opcode).TSFlags;
985
986   return ((F >> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
987 }
988
989 bool HexagonInstrInfo::isPredicatedTrue(const MachineInstr *MI) const {
990   const uint64_t F = MI->getDesc().TSFlags;
991
992   assert(isPredicated(MI));
993   return (!((F >> HexagonII::PredicatedFalsePos) &
994             HexagonII::PredicatedFalseMask));
995 }
996
997 bool HexagonInstrInfo::isPredicatedTrue(unsigned Opcode) const {
998   const uint64_t F = get(Opcode).TSFlags;
999
1000   // Make sure that the instruction is predicated.
1001   assert((F>> HexagonII::PredicatedPos) & HexagonII::PredicatedMask);
1002   return (!((F >> HexagonII::PredicatedFalsePos) &
1003             HexagonII::PredicatedFalseMask));
1004 }
1005
1006 bool HexagonInstrInfo::isPredicatedNew(const MachineInstr *MI) const {
1007   const uint64_t F = MI->getDesc().TSFlags;
1008
1009   assert(isPredicated(MI));
1010   return ((F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask);
1011 }
1012
1013 bool HexagonInstrInfo::isPredicatedNew(unsigned Opcode) const {
1014   const uint64_t F = get(Opcode).TSFlags;
1015
1016   assert(isPredicated(Opcode));
1017   return ((F >> HexagonII::PredicatedNewPos) & HexagonII::PredicatedNewMask);
1018 }
1019
1020 // Returns true, if a ST insn can be promoted to a new-value store.
1021 bool HexagonInstrInfo::mayBeNewStore(const MachineInstr *MI) const {
1022   const HexagonRegisterInfo& QRI = getRegisterInfo();
1023   const uint64_t F = MI->getDesc().TSFlags;
1024
1025   return ((F >> HexagonII::mayNVStorePos) &
1026            HexagonII::mayNVStoreMask &
1027            QRI.Subtarget.hasV4TOps());
1028 }
1029
1030 bool
1031 HexagonInstrInfo::DefinesPredicate(MachineInstr *MI,
1032                                    std::vector<MachineOperand> &Pred) const {
1033   for (unsigned oper = 0; oper < MI->getNumOperands(); ++oper) {
1034     MachineOperand MO = MI->getOperand(oper);
1035     if (MO.isReg() && MO.isDef()) {
1036       const TargetRegisterClass* RC = RI.getMinimalPhysRegClass(MO.getReg());
1037       if (RC == &Hexagon::PredRegsRegClass) {
1038         Pred.push_back(MO);
1039         return true;
1040       }
1041     }
1042   }
1043   return false;
1044 }
1045
1046
1047 bool
1048 HexagonInstrInfo::
1049 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
1050                   const SmallVectorImpl<MachineOperand> &Pred2) const {
1051   // TODO: Fix this
1052   return false;
1053 }
1054
1055
1056 //
1057 // We indicate that we want to reverse the branch by
1058 // inserting a 0 at the beginning of the Cond vector.
1059 //
1060 bool HexagonInstrInfo::
1061 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1062   if (!Cond.empty() && Cond[0].isImm() && Cond[0].getImm() == 0) {
1063     Cond.erase(Cond.begin());
1064   } else {
1065     Cond.insert(Cond.begin(), MachineOperand::CreateImm(0));
1066   }
1067   return false;
1068 }
1069
1070
1071 bool HexagonInstrInfo::
1072 isProfitableToDupForIfCvt(MachineBasicBlock &MBB,unsigned NumInstrs,
1073                           const BranchProbability &Probability) const {
1074   return (NumInstrs <= 4);
1075 }
1076
1077 bool HexagonInstrInfo::isDeallocRet(const MachineInstr *MI) const {
1078   switch (MI->getOpcode()) {
1079   default: return false;
1080   case Hexagon::DEALLOC_RET_V4 :
1081   case Hexagon::DEALLOC_RET_cPt_V4 :
1082   case Hexagon::DEALLOC_RET_cNotPt_V4 :
1083   case Hexagon::DEALLOC_RET_cdnPnt_V4 :
1084   case Hexagon::DEALLOC_RET_cNotdnPnt_V4 :
1085   case Hexagon::DEALLOC_RET_cdnPt_V4 :
1086   case Hexagon::DEALLOC_RET_cNotdnPt_V4 :
1087    return true;
1088   }
1089 }
1090
1091
1092 bool HexagonInstrInfo::
1093 isValidOffset(const int Opcode, const int Offset) const {
1094   // This function is to check whether the "Offset" is in the correct range of
1095   // the given "Opcode". If "Offset" is not in the correct range, "ADD_ri" is
1096   // inserted to calculate the final address. Due to this reason, the function
1097   // assumes that the "Offset" has correct alignment.
1098   // We used to assert if the offset was not properly aligned, however,
1099   // there are cases where a misaligned pointer recast can cause this
1100   // problem, and we need to allow for it. The front end warns of such
1101   // misaligns with respect to load size.
1102
1103   switch(Opcode) {
1104
1105   case Hexagon::L2_loadri_io:
1106   case Hexagon::LDriw_f:
1107   case Hexagon::STriw_indexed:
1108   case Hexagon::STriw:
1109   case Hexagon::STriw_f:
1110     return (Offset >= Hexagon_MEMW_OFFSET_MIN) &&
1111       (Offset <= Hexagon_MEMW_OFFSET_MAX);
1112
1113   case Hexagon::LDrid:
1114   case Hexagon::LDrid_indexed:
1115   case Hexagon::LDrid_f:
1116   case Hexagon::STrid:
1117   case Hexagon::STrid_indexed:
1118   case Hexagon::STrid_f:
1119     return (Offset >= Hexagon_MEMD_OFFSET_MIN) &&
1120       (Offset <= Hexagon_MEMD_OFFSET_MAX);
1121
1122   case Hexagon::L2_loadrh_io:
1123   case Hexagon::L2_loadruh_io:
1124   case Hexagon::STrih:
1125     return (Offset >= Hexagon_MEMH_OFFSET_MIN) &&
1126       (Offset <= Hexagon_MEMH_OFFSET_MAX);
1127
1128   case Hexagon::L2_loadrb_io:
1129   case Hexagon::STrib:
1130   case Hexagon::L2_loadrub_io:
1131     return (Offset >= Hexagon_MEMB_OFFSET_MIN) &&
1132       (Offset <= Hexagon_MEMB_OFFSET_MAX);
1133
1134   case Hexagon::ADD_ri:
1135   case Hexagon::TFR_FI:
1136     return (Offset >= Hexagon_ADDI_OFFSET_MIN) &&
1137       (Offset <= Hexagon_ADDI_OFFSET_MAX);
1138
1139   case Hexagon::MemOPw_ADDi_V4 :
1140   case Hexagon::MemOPw_SUBi_V4 :
1141   case Hexagon::MemOPw_ADDr_V4 :
1142   case Hexagon::MemOPw_SUBr_V4 :
1143   case Hexagon::MemOPw_ANDr_V4 :
1144   case Hexagon::MemOPw_ORr_V4 :
1145     return (0 <= Offset && Offset <= 255);
1146
1147   case Hexagon::MemOPh_ADDi_V4 :
1148   case Hexagon::MemOPh_SUBi_V4 :
1149   case Hexagon::MemOPh_ADDr_V4 :
1150   case Hexagon::MemOPh_SUBr_V4 :
1151   case Hexagon::MemOPh_ANDr_V4 :
1152   case Hexagon::MemOPh_ORr_V4 :
1153     return (0 <= Offset && Offset <= 127);
1154
1155   case Hexagon::MemOPb_ADDi_V4 :
1156   case Hexagon::MemOPb_SUBi_V4 :
1157   case Hexagon::MemOPb_ADDr_V4 :
1158   case Hexagon::MemOPb_SUBr_V4 :
1159   case Hexagon::MemOPb_ANDr_V4 :
1160   case Hexagon::MemOPb_ORr_V4 :
1161     return (0 <= Offset && Offset <= 63);
1162
1163   // LDri_pred and STriw_pred are pseudo operations, so it has to take offset of
1164   // any size. Later pass knows how to handle it.
1165   case Hexagon::STriw_pred:
1166   case Hexagon::LDriw_pred:
1167     return true;
1168
1169   case Hexagon::J2_loop0i:
1170     return isUInt<10>(Offset);
1171
1172   // INLINEASM is very special.
1173   case Hexagon::INLINEASM:
1174     return true;
1175   }
1176
1177   llvm_unreachable("No offset range is defined for this opcode. "
1178                    "Please define it in the above switch statement!");
1179 }
1180
1181
1182 //
1183 // Check if the Offset is a valid auto-inc imm by Load/Store Type.
1184 //
1185 bool HexagonInstrInfo::
1186 isValidAutoIncImm(const EVT VT, const int Offset) const {
1187
1188   if (VT == MVT::i64) {
1189       return (Offset >= Hexagon_MEMD_AUTOINC_MIN &&
1190               Offset <= Hexagon_MEMD_AUTOINC_MAX &&
1191               (Offset & 0x7) == 0);
1192   }
1193   if (VT == MVT::i32) {
1194       return (Offset >= Hexagon_MEMW_AUTOINC_MIN &&
1195               Offset <= Hexagon_MEMW_AUTOINC_MAX &&
1196               (Offset & 0x3) == 0);
1197   }
1198   if (VT == MVT::i16) {
1199       return (Offset >= Hexagon_MEMH_AUTOINC_MIN &&
1200               Offset <= Hexagon_MEMH_AUTOINC_MAX &&
1201               (Offset & 0x1) == 0);
1202   }
1203   if (VT == MVT::i8) {
1204       return (Offset >= Hexagon_MEMB_AUTOINC_MIN &&
1205               Offset <= Hexagon_MEMB_AUTOINC_MAX);
1206   }
1207   llvm_unreachable("Not an auto-inc opc!");
1208 }
1209
1210
1211 bool HexagonInstrInfo::
1212 isMemOp(const MachineInstr *MI) const {
1213 //  return MI->getDesc().mayLoad() && MI->getDesc().mayStore();
1214
1215   switch (MI->getOpcode())
1216   {
1217     default: return false;
1218     case Hexagon::MemOPw_ADDi_V4 :
1219     case Hexagon::MemOPw_SUBi_V4 :
1220     case Hexagon::MemOPw_ADDr_V4 :
1221     case Hexagon::MemOPw_SUBr_V4 :
1222     case Hexagon::MemOPw_ANDr_V4 :
1223     case Hexagon::MemOPw_ORr_V4 :
1224     case Hexagon::MemOPh_ADDi_V4 :
1225     case Hexagon::MemOPh_SUBi_V4 :
1226     case Hexagon::MemOPh_ADDr_V4 :
1227     case Hexagon::MemOPh_SUBr_V4 :
1228     case Hexagon::MemOPh_ANDr_V4 :
1229     case Hexagon::MemOPh_ORr_V4 :
1230     case Hexagon::MemOPb_ADDi_V4 :
1231     case Hexagon::MemOPb_SUBi_V4 :
1232     case Hexagon::MemOPb_ADDr_V4 :
1233     case Hexagon::MemOPb_SUBr_V4 :
1234     case Hexagon::MemOPb_ANDr_V4 :
1235     case Hexagon::MemOPb_ORr_V4 :
1236     case Hexagon::MemOPb_SETBITi_V4:
1237     case Hexagon::MemOPh_SETBITi_V4:
1238     case Hexagon::MemOPw_SETBITi_V4:
1239     case Hexagon::MemOPb_CLRBITi_V4:
1240     case Hexagon::MemOPh_CLRBITi_V4:
1241     case Hexagon::MemOPw_CLRBITi_V4:
1242     return true;
1243   }
1244   return false;
1245 }
1246
1247
1248 bool HexagonInstrInfo::
1249 isSpillPredRegOp(const MachineInstr *MI) const {
1250   switch (MI->getOpcode()) {
1251     default: return false;
1252     case Hexagon::STriw_pred :
1253     case Hexagon::LDriw_pred :
1254       return true;
1255   }
1256 }
1257
1258 bool HexagonInstrInfo::isNewValueJumpCandidate(const MachineInstr *MI) const {
1259   switch (MI->getOpcode()) {
1260     default: return false;
1261     case Hexagon::C2_cmpeq:
1262     case Hexagon::C2_cmpeqi:
1263     case Hexagon::C2_cmpgt:
1264     case Hexagon::C2_cmpgti:
1265     case Hexagon::C2_cmpgtu:
1266     case Hexagon::C2_cmpgtui:
1267       return true;
1268   }
1269 }
1270
1271 bool HexagonInstrInfo::
1272 isConditionalTransfer (const MachineInstr *MI) const {
1273   switch (MI->getOpcode()) {
1274     default: return false;
1275     case Hexagon::A2_tfrt:
1276     case Hexagon::A2_tfrf:
1277     case Hexagon::C2_cmoveit:
1278     case Hexagon::C2_cmoveif:
1279     case Hexagon::A2_tfrtnew:
1280     case Hexagon::A2_tfrfnew:
1281     case Hexagon::C2_cmovenewit:
1282     case Hexagon::C2_cmovenewif:
1283       return true;
1284   }
1285 }
1286
1287 bool HexagonInstrInfo::isConditionalALU32 (const MachineInstr* MI) const {
1288   switch (MI->getOpcode())
1289   {
1290     default: return false;
1291     case Hexagon::A2_paddf:
1292     case Hexagon::A2_paddfnew:
1293     case Hexagon::A2_paddt:
1294     case Hexagon::A2_paddtnew:
1295     case Hexagon::A2_pandf:
1296     case Hexagon::A2_pandfnew:
1297     case Hexagon::A2_pandt:
1298     case Hexagon::A2_pandtnew:
1299     case Hexagon::A4_paslhf:
1300     case Hexagon::A4_paslhfnew:
1301     case Hexagon::A4_paslht:
1302     case Hexagon::A4_paslhtnew:
1303     case Hexagon::A4_pasrhf:
1304     case Hexagon::A4_pasrhfnew:
1305     case Hexagon::A4_pasrht:
1306     case Hexagon::A4_pasrhtnew:
1307     case Hexagon::A2_porf:
1308     case Hexagon::A2_porfnew:
1309     case Hexagon::A2_port:
1310     case Hexagon::A2_portnew:
1311     case Hexagon::A2_psubf:
1312     case Hexagon::A2_psubfnew:
1313     case Hexagon::A2_psubt:
1314     case Hexagon::A2_psubtnew:
1315     case Hexagon::A2_pxorf:
1316     case Hexagon::A2_pxorfnew:
1317     case Hexagon::A2_pxort:
1318     case Hexagon::A2_pxortnew:
1319     case Hexagon::A4_psxthf:
1320     case Hexagon::A4_psxthfnew:
1321     case Hexagon::A4_psxtht:
1322     case Hexagon::A4_psxthtnew:
1323     case Hexagon::A4_psxtbf:
1324     case Hexagon::A4_psxtbfnew:
1325     case Hexagon::A4_psxtbt:
1326     case Hexagon::A4_psxtbtnew:
1327     case Hexagon::A4_pzxtbf:
1328     case Hexagon::A4_pzxtbfnew:
1329     case Hexagon::A4_pzxtbt:
1330     case Hexagon::A4_pzxtbtnew:
1331     case Hexagon::A4_pzxthf:
1332     case Hexagon::A4_pzxthfnew:
1333     case Hexagon::A4_pzxtht:
1334     case Hexagon::A4_pzxthtnew:
1335     case Hexagon::ADD_ri_cPt:
1336     case Hexagon::ADD_ri_cNotPt:
1337     case Hexagon::C2_ccombinewt:
1338     case Hexagon::C2_ccombinewf:
1339       return true;
1340   }
1341 }
1342
1343 bool HexagonInstrInfo::
1344 isConditionalLoad (const MachineInstr* MI) const {
1345   const HexagonRegisterInfo& QRI = getRegisterInfo();
1346   switch (MI->getOpcode())
1347   {
1348     default: return false;
1349     case Hexagon::LDrid_cPt :
1350     case Hexagon::LDrid_cNotPt :
1351     case Hexagon::LDrid_indexed_cPt :
1352     case Hexagon::LDrid_indexed_cNotPt :
1353     case Hexagon::L2_ploadrit_io:
1354     case Hexagon::L2_ploadrif_io:
1355     case Hexagon::L2_ploadrht_io:
1356     case Hexagon::L2_ploadrhf_io:
1357     case Hexagon::L2_ploadrbt_io:
1358     case Hexagon::L2_ploadrbf_io:
1359     case Hexagon::L2_ploadruht_io:
1360     case Hexagon::L2_ploadruhf_io:
1361     case Hexagon::L2_ploadrubt_io:
1362     case Hexagon::L2_ploadrubf_io:
1363       return true;
1364     case Hexagon::POST_LDrid_cPt :
1365     case Hexagon::POST_LDrid_cNotPt :
1366     case Hexagon::POST_LDriw_cPt :
1367     case Hexagon::POST_LDriw_cNotPt :
1368     case Hexagon::POST_LDrih_cPt :
1369     case Hexagon::POST_LDrih_cNotPt :
1370     case Hexagon::POST_LDrib_cPt :
1371     case Hexagon::POST_LDrib_cNotPt :
1372     case Hexagon::POST_LDriuh_cPt :
1373     case Hexagon::POST_LDriuh_cNotPt :
1374     case Hexagon::POST_LDriub_cPt :
1375     case Hexagon::POST_LDriub_cNotPt :
1376       return QRI.Subtarget.hasV4TOps();
1377     case Hexagon::LDrid_indexed_shl_cPt_V4 :
1378     case Hexagon::LDrid_indexed_shl_cNotPt_V4 :
1379     case Hexagon::LDrib_indexed_shl_cPt_V4 :
1380     case Hexagon::LDrib_indexed_shl_cNotPt_V4 :
1381     case Hexagon::LDriub_indexed_shl_cPt_V4 :
1382     case Hexagon::LDriub_indexed_shl_cNotPt_V4 :
1383     case Hexagon::LDrih_indexed_shl_cPt_V4 :
1384     case Hexagon::LDrih_indexed_shl_cNotPt_V4 :
1385     case Hexagon::LDriuh_indexed_shl_cPt_V4 :
1386     case Hexagon::LDriuh_indexed_shl_cNotPt_V4 :
1387     case Hexagon::LDriw_indexed_shl_cPt_V4 :
1388     case Hexagon::LDriw_indexed_shl_cNotPt_V4 :
1389       return QRI.Subtarget.hasV4TOps();
1390   }
1391 }
1392
1393 // Returns true if an instruction is a conditional store.
1394 //
1395 // Note: It doesn't include conditional new-value stores as they can't be
1396 // converted to .new predicate.
1397 //
1398 //               p.new NV store [ if(p0.new)memw(R0+#0)=R2.new ]
1399 //                ^           ^
1400 //               /             \ (not OK. it will cause new-value store to be
1401 //              /               X conditional on p0.new while R2 producer is
1402 //             /                 \ on p0)
1403 //            /                   \.
1404 //     p.new store                 p.old NV store
1405 // [if(p0.new)memw(R0+#0)=R2]    [if(p0)memw(R0+#0)=R2.new]
1406 //            ^                  ^
1407 //             \                /
1408 //              \              /
1409 //               \            /
1410 //                 p.old store
1411 //             [if (p0)memw(R0+#0)=R2]
1412 //
1413 // The above diagram shows the steps involoved in the conversion of a predicated
1414 // store instruction to its .new predicated new-value form.
1415 //
1416 // The following set of instructions further explains the scenario where
1417 // conditional new-value store becomes invalid when promoted to .new predicate
1418 // form.
1419 //
1420 // { 1) if (p0) r0 = add(r1, r2)
1421 //   2) p0 = cmp.eq(r3, #0) }
1422 //
1423 //   3) if (p0) memb(r1+#0) = r0  --> this instruction can't be grouped with
1424 // the first two instructions because in instr 1, r0 is conditional on old value
1425 // of p0 but its use in instr 3 is conditional on p0 modified by instr 2 which
1426 // is not valid for new-value stores.
1427 bool HexagonInstrInfo::
1428 isConditionalStore (const MachineInstr* MI) const {
1429   const HexagonRegisterInfo& QRI = getRegisterInfo();
1430   switch (MI->getOpcode())
1431   {
1432     default: return false;
1433     case Hexagon::STrib_imm_cPt_V4 :
1434     case Hexagon::STrib_imm_cNotPt_V4 :
1435     case Hexagon::STrib_indexed_shl_cPt_V4 :
1436     case Hexagon::STrib_indexed_shl_cNotPt_V4 :
1437     case Hexagon::STrib_cPt :
1438     case Hexagon::STrib_cNotPt :
1439     case Hexagon::POST_STbri_cPt :
1440     case Hexagon::POST_STbri_cNotPt :
1441     case Hexagon::STrid_indexed_cPt :
1442     case Hexagon::STrid_indexed_cNotPt :
1443     case Hexagon::STrid_indexed_shl_cPt_V4 :
1444     case Hexagon::POST_STdri_cPt :
1445     case Hexagon::POST_STdri_cNotPt :
1446     case Hexagon::STrih_cPt :
1447     case Hexagon::STrih_cNotPt :
1448     case Hexagon::STrih_indexed_cPt :
1449     case Hexagon::STrih_indexed_cNotPt :
1450     case Hexagon::STrih_imm_cPt_V4 :
1451     case Hexagon::STrih_imm_cNotPt_V4 :
1452     case Hexagon::STrih_indexed_shl_cPt_V4 :
1453     case Hexagon::STrih_indexed_shl_cNotPt_V4 :
1454     case Hexagon::POST_SThri_cPt :
1455     case Hexagon::POST_SThri_cNotPt :
1456     case Hexagon::STriw_cPt :
1457     case Hexagon::STriw_cNotPt :
1458     case Hexagon::STriw_indexed_cPt :
1459     case Hexagon::STriw_indexed_cNotPt :
1460     case Hexagon::STriw_imm_cPt_V4 :
1461     case Hexagon::STriw_imm_cNotPt_V4 :
1462     case Hexagon::STriw_indexed_shl_cPt_V4 :
1463     case Hexagon::STriw_indexed_shl_cNotPt_V4 :
1464     case Hexagon::POST_STwri_cPt :
1465     case Hexagon::POST_STwri_cNotPt :
1466       return QRI.Subtarget.hasV4TOps();
1467
1468     // V4 global address store before promoting to dot new.
1469     case Hexagon::STd_GP_cPt_V4 :
1470     case Hexagon::STd_GP_cNotPt_V4 :
1471     case Hexagon::STb_GP_cPt_V4 :
1472     case Hexagon::STb_GP_cNotPt_V4 :
1473     case Hexagon::STh_GP_cPt_V4 :
1474     case Hexagon::STh_GP_cNotPt_V4 :
1475     case Hexagon::STw_GP_cPt_V4 :
1476     case Hexagon::STw_GP_cNotPt_V4 :
1477       return QRI.Subtarget.hasV4TOps();
1478
1479     // Predicated new value stores (i.e. if (p0) memw(..)=r0.new) are excluded
1480     // from the "Conditional Store" list. Because a predicated new value store
1481     // would NOT be promoted to a double dot new store. See diagram below:
1482     // This function returns yes for those stores that are predicated but not
1483     // yet promoted to predicate dot new instructions.
1484     //
1485     //                          +---------------------+
1486     //                    /-----| if (p0) memw(..)=r0 |---------\~
1487     //                   ||     +---------------------+         ||
1488     //          promote  ||       /\       /\                   ||  promote
1489     //                   ||      /||\     /||\                  ||
1490     //                  \||/    demote     ||                  \||/
1491     //                   \/       ||       ||                   \/
1492     //       +-------------------------+   ||   +-------------------------+
1493     //       | if (p0.new) memw(..)=r0 |   ||   | if (p0) memw(..)=r0.new |
1494     //       +-------------------------+   ||   +-------------------------+
1495     //                        ||           ||         ||
1496     //                        ||         demote      \||/
1497     //                      promote        ||         \/ NOT possible
1498     //                        ||           ||         /\~
1499     //                       \||/          ||        /||\~
1500     //                        \/           ||         ||
1501     //                      +-----------------------------+
1502     //                      | if (p0.new) memw(..)=r0.new |
1503     //                      +-----------------------------+
1504     //                           Double Dot New Store
1505     //
1506   }
1507 }
1508
1509
1510 bool HexagonInstrInfo::isNewValueJump(const MachineInstr *MI) const {
1511   if (isNewValue(MI) && isBranch(MI))
1512     return true;
1513   return false;
1514 }
1515
1516 bool HexagonInstrInfo::isPostIncrement (const MachineInstr* MI) const {
1517   return (getAddrMode(MI) == HexagonII::PostInc);
1518 }
1519
1520 bool HexagonInstrInfo::isNewValue(const MachineInstr* MI) const {
1521   const uint64_t F = MI->getDesc().TSFlags;
1522   return ((F >> HexagonII::NewValuePos) & HexagonII::NewValueMask);
1523 }
1524
1525 // Returns true, if any one of the operands is a dot new
1526 // insn, whether it is predicated dot new or register dot new.
1527 bool HexagonInstrInfo::isDotNewInst (const MachineInstr* MI) const {
1528   return (isNewValueInst(MI) ||
1529      (isPredicated(MI) && isPredicatedNew(MI)));
1530 }
1531
1532 // Returns the most basic instruction for the .new predicated instructions and
1533 // new-value stores.
1534 // For example, all of the following instructions will be converted back to the
1535 // same instruction:
1536 // 1) if (p0.new) memw(R0+#0) = R1.new  --->
1537 // 2) if (p0) memw(R0+#0)= R1.new      -------> if (p0) memw(R0+#0) = R1
1538 // 3) if (p0.new) memw(R0+#0) = R1      --->
1539 //
1540
1541 int HexagonInstrInfo::GetDotOldOp(const int opc) const {
1542   int NewOp = opc;
1543   if (isPredicated(NewOp) && isPredicatedNew(NewOp)) { // Get predicate old form
1544     NewOp = Hexagon::getPredOldOpcode(NewOp);
1545     assert(NewOp >= 0 &&
1546            "Couldn't change predicate new instruction to its old form.");
1547   }
1548
1549   if (isNewValueStore(NewOp)) { // Convert into non-new-value format
1550     NewOp = Hexagon::getNonNVStore(NewOp);
1551     assert(NewOp >= 0 && "Couldn't change new-value store to its old form.");
1552   }
1553   return NewOp;
1554 }
1555
1556 // Return the new value instruction for a given store.
1557 int HexagonInstrInfo::GetDotNewOp(const MachineInstr* MI) const {
1558   int NVOpcode = Hexagon::getNewValueOpcode(MI->getOpcode());
1559   if (NVOpcode >= 0) // Valid new-value store instruction.
1560     return NVOpcode;
1561
1562   switch (MI->getOpcode()) {
1563   default: llvm_unreachable("Unknown .new type");
1564   // store new value byte
1565   case Hexagon::STrib_shl_V4:
1566     return Hexagon::STrib_shl_nv_V4;
1567
1568   case Hexagon::STrih_shl_V4:
1569     return Hexagon::STrih_shl_nv_V4;
1570
1571   case Hexagon::STriw_f:
1572     return Hexagon::STriw_nv_V4;
1573
1574   case Hexagon::STriw_indexed_f:
1575     return Hexagon::STriw_indexed_nv_V4;
1576
1577   case Hexagon::STriw_shl_V4:
1578     return Hexagon::STriw_shl_nv_V4;
1579
1580   }
1581   return 0;
1582 }
1583
1584 // Return .new predicate version for an instruction.
1585 int HexagonInstrInfo::GetDotNewPredOp(MachineInstr *MI,
1586                                       const MachineBranchProbabilityInfo
1587                                       *MBPI) const {
1588
1589   int NewOpcode = Hexagon::getPredNewOpcode(MI->getOpcode());
1590   if (NewOpcode >= 0) // Valid predicate new instruction
1591     return NewOpcode;
1592
1593   switch (MI->getOpcode()) {
1594   default: llvm_unreachable("Unknown .new type");
1595   // Condtional Jumps
1596   case Hexagon::J2_jumpt:
1597   case Hexagon::J2_jumpf:
1598     return getDotNewPredJumpOp(MI, MBPI);
1599
1600   case Hexagon::J2_jumprt:
1601     return Hexagon::J2_jumptnewpt;
1602
1603   case Hexagon::J2_jumprf:
1604     return Hexagon::J2_jumprfnewpt;
1605
1606   case Hexagon::JMPrett:
1607     return Hexagon::J2_jumprtnewpt;
1608
1609   case Hexagon::JMPretf:
1610     return Hexagon::J2_jumprfnewpt;
1611
1612
1613   // Conditional combine
1614   case Hexagon::C2_ccombinewt:
1615     return Hexagon::C2_ccombinewnewt;
1616   case Hexagon::C2_ccombinewf:
1617     return Hexagon::C2_ccombinewnewf;
1618   }
1619 }
1620
1621
1622 unsigned HexagonInstrInfo::getAddrMode(const MachineInstr* MI) const {
1623   const uint64_t F = MI->getDesc().TSFlags;
1624
1625   return((F >> HexagonII::AddrModePos) & HexagonII::AddrModeMask);
1626 }
1627
1628 /// immediateExtend - Changes the instruction in place to one using an immediate
1629 /// extender.
1630 void HexagonInstrInfo::immediateExtend(MachineInstr *MI) const {
1631   assert((isExtendable(MI)||isConstExtended(MI)) &&
1632                                "Instruction must be extendable");
1633   // Find which operand is extendable.
1634   short ExtOpNum = getCExtOpNum(MI);
1635   MachineOperand &MO = MI->getOperand(ExtOpNum);
1636   // This needs to be something we understand.
1637   assert((MO.isMBB() || MO.isImm()) &&
1638          "Branch with unknown extendable field type");
1639   // Mark given operand as extended.
1640   MO.addTargetFlag(HexagonII::HMOTF_ConstExtended);
1641 }
1642
1643 DFAPacketizer *HexagonInstrInfo::CreateTargetScheduleState(
1644     const TargetSubtargetInfo &STI) const {
1645   const InstrItineraryData *II = STI.getInstrItineraryData();
1646   return static_cast<const HexagonSubtarget &>(STI).createDFAPacketizer(II);
1647 }
1648
1649 bool HexagonInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1650                                             const MachineBasicBlock *MBB,
1651                                             const MachineFunction &MF) const {
1652   // Debug info is never a scheduling boundary. It's necessary to be explicit
1653   // due to the special treatment of IT instructions below, otherwise a
1654   // dbg_value followed by an IT will result in the IT instruction being
1655   // considered a scheduling hazard, which is wrong. It should be the actual
1656   // instruction preceding the dbg_value instruction(s), just like it is
1657   // when debug info is not present.
1658   if (MI->isDebugValue())
1659     return false;
1660
1661   // Terminators and labels can't be scheduled around.
1662   if (MI->getDesc().isTerminator() || MI->isPosition() || MI->isInlineAsm())
1663     return true;
1664
1665   return false;
1666 }
1667
1668 bool HexagonInstrInfo::isConstExtended(MachineInstr *MI) const {
1669
1670   // Constant extenders are allowed only for V4 and above.
1671   if (!Subtarget.hasV4TOps())
1672     return false;
1673
1674   const uint64_t F = MI->getDesc().TSFlags;
1675   unsigned isExtended = (F >> HexagonII::ExtendedPos) & HexagonII::ExtendedMask;
1676   if (isExtended) // Instruction must be extended.
1677     return true;
1678
1679   unsigned isExtendable = (F >> HexagonII::ExtendablePos)
1680                           & HexagonII::ExtendableMask;
1681   if (!isExtendable)
1682     return false;
1683
1684   short ExtOpNum = getCExtOpNum(MI);
1685   const MachineOperand &MO = MI->getOperand(ExtOpNum);
1686   // Use MO operand flags to determine if MO
1687   // has the HMOTF_ConstExtended flag set.
1688   if (MO.getTargetFlags() && HexagonII::HMOTF_ConstExtended)
1689     return true;
1690   // If this is a Machine BB address we are talking about, and it is
1691   // not marked as extended, say so.
1692   if (MO.isMBB())
1693     return false;
1694
1695   // We could be using an instruction with an extendable immediate and shoehorn
1696   // a global address into it. If it is a global address it will be constant
1697   // extended. We do this for COMBINE.
1698   // We currently only handle isGlobal() because it is the only kind of
1699   // object we are going to end up with here for now.
1700   // In the future we probably should add isSymbol(), etc.
1701   if (MO.isGlobal() || MO.isSymbol())
1702     return true;
1703
1704   // If the extendable operand is not 'Immediate' type, the instruction should
1705   // have 'isExtended' flag set.
1706   assert(MO.isImm() && "Extendable operand must be Immediate type");
1707
1708   int MinValue = getMinValue(MI);
1709   int MaxValue = getMaxValue(MI);
1710   int ImmValue = MO.getImm();
1711
1712   return (ImmValue < MinValue || ImmValue > MaxValue);
1713 }
1714
1715 // Returns the opcode to use when converting MI, which is a conditional jump,
1716 // into a conditional instruction which uses the .new value of the predicate.
1717 // We also use branch probabilities to add a hint to the jump.
1718 int
1719 HexagonInstrInfo::getDotNewPredJumpOp(MachineInstr *MI,
1720                                   const
1721                                   MachineBranchProbabilityInfo *MBPI) const {
1722
1723   // We assume that block can have at most two successors.
1724   bool taken = false;
1725   MachineBasicBlock *Src = MI->getParent();
1726   MachineOperand *BrTarget = &MI->getOperand(1);
1727   MachineBasicBlock *Dst = BrTarget->getMBB();
1728
1729   const BranchProbability Prediction = MBPI->getEdgeProbability(Src, Dst);
1730   if (Prediction >= BranchProbability(1,2))
1731     taken = true;
1732
1733   switch (MI->getOpcode()) {
1734   case Hexagon::J2_jumpt:
1735     return taken ? Hexagon::J2_jumptnewpt : Hexagon::J2_jumptnew;
1736   case Hexagon::J2_jumpf:
1737     return taken ? Hexagon::J2_jumpfnewpt : Hexagon::J2_jumpfnew;
1738
1739   default:
1740     llvm_unreachable("Unexpected jump instruction.");
1741   }
1742 }
1743 // Returns true if a particular operand is extendable for an instruction.
1744 bool HexagonInstrInfo::isOperandExtended(const MachineInstr *MI,
1745                                          unsigned short OperandNum) const {
1746   // Constant extenders are allowed only for V4 and above.
1747   if (!Subtarget.hasV4TOps())
1748     return false;
1749
1750   const uint64_t F = MI->getDesc().TSFlags;
1751
1752   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask)
1753           == OperandNum;
1754 }
1755
1756 // Returns Operand Index for the constant extended instruction.
1757 unsigned short HexagonInstrInfo::getCExtOpNum(const MachineInstr *MI) const {
1758   const uint64_t F = MI->getDesc().TSFlags;
1759   return ((F >> HexagonII::ExtendableOpPos) & HexagonII::ExtendableOpMask);
1760 }
1761
1762 // Returns the min value that doesn't need to be extended.
1763 int HexagonInstrInfo::getMinValue(const MachineInstr *MI) const {
1764   const uint64_t F = MI->getDesc().TSFlags;
1765   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
1766                     & HexagonII::ExtentSignedMask;
1767   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
1768                     & HexagonII::ExtentBitsMask;
1769
1770   if (isSigned) // if value is signed
1771     return -1U << (bits - 1);
1772   else
1773     return 0;
1774 }
1775
1776 // Returns the max value that doesn't need to be extended.
1777 int HexagonInstrInfo::getMaxValue(const MachineInstr *MI) const {
1778   const uint64_t F = MI->getDesc().TSFlags;
1779   unsigned isSigned = (F >> HexagonII::ExtentSignedPos)
1780                     & HexagonII::ExtentSignedMask;
1781   unsigned bits =  (F >> HexagonII::ExtentBitsPos)
1782                     & HexagonII::ExtentBitsMask;
1783
1784   if (isSigned) // if value is signed
1785     return ~(-1U << (bits - 1));
1786   else
1787     return ~(-1U << bits);
1788 }
1789
1790 // Returns true if an instruction can be converted into a non-extended
1791 // equivalent instruction.
1792 bool HexagonInstrInfo::NonExtEquivalentExists (const MachineInstr *MI) const {
1793
1794   short NonExtOpcode;
1795   // Check if the instruction has a register form that uses register in place
1796   // of the extended operand, if so return that as the non-extended form.
1797   if (Hexagon::getRegForm(MI->getOpcode()) >= 0)
1798     return true;
1799
1800   if (MI->getDesc().mayLoad() || MI->getDesc().mayStore()) {
1801     // Check addressing mode and retrieve non-ext equivalent instruction.
1802
1803     switch (getAddrMode(MI)) {
1804     case HexagonII::Absolute :
1805       // Load/store with absolute addressing mode can be converted into
1806       // base+offset mode.
1807       NonExtOpcode = Hexagon::getBasedWithImmOffset(MI->getOpcode());
1808       break;
1809     case HexagonII::BaseImmOffset :
1810       // Load/store with base+offset addressing mode can be converted into
1811       // base+register offset addressing mode. However left shift operand should
1812       // be set to 0.
1813       NonExtOpcode = Hexagon::getBaseWithRegOffset(MI->getOpcode());
1814       break;
1815     default:
1816       return false;
1817     }
1818     if (NonExtOpcode < 0)
1819       return false;
1820     return true;
1821   }
1822   return false;
1823 }
1824
1825 // Returns opcode of the non-extended equivalent instruction.
1826 short HexagonInstrInfo::getNonExtOpcode (const MachineInstr *MI) const {
1827
1828   // Check if the instruction has a register form that uses register in place
1829   // of the extended operand, if so return that as the non-extended form.
1830   short NonExtOpcode = Hexagon::getRegForm(MI->getOpcode());
1831     if (NonExtOpcode >= 0)
1832       return NonExtOpcode;
1833
1834   if (MI->getDesc().mayLoad() || MI->getDesc().mayStore()) {
1835     // Check addressing mode and retrieve non-ext equivalent instruction.
1836     switch (getAddrMode(MI)) {
1837     case HexagonII::Absolute :
1838       return Hexagon::getBasedWithImmOffset(MI->getOpcode());
1839     case HexagonII::BaseImmOffset :
1840       return Hexagon::getBaseWithRegOffset(MI->getOpcode());
1841     default:
1842       return -1;
1843     }
1844   }
1845   return -1;
1846 }
1847
1848 bool HexagonInstrInfo::PredOpcodeHasJMP_c(Opcode_t Opcode) const {
1849   return (Opcode == Hexagon::J2_jumpt) ||
1850          (Opcode == Hexagon::J2_jumpf) ||
1851          (Opcode == Hexagon::J2_jumptnewpt) ||
1852          (Opcode == Hexagon::J2_jumpfnewpt) ||
1853          (Opcode == Hexagon::J2_jumpt) ||
1854          (Opcode == Hexagon::J2_jumpf);
1855 }
1856
1857 bool HexagonInstrInfo::PredOpcodeHasNot(Opcode_t Opcode) const {
1858   return (Opcode == Hexagon::J2_jumpf) ||
1859          (Opcode == Hexagon::J2_jumpfnewpt) ||
1860          (Opcode == Hexagon::J2_jumpfnew);
1861 }