1//===-- ARMBaseInstrInfo.cpp - ARM 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 Base ARM implementation of the TargetInstrInfo class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ARMBaseInstrInfo.h"
15#include "ARM.h"
16#include "ARMBaseRegisterInfo.h"
17#include "ARMConstantPoolValue.h"
18#include "ARMHazardRecognizer.h"
19#include "ARMMachineFunctionInfo.h"
20#include "MCTargetDesc/ARMAddressingModes.h"
21#include "llvm/Constants.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalValue.h"
24#include "llvm/CodeGen/LiveVariables.h"
25#include "llvm/CodeGen/MachineConstantPool.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineJumpTableInfo.h"
29#include "llvm/CodeGen/MachineMemOperand.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/CodeGen/SelectionDAGNodes.h"
32#include "llvm/MC/MCAsmInfo.h"
33#include "llvm/Support/BranchProbability.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/ADT/STLExtras.h"
38
39#define GET_INSTRINFO_CTOR
40#include "ARMGenInstrInfo.inc"
41
42using namespace llvm;
43
44static cl::opt<bool>
45EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
46               cl::desc("Enable ARM 2-addr to 3-addr conv"));
47
48static cl::opt<bool>
49WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
50           cl::desc("Widen ARM vmovs to vmovd when possible"));
51
52static cl::opt<unsigned>
53SwiftPartialUpdateClearance("swift-partial-update-clearance",
54     cl::Hidden, cl::init(12),
55     cl::desc("Clearance before partial register updates"));
56
57/// ARM_MLxEntry - Record information about MLA / MLS instructions.
58struct ARM_MLxEntry {
59  uint16_t MLxOpc;     // MLA / MLS opcode
60  uint16_t MulOpc;     // Expanded multiplication opcode
61  uint16_t AddSubOpc;  // Expanded add / sub opcode
62  bool NegAcc;         // True if the acc is negated before the add / sub.
63  bool HasLane;        // True if instruction has an extra "lane" operand.
64};
65
66static const ARM_MLxEntry ARM_MLxTable[] = {
67  // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
68  // fp scalar ops
69  { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
70  { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
71  { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
72  { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
73  { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
74  { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
75  { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
76  { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
77
78  // fp SIMD ops
79  { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
80  { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
81  { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
82  { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
83  { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
84  { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
85  { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
86  { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
87};
88
89ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
90  : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
91    Subtarget(STI) {
92  for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
93    if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
94      assert(false && "Duplicated entries?");
95    MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
96    MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
97  }
98}
99
100// Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
101// currently defaults to no prepass hazard recognizer.
102ScheduleHazardRecognizer *ARMBaseInstrInfo::
103CreateTargetHazardRecognizer(const TargetMachine *TM,
104                             const ScheduleDAG *DAG) const {
105  if (usePreRAHazardRecognizer()) {
106    const InstrItineraryData *II = TM->getInstrItineraryData();
107    return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
108  }
109  return TargetInstrInfoImpl::CreateTargetHazardRecognizer(TM, DAG);
110}
111
112ScheduleHazardRecognizer *ARMBaseInstrInfo::
113CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
114                                   const ScheduleDAG *DAG) const {
115  if (Subtarget.isThumb2() || Subtarget.hasVFP2())
116    return (ScheduleHazardRecognizer *)
117      new ARMHazardRecognizer(II, *this, getRegisterInfo(), Subtarget, DAG);
118  return TargetInstrInfoImpl::CreateTargetPostRAHazardRecognizer(II, DAG);
119}
120
121MachineInstr *
122ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
123                                        MachineBasicBlock::iterator &MBBI,
124                                        LiveVariables *LV) const {
125  // FIXME: Thumb2 support.
126
127  if (!EnableARM3Addr)
128    return NULL;
129
130  MachineInstr *MI = MBBI;
131  MachineFunction &MF = *MI->getParent()->getParent();
132  uint64_t TSFlags = MI->getDesc().TSFlags;
133  bool isPre = false;
134  switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
135  default: return NULL;
136  case ARMII::IndexModePre:
137    isPre = true;
138    break;
139  case ARMII::IndexModePost:
140    break;
141  }
142
143  // Try splitting an indexed load/store to an un-indexed one plus an add/sub
144  // operation.
145  unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
146  if (MemOpc == 0)
147    return NULL;
148
149  MachineInstr *UpdateMI = NULL;
150  MachineInstr *MemMI = NULL;
151  unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
152  const MCInstrDesc &MCID = MI->getDesc();
153  unsigned NumOps = MCID.getNumOperands();
154  bool isLoad = !MI->mayStore();
155  const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
156  const MachineOperand &Base = MI->getOperand(2);
157  const MachineOperand &Offset = MI->getOperand(NumOps-3);
158  unsigned WBReg = WB.getReg();
159  unsigned BaseReg = Base.getReg();
160  unsigned OffReg = Offset.getReg();
161  unsigned OffImm = MI->getOperand(NumOps-2).getImm();
162  ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
163  switch (AddrMode) {
164  default: llvm_unreachable("Unknown indexed op!");
165  case ARMII::AddrMode2: {
166    bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
167    unsigned Amt = ARM_AM::getAM2Offset(OffImm);
168    if (OffReg == 0) {
169      if (ARM_AM::getSOImmVal(Amt) == -1)
170        // Can't encode it in a so_imm operand. This transformation will
171        // add more than 1 instruction. Abandon!
172        return NULL;
173      UpdateMI = BuildMI(MF, MI->getDebugLoc(),
174                         get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
175        .addReg(BaseReg).addImm(Amt)
176        .addImm(Pred).addReg(0).addReg(0);
177    } else if (Amt != 0) {
178      ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
179      unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
180      UpdateMI = BuildMI(MF, MI->getDebugLoc(),
181                         get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
182        .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
183        .addImm(Pred).addReg(0).addReg(0);
184    } else
185      UpdateMI = BuildMI(MF, MI->getDebugLoc(),
186                         get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
187        .addReg(BaseReg).addReg(OffReg)
188        .addImm(Pred).addReg(0).addReg(0);
189    break;
190  }
191  case ARMII::AddrMode3 : {
192    bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
193    unsigned Amt = ARM_AM::getAM3Offset(OffImm);
194    if (OffReg == 0)
195      // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
196      UpdateMI = BuildMI(MF, MI->getDebugLoc(),
197                         get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
198        .addReg(BaseReg).addImm(Amt)
199        .addImm(Pred).addReg(0).addReg(0);
200    else
201      UpdateMI = BuildMI(MF, MI->getDebugLoc(),
202                         get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
203        .addReg(BaseReg).addReg(OffReg)
204        .addImm(Pred).addReg(0).addReg(0);
205    break;
206  }
207  }
208
209  std::vector<MachineInstr*> NewMIs;
210  if (isPre) {
211    if (isLoad)
212      MemMI = BuildMI(MF, MI->getDebugLoc(),
213                      get(MemOpc), MI->getOperand(0).getReg())
214        .addReg(WBReg).addImm(0).addImm(Pred);
215    else
216      MemMI = BuildMI(MF, MI->getDebugLoc(),
217                      get(MemOpc)).addReg(MI->getOperand(1).getReg())
218        .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
219    NewMIs.push_back(MemMI);
220    NewMIs.push_back(UpdateMI);
221  } else {
222    if (isLoad)
223      MemMI = BuildMI(MF, MI->getDebugLoc(),
224                      get(MemOpc), MI->getOperand(0).getReg())
225        .addReg(BaseReg).addImm(0).addImm(Pred);
226    else
227      MemMI = BuildMI(MF, MI->getDebugLoc(),
228                      get(MemOpc)).addReg(MI->getOperand(1).getReg())
229        .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
230    if (WB.isDead())
231      UpdateMI->getOperand(0).setIsDead();
232    NewMIs.push_back(UpdateMI);
233    NewMIs.push_back(MemMI);
234  }
235
236  // Transfer LiveVariables states, kill / dead info.
237  if (LV) {
238    for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
239      MachineOperand &MO = MI->getOperand(i);
240      if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
241        unsigned Reg = MO.getReg();
242
243        LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
244        if (MO.isDef()) {
245          MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
246          if (MO.isDead())
247            LV->addVirtualRegisterDead(Reg, NewMI);
248        }
249        if (MO.isUse() && MO.isKill()) {
250          for (unsigned j = 0; j < 2; ++j) {
251            // Look at the two new MI's in reverse order.
252            MachineInstr *NewMI = NewMIs[j];
253            if (!NewMI->readsRegister(Reg))
254              continue;
255            LV->addVirtualRegisterKilled(Reg, NewMI);
256            if (VI.removeKill(MI))
257              VI.Kills.push_back(NewMI);
258            break;
259          }
260        }
261      }
262    }
263  }
264
265  MFI->insert(MBBI, NewMIs[1]);
266  MFI->insert(MBBI, NewMIs[0]);
267  return NewMIs[0];
268}
269
270// Branch analysis.
271bool
272ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
273                                MachineBasicBlock *&FBB,
274                                SmallVectorImpl<MachineOperand> &Cond,
275                                bool AllowModify) const {
276  // If the block has no terminators, it just falls into the block after it.
277  MachineBasicBlock::iterator I = MBB.end();
278  if (I == MBB.begin())
279    return false;
280  --I;
281  while (I->isDebugValue()) {
282    if (I == MBB.begin())
283      return false;
284    --I;
285  }
286  if (!isUnpredicatedTerminator(I))
287    return false;
288
289  // Get the last instruction in the block.
290  MachineInstr *LastInst = I;
291
292  // If there is only one terminator instruction, process it.
293  unsigned LastOpc = LastInst->getOpcode();
294  if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
295    if (isUncondBranchOpcode(LastOpc)) {
296      TBB = LastInst->getOperand(0).getMBB();
297      return false;
298    }
299    if (isCondBranchOpcode(LastOpc)) {
300      // Block ends with fall-through condbranch.
301      TBB = LastInst->getOperand(0).getMBB();
302      Cond.push_back(LastInst->getOperand(1));
303      Cond.push_back(LastInst->getOperand(2));
304      return false;
305    }
306    return true;  // Can't handle indirect branch.
307  }
308
309  // Get the instruction before it if it is a terminator.
310  MachineInstr *SecondLastInst = I;
311  unsigned SecondLastOpc = SecondLastInst->getOpcode();
312
313  // If AllowModify is true and the block ends with two or more unconditional
314  // branches, delete all but the first unconditional branch.
315  if (AllowModify && isUncondBranchOpcode(LastOpc)) {
316    while (isUncondBranchOpcode(SecondLastOpc)) {
317      LastInst->eraseFromParent();
318      LastInst = SecondLastInst;
319      LastOpc = LastInst->getOpcode();
320      if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
321        // Return now the only terminator is an unconditional branch.
322        TBB = LastInst->getOperand(0).getMBB();
323        return false;
324      } else {
325        SecondLastInst = I;
326        SecondLastOpc = SecondLastInst->getOpcode();
327      }
328    }
329  }
330
331  // If there are three terminators, we don't know what sort of block this is.
332  if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
333    return true;
334
335  // If the block ends with a B and a Bcc, handle it.
336  if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
337    TBB =  SecondLastInst->getOperand(0).getMBB();
338    Cond.push_back(SecondLastInst->getOperand(1));
339    Cond.push_back(SecondLastInst->getOperand(2));
340    FBB = LastInst->getOperand(0).getMBB();
341    return false;
342  }
343
344  // If the block ends with two unconditional branches, handle it.  The second
345  // one is not executed, so remove it.
346  if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
347    TBB = SecondLastInst->getOperand(0).getMBB();
348    I = LastInst;
349    if (AllowModify)
350      I->eraseFromParent();
351    return false;
352  }
353
354  // ...likewise if it ends with a branch table followed by an unconditional
355  // branch. The branch folder can create these, and we must get rid of them for
356  // correctness of Thumb constant islands.
357  if ((isJumpTableBranchOpcode(SecondLastOpc) ||
358       isIndirectBranchOpcode(SecondLastOpc)) &&
359      isUncondBranchOpcode(LastOpc)) {
360    I = LastInst;
361    if (AllowModify)
362      I->eraseFromParent();
363    return true;
364  }
365
366  // Otherwise, can't handle this.
367  return true;
368}
369
370
371unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
372  MachineBasicBlock::iterator I = MBB.end();
373  if (I == MBB.begin()) return 0;
374  --I;
375  while (I->isDebugValue()) {
376    if (I == MBB.begin())
377      return 0;
378    --I;
379  }
380  if (!isUncondBranchOpcode(I->getOpcode()) &&
381      !isCondBranchOpcode(I->getOpcode()))
382    return 0;
383
384  // Remove the branch.
385  I->eraseFromParent();
386
387  I = MBB.end();
388
389  if (I == MBB.begin()) return 1;
390  --I;
391  if (!isCondBranchOpcode(I->getOpcode()))
392    return 1;
393
394  // Remove the branch.
395  I->eraseFromParent();
396  return 2;
397}
398
399unsigned
400ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
401                               MachineBasicBlock *FBB,
402                               const SmallVectorImpl<MachineOperand> &Cond,
403                               DebugLoc DL) const {
404  ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
405  int BOpc   = !AFI->isThumbFunction()
406    ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
407  int BccOpc = !AFI->isThumbFunction()
408    ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
409  bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
410
411  // Shouldn't be a fall through.
412  assert(TBB && "InsertBranch must not be told to insert a fallthrough");
413  assert((Cond.size() == 2 || Cond.size() == 0) &&
414         "ARM branch conditions have two components!");
415
416  if (FBB == 0) {
417    if (Cond.empty()) { // Unconditional branch?
418      if (isThumb)
419        BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0);
420      else
421        BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
422    } else
423      BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
424        .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
425    return 1;
426  }
427
428  // Two-way conditional branch.
429  BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
430    .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
431  if (isThumb)
432    BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0);
433  else
434    BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
435  return 2;
436}
437
438bool ARMBaseInstrInfo::
439ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
440  ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
441  Cond[0].setImm(ARMCC::getOppositeCondition(CC));
442  return false;
443}
444
445bool ARMBaseInstrInfo::isPredicated(const MachineInstr *MI) const {
446  if (MI->isBundle()) {
447    MachineBasicBlock::const_instr_iterator I = MI;
448    MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
449    while (++I != E && I->isInsideBundle()) {
450      int PIdx = I->findFirstPredOperandIdx();
451      if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
452        return true;
453    }
454    return false;
455  }
456
457  int PIdx = MI->findFirstPredOperandIdx();
458  return PIdx != -1 && MI->getOperand(PIdx).getImm() != ARMCC::AL;
459}
460
461bool ARMBaseInstrInfo::
462PredicateInstruction(MachineInstr *MI,
463                     const SmallVectorImpl<MachineOperand> &Pred) const {
464  unsigned Opc = MI->getOpcode();
465  if (isUncondBranchOpcode(Opc)) {
466    MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
467    MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
468    MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
469    return true;
470  }
471
472  int PIdx = MI->findFirstPredOperandIdx();
473  if (PIdx != -1) {
474    MachineOperand &PMO = MI->getOperand(PIdx);
475    PMO.setImm(Pred[0].getImm());
476    MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
477    return true;
478  }
479  return false;
480}
481
482bool ARMBaseInstrInfo::
483SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
484                  const SmallVectorImpl<MachineOperand> &Pred2) const {
485  if (Pred1.size() > 2 || Pred2.size() > 2)
486    return false;
487
488  ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
489  ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
490  if (CC1 == CC2)
491    return true;
492
493  switch (CC1) {
494  default:
495    return false;
496  case ARMCC::AL:
497    return true;
498  case ARMCC::HS:
499    return CC2 == ARMCC::HI;
500  case ARMCC::LS:
501    return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
502  case ARMCC::GE:
503    return CC2 == ARMCC::GT;
504  case ARMCC::LE:
505    return CC2 == ARMCC::LT;
506  }
507}
508
509bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
510                                    std::vector<MachineOperand> &Pred) const {
511  bool Found = false;
512  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
513    const MachineOperand &MO = MI->getOperand(i);
514    if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
515        (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) {
516      Pred.push_back(MO);
517      Found = true;
518    }
519  }
520
521  return Found;
522}
523
524/// isPredicable - Return true if the specified instruction can be predicated.
525/// By default, this returns true for every instruction with a
526/// PredicateOperand.
527bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
528  if (!MI->isPredicable())
529    return false;
530
531  if ((MI->getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) {
532    ARMFunctionInfo *AFI =
533      MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
534    return AFI->isThumb2Function();
535  }
536  return true;
537}
538
539/// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
540LLVM_ATTRIBUTE_NOINLINE
541static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
542                                unsigned JTI);
543static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
544                                unsigned JTI) {
545  assert(JTI < JT.size());
546  return JT[JTI].MBBs.size();
547}
548
549/// GetInstSize - Return the size of the specified MachineInstr.
550///
551unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
552  const MachineBasicBlock &MBB = *MI->getParent();
553  const MachineFunction *MF = MBB.getParent();
554  const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
555
556  const MCInstrDesc &MCID = MI->getDesc();
557  if (MCID.getSize())
558    return MCID.getSize();
559
560  // If this machine instr is an inline asm, measure it.
561  if (MI->getOpcode() == ARM::INLINEASM)
562    return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
563  if (MI->isLabel())
564    return 0;
565  unsigned Opc = MI->getOpcode();
566  switch (Opc) {
567  case TargetOpcode::IMPLICIT_DEF:
568  case TargetOpcode::KILL:
569  case TargetOpcode::PROLOG_LABEL:
570  case TargetOpcode::EH_LABEL:
571  case TargetOpcode::DBG_VALUE:
572    return 0;
573  case TargetOpcode::BUNDLE:
574    return getInstBundleLength(MI);
575  case ARM::MOVi16_ga_pcrel:
576  case ARM::MOVTi16_ga_pcrel:
577  case ARM::t2MOVi16_ga_pcrel:
578  case ARM::t2MOVTi16_ga_pcrel:
579    return 4;
580  case ARM::MOVi32imm:
581  case ARM::t2MOVi32imm:
582    return 8;
583  case ARM::CONSTPOOL_ENTRY:
584    // If this machine instr is a constant pool entry, its size is recorded as
585    // operand #2.
586    return MI->getOperand(2).getImm();
587  case ARM::Int_eh_sjlj_longjmp:
588    return 16;
589  case ARM::tInt_eh_sjlj_longjmp:
590    return 10;
591  case ARM::Int_eh_sjlj_setjmp:
592  case ARM::Int_eh_sjlj_setjmp_nofp:
593    return 20;
594  case ARM::tInt_eh_sjlj_setjmp:
595  case ARM::t2Int_eh_sjlj_setjmp:
596  case ARM::t2Int_eh_sjlj_setjmp_nofp:
597    return 12;
598  case ARM::BR_JTr:
599  case ARM::BR_JTm:
600  case ARM::BR_JTadd:
601  case ARM::tBR_JTr:
602  case ARM::t2BR_JT:
603  case ARM::t2TBB_JT:
604  case ARM::t2TBH_JT: {
605    // These are jumptable branches, i.e. a branch followed by an inlined
606    // jumptable. The size is 4 + 4 * number of entries. For TBB, each
607    // entry is one byte; TBH two byte each.
608    unsigned EntrySize = (Opc == ARM::t2TBB_JT)
609      ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
610    unsigned NumOps = MCID.getNumOperands();
611    MachineOperand JTOP =
612      MI->getOperand(NumOps - (MI->isPredicable() ? 3 : 2));
613    unsigned JTI = JTOP.getIndex();
614    const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
615    assert(MJTI != 0);
616    const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
617    assert(JTI < JT.size());
618    // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
619    // 4 aligned. The assembler / linker may add 2 byte padding just before
620    // the JT entries.  The size does not include this padding; the
621    // constant islands pass does separate bookkeeping for it.
622    // FIXME: If we know the size of the function is less than (1 << 16) *2
623    // bytes, we can use 16-bit entries instead. Then there won't be an
624    // alignment issue.
625    unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
626    unsigned NumEntries = getNumJTEntries(JT, JTI);
627    if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
628      // Make sure the instruction that follows TBB is 2-byte aligned.
629      // FIXME: Constant island pass should insert an "ALIGN" instruction
630      // instead.
631      ++NumEntries;
632    return NumEntries * EntrySize + InstSize;
633  }
634  default:
635    // Otherwise, pseudo-instruction sizes are zero.
636    return 0;
637  }
638}
639
640unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr *MI) const {
641  unsigned Size = 0;
642  MachineBasicBlock::const_instr_iterator I = MI;
643  MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
644  while (++I != E && I->isInsideBundle()) {
645    assert(!I->isBundle() && "No nested bundle!");
646    Size += GetInstSizeInBytes(&*I);
647  }
648  return Size;
649}
650
651void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
652                                   MachineBasicBlock::iterator I, DebugLoc DL,
653                                   unsigned DestReg, unsigned SrcReg,
654                                   bool KillSrc) const {
655  bool GPRDest = ARM::GPRRegClass.contains(DestReg);
656  bool GPRSrc  = ARM::GPRRegClass.contains(SrcReg);
657
658  if (GPRDest && GPRSrc) {
659    AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
660                                  .addReg(SrcReg, getKillRegState(KillSrc))));
661    return;
662  }
663
664  bool SPRDest = ARM::SPRRegClass.contains(DestReg);
665  bool SPRSrc  = ARM::SPRRegClass.contains(SrcReg);
666
667  unsigned Opc = 0;
668  if (SPRDest && SPRSrc)
669    Opc = ARM::VMOVS;
670  else if (GPRDest && SPRSrc)
671    Opc = ARM::VMOVRS;
672  else if (SPRDest && GPRSrc)
673    Opc = ARM::VMOVSR;
674  else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
675    Opc = ARM::VMOVD;
676  else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
677    Opc = ARM::VORRq;
678
679  if (Opc) {
680    MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
681    MIB.addReg(SrcReg, getKillRegState(KillSrc));
682    if (Opc == ARM::VORRq)
683      MIB.addReg(SrcReg, getKillRegState(KillSrc));
684    AddDefaultPred(MIB);
685    return;
686  }
687
688  // Handle register classes that require multiple instructions.
689  unsigned BeginIdx = 0;
690  unsigned SubRegs = 0;
691  int Spacing = 1;
692
693  // Use VORRq when possible.
694  if (ARM::QQPRRegClass.contains(DestReg, SrcReg))
695    Opc = ARM::VORRq, BeginIdx = ARM::qsub_0, SubRegs = 2;
696  else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg))
697    Opc = ARM::VORRq, BeginIdx = ARM::qsub_0, SubRegs = 4;
698  // Fall back to VMOVD.
699  else if (ARM::DPairRegClass.contains(DestReg, SrcReg))
700    Opc = ARM::VMOVD, BeginIdx = ARM::dsub_0, SubRegs = 2;
701  else if (ARM::DTripleRegClass.contains(DestReg, SrcReg))
702    Opc = ARM::VMOVD, BeginIdx = ARM::dsub_0, SubRegs = 3;
703  else if (ARM::DQuadRegClass.contains(DestReg, SrcReg))
704    Opc = ARM::VMOVD, BeginIdx = ARM::dsub_0, SubRegs = 4;
705
706  else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg))
707    Opc = ARM::VMOVD, BeginIdx = ARM::dsub_0, SubRegs = 2, Spacing = 2;
708  else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg))
709    Opc = ARM::VMOVD, BeginIdx = ARM::dsub_0, SubRegs = 3, Spacing = 2;
710  else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg))
711    Opc = ARM::VMOVD, BeginIdx = ARM::dsub_0, SubRegs = 4, Spacing = 2;
712
713  assert(Opc && "Impossible reg-to-reg copy");
714
715  const TargetRegisterInfo *TRI = &getRegisterInfo();
716  MachineInstrBuilder Mov;
717
718  // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
719  if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
720    BeginIdx = BeginIdx + ((SubRegs-1)*Spacing);
721    Spacing = -Spacing;
722  }
723#ifndef NDEBUG
724  SmallSet<unsigned, 4> DstRegs;
725#endif
726  for (unsigned i = 0; i != SubRegs; ++i) {
727    unsigned Dst = TRI->getSubReg(DestReg, BeginIdx + i*Spacing);
728    unsigned Src = TRI->getSubReg(SrcReg,  BeginIdx + i*Spacing);
729    assert(Dst && Src && "Bad sub-register");
730#ifndef NDEBUG
731    assert(!DstRegs.count(Src) && "destructive vector copy");
732    DstRegs.insert(Dst);
733#endif
734    Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst)
735      .addReg(Src);
736    // VORR takes two source operands.
737    if (Opc == ARM::VORRq)
738      Mov.addReg(Src);
739    Mov = AddDefaultPred(Mov);
740  }
741  // Add implicit super-register defs and kills to the last instruction.
742  Mov->addRegisterDefined(DestReg, TRI);
743  if (KillSrc)
744    Mov->addRegisterKilled(SrcReg, TRI);
745}
746
747static const
748MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
749                             unsigned Reg, unsigned SubIdx, unsigned State,
750                             const TargetRegisterInfo *TRI) {
751  if (!SubIdx)
752    return MIB.addReg(Reg, State);
753
754  if (TargetRegisterInfo::isPhysicalRegister(Reg))
755    return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
756  return MIB.addReg(Reg, State, SubIdx);
757}
758
759void ARMBaseInstrInfo::
760storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
761                    unsigned SrcReg, bool isKill, int FI,
762                    const TargetRegisterClass *RC,
763                    const TargetRegisterInfo *TRI) const {
764  DebugLoc DL;
765  if (I != MBB.end()) DL = I->getDebugLoc();
766  MachineFunction &MF = *MBB.getParent();
767  MachineFrameInfo &MFI = *MF.getFrameInfo();
768  unsigned Align = MFI.getObjectAlignment(FI);
769
770  MachineMemOperand *MMO =
771    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
772                            MachineMemOperand::MOStore,
773                            MFI.getObjectSize(FI),
774                            Align);
775
776  switch (RC->getSize()) {
777    case 4:
778      if (ARM::GPRRegClass.hasSubClassEq(RC)) {
779        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
780                   .addReg(SrcReg, getKillRegState(isKill))
781                   .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
782      } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
783        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
784                   .addReg(SrcReg, getKillRegState(isKill))
785                   .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
786      } else
787        llvm_unreachable("Unknown reg class!");
788      break;
789    case 8:
790      if (ARM::DPRRegClass.hasSubClassEq(RC)) {
791        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
792                   .addReg(SrcReg, getKillRegState(isKill))
793                   .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
794      } else
795        llvm_unreachable("Unknown reg class!");
796      break;
797    case 16:
798      if (ARM::DPairRegClass.hasSubClassEq(RC)) {
799        // Use aligned spills if the stack can be realigned.
800        if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
801          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64))
802                     .addFrameIndex(FI).addImm(16)
803                     .addReg(SrcReg, getKillRegState(isKill))
804                     .addMemOperand(MMO));
805        } else {
806          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
807                     .addReg(SrcReg, getKillRegState(isKill))
808                     .addFrameIndex(FI)
809                     .addMemOperand(MMO));
810        }
811      } else
812        llvm_unreachable("Unknown reg class!");
813      break;
814    case 24:
815      if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
816        // Use aligned spills if the stack can be realigned.
817        if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
818          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64TPseudo))
819                     .addFrameIndex(FI).addImm(16)
820                     .addReg(SrcReg, getKillRegState(isKill))
821                     .addMemOperand(MMO));
822        } else {
823          MachineInstrBuilder MIB =
824          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
825                       .addFrameIndex(FI))
826                       .addMemOperand(MMO);
827          MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
828          MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
829          AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
830        }
831      } else
832        llvm_unreachable("Unknown reg class!");
833      break;
834    case 32:
835      if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
836        if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
837          // FIXME: It's possible to only store part of the QQ register if the
838          // spilled def has a sub-register index.
839          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
840                     .addFrameIndex(FI).addImm(16)
841                     .addReg(SrcReg, getKillRegState(isKill))
842                     .addMemOperand(MMO));
843        } else {
844          MachineInstrBuilder MIB =
845          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
846                       .addFrameIndex(FI))
847                       .addMemOperand(MMO);
848          MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
849          MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
850          MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
851                AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
852        }
853      } else
854        llvm_unreachable("Unknown reg class!");
855      break;
856    case 64:
857      if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
858        MachineInstrBuilder MIB =
859          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
860                         .addFrameIndex(FI))
861                         .addMemOperand(MMO);
862        MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
863        MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
864        MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
865        MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
866        MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
867        MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
868        MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
869              AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
870      } else
871        llvm_unreachable("Unknown reg class!");
872      break;
873    default:
874      llvm_unreachable("Unknown reg class!");
875  }
876}
877
878unsigned
879ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
880                                     int &FrameIndex) const {
881  switch (MI->getOpcode()) {
882  default: break;
883  case ARM::STRrs:
884  case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
885    if (MI->getOperand(1).isFI() &&
886        MI->getOperand(2).isReg() &&
887        MI->getOperand(3).isImm() &&
888        MI->getOperand(2).getReg() == 0 &&
889        MI->getOperand(3).getImm() == 0) {
890      FrameIndex = MI->getOperand(1).getIndex();
891      return MI->getOperand(0).getReg();
892    }
893    break;
894  case ARM::STRi12:
895  case ARM::t2STRi12:
896  case ARM::tSTRspi:
897  case ARM::VSTRD:
898  case ARM::VSTRS:
899    if (MI->getOperand(1).isFI() &&
900        MI->getOperand(2).isImm() &&
901        MI->getOperand(2).getImm() == 0) {
902      FrameIndex = MI->getOperand(1).getIndex();
903      return MI->getOperand(0).getReg();
904    }
905    break;
906  case ARM::VST1q64:
907  case ARM::VST1d64TPseudo:
908  case ARM::VST1d64QPseudo:
909    if (MI->getOperand(0).isFI() &&
910        MI->getOperand(2).getSubReg() == 0) {
911      FrameIndex = MI->getOperand(0).getIndex();
912      return MI->getOperand(2).getReg();
913    }
914    break;
915  case ARM::VSTMQIA:
916    if (MI->getOperand(1).isFI() &&
917        MI->getOperand(0).getSubReg() == 0) {
918      FrameIndex = MI->getOperand(1).getIndex();
919      return MI->getOperand(0).getReg();
920    }
921    break;
922  }
923
924  return 0;
925}
926
927unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
928                                                    int &FrameIndex) const {
929  const MachineMemOperand *Dummy;
930  return MI->mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
931}
932
933void ARMBaseInstrInfo::
934loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
935                     unsigned DestReg, int FI,
936                     const TargetRegisterClass *RC,
937                     const TargetRegisterInfo *TRI) const {
938  DebugLoc DL;
939  if (I != MBB.end()) DL = I->getDebugLoc();
940  MachineFunction &MF = *MBB.getParent();
941  MachineFrameInfo &MFI = *MF.getFrameInfo();
942  unsigned Align = MFI.getObjectAlignment(FI);
943  MachineMemOperand *MMO =
944    MF.getMachineMemOperand(
945                    MachinePointerInfo::getFixedStack(FI),
946                            MachineMemOperand::MOLoad,
947                            MFI.getObjectSize(FI),
948                            Align);
949
950  switch (RC->getSize()) {
951  case 4:
952    if (ARM::GPRRegClass.hasSubClassEq(RC)) {
953      AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
954                   .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
955
956    } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
957      AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
958                   .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
959    } else
960      llvm_unreachable("Unknown reg class!");
961    break;
962  case 8:
963    if (ARM::DPRRegClass.hasSubClassEq(RC)) {
964      AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
965                   .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
966    } else
967      llvm_unreachable("Unknown reg class!");
968    break;
969  case 16:
970    if (ARM::DPairRegClass.hasSubClassEq(RC)) {
971      if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
972        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
973                     .addFrameIndex(FI).addImm(16)
974                     .addMemOperand(MMO));
975      } else {
976        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
977                       .addFrameIndex(FI)
978                       .addMemOperand(MMO));
979      }
980    } else
981      llvm_unreachable("Unknown reg class!");
982    break;
983  case 24:
984    if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
985      if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
986        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
987                     .addFrameIndex(FI).addImm(16)
988                     .addMemOperand(MMO));
989      } else {
990        MachineInstrBuilder MIB =
991          AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
992                         .addFrameIndex(FI)
993                         .addMemOperand(MMO));
994        MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
995        MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
996        MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
997        if (TargetRegisterInfo::isPhysicalRegister(DestReg))
998          MIB.addReg(DestReg, RegState::ImplicitDefine);
999      }
1000    } else
1001      llvm_unreachable("Unknown reg class!");
1002    break;
1003   case 32:
1004    if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1005      if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1006        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1007                     .addFrameIndex(FI).addImm(16)
1008                     .addMemOperand(MMO));
1009      } else {
1010        MachineInstrBuilder MIB =
1011        AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1012                       .addFrameIndex(FI))
1013                       .addMemOperand(MMO);
1014        MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1015        MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1016        MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1017        MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1018        if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1019          MIB.addReg(DestReg, RegState::ImplicitDefine);
1020      }
1021    } else
1022      llvm_unreachable("Unknown reg class!");
1023    break;
1024  case 64:
1025    if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1026      MachineInstrBuilder MIB =
1027      AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1028                     .addFrameIndex(FI))
1029                     .addMemOperand(MMO);
1030      MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1031      MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1032      MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1033      MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1034      MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1035      MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1036      MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1037      MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1038      if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1039        MIB.addReg(DestReg, RegState::ImplicitDefine);
1040    } else
1041      llvm_unreachable("Unknown reg class!");
1042    break;
1043  default:
1044    llvm_unreachable("Unknown regclass!");
1045  }
1046}
1047
1048unsigned
1049ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
1050                                      int &FrameIndex) const {
1051  switch (MI->getOpcode()) {
1052  default: break;
1053  case ARM::LDRrs:
1054  case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
1055    if (MI->getOperand(1).isFI() &&
1056        MI->getOperand(2).isReg() &&
1057        MI->getOperand(3).isImm() &&
1058        MI->getOperand(2).getReg() == 0 &&
1059        MI->getOperand(3).getImm() == 0) {
1060      FrameIndex = MI->getOperand(1).getIndex();
1061      return MI->getOperand(0).getReg();
1062    }
1063    break;
1064  case ARM::LDRi12:
1065  case ARM::t2LDRi12:
1066  case ARM::tLDRspi:
1067  case ARM::VLDRD:
1068  case ARM::VLDRS:
1069    if (MI->getOperand(1).isFI() &&
1070        MI->getOperand(2).isImm() &&
1071        MI->getOperand(2).getImm() == 0) {
1072      FrameIndex = MI->getOperand(1).getIndex();
1073      return MI->getOperand(0).getReg();
1074    }
1075    break;
1076  case ARM::VLD1q64:
1077  case ARM::VLD1d64TPseudo:
1078  case ARM::VLD1d64QPseudo:
1079    if (MI->getOperand(1).isFI() &&
1080        MI->getOperand(0).getSubReg() == 0) {
1081      FrameIndex = MI->getOperand(1).getIndex();
1082      return MI->getOperand(0).getReg();
1083    }
1084    break;
1085  case ARM::VLDMQIA:
1086    if (MI->getOperand(1).isFI() &&
1087        MI->getOperand(0).getSubReg() == 0) {
1088      FrameIndex = MI->getOperand(1).getIndex();
1089      return MI->getOperand(0).getReg();
1090    }
1091    break;
1092  }
1093
1094  return 0;
1095}
1096
1097unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
1098                                             int &FrameIndex) const {
1099  const MachineMemOperand *Dummy;
1100  return MI->mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
1101}
1102
1103bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const{
1104  // This hook gets to expand COPY instructions before they become
1105  // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1106  // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1107  // changed into a VORR that can go down the NEON pipeline.
1108  if (!WidenVMOVS || !MI->isCopy())
1109    return false;
1110
1111  // Look for a copy between even S-registers.  That is where we keep floats
1112  // when using NEON v2f32 instructions for f32 arithmetic.
1113  unsigned DstRegS = MI->getOperand(0).getReg();
1114  unsigned SrcRegS = MI->getOperand(1).getReg();
1115  if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1116    return false;
1117
1118  const TargetRegisterInfo *TRI = &getRegisterInfo();
1119  unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1120                                              &ARM::DPRRegClass);
1121  unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1122                                              &ARM::DPRRegClass);
1123  if (!DstRegD || !SrcRegD)
1124    return false;
1125
1126  // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1127  // legal if the COPY already defines the full DstRegD, and it isn't a
1128  // sub-register insertion.
1129  if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI))
1130    return false;
1131
1132  // A dead copy shouldn't show up here, but reject it just in case.
1133  if (MI->getOperand(0).isDead())
1134    return false;
1135
1136  // All clear, widen the COPY.
1137  DEBUG(dbgs() << "widening:    " << *MI);
1138
1139  // Get rid of the old <imp-def> of DstRegD.  Leave it if it defines a Q-reg
1140  // or some other super-register.
1141  int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD);
1142  if (ImpDefIdx != -1)
1143    MI->RemoveOperand(ImpDefIdx);
1144
1145  // Change the opcode and operands.
1146  MI->setDesc(get(ARM::VMOVD));
1147  MI->getOperand(0).setReg(DstRegD);
1148  MI->getOperand(1).setReg(SrcRegD);
1149  AddDefaultPred(MachineInstrBuilder(MI));
1150
1151  // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1152  // register scavenger and machine verifier, so we need to indicate that we
1153  // are reading an undefined value from SrcRegD, but a proper value from
1154  // SrcRegS.
1155  MI->getOperand(1).setIsUndef();
1156  MachineInstrBuilder(MI).addReg(SrcRegS, RegState::Implicit);
1157
1158  // SrcRegD may actually contain an unrelated value in the ssub_1
1159  // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1160  if (MI->getOperand(1).isKill()) {
1161    MI->getOperand(1).setIsKill(false);
1162    MI->addRegisterKilled(SrcRegS, TRI, true);
1163  }
1164
1165  DEBUG(dbgs() << "replaced by: " << *MI);
1166  return true;
1167}
1168
1169MachineInstr*
1170ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
1171                                           int FrameIx, uint64_t Offset,
1172                                           const MDNode *MDPtr,
1173                                           DebugLoc DL) const {
1174  MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
1175    .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
1176  return &*MIB;
1177}
1178
1179/// Create a copy of a const pool value. Update CPI to the new index and return
1180/// the label UID.
1181static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1182  MachineConstantPool *MCP = MF.getConstantPool();
1183  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1184
1185  const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1186  assert(MCPE.isMachineConstantPoolEntry() &&
1187         "Expecting a machine constantpool entry!");
1188  ARMConstantPoolValue *ACPV =
1189    static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1190
1191  unsigned PCLabelId = AFI->createPICLabelUId();
1192  ARMConstantPoolValue *NewCPV = 0;
1193  // FIXME: The below assumes PIC relocation model and that the function
1194  // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1195  // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1196  // instructions, so that's probably OK, but is PIC always correct when
1197  // we get here?
1198  if (ACPV->isGlobalValue())
1199    NewCPV = ARMConstantPoolConstant::
1200      Create(cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId,
1201             ARMCP::CPValue, 4);
1202  else if (ACPV->isExtSymbol())
1203    NewCPV = ARMConstantPoolSymbol::
1204      Create(MF.getFunction()->getContext(),
1205             cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1206  else if (ACPV->isBlockAddress())
1207    NewCPV = ARMConstantPoolConstant::
1208      Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1209             ARMCP::CPBlockAddress, 4);
1210  else if (ACPV->isLSDA())
1211    NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId,
1212                                             ARMCP::CPLSDA, 4);
1213  else if (ACPV->isMachineBasicBlock())
1214    NewCPV = ARMConstantPoolMBB::
1215      Create(MF.getFunction()->getContext(),
1216             cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1217  else
1218    llvm_unreachable("Unexpected ARM constantpool value type!!");
1219  CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1220  return PCLabelId;
1221}
1222
1223void ARMBaseInstrInfo::
1224reMaterialize(MachineBasicBlock &MBB,
1225              MachineBasicBlock::iterator I,
1226              unsigned DestReg, unsigned SubIdx,
1227              const MachineInstr *Orig,
1228              const TargetRegisterInfo &TRI) const {
1229  unsigned Opcode = Orig->getOpcode();
1230  switch (Opcode) {
1231  default: {
1232    MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1233    MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1234    MBB.insert(I, MI);
1235    break;
1236  }
1237  case ARM::tLDRpci_pic:
1238  case ARM::t2LDRpci_pic: {
1239    MachineFunction &MF = *MBB.getParent();
1240    unsigned CPI = Orig->getOperand(1).getIndex();
1241    unsigned PCLabelId = duplicateCPV(MF, CPI);
1242    MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1243                                      DestReg)
1244      .addConstantPoolIndex(CPI).addImm(PCLabelId);
1245    MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1246    break;
1247  }
1248  }
1249}
1250
1251MachineInstr *
1252ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1253  MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
1254  switch(Orig->getOpcode()) {
1255  case ARM::tLDRpci_pic:
1256  case ARM::t2LDRpci_pic: {
1257    unsigned CPI = Orig->getOperand(1).getIndex();
1258    unsigned PCLabelId = duplicateCPV(MF, CPI);
1259    Orig->getOperand(1).setIndex(CPI);
1260    Orig->getOperand(2).setImm(PCLabelId);
1261    break;
1262  }
1263  }
1264  return MI;
1265}
1266
1267bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1268                                        const MachineInstr *MI1,
1269                                        const MachineRegisterInfo *MRI) const {
1270  int Opcode = MI0->getOpcode();
1271  if (Opcode == ARM::t2LDRpci ||
1272      Opcode == ARM::t2LDRpci_pic ||
1273      Opcode == ARM::tLDRpci ||
1274      Opcode == ARM::tLDRpci_pic ||
1275      Opcode == ARM::MOV_ga_dyn ||
1276      Opcode == ARM::MOV_ga_pcrel ||
1277      Opcode == ARM::MOV_ga_pcrel_ldr ||
1278      Opcode == ARM::t2MOV_ga_dyn ||
1279      Opcode == ARM::t2MOV_ga_pcrel) {
1280    if (MI1->getOpcode() != Opcode)
1281      return false;
1282    if (MI0->getNumOperands() != MI1->getNumOperands())
1283      return false;
1284
1285    const MachineOperand &MO0 = MI0->getOperand(1);
1286    const MachineOperand &MO1 = MI1->getOperand(1);
1287    if (MO0.getOffset() != MO1.getOffset())
1288      return false;
1289
1290    if (Opcode == ARM::MOV_ga_dyn ||
1291        Opcode == ARM::MOV_ga_pcrel ||
1292        Opcode == ARM::MOV_ga_pcrel_ldr ||
1293        Opcode == ARM::t2MOV_ga_dyn ||
1294        Opcode == ARM::t2MOV_ga_pcrel)
1295      // Ignore the PC labels.
1296      return MO0.getGlobal() == MO1.getGlobal();
1297
1298    const MachineFunction *MF = MI0->getParent()->getParent();
1299    const MachineConstantPool *MCP = MF->getConstantPool();
1300    int CPI0 = MO0.getIndex();
1301    int CPI1 = MO1.getIndex();
1302    const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1303    const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1304    bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1305    bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1306    if (isARMCP0 && isARMCP1) {
1307      ARMConstantPoolValue *ACPV0 =
1308        static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1309      ARMConstantPoolValue *ACPV1 =
1310        static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1311      return ACPV0->hasSameValue(ACPV1);
1312    } else if (!isARMCP0 && !isARMCP1) {
1313      return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1314    }
1315    return false;
1316  } else if (Opcode == ARM::PICLDR) {
1317    if (MI1->getOpcode() != Opcode)
1318      return false;
1319    if (MI0->getNumOperands() != MI1->getNumOperands())
1320      return false;
1321
1322    unsigned Addr0 = MI0->getOperand(1).getReg();
1323    unsigned Addr1 = MI1->getOperand(1).getReg();
1324    if (Addr0 != Addr1) {
1325      if (!MRI ||
1326          !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1327          !TargetRegisterInfo::isVirtualRegister(Addr1))
1328        return false;
1329
1330      // This assumes SSA form.
1331      MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1332      MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1333      // Check if the loaded value, e.g. a constantpool of a global address, are
1334      // the same.
1335      if (!produceSameValue(Def0, Def1, MRI))
1336        return false;
1337    }
1338
1339    for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1340      // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1341      const MachineOperand &MO0 = MI0->getOperand(i);
1342      const MachineOperand &MO1 = MI1->getOperand(i);
1343      if (!MO0.isIdenticalTo(MO1))
1344        return false;
1345    }
1346    return true;
1347  }
1348
1349  return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1350}
1351
1352/// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1353/// determine if two loads are loading from the same base address. It should
1354/// only return true if the base pointers are the same and the only differences
1355/// between the two addresses is the offset. It also returns the offsets by
1356/// reference.
1357bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1358                                               int64_t &Offset1,
1359                                               int64_t &Offset2) const {
1360  // Don't worry about Thumb: just ARM and Thumb2.
1361  if (Subtarget.isThumb1Only()) return false;
1362
1363  if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1364    return false;
1365
1366  switch (Load1->getMachineOpcode()) {
1367  default:
1368    return false;
1369  case ARM::LDRi12:
1370  case ARM::LDRBi12:
1371  case ARM::LDRD:
1372  case ARM::LDRH:
1373  case ARM::LDRSB:
1374  case ARM::LDRSH:
1375  case ARM::VLDRD:
1376  case ARM::VLDRS:
1377  case ARM::t2LDRi8:
1378  case ARM::t2LDRDi8:
1379  case ARM::t2LDRSHi8:
1380  case ARM::t2LDRi12:
1381  case ARM::t2LDRSHi12:
1382    break;
1383  }
1384
1385  switch (Load2->getMachineOpcode()) {
1386  default:
1387    return false;
1388  case ARM::LDRi12:
1389  case ARM::LDRBi12:
1390  case ARM::LDRD:
1391  case ARM::LDRH:
1392  case ARM::LDRSB:
1393  case ARM::LDRSH:
1394  case ARM::VLDRD:
1395  case ARM::VLDRS:
1396  case ARM::t2LDRi8:
1397  case ARM::t2LDRSHi8:
1398  case ARM::t2LDRi12:
1399  case ARM::t2LDRSHi12:
1400    break;
1401  }
1402
1403  // Check if base addresses and chain operands match.
1404  if (Load1->getOperand(0) != Load2->getOperand(0) ||
1405      Load1->getOperand(4) != Load2->getOperand(4))
1406    return false;
1407
1408  // Index should be Reg0.
1409  if (Load1->getOperand(3) != Load2->getOperand(3))
1410    return false;
1411
1412  // Determine the offsets.
1413  if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1414      isa<ConstantSDNode>(Load2->getOperand(1))) {
1415    Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1416    Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1417    return true;
1418  }
1419
1420  return false;
1421}
1422
1423/// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1424/// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1425/// be scheduled togther. On some targets if two loads are loading from
1426/// addresses in the same cache line, it's better if they are scheduled
1427/// together. This function takes two integers that represent the load offsets
1428/// from the common base address. It returns true if it decides it's desirable
1429/// to schedule the two loads together. "NumLoads" is the number of loads that
1430/// have already been scheduled after Load1.
1431bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1432                                               int64_t Offset1, int64_t Offset2,
1433                                               unsigned NumLoads) const {
1434  // Don't worry about Thumb: just ARM and Thumb2.
1435  if (Subtarget.isThumb1Only()) return false;
1436
1437  assert(Offset2 > Offset1);
1438
1439  if ((Offset2 - Offset1) / 8 > 64)
1440    return false;
1441
1442  if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1443    return false;  // FIXME: overly conservative?
1444
1445  // Four loads in a row should be sufficient.
1446  if (NumLoads >= 3)
1447    return false;
1448
1449  return true;
1450}
1451
1452bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1453                                            const MachineBasicBlock *MBB,
1454                                            const MachineFunction &MF) const {
1455  // Debug info is never a scheduling boundary. It's necessary to be explicit
1456  // due to the special treatment of IT instructions below, otherwise a
1457  // dbg_value followed by an IT will result in the IT instruction being
1458  // considered a scheduling hazard, which is wrong. It should be the actual
1459  // instruction preceding the dbg_value instruction(s), just like it is
1460  // when debug info is not present.
1461  if (MI->isDebugValue())
1462    return false;
1463
1464  // Terminators and labels can't be scheduled around.
1465  if (MI->isTerminator() || MI->isLabel())
1466    return true;
1467
1468  // Treat the start of the IT block as a scheduling boundary, but schedule
1469  // t2IT along with all instructions following it.
1470  // FIXME: This is a big hammer. But the alternative is to add all potential
1471  // true and anti dependencies to IT block instructions as implicit operands
1472  // to the t2IT instruction. The added compile time and complexity does not
1473  // seem worth it.
1474  MachineBasicBlock::const_iterator I = MI;
1475  // Make sure to skip any dbg_value instructions
1476  while (++I != MBB->end() && I->isDebugValue())
1477    ;
1478  if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1479    return true;
1480
1481  // Don't attempt to schedule around any instruction that defines
1482  // a stack-oriented pointer, as it's unlikely to be profitable. This
1483  // saves compile time, because it doesn't require every single
1484  // stack slot reference to depend on the instruction that does the
1485  // modification.
1486  // Calls don't actually change the stack pointer, even if they have imp-defs.
1487  // No ARM calling conventions change the stack pointer. (X86 calling
1488  // conventions sometimes do).
1489  if (!MI->isCall() && MI->definesRegister(ARM::SP))
1490    return true;
1491
1492  return false;
1493}
1494
1495bool ARMBaseInstrInfo::
1496isProfitableToIfCvt(MachineBasicBlock &MBB,
1497                    unsigned NumCycles, unsigned ExtraPredCycles,
1498                    const BranchProbability &Probability) const {
1499  if (!NumCycles)
1500    return false;
1501
1502  // Attempt to estimate the relative costs of predication versus branching.
1503  unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1504  UnpredCost /= Probability.getDenominator();
1505  UnpredCost += 1; // The branch itself
1506  UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1507
1508  return (NumCycles + ExtraPredCycles) <= UnpredCost;
1509}
1510
1511bool ARMBaseInstrInfo::
1512isProfitableToIfCvt(MachineBasicBlock &TMBB,
1513                    unsigned TCycles, unsigned TExtra,
1514                    MachineBasicBlock &FMBB,
1515                    unsigned FCycles, unsigned FExtra,
1516                    const BranchProbability &Probability) const {
1517  if (!TCycles || !FCycles)
1518    return false;
1519
1520  // Attempt to estimate the relative costs of predication versus branching.
1521  unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1522  TUnpredCost /= Probability.getDenominator();
1523
1524  uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1525  unsigned FUnpredCost = Comp * FCycles;
1526  FUnpredCost /= Probability.getDenominator();
1527
1528  unsigned UnpredCost = TUnpredCost + FUnpredCost;
1529  UnpredCost += 1; // The branch itself
1530  UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1531
1532  return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1533}
1534
1535bool
1536ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
1537                                            MachineBasicBlock &FMBB) const {
1538  // Reduce false anti-dependencies to let Swift's out-of-order execution
1539  // engine do its thing.
1540  return Subtarget.isSwift();
1541}
1542
1543/// getInstrPredicate - If instruction is predicated, returns its predicate
1544/// condition, otherwise returns AL. It also returns the condition code
1545/// register by reference.
1546ARMCC::CondCodes
1547llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1548  int PIdx = MI->findFirstPredOperandIdx();
1549  if (PIdx == -1) {
1550    PredReg = 0;
1551    return ARMCC::AL;
1552  }
1553
1554  PredReg = MI->getOperand(PIdx+1).getReg();
1555  return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1556}
1557
1558
1559int llvm::getMatchingCondBranchOpcode(int Opc) {
1560  if (Opc == ARM::B)
1561    return ARM::Bcc;
1562  if (Opc == ARM::tB)
1563    return ARM::tBcc;
1564  if (Opc == ARM::t2B)
1565    return ARM::t2Bcc;
1566
1567  llvm_unreachable("Unknown unconditional branch opcode!");
1568}
1569
1570/// commuteInstruction - Handle commutable instructions.
1571MachineInstr *
1572ARMBaseInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
1573  switch (MI->getOpcode()) {
1574  case ARM::MOVCCr:
1575  case ARM::t2MOVCCr: {
1576    // MOVCC can be commuted by inverting the condition.
1577    unsigned PredReg = 0;
1578    ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
1579    // MOVCC AL can't be inverted. Shouldn't happen.
1580    if (CC == ARMCC::AL || PredReg != ARM::CPSR)
1581      return NULL;
1582    MI = TargetInstrInfoImpl::commuteInstruction(MI, NewMI);
1583    if (!MI)
1584      return NULL;
1585    // After swapping the MOVCC operands, also invert the condition.
1586    MI->getOperand(MI->findFirstPredOperandIdx())
1587      .setImm(ARMCC::getOppositeCondition(CC));
1588    return MI;
1589  }
1590  }
1591  return TargetInstrInfoImpl::commuteInstruction(MI, NewMI);
1592}
1593
1594/// Identify instructions that can be folded into a MOVCC instruction, and
1595/// return the defining instruction.
1596static MachineInstr *canFoldIntoMOVCC(unsigned Reg,
1597                                      const MachineRegisterInfo &MRI,
1598                                      const TargetInstrInfo *TII) {
1599  if (!TargetRegisterInfo::isVirtualRegister(Reg))
1600    return 0;
1601  if (!MRI.hasOneNonDBGUse(Reg))
1602    return 0;
1603  MachineInstr *MI = MRI.getVRegDef(Reg);
1604  if (!MI)
1605    return 0;
1606  // MI is folded into the MOVCC by predicating it.
1607  if (!MI->isPredicable())
1608    return 0;
1609  // Check if MI has any non-dead defs or physreg uses. This also detects
1610  // predicated instructions which will be reading CPSR.
1611  for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
1612    const MachineOperand &MO = MI->getOperand(i);
1613    // Reject frame index operands, PEI can't handle the predicated pseudos.
1614    if (MO.isFI() || MO.isCPI() || MO.isJTI())
1615      return 0;
1616    if (!MO.isReg())
1617      continue;
1618    // MI can't have any tied operands, that would conflict with predication.
1619    if (MO.isTied())
1620      return 0;
1621    if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1622      return 0;
1623    if (MO.isDef() && !MO.isDead())
1624      return 0;
1625  }
1626  bool DontMoveAcrossStores = true;
1627  if (!MI->isSafeToMove(TII, /* AliasAnalysis = */ 0, DontMoveAcrossStores))
1628    return 0;
1629  return MI;
1630}
1631
1632bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr *MI,
1633                                     SmallVectorImpl<MachineOperand> &Cond,
1634                                     unsigned &TrueOp, unsigned &FalseOp,
1635                                     bool &Optimizable) const {
1636  assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1637         "Unknown select instruction");
1638  // MOVCC operands:
1639  // 0: Def.
1640  // 1: True use.
1641  // 2: False use.
1642  // 3: Condition code.
1643  // 4: CPSR use.
1644  TrueOp = 1;
1645  FalseOp = 2;
1646  Cond.push_back(MI->getOperand(3));
1647  Cond.push_back(MI->getOperand(4));
1648  // We can always fold a def.
1649  Optimizable = true;
1650  return false;
1651}
1652
1653MachineInstr *ARMBaseInstrInfo::optimizeSelect(MachineInstr *MI,
1654                                               bool PreferFalse) const {
1655  assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1656         "Unknown select instruction");
1657  const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1658  MachineInstr *DefMI = canFoldIntoMOVCC(MI->getOperand(2).getReg(), MRI, this);
1659  bool Invert = !DefMI;
1660  if (!DefMI)
1661    DefMI = canFoldIntoMOVCC(MI->getOperand(1).getReg(), MRI, this);
1662  if (!DefMI)
1663    return 0;
1664
1665  // Create a new predicated version of DefMI.
1666  // Rfalse is the first use.
1667  MachineInstrBuilder NewMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1668                                      DefMI->getDesc(),
1669                                      MI->getOperand(0).getReg());
1670
1671  // Copy all the DefMI operands, excluding its (null) predicate.
1672  const MCInstrDesc &DefDesc = DefMI->getDesc();
1673  for (unsigned i = 1, e = DefDesc.getNumOperands();
1674       i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
1675    NewMI.addOperand(DefMI->getOperand(i));
1676
1677  unsigned CondCode = MI->getOperand(3).getImm();
1678  if (Invert)
1679    NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
1680  else
1681    NewMI.addImm(CondCode);
1682  NewMI.addOperand(MI->getOperand(4));
1683
1684  // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
1685  if (NewMI->hasOptionalDef())
1686    AddDefaultCC(NewMI);
1687
1688  // The output register value when the predicate is false is an implicit
1689  // register operand tied to the first def.
1690  // The tie makes the register allocator ensure the FalseReg is allocated the
1691  // same register as operand 0.
1692  MachineOperand FalseReg = MI->getOperand(Invert ? 2 : 1);
1693  FalseReg.setImplicit();
1694  NewMI->addOperand(FalseReg);
1695  NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
1696
1697  // The caller will erase MI, but not DefMI.
1698  DefMI->eraseFromParent();
1699  return NewMI;
1700}
1701
1702/// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
1703/// instruction is encoded with an 'S' bit is determined by the optional CPSR
1704/// def operand.
1705///
1706/// This will go away once we can teach tblgen how to set the optional CPSR def
1707/// operand itself.
1708struct AddSubFlagsOpcodePair {
1709  uint16_t PseudoOpc;
1710  uint16_t MachineOpc;
1711};
1712
1713static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
1714  {ARM::ADDSri, ARM::ADDri},
1715  {ARM::ADDSrr, ARM::ADDrr},
1716  {ARM::ADDSrsi, ARM::ADDrsi},
1717  {ARM::ADDSrsr, ARM::ADDrsr},
1718
1719  {ARM::SUBSri, ARM::SUBri},
1720  {ARM::SUBSrr, ARM::SUBrr},
1721  {ARM::SUBSrsi, ARM::SUBrsi},
1722  {ARM::SUBSrsr, ARM::SUBrsr},
1723
1724  {ARM::RSBSri, ARM::RSBri},
1725  {ARM::RSBSrsi, ARM::RSBrsi},
1726  {ARM::RSBSrsr, ARM::RSBrsr},
1727
1728  {ARM::t2ADDSri, ARM::t2ADDri},
1729  {ARM::t2ADDSrr, ARM::t2ADDrr},
1730  {ARM::t2ADDSrs, ARM::t2ADDrs},
1731
1732  {ARM::t2SUBSri, ARM::t2SUBri},
1733  {ARM::t2SUBSrr, ARM::t2SUBrr},
1734  {ARM::t2SUBSrs, ARM::t2SUBrs},
1735
1736  {ARM::t2RSBSri, ARM::t2RSBri},
1737  {ARM::t2RSBSrs, ARM::t2RSBrs},
1738};
1739
1740unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
1741  for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
1742    if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
1743      return AddSubFlagsOpcodeMap[i].MachineOpc;
1744  return 0;
1745}
1746
1747void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1748                               MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1749                               unsigned DestReg, unsigned BaseReg, int NumBytes,
1750                               ARMCC::CondCodes Pred, unsigned PredReg,
1751                               const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1752  bool isSub = NumBytes < 0;
1753  if (isSub) NumBytes = -NumBytes;
1754
1755  while (NumBytes) {
1756    unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1757    unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1758    assert(ThisVal && "Didn't extract field correctly");
1759
1760    // We will handle these bits from offset, clear them.
1761    NumBytes &= ~ThisVal;
1762
1763    assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1764
1765    // Build the new ADD / SUB.
1766    unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1767    BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1768      .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1769      .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1770      .setMIFlags(MIFlags);
1771    BaseReg = DestReg;
1772  }
1773}
1774
1775bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1776                                unsigned FrameReg, int &Offset,
1777                                const ARMBaseInstrInfo &TII) {
1778  unsigned Opcode = MI.getOpcode();
1779  const MCInstrDesc &Desc = MI.getDesc();
1780  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1781  bool isSub = false;
1782
1783  // Memory operands in inline assembly always use AddrMode2.
1784  if (Opcode == ARM::INLINEASM)
1785    AddrMode = ARMII::AddrMode2;
1786
1787  if (Opcode == ARM::ADDri) {
1788    Offset += MI.getOperand(FrameRegIdx+1).getImm();
1789    if (Offset == 0) {
1790      // Turn it into a move.
1791      MI.setDesc(TII.get(ARM::MOVr));
1792      MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1793      MI.RemoveOperand(FrameRegIdx+1);
1794      Offset = 0;
1795      return true;
1796    } else if (Offset < 0) {
1797      Offset = -Offset;
1798      isSub = true;
1799      MI.setDesc(TII.get(ARM::SUBri));
1800    }
1801
1802    // Common case: small offset, fits into instruction.
1803    if (ARM_AM::getSOImmVal(Offset) != -1) {
1804      // Replace the FrameIndex with sp / fp
1805      MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1806      MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1807      Offset = 0;
1808      return true;
1809    }
1810
1811    // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1812    // as possible.
1813    unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1814    unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1815
1816    // We will handle these bits from offset, clear them.
1817    Offset &= ~ThisImmVal;
1818
1819    // Get the properly encoded SOImmVal field.
1820    assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1821           "Bit extraction didn't work?");
1822    MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1823 } else {
1824    unsigned ImmIdx = 0;
1825    int InstrOffs = 0;
1826    unsigned NumBits = 0;
1827    unsigned Scale = 1;
1828    switch (AddrMode) {
1829    case ARMII::AddrMode_i12: {
1830      ImmIdx = FrameRegIdx + 1;
1831      InstrOffs = MI.getOperand(ImmIdx).getImm();
1832      NumBits = 12;
1833      break;
1834    }
1835    case ARMII::AddrMode2: {
1836      ImmIdx = FrameRegIdx+2;
1837      InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1838      if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1839        InstrOffs *= -1;
1840      NumBits = 12;
1841      break;
1842    }
1843    case ARMII::AddrMode3: {
1844      ImmIdx = FrameRegIdx+2;
1845      InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1846      if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1847        InstrOffs *= -1;
1848      NumBits = 8;
1849      break;
1850    }
1851    case ARMII::AddrMode4:
1852    case ARMII::AddrMode6:
1853      // Can't fold any offset even if it's zero.
1854      return false;
1855    case ARMII::AddrMode5: {
1856      ImmIdx = FrameRegIdx+1;
1857      InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1858      if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1859        InstrOffs *= -1;
1860      NumBits = 8;
1861      Scale = 4;
1862      break;
1863    }
1864    default:
1865      llvm_unreachable("Unsupported addressing mode!");
1866    }
1867
1868    Offset += InstrOffs * Scale;
1869    assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1870    if (Offset < 0) {
1871      Offset = -Offset;
1872      isSub = true;
1873    }
1874
1875    // Attempt to fold address comp. if opcode has offset bits
1876    if (NumBits > 0) {
1877      // Common case: small offset, fits into instruction.
1878      MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1879      int ImmedOffset = Offset / Scale;
1880      unsigned Mask = (1 << NumBits) - 1;
1881      if ((unsigned)Offset <= Mask * Scale) {
1882        // Replace the FrameIndex with sp
1883        MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1884        // FIXME: When addrmode2 goes away, this will simplify (like the
1885        // T2 version), as the LDR.i12 versions don't need the encoding
1886        // tricks for the offset value.
1887        if (isSub) {
1888          if (AddrMode == ARMII::AddrMode_i12)
1889            ImmedOffset = -ImmedOffset;
1890          else
1891            ImmedOffset |= 1 << NumBits;
1892        }
1893        ImmOp.ChangeToImmediate(ImmedOffset);
1894        Offset = 0;
1895        return true;
1896      }
1897
1898      // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1899      ImmedOffset = ImmedOffset & Mask;
1900      if (isSub) {
1901        if (AddrMode == ARMII::AddrMode_i12)
1902          ImmedOffset = -ImmedOffset;
1903        else
1904          ImmedOffset |= 1 << NumBits;
1905      }
1906      ImmOp.ChangeToImmediate(ImmedOffset);
1907      Offset &= ~(Mask*Scale);
1908    }
1909  }
1910
1911  Offset = (isSub) ? -Offset : Offset;
1912  return Offset == 0;
1913}
1914
1915/// analyzeCompare - For a comparison instruction, return the source registers
1916/// in SrcReg and SrcReg2 if having two register operands, and the value it
1917/// compares against in CmpValue. Return true if the comparison instruction
1918/// can be analyzed.
1919bool ARMBaseInstrInfo::
1920analyzeCompare(const MachineInstr *MI, unsigned &SrcReg, unsigned &SrcReg2,
1921               int &CmpMask, int &CmpValue) const {
1922  switch (MI->getOpcode()) {
1923  default: break;
1924  case ARM::CMPri:
1925  case ARM::t2CMPri:
1926    SrcReg = MI->getOperand(0).getReg();
1927    SrcReg2 = 0;
1928    CmpMask = ~0;
1929    CmpValue = MI->getOperand(1).getImm();
1930    return true;
1931  case ARM::CMPrr:
1932  case ARM::t2CMPrr:
1933    SrcReg = MI->getOperand(0).getReg();
1934    SrcReg2 = MI->getOperand(1).getReg();
1935    CmpMask = ~0;
1936    CmpValue = 0;
1937    return true;
1938  case ARM::TSTri:
1939  case ARM::t2TSTri:
1940    SrcReg = MI->getOperand(0).getReg();
1941    SrcReg2 = 0;
1942    CmpMask = MI->getOperand(1).getImm();
1943    CmpValue = 0;
1944    return true;
1945  }
1946
1947  return false;
1948}
1949
1950/// isSuitableForMask - Identify a suitable 'and' instruction that
1951/// operates on the given source register and applies the same mask
1952/// as a 'tst' instruction. Provide a limited look-through for copies.
1953/// When successful, MI will hold the found instruction.
1954static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
1955                              int CmpMask, bool CommonUse) {
1956  switch (MI->getOpcode()) {
1957    case ARM::ANDri:
1958    case ARM::t2ANDri:
1959      if (CmpMask != MI->getOperand(2).getImm())
1960        return false;
1961      if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
1962        return true;
1963      break;
1964    case ARM::COPY: {
1965      // Walk down one instruction which is potentially an 'and'.
1966      const MachineInstr &Copy = *MI;
1967      MachineBasicBlock::iterator AND(
1968        llvm::next(MachineBasicBlock::iterator(MI)));
1969      if (AND == MI->getParent()->end()) return false;
1970      MI = AND;
1971      return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
1972                               CmpMask, true);
1973    }
1974  }
1975
1976  return false;
1977}
1978
1979/// getSwappedCondition - assume the flags are set by MI(a,b), return
1980/// the condition code if we modify the instructions such that flags are
1981/// set by MI(b,a).
1982inline static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC) {
1983  switch (CC) {
1984  default: return ARMCC::AL;
1985  case ARMCC::EQ: return ARMCC::EQ;
1986  case ARMCC::NE: return ARMCC::NE;
1987  case ARMCC::HS: return ARMCC::LS;
1988  case ARMCC::LO: return ARMCC::HI;
1989  case ARMCC::HI: return ARMCC::LO;
1990  case ARMCC::LS: return ARMCC::HS;
1991  case ARMCC::GE: return ARMCC::LE;
1992  case ARMCC::LT: return ARMCC::GT;
1993  case ARMCC::GT: return ARMCC::LT;
1994  case ARMCC::LE: return ARMCC::GE;
1995  }
1996}
1997
1998/// isRedundantFlagInstr - check whether the first instruction, whose only
1999/// purpose is to update flags, can be made redundant.
2000/// CMPrr can be made redundant by SUBrr if the operands are the same.
2001/// CMPri can be made redundant by SUBri if the operands are the same.
2002/// This function can be extended later on.
2003inline static bool isRedundantFlagInstr(MachineInstr *CmpI, unsigned SrcReg,
2004                                        unsigned SrcReg2, int ImmValue,
2005                                        MachineInstr *OI) {
2006  if ((CmpI->getOpcode() == ARM::CMPrr ||
2007       CmpI->getOpcode() == ARM::t2CMPrr) &&
2008      (OI->getOpcode() == ARM::SUBrr ||
2009       OI->getOpcode() == ARM::t2SUBrr) &&
2010      ((OI->getOperand(1).getReg() == SrcReg &&
2011        OI->getOperand(2).getReg() == SrcReg2) ||
2012       (OI->getOperand(1).getReg() == SrcReg2 &&
2013        OI->getOperand(2).getReg() == SrcReg)))
2014    return true;
2015
2016  if ((CmpI->getOpcode() == ARM::CMPri ||
2017       CmpI->getOpcode() == ARM::t2CMPri) &&
2018      (OI->getOpcode() == ARM::SUBri ||
2019       OI->getOpcode() == ARM::t2SUBri) &&
2020      OI->getOperand(1).getReg() == SrcReg &&
2021      OI->getOperand(2).getImm() == ImmValue)
2022    return true;
2023  return false;
2024}
2025
2026/// optimizeCompareInstr - Convert the instruction supplying the argument to the
2027/// comparison into one that sets the zero bit in the flags register;
2028/// Remove a redundant Compare instruction if an earlier instruction can set the
2029/// flags in the same way as Compare.
2030/// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2031/// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2032/// condition code of instructions which use the flags.
2033bool ARMBaseInstrInfo::
2034optimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, unsigned SrcReg2,
2035                     int CmpMask, int CmpValue,
2036                     const MachineRegisterInfo *MRI) const {
2037  // Get the unique definition of SrcReg.
2038  MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2039  if (!MI) return false;
2040
2041  // Masked compares sometimes use the same register as the corresponding 'and'.
2042  if (CmpMask != ~0) {
2043    if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(MI)) {
2044      MI = 0;
2045      for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
2046           UE = MRI->use_end(); UI != UE; ++UI) {
2047        if (UI->getParent() != CmpInstr->getParent()) continue;
2048        MachineInstr *PotentialAND = &*UI;
2049        if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2050            isPredicated(PotentialAND))
2051          continue;
2052        MI = PotentialAND;
2053        break;
2054      }
2055      if (!MI) return false;
2056    }
2057  }
2058
2059  // Get ready to iterate backward from CmpInstr.
2060  MachineBasicBlock::iterator I = CmpInstr, E = MI,
2061                              B = CmpInstr->getParent()->begin();
2062
2063  // Early exit if CmpInstr is at the beginning of the BB.
2064  if (I == B) return false;
2065
2066  // There are two possible candidates which can be changed to set CPSR:
2067  // One is MI, the other is a SUB instruction.
2068  // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2069  // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2070  MachineInstr *Sub = NULL;
2071  if (SrcReg2 != 0)
2072    // MI is not a candidate for CMPrr.
2073    MI = NULL;
2074  else if (MI->getParent() != CmpInstr->getParent() || CmpValue != 0) {
2075    // Conservatively refuse to convert an instruction which isn't in the same
2076    // BB as the comparison.
2077    // For CMPri, we need to check Sub, thus we can't return here.
2078    if (CmpInstr->getOpcode() == ARM::CMPri ||
2079       CmpInstr->getOpcode() == ARM::t2CMPri)
2080      MI = NULL;
2081    else
2082      return false;
2083  }
2084
2085  // Check that CPSR isn't set between the comparison instruction and the one we
2086  // want to change. At the same time, search for Sub.
2087  const TargetRegisterInfo *TRI = &getRegisterInfo();
2088  --I;
2089  for (; I != E; --I) {
2090    const MachineInstr &Instr = *I;
2091
2092    if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
2093        Instr.readsRegister(ARM::CPSR, TRI))
2094      // This instruction modifies or uses CPSR after the one we want to
2095      // change. We can't do this transformation.
2096      return false;
2097
2098    // Check whether CmpInstr can be made redundant by the current instruction.
2099    if (isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpValue, &*I)) {
2100      Sub = &*I;
2101      break;
2102    }
2103
2104    if (I == B)
2105      // The 'and' is below the comparison instruction.
2106      return false;
2107  }
2108
2109  // Return false if no candidates exist.
2110  if (!MI && !Sub)
2111    return false;
2112
2113  // The single candidate is called MI.
2114  if (!MI) MI = Sub;
2115
2116  // We can't use a predicated instruction - it doesn't always write the flags.
2117  if (isPredicated(MI))
2118    return false;
2119
2120  switch (MI->getOpcode()) {
2121  default: break;
2122  case ARM::RSBrr:
2123  case ARM::RSBri:
2124  case ARM::RSCrr:
2125  case ARM::RSCri:
2126  case ARM::ADDrr:
2127  case ARM::ADDri:
2128  case ARM::ADCrr:
2129  case ARM::ADCri:
2130  case ARM::SUBrr:
2131  case ARM::SUBri:
2132  case ARM::SBCrr:
2133  case ARM::SBCri:
2134  case ARM::t2RSBri:
2135  case ARM::t2ADDrr:
2136  case ARM::t2ADDri:
2137  case ARM::t2ADCrr:
2138  case ARM::t2ADCri:
2139  case ARM::t2SUBrr:
2140  case ARM::t2SUBri:
2141  case ARM::t2SBCrr:
2142  case ARM::t2SBCri:
2143  case ARM::ANDrr:
2144  case ARM::ANDri:
2145  case ARM::t2ANDrr:
2146  case ARM::t2ANDri:
2147  case ARM::ORRrr:
2148  case ARM::ORRri:
2149  case ARM::t2ORRrr:
2150  case ARM::t2ORRri:
2151  case ARM::EORrr:
2152  case ARM::EORri:
2153  case ARM::t2EORrr:
2154  case ARM::t2EORri: {
2155    // Scan forward for the use of CPSR
2156    // When checking against MI: if it's a conditional code requires
2157    // checking of V bit, then this is not safe to do.
2158    // It is safe to remove CmpInstr if CPSR is redefined or killed.
2159    // If we are done with the basic block, we need to check whether CPSR is
2160    // live-out.
2161    SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
2162        OperandsToUpdate;
2163    bool isSafe = false;
2164    I = CmpInstr;
2165    E = CmpInstr->getParent()->end();
2166    while (!isSafe && ++I != E) {
2167      const MachineInstr &Instr = *I;
2168      for (unsigned IO = 0, EO = Instr.getNumOperands();
2169           !isSafe && IO != EO; ++IO) {
2170        const MachineOperand &MO = Instr.getOperand(IO);
2171        if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
2172          isSafe = true;
2173          break;
2174        }
2175        if (!MO.isReg() || MO.getReg() != ARM::CPSR)
2176          continue;
2177        if (MO.isDef()) {
2178          isSafe = true;
2179          break;
2180        }
2181        // Condition code is after the operand before CPSR.
2182        ARMCC::CondCodes CC = (ARMCC::CondCodes)Instr.getOperand(IO-1).getImm();
2183        if (Sub) {
2184          ARMCC::CondCodes NewCC = getSwappedCondition(CC);
2185          if (NewCC == ARMCC::AL)
2186            return false;
2187          // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
2188          // on CMP needs to be updated to be based on SUB.
2189          // Push the condition code operands to OperandsToUpdate.
2190          // If it is safe to remove CmpInstr, the condition code of these
2191          // operands will be modified.
2192          if (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2193              Sub->getOperand(2).getReg() == SrcReg)
2194            OperandsToUpdate.push_back(std::make_pair(&((*I).getOperand(IO-1)),
2195                                                      NewCC));
2196        }
2197        else
2198          switch (CC) {
2199          default:
2200            // CPSR can be used multiple times, we should continue.
2201            break;
2202          case ARMCC::VS:
2203          case ARMCC::VC:
2204          case ARMCC::GE:
2205          case ARMCC::LT:
2206          case ARMCC::GT:
2207          case ARMCC::LE:
2208            return false;
2209          }
2210      }
2211    }
2212
2213    // If CPSR is not killed nor re-defined, we should check whether it is
2214    // live-out. If it is live-out, do not optimize.
2215    if (!isSafe) {
2216      MachineBasicBlock *MBB = CmpInstr->getParent();
2217      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
2218               SE = MBB->succ_end(); SI != SE; ++SI)
2219        if ((*SI)->isLiveIn(ARM::CPSR))
2220          return false;
2221    }
2222
2223    // Toggle the optional operand to CPSR.
2224    MI->getOperand(5).setReg(ARM::CPSR);
2225    MI->getOperand(5).setIsDef(true);
2226    assert(!isPredicated(MI) && "Can't use flags from predicated instruction");
2227    CmpInstr->eraseFromParent();
2228
2229    // Modify the condition code of operands in OperandsToUpdate.
2230    // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2231    // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2232    for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
2233      OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
2234    return true;
2235  }
2236  }
2237
2238  return false;
2239}
2240
2241bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
2242                                     MachineInstr *DefMI, unsigned Reg,
2243                                     MachineRegisterInfo *MRI) const {
2244  // Fold large immediates into add, sub, or, xor.
2245  unsigned DefOpc = DefMI->getOpcode();
2246  if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
2247    return false;
2248  if (!DefMI->getOperand(1).isImm())
2249    // Could be t2MOVi32imm <ga:xx>
2250    return false;
2251
2252  if (!MRI->hasOneNonDBGUse(Reg))
2253    return false;
2254
2255  const MCInstrDesc &DefMCID = DefMI->getDesc();
2256  if (DefMCID.hasOptionalDef()) {
2257    unsigned NumOps = DefMCID.getNumOperands();
2258    const MachineOperand &MO = DefMI->getOperand(NumOps-1);
2259    if (MO.getReg() == ARM::CPSR && !MO.isDead())
2260      // If DefMI defines CPSR and it is not dead, it's obviously not safe
2261      // to delete DefMI.
2262      return false;
2263  }
2264
2265  const MCInstrDesc &UseMCID = UseMI->getDesc();
2266  if (UseMCID.hasOptionalDef()) {
2267    unsigned NumOps = UseMCID.getNumOperands();
2268    if (UseMI->getOperand(NumOps-1).getReg() == ARM::CPSR)
2269      // If the instruction sets the flag, do not attempt this optimization
2270      // since it may change the semantics of the code.
2271      return false;
2272  }
2273
2274  unsigned UseOpc = UseMI->getOpcode();
2275  unsigned NewUseOpc = 0;
2276  uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
2277  uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
2278  bool Commute = false;
2279  switch (UseOpc) {
2280  default: return false;
2281  case ARM::SUBrr:
2282  case ARM::ADDrr:
2283  case ARM::ORRrr:
2284  case ARM::EORrr:
2285  case ARM::t2SUBrr:
2286  case ARM::t2ADDrr:
2287  case ARM::t2ORRrr:
2288  case ARM::t2EORrr: {
2289    Commute = UseMI->getOperand(2).getReg() != Reg;
2290    switch (UseOpc) {
2291    default: break;
2292    case ARM::SUBrr: {
2293      if (Commute)
2294        return false;
2295      ImmVal = -ImmVal;
2296      NewUseOpc = ARM::SUBri;
2297      // Fallthrough
2298    }
2299    case ARM::ADDrr:
2300    case ARM::ORRrr:
2301    case ARM::EORrr: {
2302      if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
2303        return false;
2304      SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
2305      SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
2306      switch (UseOpc) {
2307      default: break;
2308      case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
2309      case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
2310      case ARM::EORrr: NewUseOpc = ARM::EORri; break;
2311      }
2312      break;
2313    }
2314    case ARM::t2SUBrr: {
2315      if (Commute)
2316        return false;
2317      ImmVal = -ImmVal;
2318      NewUseOpc = ARM::t2SUBri;
2319      // Fallthrough
2320    }
2321    case ARM::t2ADDrr:
2322    case ARM::t2ORRrr:
2323    case ARM::t2EORrr: {
2324      if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
2325        return false;
2326      SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
2327      SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
2328      switch (UseOpc) {
2329      default: break;
2330      case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
2331      case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
2332      case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
2333      }
2334      break;
2335    }
2336    }
2337  }
2338  }
2339
2340  unsigned OpIdx = Commute ? 2 : 1;
2341  unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
2342  bool isKill = UseMI->getOperand(OpIdx).isKill();
2343  unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
2344  AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
2345                                      UseMI, UseMI->getDebugLoc(),
2346                                      get(NewUseOpc), NewReg)
2347                              .addReg(Reg1, getKillRegState(isKill))
2348                              .addImm(SOImmValV1)));
2349  UseMI->setDesc(get(NewUseOpc));
2350  UseMI->getOperand(1).setReg(NewReg);
2351  UseMI->getOperand(1).setIsKill();
2352  UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
2353  DefMI->eraseFromParent();
2354  return true;
2355}
2356
2357static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
2358                                        const MachineInstr *MI) {
2359  switch (MI->getOpcode()) {
2360  default: {
2361    const MCInstrDesc &Desc = MI->getDesc();
2362    int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
2363    assert(UOps >= 0 && "bad # UOps");
2364    return UOps;
2365  }
2366
2367  case ARM::LDRrs:
2368  case ARM::LDRBrs:
2369  case ARM::STRrs:
2370  case ARM::STRBrs: {
2371    unsigned ShOpVal = MI->getOperand(3).getImm();
2372    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2373    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2374    if (!isSub &&
2375        (ShImm == 0 ||
2376         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2377          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2378      return 1;
2379    return 2;
2380  }
2381
2382  case ARM::LDRH:
2383  case ARM::STRH: {
2384    if (!MI->getOperand(2).getReg())
2385      return 1;
2386
2387    unsigned ShOpVal = MI->getOperand(3).getImm();
2388    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2389    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2390    if (!isSub &&
2391        (ShImm == 0 ||
2392         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2393          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2394      return 1;
2395    return 2;
2396  }
2397
2398  case ARM::LDRSB:
2399  case ARM::LDRSH:
2400    return (ARM_AM::getAM3Op(MI->getOperand(3).getImm()) == ARM_AM::sub) ? 3:2;
2401
2402  case ARM::LDRSB_POST:
2403  case ARM::LDRSH_POST: {
2404    unsigned Rt = MI->getOperand(0).getReg();
2405    unsigned Rm = MI->getOperand(3).getReg();
2406    return (Rt == Rm) ? 4 : 3;
2407  }
2408
2409  case ARM::LDR_PRE_REG:
2410  case ARM::LDRB_PRE_REG: {
2411    unsigned Rt = MI->getOperand(0).getReg();
2412    unsigned Rm = MI->getOperand(3).getReg();
2413    if (Rt == Rm)
2414      return 3;
2415    unsigned ShOpVal = MI->getOperand(4).getImm();
2416    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2417    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2418    if (!isSub &&
2419        (ShImm == 0 ||
2420         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2421          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2422      return 2;
2423    return 3;
2424  }
2425
2426  case ARM::STR_PRE_REG:
2427  case ARM::STRB_PRE_REG: {
2428    unsigned ShOpVal = MI->getOperand(4).getImm();
2429    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2430    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2431    if (!isSub &&
2432        (ShImm == 0 ||
2433         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2434          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2435      return 2;
2436    return 3;
2437  }
2438
2439  case ARM::LDRH_PRE:
2440  case ARM::STRH_PRE: {
2441    unsigned Rt = MI->getOperand(0).getReg();
2442    unsigned Rm = MI->getOperand(3).getReg();
2443    if (!Rm)
2444      return 2;
2445    if (Rt == Rm)
2446      return 3;
2447    return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub)
2448      ? 3 : 2;
2449  }
2450
2451  case ARM::LDR_POST_REG:
2452  case ARM::LDRB_POST_REG:
2453  case ARM::LDRH_POST: {
2454    unsigned Rt = MI->getOperand(0).getReg();
2455    unsigned Rm = MI->getOperand(3).getReg();
2456    return (Rt == Rm) ? 3 : 2;
2457  }
2458
2459  case ARM::LDR_PRE_IMM:
2460  case ARM::LDRB_PRE_IMM:
2461  case ARM::LDR_POST_IMM:
2462  case ARM::LDRB_POST_IMM:
2463  case ARM::STRB_POST_IMM:
2464  case ARM::STRB_POST_REG:
2465  case ARM::STRB_PRE_IMM:
2466  case ARM::STRH_POST:
2467  case ARM::STR_POST_IMM:
2468  case ARM::STR_POST_REG:
2469  case ARM::STR_PRE_IMM:
2470    return 2;
2471
2472  case ARM::LDRSB_PRE:
2473  case ARM::LDRSH_PRE: {
2474    unsigned Rm = MI->getOperand(3).getReg();
2475    if (Rm == 0)
2476      return 3;
2477    unsigned Rt = MI->getOperand(0).getReg();
2478    if (Rt == Rm)
2479      return 4;
2480    unsigned ShOpVal = MI->getOperand(4).getImm();
2481    bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2482    unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2483    if (!isSub &&
2484        (ShImm == 0 ||
2485         ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2486          ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2487      return 3;
2488    return 4;
2489  }
2490
2491  case ARM::LDRD: {
2492    unsigned Rt = MI->getOperand(0).getReg();
2493    unsigned Rn = MI->getOperand(2).getReg();
2494    unsigned Rm = MI->getOperand(3).getReg();
2495    if (Rm)
2496      return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2497    return (Rt == Rn) ? 3 : 2;
2498  }
2499
2500  case ARM::STRD: {
2501    unsigned Rm = MI->getOperand(3).getReg();
2502    if (Rm)
2503      return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2504    return 2;
2505  }
2506
2507  case ARM::LDRD_POST:
2508  case ARM::t2LDRD_POST:
2509    return 3;
2510
2511  case ARM::STRD_POST:
2512  case ARM::t2STRD_POST:
2513    return 4;
2514
2515  case ARM::LDRD_PRE: {
2516    unsigned Rt = MI->getOperand(0).getReg();
2517    unsigned Rn = MI->getOperand(3).getReg();
2518    unsigned Rm = MI->getOperand(4).getReg();
2519    if (Rm)
2520      return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2521    return (Rt == Rn) ? 4 : 3;
2522  }
2523
2524  case ARM::t2LDRD_PRE: {
2525    unsigned Rt = MI->getOperand(0).getReg();
2526    unsigned Rn = MI->getOperand(3).getReg();
2527    return (Rt == Rn) ? 4 : 3;
2528  }
2529
2530  case ARM::STRD_PRE: {
2531    unsigned Rm = MI->getOperand(4).getReg();
2532    if (Rm)
2533      return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2534    return 3;
2535  }
2536
2537  case ARM::t2STRD_PRE:
2538    return 3;
2539
2540  case ARM::t2LDR_POST:
2541  case ARM::t2LDRB_POST:
2542  case ARM::t2LDRB_PRE:
2543  case ARM::t2LDRSBi12:
2544  case ARM::t2LDRSBi8:
2545  case ARM::t2LDRSBpci:
2546  case ARM::t2LDRSBs:
2547  case ARM::t2LDRH_POST:
2548  case ARM::t2LDRH_PRE:
2549  case ARM::t2LDRSBT:
2550  case ARM::t2LDRSB_POST:
2551  case ARM::t2LDRSB_PRE:
2552  case ARM::t2LDRSH_POST:
2553  case ARM::t2LDRSH_PRE:
2554  case ARM::t2LDRSHi12:
2555  case ARM::t2LDRSHi8:
2556  case ARM::t2LDRSHpci:
2557  case ARM::t2LDRSHs:
2558    return 2;
2559
2560  case ARM::t2LDRDi8: {
2561    unsigned Rt = MI->getOperand(0).getReg();
2562    unsigned Rn = MI->getOperand(2).getReg();
2563    return (Rt == Rn) ? 3 : 2;
2564  }
2565
2566  case ARM::t2STRB_POST:
2567  case ARM::t2STRB_PRE:
2568  case ARM::t2STRBs:
2569  case ARM::t2STRDi8:
2570  case ARM::t2STRH_POST:
2571  case ARM::t2STRH_PRE:
2572  case ARM::t2STRHs:
2573  case ARM::t2STR_POST:
2574  case ARM::t2STR_PRE:
2575  case ARM::t2STRs:
2576    return 2;
2577  }
2578}
2579
2580// Return the number of 32-bit words loaded by LDM or stored by STM. If this
2581// can't be easily determined return 0 (missing MachineMemOperand).
2582//
2583// FIXME: The current MachineInstr design does not support relying on machine
2584// mem operands to determine the width of a memory access. Instead, we expect
2585// the target to provide this information based on the instruction opcode and
2586// operands. However, using MachineMemOperand is a the best solution now for
2587// two reasons:
2588//
2589// 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
2590// operands. This is much more dangerous than using the MachineMemOperand
2591// sizes because CodeGen passes can insert/remove optional machine operands. In
2592// fact, it's totally incorrect for preRA passes and appears to be wrong for
2593// postRA passes as well.
2594//
2595// 2) getNumLDMAddresses is only used by the scheduling machine model and any
2596// machine model that calls this should handle the unknown (zero size) case.
2597//
2598// Long term, we should require a target hook that verifies MachineMemOperand
2599// sizes during MC lowering. That target hook should be local to MC lowering
2600// because we can't ensure that it is aware of other MI forms. Doing this will
2601// ensure that MachineMemOperands are correctly propagated through all passes.
2602unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr *MI) const {
2603  unsigned Size = 0;
2604  for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
2605         E = MI->memoperands_end(); I != E; ++I) {
2606    Size += (*I)->getSize();
2607  }
2608  return Size / 4;
2609}
2610
2611unsigned
2612ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
2613                                 const MachineInstr *MI) const {
2614  if (!ItinData || ItinData->isEmpty())
2615    return 1;
2616
2617  const MCInstrDesc &Desc = MI->getDesc();
2618  unsigned Class = Desc.getSchedClass();
2619  int ItinUOps = ItinData->getNumMicroOps(Class);
2620  if (ItinUOps >= 0) {
2621    if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
2622      return getNumMicroOpsSwiftLdSt(ItinData, MI);
2623
2624    return ItinUOps;
2625  }
2626
2627  unsigned Opc = MI->getOpcode();
2628  switch (Opc) {
2629  default:
2630    llvm_unreachable("Unexpected multi-uops instruction!");
2631  case ARM::VLDMQIA:
2632  case ARM::VSTMQIA:
2633    return 2;
2634
2635  // The number of uOps for load / store multiple are determined by the number
2636  // registers.
2637  //
2638  // On Cortex-A8, each pair of register loads / stores can be scheduled on the
2639  // same cycle. The scheduling for the first load / store must be done
2640  // separately by assuming the address is not 64-bit aligned.
2641  //
2642  // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
2643  // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
2644  // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
2645  case ARM::VLDMDIA:
2646  case ARM::VLDMDIA_UPD:
2647  case ARM::VLDMDDB_UPD:
2648  case ARM::VLDMSIA:
2649  case ARM::VLDMSIA_UPD:
2650  case ARM::VLDMSDB_UPD:
2651  case ARM::VSTMDIA:
2652  case ARM::VSTMDIA_UPD:
2653  case ARM::VSTMDDB_UPD:
2654  case ARM::VSTMSIA:
2655  case ARM::VSTMSIA_UPD:
2656  case ARM::VSTMSDB_UPD: {
2657    unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
2658    return (NumRegs / 2) + (NumRegs % 2) + 1;
2659  }
2660
2661  case ARM::LDMIA_RET:
2662  case ARM::LDMIA:
2663  case ARM::LDMDA:
2664  case ARM::LDMDB:
2665  case ARM::LDMIB:
2666  case ARM::LDMIA_UPD:
2667  case ARM::LDMDA_UPD:
2668  case ARM::LDMDB_UPD:
2669  case ARM::LDMIB_UPD:
2670  case ARM::STMIA:
2671  case ARM::STMDA:
2672  case ARM::STMDB:
2673  case ARM::STMIB:
2674  case ARM::STMIA_UPD:
2675  case ARM::STMDA_UPD:
2676  case ARM::STMDB_UPD:
2677  case ARM::STMIB_UPD:
2678  case ARM::tLDMIA:
2679  case ARM::tLDMIA_UPD:
2680  case ARM::tSTMIA_UPD:
2681  case ARM::tPOP_RET:
2682  case ARM::tPOP:
2683  case ARM::tPUSH:
2684  case ARM::t2LDMIA_RET:
2685  case ARM::t2LDMIA:
2686  case ARM::t2LDMDB:
2687  case ARM::t2LDMIA_UPD:
2688  case ARM::t2LDMDB_UPD:
2689  case ARM::t2STMIA:
2690  case ARM::t2STMDB:
2691  case ARM::t2STMIA_UPD:
2692  case ARM::t2STMDB_UPD: {
2693    unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
2694    if (Subtarget.isSwift()) {
2695      // rdar://8402126
2696      int UOps = 1 + NumRegs;  // One for address computation, one for each ld / st.
2697      switch (Opc) {
2698      default: break;
2699      case ARM::VLDMDIA_UPD:
2700      case ARM::VLDMDDB_UPD:
2701      case ARM::VLDMSIA_UPD:
2702      case ARM::VLDMSDB_UPD:
2703      case ARM::VSTMDIA_UPD:
2704      case ARM::VSTMDDB_UPD:
2705      case ARM::VSTMSIA_UPD:
2706      case ARM::VSTMSDB_UPD:
2707      case ARM::LDMIA_UPD:
2708      case ARM::LDMDA_UPD:
2709      case ARM::LDMDB_UPD:
2710      case ARM::LDMIB_UPD:
2711      case ARM::STMIA_UPD:
2712      case ARM::STMDA_UPD:
2713      case ARM::STMDB_UPD:
2714      case ARM::STMIB_UPD:
2715      case ARM::tLDMIA_UPD:
2716      case ARM::tSTMIA_UPD:
2717      case ARM::t2LDMIA_UPD:
2718      case ARM::t2LDMDB_UPD:
2719      case ARM::t2STMIA_UPD:
2720      case ARM::t2STMDB_UPD:
2721        ++UOps; // One for base register writeback.
2722        break;
2723      case ARM::LDMIA_RET:
2724      case ARM::tPOP_RET:
2725      case ARM::t2LDMIA_RET:
2726        UOps += 2; // One for base reg wb, one for write to pc.
2727        break;
2728      }
2729      return UOps;
2730    } else if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
2731      if (NumRegs < 4)
2732        return 2;
2733      // 4 registers would be issued: 2, 2.
2734      // 5 registers would be issued: 2, 2, 1.
2735      int A8UOps = (NumRegs / 2);
2736      if (NumRegs % 2)
2737        ++A8UOps;
2738      return A8UOps;
2739    } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2740      int A9UOps = (NumRegs / 2);
2741      // If there are odd number of registers or if it's not 64-bit aligned,
2742      // then it takes an extra AGU (Address Generation Unit) cycle.
2743      if ((NumRegs % 2) ||
2744          !MI->hasOneMemOperand() ||
2745          (*MI->memoperands_begin())->getAlignment() < 8)
2746        ++A9UOps;
2747      return A9UOps;
2748    } else {
2749      // Assume the worst.
2750      return NumRegs;
2751    }
2752  }
2753  }
2754}
2755
2756int
2757ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
2758                                  const MCInstrDesc &DefMCID,
2759                                  unsigned DefClass,
2760                                  unsigned DefIdx, unsigned DefAlign) const {
2761  int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2762  if (RegNo <= 0)
2763    // Def is the address writeback.
2764    return ItinData->getOperandCycle(DefClass, DefIdx);
2765
2766  int DefCycle;
2767  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
2768    // (regno / 2) + (regno % 2) + 1
2769    DefCycle = RegNo / 2 + 1;
2770    if (RegNo % 2)
2771      ++DefCycle;
2772  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2773    DefCycle = RegNo;
2774    bool isSLoad = false;
2775
2776    switch (DefMCID.getOpcode()) {
2777    default: break;
2778    case ARM::VLDMSIA:
2779    case ARM::VLDMSIA_UPD:
2780    case ARM::VLDMSDB_UPD:
2781      isSLoad = true;
2782      break;
2783    }
2784
2785    // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2786    // then it takes an extra cycle.
2787    if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
2788      ++DefCycle;
2789  } else {
2790    // Assume the worst.
2791    DefCycle = RegNo + 2;
2792  }
2793
2794  return DefCycle;
2795}
2796
2797int
2798ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
2799                                 const MCInstrDesc &DefMCID,
2800                                 unsigned DefClass,
2801                                 unsigned DefIdx, unsigned DefAlign) const {
2802  int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2803  if (RegNo <= 0)
2804    // Def is the address writeback.
2805    return ItinData->getOperandCycle(DefClass, DefIdx);
2806
2807  int DefCycle;
2808  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
2809    // 4 registers would be issued: 1, 2, 1.
2810    // 5 registers would be issued: 1, 2, 2.
2811    DefCycle = RegNo / 2;
2812    if (DefCycle < 1)
2813      DefCycle = 1;
2814    // Result latency is issue cycle + 2: E2.
2815    DefCycle += 2;
2816  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2817    DefCycle = (RegNo / 2);
2818    // If there are odd number of registers or if it's not 64-bit aligned,
2819    // then it takes an extra AGU (Address Generation Unit) cycle.
2820    if ((RegNo % 2) || DefAlign < 8)
2821      ++DefCycle;
2822    // Result latency is AGU cycles + 2.
2823    DefCycle += 2;
2824  } else {
2825    // Assume the worst.
2826    DefCycle = RegNo + 2;
2827  }
2828
2829  return DefCycle;
2830}
2831
2832int
2833ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
2834                                  const MCInstrDesc &UseMCID,
2835                                  unsigned UseClass,
2836                                  unsigned UseIdx, unsigned UseAlign) const {
2837  int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2838  if (RegNo <= 0)
2839    return ItinData->getOperandCycle(UseClass, UseIdx);
2840
2841  int UseCycle;
2842  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
2843    // (regno / 2) + (regno % 2) + 1
2844    UseCycle = RegNo / 2 + 1;
2845    if (RegNo % 2)
2846      ++UseCycle;
2847  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2848    UseCycle = RegNo;
2849    bool isSStore = false;
2850
2851    switch (UseMCID.getOpcode()) {
2852    default: break;
2853    case ARM::VSTMSIA:
2854    case ARM::VSTMSIA_UPD:
2855    case ARM::VSTMSDB_UPD:
2856      isSStore = true;
2857      break;
2858    }
2859
2860    // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2861    // then it takes an extra cycle.
2862    if ((isSStore && (RegNo % 2)) || UseAlign < 8)
2863      ++UseCycle;
2864  } else {
2865    // Assume the worst.
2866    UseCycle = RegNo + 2;
2867  }
2868
2869  return UseCycle;
2870}
2871
2872int
2873ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
2874                                 const MCInstrDesc &UseMCID,
2875                                 unsigned UseClass,
2876                                 unsigned UseIdx, unsigned UseAlign) const {
2877  int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2878  if (RegNo <= 0)
2879    return ItinData->getOperandCycle(UseClass, UseIdx);
2880
2881  int UseCycle;
2882  if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
2883    UseCycle = RegNo / 2;
2884    if (UseCycle < 2)
2885      UseCycle = 2;
2886    // Read in E3.
2887    UseCycle += 2;
2888  } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2889    UseCycle = (RegNo / 2);
2890    // If there are odd number of registers or if it's not 64-bit aligned,
2891    // then it takes an extra AGU (Address Generation Unit) cycle.
2892    if ((RegNo % 2) || UseAlign < 8)
2893      ++UseCycle;
2894  } else {
2895    // Assume the worst.
2896    UseCycle = 1;
2897  }
2898  return UseCycle;
2899}
2900
2901int
2902ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2903                                    const MCInstrDesc &DefMCID,
2904                                    unsigned DefIdx, unsigned DefAlign,
2905                                    const MCInstrDesc &UseMCID,
2906                                    unsigned UseIdx, unsigned UseAlign) const {
2907  unsigned DefClass = DefMCID.getSchedClass();
2908  unsigned UseClass = UseMCID.getSchedClass();
2909
2910  if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
2911    return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2912
2913  // This may be a def / use of a variable_ops instruction, the operand
2914  // latency might be determinable dynamically. Let the target try to
2915  // figure it out.
2916  int DefCycle = -1;
2917  bool LdmBypass = false;
2918  switch (DefMCID.getOpcode()) {
2919  default:
2920    DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2921    break;
2922
2923  case ARM::VLDMDIA:
2924  case ARM::VLDMDIA_UPD:
2925  case ARM::VLDMDDB_UPD:
2926  case ARM::VLDMSIA:
2927  case ARM::VLDMSIA_UPD:
2928  case ARM::VLDMSDB_UPD:
2929    DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2930    break;
2931
2932  case ARM::LDMIA_RET:
2933  case ARM::LDMIA:
2934  case ARM::LDMDA:
2935  case ARM::LDMDB:
2936  case ARM::LDMIB:
2937  case ARM::LDMIA_UPD:
2938  case ARM::LDMDA_UPD:
2939  case ARM::LDMDB_UPD:
2940  case ARM::LDMIB_UPD:
2941  case ARM::tLDMIA:
2942  case ARM::tLDMIA_UPD:
2943  case ARM::tPUSH:
2944  case ARM::t2LDMIA_RET:
2945  case ARM::t2LDMIA:
2946  case ARM::t2LDMDB:
2947  case ARM::t2LDMIA_UPD:
2948  case ARM::t2LDMDB_UPD:
2949    LdmBypass = 1;
2950    DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2951    break;
2952  }
2953
2954  if (DefCycle == -1)
2955    // We can't seem to determine the result latency of the def, assume it's 2.
2956    DefCycle = 2;
2957
2958  int UseCycle = -1;
2959  switch (UseMCID.getOpcode()) {
2960  default:
2961    UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
2962    break;
2963
2964  case ARM::VSTMDIA:
2965  case ARM::VSTMDIA_UPD:
2966  case ARM::VSTMDDB_UPD:
2967  case ARM::VSTMSIA:
2968  case ARM::VSTMSIA_UPD:
2969  case ARM::VSTMSDB_UPD:
2970    UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2971    break;
2972
2973  case ARM::STMIA:
2974  case ARM::STMDA:
2975  case ARM::STMDB:
2976  case ARM::STMIB:
2977  case ARM::STMIA_UPD:
2978  case ARM::STMDA_UPD:
2979  case ARM::STMDB_UPD:
2980  case ARM::STMIB_UPD:
2981  case ARM::tSTMIA_UPD:
2982  case ARM::tPOP_RET:
2983  case ARM::tPOP:
2984  case ARM::t2STMIA:
2985  case ARM::t2STMDB:
2986  case ARM::t2STMIA_UPD:
2987  case ARM::t2STMDB_UPD:
2988    UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2989    break;
2990  }
2991
2992  if (UseCycle == -1)
2993    // Assume it's read in the first stage.
2994    UseCycle = 1;
2995
2996  UseCycle = DefCycle - UseCycle + 1;
2997  if (UseCycle > 0) {
2998    if (LdmBypass) {
2999      // It's a variable_ops instruction so we can't use DefIdx here. Just use
3000      // first def operand.
3001      if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
3002                                          UseClass, UseIdx))
3003        --UseCycle;
3004    } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
3005                                               UseClass, UseIdx)) {
3006      --UseCycle;
3007    }
3008  }
3009
3010  return UseCycle;
3011}
3012
3013static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
3014                                           const MachineInstr *MI, unsigned Reg,
3015                                           unsigned &DefIdx, unsigned &Dist) {
3016  Dist = 0;
3017
3018  MachineBasicBlock::const_iterator I = MI; ++I;
3019  MachineBasicBlock::const_instr_iterator II =
3020    llvm::prior(I.getInstrIterator());
3021  assert(II->isInsideBundle() && "Empty bundle?");
3022
3023  int Idx = -1;
3024  while (II->isInsideBundle()) {
3025    Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
3026    if (Idx != -1)
3027      break;
3028    --II;
3029    ++Dist;
3030  }
3031
3032  assert(Idx != -1 && "Cannot find bundled definition!");
3033  DefIdx = Idx;
3034  return II;
3035}
3036
3037static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
3038                                           const MachineInstr *MI, unsigned Reg,
3039                                           unsigned &UseIdx, unsigned &Dist) {
3040  Dist = 0;
3041
3042  MachineBasicBlock::const_instr_iterator II = MI; ++II;
3043  assert(II->isInsideBundle() && "Empty bundle?");
3044  MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3045
3046  // FIXME: This doesn't properly handle multiple uses.
3047  int Idx = -1;
3048  while (II != E && II->isInsideBundle()) {
3049    Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
3050    if (Idx != -1)
3051      break;
3052    if (II->getOpcode() != ARM::t2IT)
3053      ++Dist;
3054    ++II;
3055  }
3056
3057  if (Idx == -1) {
3058    Dist = 0;
3059    return 0;
3060  }
3061
3062  UseIdx = Idx;
3063  return II;
3064}
3065
3066/// Return the number of cycles to add to (or subtract from) the static
3067/// itinerary based on the def opcode and alignment. The caller will ensure that
3068/// adjusted latency is at least one cycle.
3069static int adjustDefLatency(const ARMSubtarget &Subtarget,
3070                            const MachineInstr *DefMI,
3071                            const MCInstrDesc *DefMCID, unsigned DefAlign) {
3072  int Adjust = 0;
3073  if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
3074    // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3075    // variants are one cycle cheaper.
3076    switch (DefMCID->getOpcode()) {
3077    default: break;
3078    case ARM::LDRrs:
3079    case ARM::LDRBrs: {
3080      unsigned ShOpVal = DefMI->getOperand(3).getImm();
3081      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3082      if (ShImm == 0 ||
3083          (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3084        --Adjust;
3085      break;
3086    }
3087    case ARM::t2LDRs:
3088    case ARM::t2LDRBs:
3089    case ARM::t2LDRHs:
3090    case ARM::t2LDRSHs: {
3091      // Thumb2 mode: lsl only.
3092      unsigned ShAmt = DefMI->getOperand(3).getImm();
3093      if (ShAmt == 0 || ShAmt == 2)
3094        --Adjust;
3095      break;
3096    }
3097    }
3098  } else if (Subtarget.isSwift()) {
3099    // FIXME: Properly handle all of the latency adjustments for address
3100    // writeback.
3101    switch (DefMCID->getOpcode()) {
3102    default: break;
3103    case ARM::LDRrs:
3104    case ARM::LDRBrs: {
3105      unsigned ShOpVal = DefMI->getOperand(3).getImm();
3106      bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3107      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3108      if (!isSub &&
3109          (ShImm == 0 ||
3110           ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3111            ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3112        Adjust -= 2;
3113      else if (!isSub &&
3114               ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3115        --Adjust;
3116      break;
3117    }
3118    case ARM::t2LDRs:
3119    case ARM::t2LDRBs:
3120    case ARM::t2LDRHs:
3121    case ARM::t2LDRSHs: {
3122      // Thumb2 mode: lsl only.
3123      unsigned ShAmt = DefMI->getOperand(3).getImm();
3124      if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
3125        Adjust -= 2;
3126      break;
3127    }
3128    }
3129  }
3130
3131  if (DefAlign < 8 && Subtarget.isLikeA9()) {
3132    switch (DefMCID->getOpcode()) {
3133    default: break;
3134    case ARM::VLD1q8:
3135    case ARM::VLD1q16:
3136    case ARM::VLD1q32:
3137    case ARM::VLD1q64:
3138    case ARM::VLD1q8wb_fixed:
3139    case ARM::VLD1q16wb_fixed:
3140    case ARM::VLD1q32wb_fixed:
3141    case ARM::VLD1q64wb_fixed:
3142    case ARM::VLD1q8wb_register:
3143    case ARM::VLD1q16wb_register:
3144    case ARM::VLD1q32wb_register:
3145    case ARM::VLD1q64wb_register:
3146    case ARM::VLD2d8:
3147    case ARM::VLD2d16:
3148    case ARM::VLD2d32:
3149    case ARM::VLD2q8:
3150    case ARM::VLD2q16:
3151    case ARM::VLD2q32:
3152    case ARM::VLD2d8wb_fixed:
3153    case ARM::VLD2d16wb_fixed:
3154    case ARM::VLD2d32wb_fixed:
3155    case ARM::VLD2q8wb_fixed:
3156    case ARM::VLD2q16wb_fixed:
3157    case ARM::VLD2q32wb_fixed:
3158    case ARM::VLD2d8wb_register:
3159    case ARM::VLD2d16wb_register:
3160    case ARM::VLD2d32wb_register:
3161    case ARM::VLD2q8wb_register:
3162    case ARM::VLD2q16wb_register:
3163    case ARM::VLD2q32wb_register:
3164    case ARM::VLD3d8:
3165    case ARM::VLD3d16:
3166    case ARM::VLD3d32:
3167    case ARM::VLD1d64T:
3168    case ARM::VLD3d8_UPD:
3169    case ARM::VLD3d16_UPD:
3170    case ARM::VLD3d32_UPD:
3171    case ARM::VLD1d64Twb_fixed:
3172    case ARM::VLD1d64Twb_register:
3173    case ARM::VLD3q8_UPD:
3174    case ARM::VLD3q16_UPD:
3175    case ARM::VLD3q32_UPD:
3176    case ARM::VLD4d8:
3177    case ARM::VLD4d16:
3178    case ARM::VLD4d32:
3179    case ARM::VLD1d64Q:
3180    case ARM::VLD4d8_UPD:
3181    case ARM::VLD4d16_UPD:
3182    case ARM::VLD4d32_UPD:
3183    case ARM::VLD1d64Qwb_fixed:
3184    case ARM::VLD1d64Qwb_register:
3185    case ARM::VLD4q8_UPD:
3186    case ARM::VLD4q16_UPD:
3187    case ARM::VLD4q32_UPD:
3188    case ARM::VLD1DUPq8:
3189    case ARM::VLD1DUPq16:
3190    case ARM::VLD1DUPq32:
3191    case ARM::VLD1DUPq8wb_fixed:
3192    case ARM::VLD1DUPq16wb_fixed:
3193    case ARM::VLD1DUPq32wb_fixed:
3194    case ARM::VLD1DUPq8wb_register:
3195    case ARM::VLD1DUPq16wb_register:
3196    case ARM::VLD1DUPq32wb_register:
3197    case ARM::VLD2DUPd8:
3198    case ARM::VLD2DUPd16:
3199    case ARM::VLD2DUPd32:
3200    case ARM::VLD2DUPd8wb_fixed:
3201    case ARM::VLD2DUPd16wb_fixed:
3202    case ARM::VLD2DUPd32wb_fixed:
3203    case ARM::VLD2DUPd8wb_register:
3204    case ARM::VLD2DUPd16wb_register:
3205    case ARM::VLD2DUPd32wb_register:
3206    case ARM::VLD4DUPd8:
3207    case ARM::VLD4DUPd16:
3208    case ARM::VLD4DUPd32:
3209    case ARM::VLD4DUPd8_UPD:
3210    case ARM::VLD4DUPd16_UPD:
3211    case ARM::VLD4DUPd32_UPD:
3212    case ARM::VLD1LNd8:
3213    case ARM::VLD1LNd16:
3214    case ARM::VLD1LNd32:
3215    case ARM::VLD1LNd8_UPD:
3216    case ARM::VLD1LNd16_UPD:
3217    case ARM::VLD1LNd32_UPD:
3218    case ARM::VLD2LNd8:
3219    case ARM::VLD2LNd16:
3220    case ARM::VLD2LNd32:
3221    case ARM::VLD2LNq16:
3222    case ARM::VLD2LNq32:
3223    case ARM::VLD2LNd8_UPD:
3224    case ARM::VLD2LNd16_UPD:
3225    case ARM::VLD2LNd32_UPD:
3226    case ARM::VLD2LNq16_UPD:
3227    case ARM::VLD2LNq32_UPD:
3228    case ARM::VLD4LNd8:
3229    case ARM::VLD4LNd16:
3230    case ARM::VLD4LNd32:
3231    case ARM::VLD4LNq16:
3232    case ARM::VLD4LNq32:
3233    case ARM::VLD4LNd8_UPD:
3234    case ARM::VLD4LNd16_UPD:
3235    case ARM::VLD4LNd32_UPD:
3236    case ARM::VLD4LNq16_UPD:
3237    case ARM::VLD4LNq32_UPD:
3238      // If the address is not 64-bit aligned, the latencies of these
3239      // instructions increases by one.
3240      ++Adjust;
3241      break;
3242    }
3243  }
3244  return Adjust;
3245}
3246
3247
3248
3249int
3250ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3251                                    const MachineInstr *DefMI, unsigned DefIdx,
3252                                    const MachineInstr *UseMI,
3253                                    unsigned UseIdx) const {
3254  // No operand latency. The caller may fall back to getInstrLatency.
3255  if (!ItinData || ItinData->isEmpty())
3256    return -1;
3257
3258  const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
3259  unsigned Reg = DefMO.getReg();
3260  const MCInstrDesc *DefMCID = &DefMI->getDesc();
3261  const MCInstrDesc *UseMCID = &UseMI->getDesc();
3262
3263  unsigned DefAdj = 0;
3264  if (DefMI->isBundle()) {
3265    DefMI = getBundledDefMI(&getRegisterInfo(), DefMI, Reg, DefIdx, DefAdj);
3266    DefMCID = &DefMI->getDesc();
3267  }
3268  if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
3269      DefMI->isRegSequence() || DefMI->isImplicitDef()) {
3270    return 1;
3271  }
3272
3273  unsigned UseAdj = 0;
3274  if (UseMI->isBundle()) {
3275    unsigned NewUseIdx;
3276    const MachineInstr *NewUseMI = getBundledUseMI(&getRegisterInfo(), UseMI,
3277                                                   Reg, NewUseIdx, UseAdj);
3278    if (!NewUseMI)
3279      return -1;
3280
3281    UseMI = NewUseMI;
3282    UseIdx = NewUseIdx;
3283    UseMCID = &UseMI->getDesc();
3284  }
3285
3286  if (Reg == ARM::CPSR) {
3287    if (DefMI->getOpcode() == ARM::FMSTAT) {
3288      // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
3289      return Subtarget.isLikeA9() ? 1 : 20;
3290    }
3291
3292    // CPSR set and branch can be paired in the same cycle.
3293    if (UseMI->isBranch())
3294      return 0;
3295
3296    // Otherwise it takes the instruction latency (generally one).
3297    unsigned Latency = getInstrLatency(ItinData, DefMI);
3298
3299    // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
3300    // its uses. Instructions which are otherwise scheduled between them may
3301    // incur a code size penalty (not able to use the CPSR setting 16-bit
3302    // instructions).
3303    if (Latency > 0 && Subtarget.isThumb2()) {
3304      const MachineFunction *MF = DefMI->getParent()->getParent();
3305      if (MF->getFunction()->getFnAttributes().hasOptimizeForSizeAttr())
3306        --Latency;
3307    }
3308    return Latency;
3309  }
3310
3311  if (DefMO.isImplicit() || UseMI->getOperand(UseIdx).isImplicit())
3312    return -1;
3313
3314  unsigned DefAlign = DefMI->hasOneMemOperand()
3315    ? (*DefMI->memoperands_begin())->getAlignment() : 0;
3316  unsigned UseAlign = UseMI->hasOneMemOperand()
3317    ? (*UseMI->memoperands_begin())->getAlignment() : 0;
3318
3319  // Get the itinerary's latency if possible, and handle variable_ops.
3320  int Latency = getOperandLatency(ItinData, *DefMCID, DefIdx, DefAlign,
3321                                  *UseMCID, UseIdx, UseAlign);
3322  // Unable to find operand latency. The caller may resort to getInstrLatency.
3323  if (Latency < 0)
3324    return Latency;
3325
3326  // Adjust for IT block position.
3327  int Adj = DefAdj + UseAdj;
3328
3329  // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3330  Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
3331  if (Adj >= 0 || (int)Latency > -Adj) {
3332    return Latency + Adj;
3333  }
3334  // Return the itinerary latency, which may be zero but not less than zero.
3335  return Latency;
3336}
3337
3338int
3339ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3340                                    SDNode *DefNode, unsigned DefIdx,
3341                                    SDNode *UseNode, unsigned UseIdx) const {
3342  if (!DefNode->isMachineOpcode())
3343    return 1;
3344
3345  const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
3346
3347  if (isZeroCost(DefMCID.Opcode))
3348    return 0;
3349
3350  if (!ItinData || ItinData->isEmpty())
3351    return DefMCID.mayLoad() ? 3 : 1;
3352
3353  if (!UseNode->isMachineOpcode()) {
3354    int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
3355    if (Subtarget.isLikeA9() || Subtarget.isSwift())
3356      return Latency <= 2 ? 1 : Latency - 1;
3357    else
3358      return Latency <= 3 ? 1 : Latency - 2;
3359  }
3360
3361  const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
3362  const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
3363  unsigned DefAlign = !DefMN->memoperands_empty()
3364    ? (*DefMN->memoperands_begin())->getAlignment() : 0;
3365  const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
3366  unsigned UseAlign = !UseMN->memoperands_empty()
3367    ? (*UseMN->memoperands_begin())->getAlignment() : 0;
3368  int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
3369                                  UseMCID, UseIdx, UseAlign);
3370
3371  if (Latency > 1 &&
3372      (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
3373       Subtarget.isCortexA7())) {
3374    // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3375    // variants are one cycle cheaper.
3376    switch (DefMCID.getOpcode()) {
3377    default: break;
3378    case ARM::LDRrs:
3379    case ARM::LDRBrs: {
3380      unsigned ShOpVal =
3381        cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3382      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3383      if (ShImm == 0 ||
3384          (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3385        --Latency;
3386      break;
3387    }
3388    case ARM::t2LDRs:
3389    case ARM::t2LDRBs:
3390    case ARM::t2LDRHs:
3391    case ARM::t2LDRSHs: {
3392      // Thumb2 mode: lsl only.
3393      unsigned ShAmt =
3394        cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3395      if (ShAmt == 0 || ShAmt == 2)
3396        --Latency;
3397      break;
3398    }
3399    }
3400  } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
3401    // FIXME: Properly handle all of the latency adjustments for address
3402    // writeback.
3403    switch (DefMCID.getOpcode()) {
3404    default: break;
3405    case ARM::LDRrs:
3406    case ARM::LDRBrs: {
3407      unsigned ShOpVal =
3408        cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3409      unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3410      if (ShImm == 0 ||
3411          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3412           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3413        Latency -= 2;
3414      else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3415        --Latency;
3416      break;
3417    }
3418    case ARM::t2LDRs:
3419    case ARM::t2LDRBs:
3420    case ARM::t2LDRHs:
3421    case ARM::t2LDRSHs: {
3422      // Thumb2 mode: lsl 0-3 only.
3423      Latency -= 2;
3424      break;
3425    }
3426    }
3427  }
3428
3429  if (DefAlign < 8 && Subtarget.isLikeA9())
3430    switch (DefMCID.getOpcode()) {
3431    default: break;
3432    case ARM::VLD1q8:
3433    case ARM::VLD1q16:
3434    case ARM::VLD1q32:
3435    case ARM::VLD1q64:
3436    case ARM::VLD1q8wb_register:
3437    case ARM::VLD1q16wb_register:
3438    case ARM::VLD1q32wb_register:
3439    case ARM::VLD1q64wb_register:
3440    case ARM::VLD1q8wb_fixed:
3441    case ARM::VLD1q16wb_fixed:
3442    case ARM::VLD1q32wb_fixed:
3443    case ARM::VLD1q64wb_fixed:
3444    case ARM::VLD2d8:
3445    case ARM::VLD2d16:
3446    case ARM::VLD2d32:
3447    case ARM::VLD2q8Pseudo:
3448    case ARM::VLD2q16Pseudo:
3449    case ARM::VLD2q32Pseudo:
3450    case ARM::VLD2d8wb_fixed:
3451    case ARM::VLD2d16wb_fixed:
3452    case ARM::VLD2d32wb_fixed:
3453    case ARM::VLD2q8PseudoWB_fixed:
3454    case ARM::VLD2q16PseudoWB_fixed:
3455    case ARM::VLD2q32PseudoWB_fixed:
3456    case ARM::VLD2d8wb_register:
3457    case ARM::VLD2d16wb_register:
3458    case ARM::VLD2d32wb_register:
3459    case ARM::VLD2q8PseudoWB_register:
3460    case ARM::VLD2q16PseudoWB_register:
3461    case ARM::VLD2q32PseudoWB_register:
3462    case ARM::VLD3d8Pseudo:
3463    case ARM::VLD3d16Pseudo:
3464    case ARM::VLD3d32Pseudo:
3465    case ARM::VLD1d64TPseudo:
3466    case ARM::VLD3d8Pseudo_UPD:
3467    case ARM::VLD3d16Pseudo_UPD:
3468    case ARM::VLD3d32Pseudo_UPD:
3469    case ARM::VLD3q8Pseudo_UPD:
3470    case ARM::VLD3q16Pseudo_UPD:
3471    case ARM::VLD3q32Pseudo_UPD:
3472    case ARM::VLD3q8oddPseudo:
3473    case ARM::VLD3q16oddPseudo:
3474    case ARM::VLD3q32oddPseudo:
3475    case ARM::VLD3q8oddPseudo_UPD:
3476    case ARM::VLD3q16oddPseudo_UPD:
3477    case ARM::VLD3q32oddPseudo_UPD:
3478    case ARM::VLD4d8Pseudo:
3479    case ARM::VLD4d16Pseudo:
3480    case ARM::VLD4d32Pseudo:
3481    case ARM::VLD1d64QPseudo:
3482    case ARM::VLD4d8Pseudo_UPD:
3483    case ARM::VLD4d16Pseudo_UPD:
3484    case ARM::VLD4d32Pseudo_UPD:
3485    case ARM::VLD4q8Pseudo_UPD:
3486    case ARM::VLD4q16Pseudo_UPD:
3487    case ARM::VLD4q32Pseudo_UPD:
3488    case ARM::VLD4q8oddPseudo:
3489    case ARM::VLD4q16oddPseudo:
3490    case ARM::VLD4q32oddPseudo:
3491    case ARM::VLD4q8oddPseudo_UPD:
3492    case ARM::VLD4q16oddPseudo_UPD:
3493    case ARM::VLD4q32oddPseudo_UPD:
3494    case ARM::VLD1DUPq8:
3495    case ARM::VLD1DUPq16:
3496    case ARM::VLD1DUPq32:
3497    case ARM::VLD1DUPq8wb_fixed:
3498    case ARM::VLD1DUPq16wb_fixed:
3499    case ARM::VLD1DUPq32wb_fixed:
3500    case ARM::VLD1DUPq8wb_register:
3501    case ARM::VLD1DUPq16wb_register:
3502    case ARM::VLD1DUPq32wb_register:
3503    case ARM::VLD2DUPd8:
3504    case ARM::VLD2DUPd16:
3505    case ARM::VLD2DUPd32:
3506    case ARM::VLD2DUPd8wb_fixed:
3507    case ARM::VLD2DUPd16wb_fixed:
3508    case ARM::VLD2DUPd32wb_fixed:
3509    case ARM::VLD2DUPd8wb_register:
3510    case ARM::VLD2DUPd16wb_register:
3511    case ARM::VLD2DUPd32wb_register:
3512    case ARM::VLD4DUPd8Pseudo:
3513    case ARM::VLD4DUPd16Pseudo:
3514    case ARM::VLD4DUPd32Pseudo:
3515    case ARM::VLD4DUPd8Pseudo_UPD:
3516    case ARM::VLD4DUPd16Pseudo_UPD:
3517    case ARM::VLD4DUPd32Pseudo_UPD:
3518    case ARM::VLD1LNq8Pseudo:
3519    case ARM::VLD1LNq16Pseudo:
3520    case ARM::VLD1LNq32Pseudo:
3521    case ARM::VLD1LNq8Pseudo_UPD:
3522    case ARM::VLD1LNq16Pseudo_UPD:
3523    case ARM::VLD1LNq32Pseudo_UPD:
3524    case ARM::VLD2LNd8Pseudo:
3525    case ARM::VLD2LNd16Pseudo:
3526    case ARM::VLD2LNd32Pseudo:
3527    case ARM::VLD2LNq16Pseudo:
3528    case ARM::VLD2LNq32Pseudo:
3529    case ARM::VLD2LNd8Pseudo_UPD:
3530    case ARM::VLD2LNd16Pseudo_UPD:
3531    case ARM::VLD2LNd32Pseudo_UPD:
3532    case ARM::VLD2LNq16Pseudo_UPD:
3533    case ARM::VLD2LNq32Pseudo_UPD:
3534    case ARM::VLD4LNd8Pseudo:
3535    case ARM::VLD4LNd16Pseudo:
3536    case ARM::VLD4LNd32Pseudo:
3537    case ARM::VLD4LNq16Pseudo:
3538    case ARM::VLD4LNq32Pseudo:
3539    case ARM::VLD4LNd8Pseudo_UPD:
3540    case ARM::VLD4LNd16Pseudo_UPD:
3541    case ARM::VLD4LNd32Pseudo_UPD:
3542    case ARM::VLD4LNq16Pseudo_UPD:
3543    case ARM::VLD4LNq32Pseudo_UPD:
3544      // If the address is not 64-bit aligned, the latencies of these
3545      // instructions increases by one.
3546      ++Latency;
3547      break;
3548    }
3549
3550  return Latency;
3551}
3552
3553unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3554                                           const MachineInstr *MI,
3555                                           unsigned *PredCost) const {
3556  if (MI->isCopyLike() || MI->isInsertSubreg() ||
3557      MI->isRegSequence() || MI->isImplicitDef())
3558    return 1;
3559
3560  // An instruction scheduler typically runs on unbundled instructions, however
3561  // other passes may query the latency of a bundled instruction.
3562  if (MI->isBundle()) {
3563    unsigned Latency = 0;
3564    MachineBasicBlock::const_instr_iterator I = MI;
3565    MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3566    while (++I != E && I->isInsideBundle()) {
3567      if (I->getOpcode() != ARM::t2IT)
3568        Latency += getInstrLatency(ItinData, I, PredCost);
3569    }
3570    return Latency;
3571  }
3572
3573  const MCInstrDesc &MCID = MI->getDesc();
3574  if (PredCost && (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR))) {
3575    // When predicated, CPSR is an additional source operand for CPSR updating
3576    // instructions, this apparently increases their latencies.
3577    *PredCost = 1;
3578  }
3579  // Be sure to call getStageLatency for an empty itinerary in case it has a
3580  // valid MinLatency property.
3581  if (!ItinData)
3582    return MI->mayLoad() ? 3 : 1;
3583
3584  unsigned Class = MCID.getSchedClass();
3585
3586  // For instructions with variable uops, use uops as latency.
3587  if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
3588    return getNumMicroOps(ItinData, MI);
3589
3590  // For the common case, fall back on the itinerary's latency.
3591  unsigned Latency = ItinData->getStageLatency(Class);
3592
3593  // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3594  unsigned DefAlign = MI->hasOneMemOperand()
3595    ? (*MI->memoperands_begin())->getAlignment() : 0;
3596  int Adj = adjustDefLatency(Subtarget, MI, &MCID, DefAlign);
3597  if (Adj >= 0 || (int)Latency > -Adj) {
3598    return Latency + Adj;
3599  }
3600  return Latency;
3601}
3602
3603int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3604                                      SDNode *Node) const {
3605  if (!Node->isMachineOpcode())
3606    return 1;
3607
3608  if (!ItinData || ItinData->isEmpty())
3609    return 1;
3610
3611  unsigned Opcode = Node->getMachineOpcode();
3612  switch (Opcode) {
3613  default:
3614    return ItinData->getStageLatency(get(Opcode).getSchedClass());
3615  case ARM::VLDMQIA:
3616  case ARM::VSTMQIA:
3617    return 2;
3618  }
3619}
3620
3621bool ARMBaseInstrInfo::
3622hasHighOperandLatency(const InstrItineraryData *ItinData,
3623                      const MachineRegisterInfo *MRI,
3624                      const MachineInstr *DefMI, unsigned DefIdx,
3625                      const MachineInstr *UseMI, unsigned UseIdx) const {
3626  unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3627  unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
3628  if (Subtarget.isCortexA8() &&
3629      (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
3630    // CortexA8 VFP instructions are not pipelined.
3631    return true;
3632
3633  // Hoist VFP / NEON instructions with 4 or higher latency.
3634  int Latency = computeOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx,
3635                                      /*FindMin=*/false);
3636  if (Latency < 0)
3637    Latency = getInstrLatency(ItinData, DefMI);
3638  if (Latency <= 3)
3639    return false;
3640  return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
3641         UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
3642}
3643
3644bool ARMBaseInstrInfo::
3645hasLowDefLatency(const InstrItineraryData *ItinData,
3646                 const MachineInstr *DefMI, unsigned DefIdx) const {
3647  if (!ItinData || ItinData->isEmpty())
3648    return false;
3649
3650  unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3651  if (DDomain == ARMII::DomainGeneral) {
3652    unsigned DefClass = DefMI->getDesc().getSchedClass();
3653    int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3654    return (DefCycle != -1 && DefCycle <= 2);
3655  }
3656  return false;
3657}
3658
3659bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI,
3660                                         StringRef &ErrInfo) const {
3661  if (convertAddSubFlagsOpcode(MI->getOpcode())) {
3662    ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
3663    return false;
3664  }
3665  return true;
3666}
3667
3668bool
3669ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
3670                                     unsigned &AddSubOpc,
3671                                     bool &NegAcc, bool &HasLane) const {
3672  DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
3673  if (I == MLxEntryMap.end())
3674    return false;
3675
3676  const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
3677  MulOpc = Entry.MulOpc;
3678  AddSubOpc = Entry.AddSubOpc;
3679  NegAcc = Entry.NegAcc;
3680  HasLane = Entry.HasLane;
3681  return true;
3682}
3683
3684//===----------------------------------------------------------------------===//
3685// Execution domains.
3686//===----------------------------------------------------------------------===//
3687//
3688// Some instructions go down the NEON pipeline, some go down the VFP pipeline,
3689// and some can go down both.  The vmov instructions go down the VFP pipeline,
3690// but they can be changed to vorr equivalents that are executed by the NEON
3691// pipeline.
3692//
3693// We use the following execution domain numbering:
3694//
3695enum ARMExeDomain {
3696  ExeGeneric = 0,
3697  ExeVFP = 1,
3698  ExeNEON = 2
3699};
3700//
3701// Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
3702//
3703std::pair<uint16_t, uint16_t>
3704ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const {
3705  // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
3706  // if they are not predicated.
3707  if (MI->getOpcode() == ARM::VMOVD && !isPredicated(MI))
3708    return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
3709
3710  // A9-like cores are particularly picky about mixing the two and want these
3711  // converted.
3712  if (Subtarget.isLikeA9() && !isPredicated(MI) &&
3713      (MI->getOpcode() == ARM::VMOVRS ||
3714       MI->getOpcode() == ARM::VMOVSR ||
3715       MI->getOpcode() == ARM::VMOVS))
3716    return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
3717
3718  // No other instructions can be swizzled, so just determine their domain.
3719  unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
3720
3721  if (Domain & ARMII::DomainNEON)
3722    return std::make_pair(ExeNEON, 0);
3723
3724  // Certain instructions can go either way on Cortex-A8.
3725  // Treat them as NEON instructions.
3726  if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
3727    return std::make_pair(ExeNEON, 0);
3728
3729  if (Domain & ARMII::DomainVFP)
3730    return std::make_pair(ExeVFP, 0);
3731
3732  return std::make_pair(ExeGeneric, 0);
3733}
3734
3735static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
3736                                            unsigned SReg, unsigned &Lane) {
3737  unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
3738  Lane = 0;
3739
3740  if (DReg != ARM::NoRegister)
3741   return DReg;
3742
3743  Lane = 1;
3744  DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
3745
3746  assert(DReg && "S-register with no D super-register?");
3747  return DReg;
3748}
3749
3750/// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
3751/// set ImplicitSReg to a register number that must be marked as implicit-use or
3752/// zero if no register needs to be defined as implicit-use.
3753///
3754/// If the function cannot determine if an SPR should be marked implicit use or
3755/// not, it returns false.
3756///
3757/// This function handles cases where an instruction is being modified from taking
3758/// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
3759/// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
3760/// lane of the DPR).
3761///
3762/// If the other SPR is defined, an implicit-use of it should be added. Else,
3763/// (including the case where the DPR itself is defined), it should not.
3764///
3765static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
3766                                       MachineInstr *MI,
3767                                       unsigned DReg, unsigned Lane,
3768                                       unsigned &ImplicitSReg) {
3769  // If the DPR is defined or used already, the other SPR lane will be chained
3770  // correctly, so there is nothing to be done.
3771  if (MI->definesRegister(DReg, TRI) || MI->readsRegister(DReg, TRI)) {
3772    ImplicitSReg = 0;
3773    return true;
3774  }
3775
3776  // Otherwise we need to go searching to see if the SPR is set explicitly.
3777  ImplicitSReg = TRI->getSubReg(DReg,
3778                                (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
3779  MachineBasicBlock::LivenessQueryResult LQR =
3780    MI->getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
3781
3782  if (LQR == MachineBasicBlock::LQR_Live)
3783    return true;
3784  else if (LQR == MachineBasicBlock::LQR_Unknown)
3785    return false;
3786
3787  // If the register is known not to be live, there is no need to add an
3788  // implicit-use.
3789  ImplicitSReg = 0;
3790  return true;
3791}
3792
3793void
3794ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const {
3795  unsigned DstReg, SrcReg, DReg;
3796  unsigned Lane;
3797  MachineInstrBuilder MIB(MI);
3798  const TargetRegisterInfo *TRI = &getRegisterInfo();
3799  switch (MI->getOpcode()) {
3800    default:
3801      llvm_unreachable("cannot handle opcode!");
3802      break;
3803    case ARM::VMOVD:
3804      if (Domain != ExeNEON)
3805        break;
3806
3807      // Zap the predicate operands.
3808      assert(!isPredicated(MI) && "Cannot predicate a VORRd");
3809
3810      // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
3811      DstReg = MI->getOperand(0).getReg();
3812      SrcReg = MI->getOperand(1).getReg();
3813
3814      for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3815        MI->RemoveOperand(i-1);
3816
3817      // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
3818      MI->setDesc(get(ARM::VORRd));
3819      AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
3820                        .addReg(SrcReg)
3821                        .addReg(SrcReg));
3822      break;
3823    case ARM::VMOVRS:
3824      if (Domain != ExeNEON)
3825        break;
3826      assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
3827
3828      // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
3829      DstReg = MI->getOperand(0).getReg();
3830      SrcReg = MI->getOperand(1).getReg();
3831
3832      for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3833        MI->RemoveOperand(i-1);
3834
3835      DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
3836
3837      // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
3838      // Note that DSrc has been widened and the other lane may be undef, which
3839      // contaminates the entire register.
3840      MI->setDesc(get(ARM::VGETLNi32));
3841      AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
3842                        .addReg(DReg, RegState::Undef)
3843                        .addImm(Lane));
3844
3845      // The old source should be an implicit use, otherwise we might think it
3846      // was dead before here.
3847      MIB.addReg(SrcReg, RegState::Implicit);
3848      break;
3849    case ARM::VMOVSR: {
3850      if (Domain != ExeNEON)
3851        break;
3852      assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
3853
3854      // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
3855      DstReg = MI->getOperand(0).getReg();
3856      SrcReg = MI->getOperand(1).getReg();
3857
3858      DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
3859
3860      unsigned ImplicitSReg;
3861      if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
3862        break;
3863
3864      for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3865        MI->RemoveOperand(i-1);
3866
3867      // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
3868      // Again DDst may be undefined at the beginning of this instruction.
3869      MI->setDesc(get(ARM::VSETLNi32));
3870      MIB.addReg(DReg, RegState::Define)
3871         .addReg(DReg, getUndefRegState(!MI->readsRegister(DReg, TRI)))
3872         .addReg(SrcReg)
3873         .addImm(Lane);
3874      AddDefaultPred(MIB);
3875
3876      // The narrower destination must be marked as set to keep previous chains
3877      // in place.
3878      MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
3879      if (ImplicitSReg != 0)
3880        MIB.addReg(ImplicitSReg, RegState::Implicit);
3881      break;
3882    }
3883    case ARM::VMOVS: {
3884      if (Domain != ExeNEON)
3885        break;
3886
3887      // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
3888      DstReg = MI->getOperand(0).getReg();
3889      SrcReg = MI->getOperand(1).getReg();
3890
3891      unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
3892      DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
3893      DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
3894
3895      unsigned ImplicitSReg;
3896      if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
3897        break;
3898
3899      for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
3900        MI->RemoveOperand(i-1);
3901
3902      if (DSrc == DDst) {
3903        // Destination can be:
3904        //     %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
3905        MI->setDesc(get(ARM::VDUPLN32d));
3906        MIB.addReg(DDst, RegState::Define)
3907           .addReg(DDst, getUndefRegState(!MI->readsRegister(DDst, TRI)))
3908           .addImm(SrcLane);
3909        AddDefaultPred(MIB);
3910
3911        // Neither the source or the destination are naturally represented any
3912        // more, so add them in manually.
3913        MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
3914        MIB.addReg(SrcReg, RegState::Implicit);
3915        if (ImplicitSReg != 0)
3916          MIB.addReg(ImplicitSReg, RegState::Implicit);
3917        break;
3918      }
3919
3920      // In general there's no single instruction that can perform an S <-> S
3921      // move in NEON space, but a pair of VEXT instructions *can* do the
3922      // job. It turns out that the VEXTs needed will only use DSrc once, with
3923      // the position based purely on the combination of lane-0 and lane-1
3924      // involved. For example
3925      //     vmov s0, s2 -> vext.32 d0, d0, d1, #1  vext.32 d0, d0, d0, #1
3926      //     vmov s1, s3 -> vext.32 d0, d1, d0, #1  vext.32 d0, d0, d0, #1
3927      //     vmov s0, s3 -> vext.32 d0, d0, d0, #1  vext.32 d0, d1, d0, #1
3928      //     vmov s1, s2 -> vext.32 d0, d0, d0, #1  vext.32 d0, d0, d1, #1
3929      //
3930      // Pattern of the MachineInstrs is:
3931      //     %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
3932      MachineInstrBuilder NewMIB;
3933      NewMIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3934                       get(ARM::VEXTd32), DDst);
3935
3936      // On the first instruction, both DSrc and DDst may be <undef> if present.
3937      // Specifically when the original instruction didn't have them as an
3938      // <imp-use>.
3939      unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
3940      bool CurUndef = !MI->readsRegister(CurReg, TRI);
3941      NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
3942
3943      CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
3944      CurUndef = !MI->readsRegister(CurReg, TRI);
3945      NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
3946
3947      NewMIB.addImm(1);
3948      AddDefaultPred(NewMIB);
3949
3950      if (SrcLane == DstLane)
3951        NewMIB.addReg(SrcReg, RegState::Implicit);
3952
3953      MI->setDesc(get(ARM::VEXTd32));
3954      MIB.addReg(DDst, RegState::Define);
3955
3956      // On the second instruction, DDst has definitely been defined above, so
3957      // it is not <undef>. DSrc, if present, can be <undef> as above.
3958      CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
3959      CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
3960      MIB.addReg(CurReg, getUndefRegState(CurUndef));
3961
3962      CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
3963      CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
3964      MIB.addReg(CurReg, getUndefRegState(CurUndef));
3965
3966      MIB.addImm(1);
3967      AddDefaultPred(MIB);
3968
3969      if (SrcLane != DstLane)
3970        MIB.addReg(SrcReg, RegState::Implicit);
3971
3972      // As before, the original destination is no longer represented, add it
3973      // implicitly.
3974      MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
3975      if (ImplicitSReg != 0)
3976        MIB.addReg(ImplicitSReg, RegState::Implicit);
3977      break;
3978    }
3979  }
3980
3981}
3982
3983//===----------------------------------------------------------------------===//
3984// Partial register updates
3985//===----------------------------------------------------------------------===//
3986//
3987// Swift renames NEON registers with 64-bit granularity.  That means any
3988// instruction writing an S-reg implicitly reads the containing D-reg.  The
3989// problem is mostly avoided by translating f32 operations to v2f32 operations
3990// on D-registers, but f32 loads are still a problem.
3991//
3992// These instructions can load an f32 into a NEON register:
3993//
3994// VLDRS - Only writes S, partial D update.
3995// VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
3996// VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
3997//
3998// FCONSTD can be used as a dependency-breaking instruction.
3999
4000
4001unsigned ARMBaseInstrInfo::
4002getPartialRegUpdateClearance(const MachineInstr *MI,
4003                             unsigned OpNum,
4004                             const TargetRegisterInfo *TRI) const {
4005  // Only Swift has partial register update problems.
4006  if (!SwiftPartialUpdateClearance || !Subtarget.isSwift())
4007    return 0;
4008
4009  assert(TRI && "Need TRI instance");
4010
4011  const MachineOperand &MO = MI->getOperand(OpNum);
4012  if (MO.readsReg())
4013    return 0;
4014  unsigned Reg = MO.getReg();
4015  int UseOp = -1;
4016
4017  switch(MI->getOpcode()) {
4018    // Normal instructions writing only an S-register.
4019  case ARM::VLDRS:
4020  case ARM::FCONSTS:
4021  case ARM::VMOVSR:
4022    // rdar://problem/8791586
4023  case ARM::VMOVv8i8:
4024  case ARM::VMOVv4i16:
4025  case ARM::VMOVv2i32:
4026  case ARM::VMOVv2f32:
4027  case ARM::VMOVv1i64:
4028    UseOp = MI->findRegisterUseOperandIdx(Reg, false, TRI);
4029    break;
4030
4031    // Explicitly reads the dependency.
4032  case ARM::VLD1LNd32:
4033    UseOp = 1;
4034    break;
4035  default:
4036    return 0;
4037  }
4038
4039  // If this instruction actually reads a value from Reg, there is no unwanted
4040  // dependency.
4041  if (UseOp != -1 && MI->getOperand(UseOp).readsReg())
4042    return 0;
4043
4044  // We must be able to clobber the whole D-reg.
4045  if (TargetRegisterInfo::isVirtualRegister(Reg)) {
4046    // Virtual register must be a foo:ssub_0<def,undef> operand.
4047    if (!MO.getSubReg() || MI->readsVirtualRegister(Reg))
4048      return 0;
4049  } else if (ARM::SPRRegClass.contains(Reg)) {
4050    // Physical register: MI must define the full D-reg.
4051    unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
4052                                             &ARM::DPRRegClass);
4053    if (!DReg || !MI->definesRegister(DReg, TRI))
4054      return 0;
4055  }
4056
4057  // MI has an unwanted D-register dependency.
4058  // Avoid defs in the previous N instructrions.
4059  return SwiftPartialUpdateClearance;
4060}
4061
4062// Break a partial register dependency after getPartialRegUpdateClearance
4063// returned non-zero.
4064void ARMBaseInstrInfo::
4065breakPartialRegDependency(MachineBasicBlock::iterator MI,
4066                          unsigned OpNum,
4067                          const TargetRegisterInfo *TRI) const {
4068  assert(MI && OpNum < MI->getDesc().getNumDefs() && "OpNum is not a def");
4069  assert(TRI && "Need TRI instance");
4070
4071  const MachineOperand &MO = MI->getOperand(OpNum);
4072  unsigned Reg = MO.getReg();
4073  assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
4074         "Can't break virtual register dependencies.");
4075  unsigned DReg = Reg;
4076
4077  // If MI defines an S-reg, find the corresponding D super-register.
4078  if (ARM::SPRRegClass.contains(Reg)) {
4079    DReg = ARM::D0 + (Reg - ARM::S0) / 2;
4080    assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
4081  }
4082
4083  assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
4084  assert(MI->definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
4085
4086  // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
4087  // the full D-register by loading the same value to both lanes.  The
4088  // instruction is micro-coded with 2 uops, so don't do this until we can
4089  // properly schedule micro-coded instuctions.  The dispatcher stalls cause
4090  // too big regressions.
4091
4092  // Insert the dependency-breaking FCONSTD before MI.
4093  // 96 is the encoding of 0.5, but the actual value doesn't matter here.
4094  AddDefaultPred(BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4095                         get(ARM::FCONSTD), DReg).addImm(96));
4096  MI->addRegisterKilled(DReg, TRI, true);
4097}
4098
4099bool ARMBaseInstrInfo::hasNOP() const {
4100  return (Subtarget.getFeatureBits() & ARM::HasV6T2Ops) != 0;
4101}
4102