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