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