1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the Base ARM implementation of the TargetInstrInfo class.
12 //===----------------------------------------------------------------------===//
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMFeatures.h"
19 #include "ARMHazardRecognizer.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCExpr.h"
36 #include "llvm/Support/BranchProbability.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
43 #define DEBUG_TYPE "arm-instrinfo"
45 #define GET_INSTRINFO_CTOR_DTOR
46 #include "ARMGenInstrInfo.inc"
49 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
50 cl::desc("Enable ARM 2-addr to 3-addr conv"));
53 WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
54 cl::desc("Widen ARM vmovs to vmovd when possible"));
56 static cl::opt<unsigned>
57 SwiftPartialUpdateClearance("swift-partial-update-clearance",
58 cl::Hidden, cl::init(12),
59 cl::desc("Clearance before partial register updates"));
61 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
63 uint16_t MLxOpc; // MLA / MLS opcode
64 uint16_t MulOpc; // Expanded multiplication opcode
65 uint16_t AddSubOpc; // Expanded add / sub opcode
66 bool NegAcc; // True if the acc is negated before the add / sub.
67 bool HasLane; // True if instruction has an extra "lane" operand.
70 static const ARM_MLxEntry ARM_MLxTable[] = {
71 // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane
73 { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false },
74 { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false },
75 { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false },
76 { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false },
77 { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false },
78 { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false },
79 { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false },
80 { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false },
83 { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false },
84 { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false },
85 { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false },
86 { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false },
87 { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true },
88 { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true },
89 { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true },
90 { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true },
93 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
94 : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
96 for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
97 if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
98 assert(false && "Duplicated entries?");
99 MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
100 MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
104 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
105 // currently defaults to no prepass hazard recognizer.
106 ScheduleHazardRecognizer *
107 ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
108 const ScheduleDAG *DAG) const {
109 if (usePreRAHazardRecognizer()) {
110 const InstrItineraryData *II =
111 static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
112 return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
114 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
117 ScheduleHazardRecognizer *ARMBaseInstrInfo::
118 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
119 const ScheduleDAG *DAG) const {
120 if (Subtarget.isThumb2() || Subtarget.hasVFP2())
121 return (ScheduleHazardRecognizer *)new ARMHazardRecognizer(II, DAG);
122 return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
126 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
127 MachineBasicBlock::iterator &MBBI,
128 LiveVariables *LV) const {
129 // FIXME: Thumb2 support.
134 MachineInstr *MI = MBBI;
135 MachineFunction &MF = *MI->getParent()->getParent();
136 uint64_t TSFlags = MI->getDesc().TSFlags;
138 switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
139 default: return nullptr;
140 case ARMII::IndexModePre:
143 case ARMII::IndexModePost:
147 // Try splitting an indexed load/store to an un-indexed one plus an add/sub
149 unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
153 MachineInstr *UpdateMI = nullptr;
154 MachineInstr *MemMI = nullptr;
155 unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
156 const MCInstrDesc &MCID = MI->getDesc();
157 unsigned NumOps = MCID.getNumOperands();
158 bool isLoad = !MI->mayStore();
159 const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
160 const MachineOperand &Base = MI->getOperand(2);
161 const MachineOperand &Offset = MI->getOperand(NumOps-3);
162 unsigned WBReg = WB.getReg();
163 unsigned BaseReg = Base.getReg();
164 unsigned OffReg = Offset.getReg();
165 unsigned OffImm = MI->getOperand(NumOps-2).getImm();
166 ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
168 default: llvm_unreachable("Unknown indexed op!");
169 case ARMII::AddrMode2: {
170 bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
171 unsigned Amt = ARM_AM::getAM2Offset(OffImm);
173 if (ARM_AM::getSOImmVal(Amt) == -1)
174 // Can't encode it in a so_imm operand. This transformation will
175 // add more than 1 instruction. Abandon!
177 UpdateMI = BuildMI(MF, MI->getDebugLoc(),
178 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
179 .addReg(BaseReg).addImm(Amt)
180 .addImm(Pred).addReg(0).addReg(0);
181 } else if (Amt != 0) {
182 ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
183 unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
184 UpdateMI = BuildMI(MF, MI->getDebugLoc(),
185 get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
186 .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
187 .addImm(Pred).addReg(0).addReg(0);
189 UpdateMI = BuildMI(MF, MI->getDebugLoc(),
190 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
191 .addReg(BaseReg).addReg(OffReg)
192 .addImm(Pred).addReg(0).addReg(0);
195 case ARMII::AddrMode3 : {
196 bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
197 unsigned Amt = ARM_AM::getAM3Offset(OffImm);
199 // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
200 UpdateMI = BuildMI(MF, MI->getDebugLoc(),
201 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
202 .addReg(BaseReg).addImm(Amt)
203 .addImm(Pred).addReg(0).addReg(0);
205 UpdateMI = BuildMI(MF, MI->getDebugLoc(),
206 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
207 .addReg(BaseReg).addReg(OffReg)
208 .addImm(Pred).addReg(0).addReg(0);
213 std::vector<MachineInstr*> NewMIs;
216 MemMI = BuildMI(MF, MI->getDebugLoc(),
217 get(MemOpc), MI->getOperand(0).getReg())
218 .addReg(WBReg).addImm(0).addImm(Pred);
220 MemMI = BuildMI(MF, MI->getDebugLoc(),
221 get(MemOpc)).addReg(MI->getOperand(1).getReg())
222 .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
223 NewMIs.push_back(MemMI);
224 NewMIs.push_back(UpdateMI);
227 MemMI = BuildMI(MF, MI->getDebugLoc(),
228 get(MemOpc), MI->getOperand(0).getReg())
229 .addReg(BaseReg).addImm(0).addImm(Pred);
231 MemMI = BuildMI(MF, MI->getDebugLoc(),
232 get(MemOpc)).addReg(MI->getOperand(1).getReg())
233 .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
235 UpdateMI->getOperand(0).setIsDead();
236 NewMIs.push_back(UpdateMI);
237 NewMIs.push_back(MemMI);
240 // Transfer LiveVariables states, kill / dead info.
242 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
243 MachineOperand &MO = MI->getOperand(i);
244 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
245 unsigned Reg = MO.getReg();
247 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
249 MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
251 LV->addVirtualRegisterDead(Reg, NewMI);
253 if (MO.isUse() && MO.isKill()) {
254 for (unsigned j = 0; j < 2; ++j) {
255 // Look at the two new MI's in reverse order.
256 MachineInstr *NewMI = NewMIs[j];
257 if (!NewMI->readsRegister(Reg))
259 LV->addVirtualRegisterKilled(Reg, NewMI);
260 if (VI.removeKill(MI))
261 VI.Kills.push_back(NewMI);
269 MFI->insert(MBBI, NewMIs[1]);
270 MFI->insert(MBBI, NewMIs[0]);
276 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
277 MachineBasicBlock *&FBB,
278 SmallVectorImpl<MachineOperand> &Cond,
279 bool AllowModify) const {
283 MachineBasicBlock::iterator I = MBB.end();
284 if (I == MBB.begin())
285 return false; // Empty blocks are easy.
288 // Walk backwards from the end of the basic block until the branch is
289 // analyzed or we give up.
290 while (isPredicated(I) || I->isTerminator() || I->isDebugValue()) {
292 // Flag to be raised on unanalyzeable instructions. This is useful in cases
293 // where we want to clean up on the end of the basic block before we bail
295 bool CantAnalyze = false;
297 // Skip over DEBUG values and predicated nonterminators.
298 while (I->isDebugValue() || !I->isTerminator()) {
299 if (I == MBB.begin())
304 if (isIndirectBranchOpcode(I->getOpcode()) ||
305 isJumpTableBranchOpcode(I->getOpcode())) {
306 // Indirect branches and jump tables can't be analyzed, but we still want
307 // to clean up any instructions at the tail of the basic block.
309 } else if (isUncondBranchOpcode(I->getOpcode())) {
310 TBB = I->getOperand(0).getMBB();
311 } else if (isCondBranchOpcode(I->getOpcode())) {
312 // Bail out if we encounter multiple conditional branches.
316 assert(!FBB && "FBB should have been null.");
318 TBB = I->getOperand(0).getMBB();
319 Cond.push_back(I->getOperand(1));
320 Cond.push_back(I->getOperand(2));
321 } else if (I->isReturn()) {
322 // Returns can't be analyzed, but we should run cleanup.
323 CantAnalyze = !isPredicated(I);
325 // We encountered other unrecognized terminator. Bail out immediately.
329 // Cleanup code - to be run for unpredicated unconditional branches and
331 if (!isPredicated(I) &&
332 (isUncondBranchOpcode(I->getOpcode()) ||
333 isIndirectBranchOpcode(I->getOpcode()) ||
334 isJumpTableBranchOpcode(I->getOpcode()) ||
336 // Forget any previous condition branch information - it no longer applies.
340 // If we can modify the function, delete everything below this
341 // unconditional branch.
343 MachineBasicBlock::iterator DI = std::next(I);
344 while (DI != MBB.end()) {
345 MachineInstr *InstToDelete = DI;
347 InstToDelete->eraseFromParent();
355 if (I == MBB.begin())
361 // We made it past the terminators without bailing out - we must have
362 // analyzed this branch successfully.
367 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
368 MachineBasicBlock::iterator I = MBB.end();
369 if (I == MBB.begin()) return 0;
371 while (I->isDebugValue()) {
372 if (I == MBB.begin())
376 if (!isUncondBranchOpcode(I->getOpcode()) &&
377 !isCondBranchOpcode(I->getOpcode()))
380 // Remove the branch.
381 I->eraseFromParent();
385 if (I == MBB.begin()) return 1;
387 if (!isCondBranchOpcode(I->getOpcode()))
390 // Remove the branch.
391 I->eraseFromParent();
396 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
397 MachineBasicBlock *FBB,
398 const SmallVectorImpl<MachineOperand> &Cond,
400 ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
401 int BOpc = !AFI->isThumbFunction()
402 ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
403 int BccOpc = !AFI->isThumbFunction()
404 ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
405 bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
407 // Shouldn't be a fall through.
408 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
409 assert((Cond.size() == 2 || Cond.size() == 0) &&
410 "ARM branch conditions have two components!");
413 if (Cond.empty()) { // Unconditional branch?
415 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0);
417 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
419 BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
420 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
424 // Two-way conditional branch.
425 BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
426 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
428 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0);
430 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
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));
441 bool ARMBaseInstrInfo::isPredicated(const MachineInstr *MI) const {
442 if (MI->isBundle()) {
443 MachineBasicBlock::const_instr_iterator I = MI;
444 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
445 while (++I != E && I->isInsideBundle()) {
446 int PIdx = I->findFirstPredOperandIdx();
447 if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
453 int PIdx = MI->findFirstPredOperandIdx();
454 return PIdx != -1 && MI->getOperand(PIdx).getImm() != ARMCC::AL;
457 bool ARMBaseInstrInfo::
458 PredicateInstruction(MachineInstr *MI,
459 const SmallVectorImpl<MachineOperand> &Pred) const {
460 unsigned Opc = MI->getOpcode();
461 if (isUncondBranchOpcode(Opc)) {
462 MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
463 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
464 .addImm(Pred[0].getImm())
465 .addReg(Pred[1].getReg());
469 int PIdx = MI->findFirstPredOperandIdx();
471 MachineOperand &PMO = MI->getOperand(PIdx);
472 PMO.setImm(Pred[0].getImm());
473 MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
479 bool ARMBaseInstrInfo::
480 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
481 const SmallVectorImpl<MachineOperand> &Pred2) const {
482 if (Pred1.size() > 2 || Pred2.size() > 2)
485 ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
486 ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
496 return CC2 == ARMCC::HI;
498 return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
500 return CC2 == ARMCC::GT;
502 return CC2 == ARMCC::LT;
506 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
507 std::vector<MachineOperand> &Pred) const {
509 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
510 const MachineOperand &MO = MI->getOperand(i);
511 if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
512 (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) {
521 /// isPredicable - Return true if the specified instruction can be predicated.
522 /// By default, this returns true for every instruction with a
523 /// PredicateOperand.
524 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
525 if (!MI->isPredicable())
528 ARMFunctionInfo *AFI =
529 MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
531 if (AFI->isThumb2Function()) {
532 if (getSubtarget().restrictIT())
533 return isV8EligibleForIT(MI);
534 } else { // non-Thumb
535 if ((MI->getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
543 template <> bool IsCPSRDead<MachineInstr>(MachineInstr *MI) {
544 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
545 const MachineOperand &MO = MI->getOperand(i);
546 if (!MO.isReg() || MO.isUndef() || MO.isUse())
548 if (MO.getReg() != ARM::CPSR)
553 // all definitions of CPSR are dead
558 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
559 LLVM_ATTRIBUTE_NOINLINE
560 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
562 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
564 assert(JTI < JT.size());
565 return JT[JTI].MBBs.size();
568 /// GetInstSize - Return the size of the specified MachineInstr.
570 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
571 const MachineBasicBlock &MBB = *MI->getParent();
572 const MachineFunction *MF = MBB.getParent();
573 const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
575 const MCInstrDesc &MCID = MI->getDesc();
577 return MCID.getSize();
579 // If this machine instr is an inline asm, measure it.
580 if (MI->getOpcode() == ARM::INLINEASM)
581 return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
582 unsigned Opc = MI->getOpcode();
585 // pseudo-instruction sizes are zero.
587 case TargetOpcode::BUNDLE:
588 return getInstBundleLength(MI);
589 case ARM::MOVi16_ga_pcrel:
590 case ARM::MOVTi16_ga_pcrel:
591 case ARM::t2MOVi16_ga_pcrel:
592 case ARM::t2MOVTi16_ga_pcrel:
595 case ARM::t2MOVi32imm:
597 case ARM::CONSTPOOL_ENTRY:
598 // If this machine instr is a constant pool entry, its size is recorded as
600 return MI->getOperand(2).getImm();
601 case ARM::Int_eh_sjlj_longjmp:
603 case ARM::tInt_eh_sjlj_longjmp:
605 case ARM::Int_eh_sjlj_setjmp:
606 case ARM::Int_eh_sjlj_setjmp_nofp:
608 case ARM::tInt_eh_sjlj_setjmp:
609 case ARM::t2Int_eh_sjlj_setjmp:
610 case ARM::t2Int_eh_sjlj_setjmp_nofp:
618 case ARM::t2TBH_JT: {
619 // These are jumptable branches, i.e. a branch followed by an inlined
620 // jumptable. The size is 4 + 4 * number of entries. For TBB, each
621 // entry is one byte; TBH two byte each.
622 unsigned EntrySize = (Opc == ARM::t2TBB_JT)
623 ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
624 unsigned NumOps = MCID.getNumOperands();
625 MachineOperand JTOP =
626 MI->getOperand(NumOps - (MI->isPredicable() ? 3 : 2));
627 unsigned JTI = JTOP.getIndex();
628 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
629 assert(MJTI != nullptr);
630 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
631 assert(JTI < JT.size());
632 // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
633 // 4 aligned. The assembler / linker may add 2 byte padding just before
634 // the JT entries. The size does not include this padding; the
635 // constant islands pass does separate bookkeeping for it.
636 // FIXME: If we know the size of the function is less than (1 << 16) *2
637 // bytes, we can use 16-bit entries instead. Then there won't be an
639 unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
640 unsigned NumEntries = getNumJTEntries(JT, JTI);
641 if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
642 // Make sure the instruction that follows TBB is 2-byte aligned.
643 // FIXME: Constant island pass should insert an "ALIGN" instruction
646 return NumEntries * EntrySize + InstSize;
651 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr *MI) const {
653 MachineBasicBlock::const_instr_iterator I = MI;
654 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
655 while (++I != E && I->isInsideBundle()) {
656 assert(!I->isBundle() && "No nested bundle!");
657 Size += GetInstSizeInBytes(&*I);
662 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
663 MachineBasicBlock::iterator I, DebugLoc DL,
664 unsigned DestReg, unsigned SrcReg,
665 bool KillSrc) const {
666 bool GPRDest = ARM::GPRRegClass.contains(DestReg);
667 bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
669 if (GPRDest && GPRSrc) {
670 AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
671 .addReg(SrcReg, getKillRegState(KillSrc))));
675 bool SPRDest = ARM::SPRRegClass.contains(DestReg);
676 bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
679 if (SPRDest && SPRSrc)
681 else if (GPRDest && SPRSrc)
683 else if (SPRDest && GPRSrc)
685 else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
687 else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
691 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
692 MIB.addReg(SrcReg, getKillRegState(KillSrc));
693 if (Opc == ARM::VORRq)
694 MIB.addReg(SrcReg, getKillRegState(KillSrc));
699 // Handle register classes that require multiple instructions.
700 unsigned BeginIdx = 0;
701 unsigned SubRegs = 0;
704 // Use VORRq when possible.
705 if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
707 BeginIdx = ARM::qsub_0;
709 } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
711 BeginIdx = ARM::qsub_0;
713 // Fall back to VMOVD.
714 } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
716 BeginIdx = ARM::dsub_0;
718 } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
720 BeginIdx = ARM::dsub_0;
722 } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
724 BeginIdx = ARM::dsub_0;
726 } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
727 Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
728 BeginIdx = ARM::gsub_0;
730 } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
732 BeginIdx = ARM::dsub_0;
735 } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
737 BeginIdx = ARM::dsub_0;
740 } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
742 BeginIdx = ARM::dsub_0;
747 assert(Opc && "Impossible reg-to-reg copy");
749 const TargetRegisterInfo *TRI = &getRegisterInfo();
750 MachineInstrBuilder Mov;
752 // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
753 if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
754 BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
758 SmallSet<unsigned, 4> DstRegs;
760 for (unsigned i = 0; i != SubRegs; ++i) {
761 unsigned Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
762 unsigned Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
763 assert(Dst && Src && "Bad sub-register");
765 assert(!DstRegs.count(Src) && "destructive vector copy");
768 Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
769 // VORR takes two source operands.
770 if (Opc == ARM::VORRq)
772 Mov = AddDefaultPred(Mov);
774 if (Opc == ARM::MOVr)
775 Mov = AddDefaultCC(Mov);
777 // Add implicit super-register defs and kills to the last instruction.
778 Mov->addRegisterDefined(DestReg, TRI);
780 Mov->addRegisterKilled(SrcReg, TRI);
783 const MachineInstrBuilder &
784 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
785 unsigned SubIdx, unsigned State,
786 const TargetRegisterInfo *TRI) const {
788 return MIB.addReg(Reg, State);
790 if (TargetRegisterInfo::isPhysicalRegister(Reg))
791 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
792 return MIB.addReg(Reg, State, SubIdx);
795 void ARMBaseInstrInfo::
796 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
797 unsigned SrcReg, bool isKill, int FI,
798 const TargetRegisterClass *RC,
799 const TargetRegisterInfo *TRI) const {
801 if (I != MBB.end()) DL = I->getDebugLoc();
802 MachineFunction &MF = *MBB.getParent();
803 MachineFrameInfo &MFI = *MF.getFrameInfo();
804 unsigned Align = MFI.getObjectAlignment(FI);
806 MachineMemOperand *MMO =
807 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
808 MachineMemOperand::MOStore,
809 MFI.getObjectSize(FI),
812 switch (RC->getSize()) {
814 if (ARM::GPRRegClass.hasSubClassEq(RC)) {
815 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
816 .addReg(SrcReg, getKillRegState(isKill))
817 .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
818 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
819 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
820 .addReg(SrcReg, getKillRegState(isKill))
821 .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
823 llvm_unreachable("Unknown reg class!");
826 if (ARM::DPRRegClass.hasSubClassEq(RC)) {
827 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
828 .addReg(SrcReg, getKillRegState(isKill))
829 .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
830 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
831 if (Subtarget.hasV5TEOps()) {
832 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::STRD));
833 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
834 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
835 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO);
839 // Fallback to STM instruction, which has existed since the dawn of
841 MachineInstrBuilder MIB =
842 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STMIA))
843 .addFrameIndex(FI).addMemOperand(MMO));
844 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
845 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
848 llvm_unreachable("Unknown reg class!");
851 if (ARM::DPairRegClass.hasSubClassEq(RC)) {
852 // Use aligned spills if the stack can be realigned.
853 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
854 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64))
855 .addFrameIndex(FI).addImm(16)
856 .addReg(SrcReg, getKillRegState(isKill))
857 .addMemOperand(MMO));
859 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
860 .addReg(SrcReg, getKillRegState(isKill))
862 .addMemOperand(MMO));
865 llvm_unreachable("Unknown reg class!");
868 if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
869 // Use aligned spills if the stack can be realigned.
870 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
871 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64TPseudo))
872 .addFrameIndex(FI).addImm(16)
873 .addReg(SrcReg, getKillRegState(isKill))
874 .addMemOperand(MMO));
876 MachineInstrBuilder MIB =
877 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
880 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
881 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
882 AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
885 llvm_unreachable("Unknown reg class!");
888 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
889 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
890 // FIXME: It's possible to only store part of the QQ register if the
891 // spilled def has a sub-register index.
892 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
893 .addFrameIndex(FI).addImm(16)
894 .addReg(SrcReg, getKillRegState(isKill))
895 .addMemOperand(MMO));
897 MachineInstrBuilder MIB =
898 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
901 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
902 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
903 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
904 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
907 llvm_unreachable("Unknown reg class!");
910 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
911 MachineInstrBuilder MIB =
912 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
915 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
916 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
917 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
918 MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
919 MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
920 MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
921 MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
922 AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
924 llvm_unreachable("Unknown reg class!");
927 llvm_unreachable("Unknown reg class!");
932 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
933 int &FrameIndex) const {
934 switch (MI->getOpcode()) {
937 case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
938 if (MI->getOperand(1).isFI() &&
939 MI->getOperand(2).isReg() &&
940 MI->getOperand(3).isImm() &&
941 MI->getOperand(2).getReg() == 0 &&
942 MI->getOperand(3).getImm() == 0) {
943 FrameIndex = MI->getOperand(1).getIndex();
944 return MI->getOperand(0).getReg();
952 if (MI->getOperand(1).isFI() &&
953 MI->getOperand(2).isImm() &&
954 MI->getOperand(2).getImm() == 0) {
955 FrameIndex = MI->getOperand(1).getIndex();
956 return MI->getOperand(0).getReg();
960 case ARM::VST1d64TPseudo:
961 case ARM::VST1d64QPseudo:
962 if (MI->getOperand(0).isFI() &&
963 MI->getOperand(2).getSubReg() == 0) {
964 FrameIndex = MI->getOperand(0).getIndex();
965 return MI->getOperand(2).getReg();
969 if (MI->getOperand(1).isFI() &&
970 MI->getOperand(0).getSubReg() == 0) {
971 FrameIndex = MI->getOperand(1).getIndex();
972 return MI->getOperand(0).getReg();
980 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
981 int &FrameIndex) const {
982 const MachineMemOperand *Dummy;
983 return MI->mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
986 void ARMBaseInstrInfo::
987 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
988 unsigned DestReg, int FI,
989 const TargetRegisterClass *RC,
990 const TargetRegisterInfo *TRI) const {
992 if (I != MBB.end()) DL = I->getDebugLoc();
993 MachineFunction &MF = *MBB.getParent();
994 MachineFrameInfo &MFI = *MF.getFrameInfo();
995 unsigned Align = MFI.getObjectAlignment(FI);
996 MachineMemOperand *MMO =
997 MF.getMachineMemOperand(
998 MachinePointerInfo::getFixedStack(FI),
999 MachineMemOperand::MOLoad,
1000 MFI.getObjectSize(FI),
1003 switch (RC->getSize()) {
1005 if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1006 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
1007 .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1009 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1010 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
1011 .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1013 llvm_unreachable("Unknown reg class!");
1016 if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1017 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1018 .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1019 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1020 MachineInstrBuilder MIB;
1022 if (Subtarget.hasV5TEOps()) {
1023 MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1024 AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1025 AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1026 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO);
1028 AddDefaultPred(MIB);
1030 // Fallback to LDM instruction, which has existed since the dawn of
1032 MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDMIA))
1033 .addFrameIndex(FI).addMemOperand(MMO));
1034 MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1035 MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1038 if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1039 MIB.addReg(DestReg, RegState::ImplicitDefine);
1041 llvm_unreachable("Unknown reg class!");
1044 if (ARM::DPairRegClass.hasSubClassEq(RC)) {
1045 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1046 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1047 .addFrameIndex(FI).addImm(16)
1048 .addMemOperand(MMO));
1050 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1052 .addMemOperand(MMO));
1055 llvm_unreachable("Unknown reg class!");
1058 if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1059 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1060 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1061 .addFrameIndex(FI).addImm(16)
1062 .addMemOperand(MMO));
1064 MachineInstrBuilder MIB =
1065 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1067 .addMemOperand(MMO));
1068 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1069 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1070 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1071 if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1072 MIB.addReg(DestReg, RegState::ImplicitDefine);
1075 llvm_unreachable("Unknown reg class!");
1078 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1079 if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1080 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1081 .addFrameIndex(FI).addImm(16)
1082 .addMemOperand(MMO));
1084 MachineInstrBuilder MIB =
1085 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1087 .addMemOperand(MMO);
1088 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1089 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1090 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1091 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1092 if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1093 MIB.addReg(DestReg, RegState::ImplicitDefine);
1096 llvm_unreachable("Unknown reg class!");
1099 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1100 MachineInstrBuilder MIB =
1101 AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1103 .addMemOperand(MMO);
1104 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1105 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1106 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1107 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1108 MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1109 MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1110 MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1111 MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1112 if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1113 MIB.addReg(DestReg, RegState::ImplicitDefine);
1115 llvm_unreachable("Unknown reg class!");
1118 llvm_unreachable("Unknown regclass!");
1123 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
1124 int &FrameIndex) const {
1125 switch (MI->getOpcode()) {
1128 case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame.
1129 if (MI->getOperand(1).isFI() &&
1130 MI->getOperand(2).isReg() &&
1131 MI->getOperand(3).isImm() &&
1132 MI->getOperand(2).getReg() == 0 &&
1133 MI->getOperand(3).getImm() == 0) {
1134 FrameIndex = MI->getOperand(1).getIndex();
1135 return MI->getOperand(0).getReg();
1143 if (MI->getOperand(1).isFI() &&
1144 MI->getOperand(2).isImm() &&
1145 MI->getOperand(2).getImm() == 0) {
1146 FrameIndex = MI->getOperand(1).getIndex();
1147 return MI->getOperand(0).getReg();
1151 case ARM::VLD1d64TPseudo:
1152 case ARM::VLD1d64QPseudo:
1153 if (MI->getOperand(1).isFI() &&
1154 MI->getOperand(0).getSubReg() == 0) {
1155 FrameIndex = MI->getOperand(1).getIndex();
1156 return MI->getOperand(0).getReg();
1160 if (MI->getOperand(1).isFI() &&
1161 MI->getOperand(0).getSubReg() == 0) {
1162 FrameIndex = MI->getOperand(1).getIndex();
1163 return MI->getOperand(0).getReg();
1171 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
1172 int &FrameIndex) const {
1173 const MachineMemOperand *Dummy;
1174 return MI->mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
1178 ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
1179 MachineFunction &MF = *MI->getParent()->getParent();
1180 Reloc::Model RM = MF.getTarget().getRelocationModel();
1182 if (MI->getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
1183 assert(getSubtarget().getTargetTriple().getObjectFormat() ==
1185 "LOAD_STACK_GUARD currently supported only for MachO.");
1186 expandLoadStackGuard(MI, RM);
1187 MI->getParent()->erase(MI);
1191 // This hook gets to expand COPY instructions before they become
1192 // copyPhysReg() calls. Look for VMOVS instructions that can legally be
1193 // widened to VMOVD. We prefer the VMOVD when possible because it may be
1194 // changed into a VORR that can go down the NEON pipeline.
1195 if (!WidenVMOVS || !MI->isCopy() || Subtarget.isCortexA15())
1198 // Look for a copy between even S-registers. That is where we keep floats
1199 // when using NEON v2f32 instructions for f32 arithmetic.
1200 unsigned DstRegS = MI->getOperand(0).getReg();
1201 unsigned SrcRegS = MI->getOperand(1).getReg();
1202 if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1205 const TargetRegisterInfo *TRI = &getRegisterInfo();
1206 unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1208 unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1210 if (!DstRegD || !SrcRegD)
1213 // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only
1214 // legal if the COPY already defines the full DstRegD, and it isn't a
1215 // sub-register insertion.
1216 if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI))
1219 // A dead copy shouldn't show up here, but reject it just in case.
1220 if (MI->getOperand(0).isDead())
1223 // All clear, widen the COPY.
1224 DEBUG(dbgs() << "widening: " << *MI);
1225 MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
1227 // Get rid of the old <imp-def> of DstRegD. Leave it if it defines a Q-reg
1228 // or some other super-register.
1229 int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD);
1230 if (ImpDefIdx != -1)
1231 MI->RemoveOperand(ImpDefIdx);
1233 // Change the opcode and operands.
1234 MI->setDesc(get(ARM::VMOVD));
1235 MI->getOperand(0).setReg(DstRegD);
1236 MI->getOperand(1).setReg(SrcRegD);
1237 AddDefaultPred(MIB);
1239 // We are now reading SrcRegD instead of SrcRegS. This may upset the
1240 // register scavenger and machine verifier, so we need to indicate that we
1241 // are reading an undefined value from SrcRegD, but a proper value from
1243 MI->getOperand(1).setIsUndef();
1244 MIB.addReg(SrcRegS, RegState::Implicit);
1246 // SrcRegD may actually contain an unrelated value in the ssub_1
1247 // sub-register. Don't kill it. Only kill the ssub_0 sub-register.
1248 if (MI->getOperand(1).isKill()) {
1249 MI->getOperand(1).setIsKill(false);
1250 MI->addRegisterKilled(SrcRegS, TRI, true);
1253 DEBUG(dbgs() << "replaced by: " << *MI);
1257 /// Create a copy of a const pool value. Update CPI to the new index and return
1259 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1260 MachineConstantPool *MCP = MF.getConstantPool();
1261 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1263 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1264 assert(MCPE.isMachineConstantPoolEntry() &&
1265 "Expecting a machine constantpool entry!");
1266 ARMConstantPoolValue *ACPV =
1267 static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1269 unsigned PCLabelId = AFI->createPICLabelUId();
1270 ARMConstantPoolValue *NewCPV = nullptr;
1272 // FIXME: The below assumes PIC relocation model and that the function
1273 // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1274 // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1275 // instructions, so that's probably OK, but is PIC always correct when
1277 if (ACPV->isGlobalValue())
1278 NewCPV = ARMConstantPoolConstant::
1279 Create(cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId,
1281 else if (ACPV->isExtSymbol())
1282 NewCPV = ARMConstantPoolSymbol::
1283 Create(MF.getFunction()->getContext(),
1284 cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1285 else if (ACPV->isBlockAddress())
1286 NewCPV = ARMConstantPoolConstant::
1287 Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1288 ARMCP::CPBlockAddress, 4);
1289 else if (ACPV->isLSDA())
1290 NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId,
1292 else if (ACPV->isMachineBasicBlock())
1293 NewCPV = ARMConstantPoolMBB::
1294 Create(MF.getFunction()->getContext(),
1295 cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1297 llvm_unreachable("Unexpected ARM constantpool value type!!");
1298 CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1302 void ARMBaseInstrInfo::
1303 reMaterialize(MachineBasicBlock &MBB,
1304 MachineBasicBlock::iterator I,
1305 unsigned DestReg, unsigned SubIdx,
1306 const MachineInstr *Orig,
1307 const TargetRegisterInfo &TRI) const {
1308 unsigned Opcode = Orig->getOpcode();
1311 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1312 MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1316 case ARM::tLDRpci_pic:
1317 case ARM::t2LDRpci_pic: {
1318 MachineFunction &MF = *MBB.getParent();
1319 unsigned CPI = Orig->getOperand(1).getIndex();
1320 unsigned PCLabelId = duplicateCPV(MF, CPI);
1321 MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1323 .addConstantPoolIndex(CPI).addImm(PCLabelId);
1324 MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1331 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1332 MachineInstr *MI = TargetInstrInfo::duplicate(Orig, MF);
1333 switch(Orig->getOpcode()) {
1334 case ARM::tLDRpci_pic:
1335 case ARM::t2LDRpci_pic: {
1336 unsigned CPI = Orig->getOperand(1).getIndex();
1337 unsigned PCLabelId = duplicateCPV(MF, CPI);
1338 Orig->getOperand(1).setIndex(CPI);
1339 Orig->getOperand(2).setImm(PCLabelId);
1346 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1347 const MachineInstr *MI1,
1348 const MachineRegisterInfo *MRI) const {
1349 int Opcode = MI0->getOpcode();
1350 if (Opcode == ARM::t2LDRpci ||
1351 Opcode == ARM::t2LDRpci_pic ||
1352 Opcode == ARM::tLDRpci ||
1353 Opcode == ARM::tLDRpci_pic ||
1354 Opcode == ARM::LDRLIT_ga_pcrel ||
1355 Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1356 Opcode == ARM::tLDRLIT_ga_pcrel ||
1357 Opcode == ARM::MOV_ga_pcrel ||
1358 Opcode == ARM::MOV_ga_pcrel_ldr ||
1359 Opcode == ARM::t2MOV_ga_pcrel) {
1360 if (MI1->getOpcode() != Opcode)
1362 if (MI0->getNumOperands() != MI1->getNumOperands())
1365 const MachineOperand &MO0 = MI0->getOperand(1);
1366 const MachineOperand &MO1 = MI1->getOperand(1);
1367 if (MO0.getOffset() != MO1.getOffset())
1370 if (Opcode == ARM::LDRLIT_ga_pcrel ||
1371 Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1372 Opcode == ARM::tLDRLIT_ga_pcrel ||
1373 Opcode == ARM::MOV_ga_pcrel ||
1374 Opcode == ARM::MOV_ga_pcrel_ldr ||
1375 Opcode == ARM::t2MOV_ga_pcrel)
1376 // Ignore the PC labels.
1377 return MO0.getGlobal() == MO1.getGlobal();
1379 const MachineFunction *MF = MI0->getParent()->getParent();
1380 const MachineConstantPool *MCP = MF->getConstantPool();
1381 int CPI0 = MO0.getIndex();
1382 int CPI1 = MO1.getIndex();
1383 const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1384 const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1385 bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1386 bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1387 if (isARMCP0 && isARMCP1) {
1388 ARMConstantPoolValue *ACPV0 =
1389 static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1390 ARMConstantPoolValue *ACPV1 =
1391 static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1392 return ACPV0->hasSameValue(ACPV1);
1393 } else if (!isARMCP0 && !isARMCP1) {
1394 return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1397 } else if (Opcode == ARM::PICLDR) {
1398 if (MI1->getOpcode() != Opcode)
1400 if (MI0->getNumOperands() != MI1->getNumOperands())
1403 unsigned Addr0 = MI0->getOperand(1).getReg();
1404 unsigned Addr1 = MI1->getOperand(1).getReg();
1405 if (Addr0 != Addr1) {
1407 !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1408 !TargetRegisterInfo::isVirtualRegister(Addr1))
1411 // This assumes SSA form.
1412 MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1413 MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1414 // Check if the loaded value, e.g. a constantpool of a global address, are
1416 if (!produceSameValue(Def0, Def1, MRI))
1420 for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1421 // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1422 const MachineOperand &MO0 = MI0->getOperand(i);
1423 const MachineOperand &MO1 = MI1->getOperand(i);
1424 if (!MO0.isIdenticalTo(MO1))
1430 return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1433 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1434 /// determine if two loads are loading from the same base address. It should
1435 /// only return true if the base pointers are the same and the only differences
1436 /// between the two addresses is the offset. It also returns the offsets by
1439 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1440 /// is permanently disabled.
1441 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1443 int64_t &Offset2) const {
1444 // Don't worry about Thumb: just ARM and Thumb2.
1445 if (Subtarget.isThumb1Only()) return false;
1447 if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1450 switch (Load1->getMachineOpcode()) {
1464 case ARM::t2LDRSHi8:
1466 case ARM::t2LDRBi12:
1467 case ARM::t2LDRSHi12:
1471 switch (Load2->getMachineOpcode()) {
1484 case ARM::t2LDRSHi8:
1486 case ARM::t2LDRBi12:
1487 case ARM::t2LDRSHi12:
1491 // Check if base addresses and chain operands match.
1492 if (Load1->getOperand(0) != Load2->getOperand(0) ||
1493 Load1->getOperand(4) != Load2->getOperand(4))
1496 // Index should be Reg0.
1497 if (Load1->getOperand(3) != Load2->getOperand(3))
1500 // Determine the offsets.
1501 if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1502 isa<ConstantSDNode>(Load2->getOperand(1))) {
1503 Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1504 Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1511 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1512 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1513 /// be scheduled togther. On some targets if two loads are loading from
1514 /// addresses in the same cache line, it's better if they are scheduled
1515 /// together. This function takes two integers that represent the load offsets
1516 /// from the common base address. It returns true if it decides it's desirable
1517 /// to schedule the two loads together. "NumLoads" is the number of loads that
1518 /// have already been scheduled after Load1.
1520 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1521 /// is permanently disabled.
1522 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1523 int64_t Offset1, int64_t Offset2,
1524 unsigned NumLoads) const {
1525 // Don't worry about Thumb: just ARM and Thumb2.
1526 if (Subtarget.isThumb1Only()) return false;
1528 assert(Offset2 > Offset1);
1530 if ((Offset2 - Offset1) / 8 > 64)
1533 // Check if the machine opcodes are different. If they are different
1534 // then we consider them to not be of the same base address,
1535 // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
1536 // In this case, they are considered to be the same because they are different
1537 // encoding forms of the same basic instruction.
1538 if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
1539 !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
1540 Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
1541 (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
1542 Load2->getMachineOpcode() == ARM::t2LDRBi8)))
1543 return false; // FIXME: overly conservative?
1545 // Four loads in a row should be sufficient.
1552 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1553 const MachineBasicBlock *MBB,
1554 const MachineFunction &MF) const {
1555 // Debug info is never a scheduling boundary. It's necessary to be explicit
1556 // due to the special treatment of IT instructions below, otherwise a
1557 // dbg_value followed by an IT will result in the IT instruction being
1558 // considered a scheduling hazard, which is wrong. It should be the actual
1559 // instruction preceding the dbg_value instruction(s), just like it is
1560 // when debug info is not present.
1561 if (MI->isDebugValue())
1564 // Terminators and labels can't be scheduled around.
1565 if (MI->isTerminator() || MI->isPosition())
1568 // Treat the start of the IT block as a scheduling boundary, but schedule
1569 // t2IT along with all instructions following it.
1570 // FIXME: This is a big hammer. But the alternative is to add all potential
1571 // true and anti dependencies to IT block instructions as implicit operands
1572 // to the t2IT instruction. The added compile time and complexity does not
1574 MachineBasicBlock::const_iterator I = MI;
1575 // Make sure to skip any dbg_value instructions
1576 while (++I != MBB->end() && I->isDebugValue())
1578 if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1581 // Don't attempt to schedule around any instruction that defines
1582 // a stack-oriented pointer, as it's unlikely to be profitable. This
1583 // saves compile time, because it doesn't require every single
1584 // stack slot reference to depend on the instruction that does the
1586 // Calls don't actually change the stack pointer, even if they have imp-defs.
1587 // No ARM calling conventions change the stack pointer. (X86 calling
1588 // conventions sometimes do).
1589 if (!MI->isCall() && MI->definesRegister(ARM::SP))
1595 bool ARMBaseInstrInfo::
1596 isProfitableToIfCvt(MachineBasicBlock &MBB,
1597 unsigned NumCycles, unsigned ExtraPredCycles,
1598 const BranchProbability &Probability) const {
1602 // Attempt to estimate the relative costs of predication versus branching.
1603 unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1604 UnpredCost /= Probability.getDenominator();
1605 UnpredCost += 1; // The branch itself
1606 UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1608 return (NumCycles + ExtraPredCycles) <= UnpredCost;
1611 bool ARMBaseInstrInfo::
1612 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1613 unsigned TCycles, unsigned TExtra,
1614 MachineBasicBlock &FMBB,
1615 unsigned FCycles, unsigned FExtra,
1616 const BranchProbability &Probability) const {
1617 if (!TCycles || !FCycles)
1620 // Attempt to estimate the relative costs of predication versus branching.
1621 unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1622 TUnpredCost /= Probability.getDenominator();
1624 uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1625 unsigned FUnpredCost = Comp * FCycles;
1626 FUnpredCost /= Probability.getDenominator();
1628 unsigned UnpredCost = TUnpredCost + FUnpredCost;
1629 UnpredCost += 1; // The branch itself
1630 UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1632 return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1636 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
1637 MachineBasicBlock &FMBB) const {
1638 // Reduce false anti-dependencies to let Swift's out-of-order execution
1639 // engine do its thing.
1640 return Subtarget.isSwift();
1643 /// getInstrPredicate - If instruction is predicated, returns its predicate
1644 /// condition, otherwise returns AL. It also returns the condition code
1645 /// register by reference.
1647 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1648 int PIdx = MI->findFirstPredOperandIdx();
1654 PredReg = MI->getOperand(PIdx+1).getReg();
1655 return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1659 int llvm::getMatchingCondBranchOpcode(int Opc) {
1664 if (Opc == ARM::t2B)
1667 llvm_unreachable("Unknown unconditional branch opcode!");
1670 /// commuteInstruction - Handle commutable instructions.
1672 ARMBaseInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
1673 switch (MI->getOpcode()) {
1675 case ARM::t2MOVCCr: {
1676 // MOVCC can be commuted by inverting the condition.
1677 unsigned PredReg = 0;
1678 ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
1679 // MOVCC AL can't be inverted. Shouldn't happen.
1680 if (CC == ARMCC::AL || PredReg != ARM::CPSR)
1682 MI = TargetInstrInfo::commuteInstruction(MI, NewMI);
1685 // After swapping the MOVCC operands, also invert the condition.
1686 MI->getOperand(MI->findFirstPredOperandIdx())
1687 .setImm(ARMCC::getOppositeCondition(CC));
1691 return TargetInstrInfo::commuteInstruction(MI, NewMI);
1694 /// Identify instructions that can be folded into a MOVCC instruction, and
1695 /// return the defining instruction.
1696 static MachineInstr *canFoldIntoMOVCC(unsigned Reg,
1697 const MachineRegisterInfo &MRI,
1698 const TargetInstrInfo *TII) {
1699 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1701 if (!MRI.hasOneNonDBGUse(Reg))
1703 MachineInstr *MI = MRI.getVRegDef(Reg);
1706 // MI is folded into the MOVCC by predicating it.
1707 if (!MI->isPredicable())
1709 // Check if MI has any non-dead defs or physreg uses. This also detects
1710 // predicated instructions which will be reading CPSR.
1711 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
1712 const MachineOperand &MO = MI->getOperand(i);
1713 // Reject frame index operands, PEI can't handle the predicated pseudos.
1714 if (MO.isFI() || MO.isCPI() || MO.isJTI())
1718 // MI can't have any tied operands, that would conflict with predication.
1721 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1723 if (MO.isDef() && !MO.isDead())
1726 bool DontMoveAcrossStores = true;
1727 if (!MI->isSafeToMove(TII, /* AliasAnalysis = */ nullptr,
1728 DontMoveAcrossStores))
1733 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr *MI,
1734 SmallVectorImpl<MachineOperand> &Cond,
1735 unsigned &TrueOp, unsigned &FalseOp,
1736 bool &Optimizable) const {
1737 assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1738 "Unknown select instruction");
1743 // 3: Condition code.
1747 Cond.push_back(MI->getOperand(3));
1748 Cond.push_back(MI->getOperand(4));
1749 // We can always fold a def.
1754 MachineInstr *ARMBaseInstrInfo::optimizeSelect(MachineInstr *MI,
1755 bool PreferFalse) const {
1756 assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1757 "Unknown select instruction");
1758 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1759 MachineInstr *DefMI = canFoldIntoMOVCC(MI->getOperand(2).getReg(), MRI, this);
1760 bool Invert = !DefMI;
1762 DefMI = canFoldIntoMOVCC(MI->getOperand(1).getReg(), MRI, this);
1766 // Find new register class to use.
1767 MachineOperand FalseReg = MI->getOperand(Invert ? 2 : 1);
1768 unsigned DestReg = MI->getOperand(0).getReg();
1769 const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
1770 if (!MRI.constrainRegClass(DestReg, PreviousClass))
1773 // Create a new predicated version of DefMI.
1774 // Rfalse is the first use.
1775 MachineInstrBuilder NewMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1776 DefMI->getDesc(), DestReg);
1778 // Copy all the DefMI operands, excluding its (null) predicate.
1779 const MCInstrDesc &DefDesc = DefMI->getDesc();
1780 for (unsigned i = 1, e = DefDesc.getNumOperands();
1781 i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
1782 NewMI.addOperand(DefMI->getOperand(i));
1784 unsigned CondCode = MI->getOperand(3).getImm();
1786 NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
1788 NewMI.addImm(CondCode);
1789 NewMI.addOperand(MI->getOperand(4));
1791 // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
1792 if (NewMI->hasOptionalDef())
1793 AddDefaultCC(NewMI);
1795 // The output register value when the predicate is false is an implicit
1796 // register operand tied to the first def.
1797 // The tie makes the register allocator ensure the FalseReg is allocated the
1798 // same register as operand 0.
1799 FalseReg.setImplicit();
1800 NewMI.addOperand(FalseReg);
1801 NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
1803 // The caller will erase MI, but not DefMI.
1804 DefMI->eraseFromParent();
1808 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
1809 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
1812 /// This will go away once we can teach tblgen how to set the optional CPSR def
1814 struct AddSubFlagsOpcodePair {
1816 uint16_t MachineOpc;
1819 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
1820 {ARM::ADDSri, ARM::ADDri},
1821 {ARM::ADDSrr, ARM::ADDrr},
1822 {ARM::ADDSrsi, ARM::ADDrsi},
1823 {ARM::ADDSrsr, ARM::ADDrsr},
1825 {ARM::SUBSri, ARM::SUBri},
1826 {ARM::SUBSrr, ARM::SUBrr},
1827 {ARM::SUBSrsi, ARM::SUBrsi},
1828 {ARM::SUBSrsr, ARM::SUBrsr},
1830 {ARM::RSBSri, ARM::RSBri},
1831 {ARM::RSBSrsi, ARM::RSBrsi},
1832 {ARM::RSBSrsr, ARM::RSBrsr},
1834 {ARM::t2ADDSri, ARM::t2ADDri},
1835 {ARM::t2ADDSrr, ARM::t2ADDrr},
1836 {ARM::t2ADDSrs, ARM::t2ADDrs},
1838 {ARM::t2SUBSri, ARM::t2SUBri},
1839 {ARM::t2SUBSrr, ARM::t2SUBrr},
1840 {ARM::t2SUBSrs, ARM::t2SUBrs},
1842 {ARM::t2RSBSri, ARM::t2RSBri},
1843 {ARM::t2RSBSrs, ARM::t2RSBrs},
1846 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
1847 for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
1848 if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
1849 return AddSubFlagsOpcodeMap[i].MachineOpc;
1853 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1854 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1855 unsigned DestReg, unsigned BaseReg, int NumBytes,
1856 ARMCC::CondCodes Pred, unsigned PredReg,
1857 const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1858 if (NumBytes == 0 && DestReg != BaseReg) {
1859 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
1860 .addReg(BaseReg, RegState::Kill)
1861 .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1862 .setMIFlags(MIFlags);
1866 bool isSub = NumBytes < 0;
1867 if (isSub) NumBytes = -NumBytes;
1870 unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1871 unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1872 assert(ThisVal && "Didn't extract field correctly");
1874 // We will handle these bits from offset, clear them.
1875 NumBytes &= ~ThisVal;
1877 assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1879 // Build the new ADD / SUB.
1880 unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1881 BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1882 .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1883 .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1884 .setMIFlags(MIFlags);
1889 static bool isAnySubRegLive(unsigned Reg, const TargetRegisterInfo *TRI,
1891 for (MCSubRegIterator Subreg(Reg, TRI, /* IncludeSelf */ true);
1892 Subreg.isValid(); ++Subreg)
1893 if (MI->getParent()->computeRegisterLiveness(TRI, *Subreg, MI) !=
1894 MachineBasicBlock::LQR_Dead)
1898 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
1899 MachineFunction &MF, MachineInstr *MI,
1900 unsigned NumBytes) {
1901 // This optimisation potentially adds lots of load and store
1902 // micro-operations, it's only really a great benefit to code-size.
1903 if (!MF.getFunction()->getAttributes().hasAttribute(
1904 AttributeSet::FunctionIndex, Attribute::MinSize))
1907 // If only one register is pushed/popped, LLVM can use an LDR/STR
1908 // instead. We can't modify those so make sure we're dealing with an
1909 // instruction we understand.
1910 bool IsPop = isPopOpcode(MI->getOpcode());
1911 bool IsPush = isPushOpcode(MI->getOpcode());
1912 if (!IsPush && !IsPop)
1915 bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
1916 MI->getOpcode() == ARM::VLDMDIA_UPD;
1917 bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
1918 MI->getOpcode() == ARM::tPOP ||
1919 MI->getOpcode() == ARM::tPOP_RET;
1921 assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
1922 MI->getOperand(1).getReg() == ARM::SP)) &&
1923 "trying to fold sp update into non-sp-updating push/pop");
1925 // The VFP push & pop act on D-registers, so we can only fold an adjustment
1926 // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
1927 // if this is violated.
1928 if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
1931 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
1932 // pred) so the list starts at 4. Thumb1 starts after the predicate.
1933 int RegListIdx = IsT1PushPop ? 2 : 4;
1935 // Calculate the space we'll need in terms of registers.
1936 unsigned FirstReg = MI->getOperand(RegListIdx).getReg();
1937 unsigned RD0Reg, RegsNeeded;
1940 RegsNeeded = NumBytes / 8;
1943 RegsNeeded = NumBytes / 4;
1946 // We're going to have to strip all list operands off before
1947 // re-adding them since the order matters, so save the existing ones
1949 SmallVector<MachineOperand, 4> RegList;
1950 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
1951 RegList.push_back(MI->getOperand(i));
1953 const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
1954 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
1956 // Now try to find enough space in the reglist to allocate NumBytes.
1957 for (unsigned CurReg = FirstReg - 1; CurReg >= RD0Reg && RegsNeeded;
1960 // Pushing any register is completely harmless, mark the
1961 // register involved as undef since we don't care about it in
1963 RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
1964 false, false, true));
1969 // However, we can only pop an extra register if it's not live. For
1970 // registers live within the function we might clobber a return value
1971 // register; the other way a register can be live here is if it's
1973 // TODO: Currently, computeRegisterLiveness() does not report "live" if a
1974 // sub reg is live. When computeRegisterLiveness() works for sub reg, it
1975 // can replace isAnySubRegLive().
1976 if (isCalleeSavedRegister(CurReg, CSRegs) ||
1977 isAnySubRegLive(CurReg, TRI, MI)) {
1978 // VFP pops don't allow holes in the register list, so any skip is fatal
1979 // for our transformation. GPR pops do, so we should just keep looking.
1986 // Mark the unimportant registers as <def,dead> in the POP.
1987 RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
1995 // Finally we know we can profitably perform the optimisation so go
1996 // ahead: strip all existing registers off and add them back again
1997 // in the right order.
1998 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
1999 MI->RemoveOperand(i);
2001 // Add the complete list back in.
2002 MachineInstrBuilder MIB(MF, &*MI);
2003 for (int i = RegList.size() - 1; i >= 0; --i)
2004 MIB.addOperand(RegList[i]);
2009 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
2010 unsigned FrameReg, int &Offset,
2011 const ARMBaseInstrInfo &TII) {
2012 unsigned Opcode = MI.getOpcode();
2013 const MCInstrDesc &Desc = MI.getDesc();
2014 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
2017 // Memory operands in inline assembly always use AddrMode2.
2018 if (Opcode == ARM::INLINEASM)
2019 AddrMode = ARMII::AddrMode2;
2021 if (Opcode == ARM::ADDri) {
2022 Offset += MI.getOperand(FrameRegIdx+1).getImm();
2024 // Turn it into a move.
2025 MI.setDesc(TII.get(ARM::MOVr));
2026 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2027 MI.RemoveOperand(FrameRegIdx+1);
2030 } else if (Offset < 0) {
2033 MI.setDesc(TII.get(ARM::SUBri));
2036 // Common case: small offset, fits into instruction.
2037 if (ARM_AM::getSOImmVal(Offset) != -1) {
2038 // Replace the FrameIndex with sp / fp
2039 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2040 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
2045 // Otherwise, pull as much of the immedidate into this ADDri/SUBri
2047 unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
2048 unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
2050 // We will handle these bits from offset, clear them.
2051 Offset &= ~ThisImmVal;
2053 // Get the properly encoded SOImmVal field.
2054 assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
2055 "Bit extraction didn't work?");
2056 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
2058 unsigned ImmIdx = 0;
2060 unsigned NumBits = 0;
2063 case ARMII::AddrMode_i12: {
2064 ImmIdx = FrameRegIdx + 1;
2065 InstrOffs = MI.getOperand(ImmIdx).getImm();
2069 case ARMII::AddrMode2: {
2070 ImmIdx = FrameRegIdx+2;
2071 InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
2072 if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2077 case ARMII::AddrMode3: {
2078 ImmIdx = FrameRegIdx+2;
2079 InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
2080 if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2085 case ARMII::AddrMode4:
2086 case ARMII::AddrMode6:
2087 // Can't fold any offset even if it's zero.
2089 case ARMII::AddrMode5: {
2090 ImmIdx = FrameRegIdx+1;
2091 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2092 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2099 llvm_unreachable("Unsupported addressing mode!");
2102 Offset += InstrOffs * Scale;
2103 assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
2109 // Attempt to fold address comp. if opcode has offset bits
2111 // Common case: small offset, fits into instruction.
2112 MachineOperand &ImmOp = MI.getOperand(ImmIdx);
2113 int ImmedOffset = Offset / Scale;
2114 unsigned Mask = (1 << NumBits) - 1;
2115 if ((unsigned)Offset <= Mask * Scale) {
2116 // Replace the FrameIndex with sp
2117 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2118 // FIXME: When addrmode2 goes away, this will simplify (like the
2119 // T2 version), as the LDR.i12 versions don't need the encoding
2120 // tricks for the offset value.
2122 if (AddrMode == ARMII::AddrMode_i12)
2123 ImmedOffset = -ImmedOffset;
2125 ImmedOffset |= 1 << NumBits;
2127 ImmOp.ChangeToImmediate(ImmedOffset);
2132 // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
2133 ImmedOffset = ImmedOffset & Mask;
2135 if (AddrMode == ARMII::AddrMode_i12)
2136 ImmedOffset = -ImmedOffset;
2138 ImmedOffset |= 1 << NumBits;
2140 ImmOp.ChangeToImmediate(ImmedOffset);
2141 Offset &= ~(Mask*Scale);
2145 Offset = (isSub) ? -Offset : Offset;
2149 /// analyzeCompare - For a comparison instruction, return the source registers
2150 /// in SrcReg and SrcReg2 if having two register operands, and the value it
2151 /// compares against in CmpValue. Return true if the comparison instruction
2152 /// can be analyzed.
2153 bool ARMBaseInstrInfo::
2154 analyzeCompare(const MachineInstr *MI, unsigned &SrcReg, unsigned &SrcReg2,
2155 int &CmpMask, int &CmpValue) const {
2156 switch (MI->getOpcode()) {
2160 SrcReg = MI->getOperand(0).getReg();
2163 CmpValue = MI->getOperand(1).getImm();
2167 SrcReg = MI->getOperand(0).getReg();
2168 SrcReg2 = MI->getOperand(1).getReg();
2174 SrcReg = MI->getOperand(0).getReg();
2176 CmpMask = MI->getOperand(1).getImm();
2184 /// isSuitableForMask - Identify a suitable 'and' instruction that
2185 /// operates on the given source register and applies the same mask
2186 /// as a 'tst' instruction. Provide a limited look-through for copies.
2187 /// When successful, MI will hold the found instruction.
2188 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
2189 int CmpMask, bool CommonUse) {
2190 switch (MI->getOpcode()) {
2193 if (CmpMask != MI->getOperand(2).getImm())
2195 if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2199 // Walk down one instruction which is potentially an 'and'.
2200 const MachineInstr &Copy = *MI;
2201 MachineBasicBlock::iterator AND(
2202 std::next(MachineBasicBlock::iterator(MI)));
2203 if (AND == MI->getParent()->end()) return false;
2205 return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
2213 /// getSwappedCondition - assume the flags are set by MI(a,b), return
2214 /// the condition code if we modify the instructions such that flags are
2216 inline static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC) {
2218 default: return ARMCC::AL;
2219 case ARMCC::EQ: return ARMCC::EQ;
2220 case ARMCC::NE: return ARMCC::NE;
2221 case ARMCC::HS: return ARMCC::LS;
2222 case ARMCC::LO: return ARMCC::HI;
2223 case ARMCC::HI: return ARMCC::LO;
2224 case ARMCC::LS: return ARMCC::HS;
2225 case ARMCC::GE: return ARMCC::LE;
2226 case ARMCC::LT: return ARMCC::GT;
2227 case ARMCC::GT: return ARMCC::LT;
2228 case ARMCC::LE: return ARMCC::GE;
2232 /// isRedundantFlagInstr - check whether the first instruction, whose only
2233 /// purpose is to update flags, can be made redundant.
2234 /// CMPrr can be made redundant by SUBrr if the operands are the same.
2235 /// CMPri can be made redundant by SUBri if the operands are the same.
2236 /// This function can be extended later on.
2237 inline static bool isRedundantFlagInstr(MachineInstr *CmpI, unsigned SrcReg,
2238 unsigned SrcReg2, int ImmValue,
2240 if ((CmpI->getOpcode() == ARM::CMPrr ||
2241 CmpI->getOpcode() == ARM::t2CMPrr) &&
2242 (OI->getOpcode() == ARM::SUBrr ||
2243 OI->getOpcode() == ARM::t2SUBrr) &&
2244 ((OI->getOperand(1).getReg() == SrcReg &&
2245 OI->getOperand(2).getReg() == SrcReg2) ||
2246 (OI->getOperand(1).getReg() == SrcReg2 &&
2247 OI->getOperand(2).getReg() == SrcReg)))
2250 if ((CmpI->getOpcode() == ARM::CMPri ||
2251 CmpI->getOpcode() == ARM::t2CMPri) &&
2252 (OI->getOpcode() == ARM::SUBri ||
2253 OI->getOpcode() == ARM::t2SUBri) &&
2254 OI->getOperand(1).getReg() == SrcReg &&
2255 OI->getOperand(2).getImm() == ImmValue)
2260 /// optimizeCompareInstr - Convert the instruction supplying the argument to the
2261 /// comparison into one that sets the zero bit in the flags register;
2262 /// Remove a redundant Compare instruction if an earlier instruction can set the
2263 /// flags in the same way as Compare.
2264 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2265 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2266 /// condition code of instructions which use the flags.
2267 bool ARMBaseInstrInfo::
2268 optimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, unsigned SrcReg2,
2269 int CmpMask, int CmpValue,
2270 const MachineRegisterInfo *MRI) const {
2271 // Get the unique definition of SrcReg.
2272 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2273 if (!MI) return false;
2275 // Masked compares sometimes use the same register as the corresponding 'and'.
2276 if (CmpMask != ~0) {
2277 if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(MI)) {
2279 for (MachineRegisterInfo::use_instr_iterator
2280 UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
2282 if (UI->getParent() != CmpInstr->getParent()) continue;
2283 MachineInstr *PotentialAND = &*UI;
2284 if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2285 isPredicated(PotentialAND))
2290 if (!MI) return false;
2294 // Get ready to iterate backward from CmpInstr.
2295 MachineBasicBlock::iterator I = CmpInstr, E = MI,
2296 B = CmpInstr->getParent()->begin();
2298 // Early exit if CmpInstr is at the beginning of the BB.
2299 if (I == B) return false;
2301 // There are two possible candidates which can be changed to set CPSR:
2302 // One is MI, the other is a SUB instruction.
2303 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2304 // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2305 MachineInstr *Sub = nullptr;
2307 // MI is not a candidate for CMPrr.
2309 else if (MI->getParent() != CmpInstr->getParent() || CmpValue != 0) {
2310 // Conservatively refuse to convert an instruction which isn't in the same
2311 // BB as the comparison.
2312 // For CMPri, we need to check Sub, thus we can't return here.
2313 if (CmpInstr->getOpcode() == ARM::CMPri ||
2314 CmpInstr->getOpcode() == ARM::t2CMPri)
2320 // Check that CPSR isn't set between the comparison instruction and the one we
2321 // want to change. At the same time, search for Sub.
2322 const TargetRegisterInfo *TRI = &getRegisterInfo();
2324 for (; I != E; --I) {
2325 const MachineInstr &Instr = *I;
2327 if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
2328 Instr.readsRegister(ARM::CPSR, TRI))
2329 // This instruction modifies or uses CPSR after the one we want to
2330 // change. We can't do this transformation.
2333 // Check whether CmpInstr can be made redundant by the current instruction.
2334 if (isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpValue, &*I)) {
2340 // The 'and' is below the comparison instruction.
2344 // Return false if no candidates exist.
2348 // The single candidate is called MI.
2351 // We can't use a predicated instruction - it doesn't always write the flags.
2352 if (isPredicated(MI))
2355 switch (MI->getOpcode()) {
2389 case ARM::t2EORri: {
2390 // Scan forward for the use of CPSR
2391 // When checking against MI: if it's a conditional code requires
2392 // checking of V bit, then this is not safe to do.
2393 // It is safe to remove CmpInstr if CPSR is redefined or killed.
2394 // If we are done with the basic block, we need to check whether CPSR is
2396 SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
2398 bool isSafe = false;
2400 E = CmpInstr->getParent()->end();
2401 while (!isSafe && ++I != E) {
2402 const MachineInstr &Instr = *I;
2403 for (unsigned IO = 0, EO = Instr.getNumOperands();
2404 !isSafe && IO != EO; ++IO) {
2405 const MachineOperand &MO = Instr.getOperand(IO);
2406 if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
2410 if (!MO.isReg() || MO.getReg() != ARM::CPSR)
2416 // Condition code is after the operand before CPSR except for VSELs.
2417 ARMCC::CondCodes CC;
2418 bool IsInstrVSel = true;
2419 switch (Instr.getOpcode()) {
2421 IsInstrVSel = false;
2422 CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
2443 ARMCC::CondCodes NewCC = getSwappedCondition(CC);
2444 if (NewCC == ARMCC::AL)
2446 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
2447 // on CMP needs to be updated to be based on SUB.
2448 // Push the condition code operands to OperandsToUpdate.
2449 // If it is safe to remove CmpInstr, the condition code of these
2450 // operands will be modified.
2451 if (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2452 Sub->getOperand(2).getReg() == SrcReg) {
2453 // VSel doesn't support condition code update.
2456 OperandsToUpdate.push_back(
2457 std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
2462 // CPSR can be used multiple times, we should continue.
2475 // If CPSR is not killed nor re-defined, we should check whether it is
2476 // live-out. If it is live-out, do not optimize.
2478 MachineBasicBlock *MBB = CmpInstr->getParent();
2479 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
2480 SE = MBB->succ_end(); SI != SE; ++SI)
2481 if ((*SI)->isLiveIn(ARM::CPSR))
2485 // Toggle the optional operand to CPSR.
2486 MI->getOperand(5).setReg(ARM::CPSR);
2487 MI->getOperand(5).setIsDef(true);
2488 assert(!isPredicated(MI) && "Can't use flags from predicated instruction");
2489 CmpInstr->eraseFromParent();
2491 // Modify the condition code of operands in OperandsToUpdate.
2492 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2493 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2494 for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
2495 OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
2503 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
2504 MachineInstr *DefMI, unsigned Reg,
2505 MachineRegisterInfo *MRI) const {
2506 // Fold large immediates into add, sub, or, xor.
2507 unsigned DefOpc = DefMI->getOpcode();
2508 if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
2510 if (!DefMI->getOperand(1).isImm())
2511 // Could be t2MOVi32imm <ga:xx>
2514 if (!MRI->hasOneNonDBGUse(Reg))
2517 const MCInstrDesc &DefMCID = DefMI->getDesc();
2518 if (DefMCID.hasOptionalDef()) {
2519 unsigned NumOps = DefMCID.getNumOperands();
2520 const MachineOperand &MO = DefMI->getOperand(NumOps-1);
2521 if (MO.getReg() == ARM::CPSR && !MO.isDead())
2522 // If DefMI defines CPSR and it is not dead, it's obviously not safe
2527 const MCInstrDesc &UseMCID = UseMI->getDesc();
2528 if (UseMCID.hasOptionalDef()) {
2529 unsigned NumOps = UseMCID.getNumOperands();
2530 if (UseMI->getOperand(NumOps-1).getReg() == ARM::CPSR)
2531 // If the instruction sets the flag, do not attempt this optimization
2532 // since it may change the semantics of the code.
2536 unsigned UseOpc = UseMI->getOpcode();
2537 unsigned NewUseOpc = 0;
2538 uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
2539 uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
2540 bool Commute = false;
2542 default: return false;
2550 case ARM::t2EORrr: {
2551 Commute = UseMI->getOperand(2).getReg() != Reg;
2558 NewUseOpc = ARM::SUBri;
2564 if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
2566 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
2567 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
2570 case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
2571 case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
2572 case ARM::EORrr: NewUseOpc = ARM::EORri; break;
2576 case ARM::t2SUBrr: {
2580 NewUseOpc = ARM::t2SUBri;
2585 case ARM::t2EORrr: {
2586 if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
2588 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
2589 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
2592 case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
2593 case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
2594 case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
2602 unsigned OpIdx = Commute ? 2 : 1;
2603 unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
2604 bool isKill = UseMI->getOperand(OpIdx).isKill();
2605 unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
2606 AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
2607 UseMI, UseMI->getDebugLoc(),
2608 get(NewUseOpc), NewReg)
2609 .addReg(Reg1, getKillRegState(isKill))
2610 .addImm(SOImmValV1)));
2611 UseMI->setDesc(get(NewUseOpc));
2612 UseMI->getOperand(1).setReg(NewReg);
2613 UseMI->getOperand(1).setIsKill();
2614 UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
2615 DefMI->eraseFromParent();
2619 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
2620 const MachineInstr *MI) {
2621 switch (MI->getOpcode()) {
2623 const MCInstrDesc &Desc = MI->getDesc();
2624 int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
2625 assert(UOps >= 0 && "bad # UOps");
2633 unsigned ShOpVal = MI->getOperand(3).getImm();
2634 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2635 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2638 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2639 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2646 if (!MI->getOperand(2).getReg())
2649 unsigned ShOpVal = MI->getOperand(3).getImm();
2650 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2651 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2654 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2655 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2662 return (ARM_AM::getAM3Op(MI->getOperand(3).getImm()) == ARM_AM::sub) ? 3:2;
2664 case ARM::LDRSB_POST:
2665 case ARM::LDRSH_POST: {
2666 unsigned Rt = MI->getOperand(0).getReg();
2667 unsigned Rm = MI->getOperand(3).getReg();
2668 return (Rt == Rm) ? 4 : 3;
2671 case ARM::LDR_PRE_REG:
2672 case ARM::LDRB_PRE_REG: {
2673 unsigned Rt = MI->getOperand(0).getReg();
2674 unsigned Rm = MI->getOperand(3).getReg();
2677 unsigned ShOpVal = MI->getOperand(4).getImm();
2678 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2679 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2682 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2683 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2688 case ARM::STR_PRE_REG:
2689 case ARM::STRB_PRE_REG: {
2690 unsigned ShOpVal = MI->getOperand(4).getImm();
2691 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2692 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2695 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2696 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2702 case ARM::STRH_PRE: {
2703 unsigned Rt = MI->getOperand(0).getReg();
2704 unsigned Rm = MI->getOperand(3).getReg();
2709 return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub)
2713 case ARM::LDR_POST_REG:
2714 case ARM::LDRB_POST_REG:
2715 case ARM::LDRH_POST: {
2716 unsigned Rt = MI->getOperand(0).getReg();
2717 unsigned Rm = MI->getOperand(3).getReg();
2718 return (Rt == Rm) ? 3 : 2;
2721 case ARM::LDR_PRE_IMM:
2722 case ARM::LDRB_PRE_IMM:
2723 case ARM::LDR_POST_IMM:
2724 case ARM::LDRB_POST_IMM:
2725 case ARM::STRB_POST_IMM:
2726 case ARM::STRB_POST_REG:
2727 case ARM::STRB_PRE_IMM:
2728 case ARM::STRH_POST:
2729 case ARM::STR_POST_IMM:
2730 case ARM::STR_POST_REG:
2731 case ARM::STR_PRE_IMM:
2734 case ARM::LDRSB_PRE:
2735 case ARM::LDRSH_PRE: {
2736 unsigned Rm = MI->getOperand(3).getReg();
2739 unsigned Rt = MI->getOperand(0).getReg();
2742 unsigned ShOpVal = MI->getOperand(4).getImm();
2743 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2744 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2747 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2748 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2754 unsigned Rt = MI->getOperand(0).getReg();
2755 unsigned Rn = MI->getOperand(2).getReg();
2756 unsigned Rm = MI->getOperand(3).getReg();
2758 return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2759 return (Rt == Rn) ? 3 : 2;
2763 unsigned Rm = MI->getOperand(3).getReg();
2765 return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2769 case ARM::LDRD_POST:
2770 case ARM::t2LDRD_POST:
2773 case ARM::STRD_POST:
2774 case ARM::t2STRD_POST:
2777 case ARM::LDRD_PRE: {
2778 unsigned Rt = MI->getOperand(0).getReg();
2779 unsigned Rn = MI->getOperand(3).getReg();
2780 unsigned Rm = MI->getOperand(4).getReg();
2782 return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2783 return (Rt == Rn) ? 4 : 3;
2786 case ARM::t2LDRD_PRE: {
2787 unsigned Rt = MI->getOperand(0).getReg();
2788 unsigned Rn = MI->getOperand(3).getReg();
2789 return (Rt == Rn) ? 4 : 3;
2792 case ARM::STRD_PRE: {
2793 unsigned Rm = MI->getOperand(4).getReg();
2795 return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2799 case ARM::t2STRD_PRE:
2802 case ARM::t2LDR_POST:
2803 case ARM::t2LDRB_POST:
2804 case ARM::t2LDRB_PRE:
2805 case ARM::t2LDRSBi12:
2806 case ARM::t2LDRSBi8:
2807 case ARM::t2LDRSBpci:
2809 case ARM::t2LDRH_POST:
2810 case ARM::t2LDRH_PRE:
2812 case ARM::t2LDRSB_POST:
2813 case ARM::t2LDRSB_PRE:
2814 case ARM::t2LDRSH_POST:
2815 case ARM::t2LDRSH_PRE:
2816 case ARM::t2LDRSHi12:
2817 case ARM::t2LDRSHi8:
2818 case ARM::t2LDRSHpci:
2822 case ARM::t2LDRDi8: {
2823 unsigned Rt = MI->getOperand(0).getReg();
2824 unsigned Rn = MI->getOperand(2).getReg();
2825 return (Rt == Rn) ? 3 : 2;
2828 case ARM::t2STRB_POST:
2829 case ARM::t2STRB_PRE:
2832 case ARM::t2STRH_POST:
2833 case ARM::t2STRH_PRE:
2835 case ARM::t2STR_POST:
2836 case ARM::t2STR_PRE:
2842 // Return the number of 32-bit words loaded by LDM or stored by STM. If this
2843 // can't be easily determined return 0 (missing MachineMemOperand).
2845 // FIXME: The current MachineInstr design does not support relying on machine
2846 // mem operands to determine the width of a memory access. Instead, we expect
2847 // the target to provide this information based on the instruction opcode and
2848 // operands. However, using MachineMemOperand is a the best solution now for
2851 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
2852 // operands. This is much more dangerous than using the MachineMemOperand
2853 // sizes because CodeGen passes can insert/remove optional machine operands. In
2854 // fact, it's totally incorrect for preRA passes and appears to be wrong for
2855 // postRA passes as well.
2857 // 2) getNumLDMAddresses is only used by the scheduling machine model and any
2858 // machine model that calls this should handle the unknown (zero size) case.
2860 // Long term, we should require a target hook that verifies MachineMemOperand
2861 // sizes during MC lowering. That target hook should be local to MC lowering
2862 // because we can't ensure that it is aware of other MI forms. Doing this will
2863 // ensure that MachineMemOperands are correctly propagated through all passes.
2864 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr *MI) const {
2866 for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
2867 E = MI->memoperands_end(); I != E; ++I) {
2868 Size += (*I)->getSize();
2874 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
2875 const MachineInstr *MI) const {
2876 if (!ItinData || ItinData->isEmpty())
2879 const MCInstrDesc &Desc = MI->getDesc();
2880 unsigned Class = Desc.getSchedClass();
2881 int ItinUOps = ItinData->getNumMicroOps(Class);
2882 if (ItinUOps >= 0) {
2883 if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
2884 return getNumMicroOpsSwiftLdSt(ItinData, MI);
2889 unsigned Opc = MI->getOpcode();
2892 llvm_unreachable("Unexpected multi-uops instruction!");
2897 // The number of uOps for load / store multiple are determined by the number
2900 // On Cortex-A8, each pair of register loads / stores can be scheduled on the
2901 // same cycle. The scheduling for the first load / store must be done
2902 // separately by assuming the address is not 64-bit aligned.
2904 // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
2905 // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON
2906 // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
2908 case ARM::VLDMDIA_UPD:
2909 case ARM::VLDMDDB_UPD:
2911 case ARM::VLDMSIA_UPD:
2912 case ARM::VLDMSDB_UPD:
2914 case ARM::VSTMDIA_UPD:
2915 case ARM::VSTMDDB_UPD:
2917 case ARM::VSTMSIA_UPD:
2918 case ARM::VSTMSDB_UPD: {
2919 unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
2920 return (NumRegs / 2) + (NumRegs % 2) + 1;
2923 case ARM::LDMIA_RET:
2928 case ARM::LDMIA_UPD:
2929 case ARM::LDMDA_UPD:
2930 case ARM::LDMDB_UPD:
2931 case ARM::LDMIB_UPD:
2936 case ARM::STMIA_UPD:
2937 case ARM::STMDA_UPD:
2938 case ARM::STMDB_UPD:
2939 case ARM::STMIB_UPD:
2941 case ARM::tLDMIA_UPD:
2942 case ARM::tSTMIA_UPD:
2946 case ARM::t2LDMIA_RET:
2949 case ARM::t2LDMIA_UPD:
2950 case ARM::t2LDMDB_UPD:
2953 case ARM::t2STMIA_UPD:
2954 case ARM::t2STMDB_UPD: {
2955 unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
2956 if (Subtarget.isSwift()) {
2957 int UOps = 1 + NumRegs; // One for address computation, one for each ld / st.
2960 case ARM::VLDMDIA_UPD:
2961 case ARM::VLDMDDB_UPD:
2962 case ARM::VLDMSIA_UPD:
2963 case ARM::VLDMSDB_UPD:
2964 case ARM::VSTMDIA_UPD:
2965 case ARM::VSTMDDB_UPD:
2966 case ARM::VSTMSIA_UPD:
2967 case ARM::VSTMSDB_UPD:
2968 case ARM::LDMIA_UPD:
2969 case ARM::LDMDA_UPD:
2970 case ARM::LDMDB_UPD:
2971 case ARM::LDMIB_UPD:
2972 case ARM::STMIA_UPD:
2973 case ARM::STMDA_UPD:
2974 case ARM::STMDB_UPD:
2975 case ARM::STMIB_UPD:
2976 case ARM::tLDMIA_UPD:
2977 case ARM::tSTMIA_UPD:
2978 case ARM::t2LDMIA_UPD:
2979 case ARM::t2LDMDB_UPD:
2980 case ARM::t2STMIA_UPD:
2981 case ARM::t2STMDB_UPD:
2982 ++UOps; // One for base register writeback.
2984 case ARM::LDMIA_RET:
2986 case ARM::t2LDMIA_RET:
2987 UOps += 2; // One for base reg wb, one for write to pc.
2991 } else if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
2994 // 4 registers would be issued: 2, 2.
2995 // 5 registers would be issued: 2, 2, 1.
2996 int A8UOps = (NumRegs / 2);
3000 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3001 int A9UOps = (NumRegs / 2);
3002 // If there are odd number of registers or if it's not 64-bit aligned,
3003 // then it takes an extra AGU (Address Generation Unit) cycle.
3004 if ((NumRegs % 2) ||
3005 !MI->hasOneMemOperand() ||
3006 (*MI->memoperands_begin())->getAlignment() < 8)
3010 // Assume the worst.
3018 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
3019 const MCInstrDesc &DefMCID,
3021 unsigned DefIdx, unsigned DefAlign) const {
3022 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3024 // Def is the address writeback.
3025 return ItinData->getOperandCycle(DefClass, DefIdx);
3028 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3029 // (regno / 2) + (regno % 2) + 1
3030 DefCycle = RegNo / 2 + 1;
3033 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3035 bool isSLoad = false;
3037 switch (DefMCID.getOpcode()) {
3040 case ARM::VLDMSIA_UPD:
3041 case ARM::VLDMSDB_UPD:
3046 // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3047 // then it takes an extra cycle.
3048 if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
3051 // Assume the worst.
3052 DefCycle = RegNo + 2;
3059 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
3060 const MCInstrDesc &DefMCID,
3062 unsigned DefIdx, unsigned DefAlign) const {
3063 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3065 // Def is the address writeback.
3066 return ItinData->getOperandCycle(DefClass, DefIdx);
3069 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3070 // 4 registers would be issued: 1, 2, 1.
3071 // 5 registers would be issued: 1, 2, 2.
3072 DefCycle = RegNo / 2;
3075 // Result latency is issue cycle + 2: E2.
3077 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3078 DefCycle = (RegNo / 2);
3079 // If there are odd number of registers or if it's not 64-bit aligned,
3080 // then it takes an extra AGU (Address Generation Unit) cycle.
3081 if ((RegNo % 2) || DefAlign < 8)
3083 // Result latency is AGU cycles + 2.
3086 // Assume the worst.
3087 DefCycle = RegNo + 2;
3094 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
3095 const MCInstrDesc &UseMCID,
3097 unsigned UseIdx, unsigned UseAlign) const {
3098 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3100 return ItinData->getOperandCycle(UseClass, UseIdx);
3103 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3104 // (regno / 2) + (regno % 2) + 1
3105 UseCycle = RegNo / 2 + 1;
3108 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3110 bool isSStore = false;
3112 switch (UseMCID.getOpcode()) {
3115 case ARM::VSTMSIA_UPD:
3116 case ARM::VSTMSDB_UPD:
3121 // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3122 // then it takes an extra cycle.
3123 if ((isSStore && (RegNo % 2)) || UseAlign < 8)
3126 // Assume the worst.
3127 UseCycle = RegNo + 2;
3134 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
3135 const MCInstrDesc &UseMCID,
3137 unsigned UseIdx, unsigned UseAlign) const {
3138 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3140 return ItinData->getOperandCycle(UseClass, UseIdx);
3143 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3144 UseCycle = RegNo / 2;
3149 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3150 UseCycle = (RegNo / 2);
3151 // If there are odd number of registers or if it's not 64-bit aligned,
3152 // then it takes an extra AGU (Address Generation Unit) cycle.
3153 if ((RegNo % 2) || UseAlign < 8)
3156 // Assume the worst.
3163 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3164 const MCInstrDesc &DefMCID,
3165 unsigned DefIdx, unsigned DefAlign,
3166 const MCInstrDesc &UseMCID,
3167 unsigned UseIdx, unsigned UseAlign) const {
3168 unsigned DefClass = DefMCID.getSchedClass();
3169 unsigned UseClass = UseMCID.getSchedClass();
3171 if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
3172 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
3174 // This may be a def / use of a variable_ops instruction, the operand
3175 // latency might be determinable dynamically. Let the target try to
3178 bool LdmBypass = false;
3179 switch (DefMCID.getOpcode()) {
3181 DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3185 case ARM::VLDMDIA_UPD:
3186 case ARM::VLDMDDB_UPD:
3188 case ARM::VLDMSIA_UPD:
3189 case ARM::VLDMSDB_UPD:
3190 DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3193 case ARM::LDMIA_RET:
3198 case ARM::LDMIA_UPD:
3199 case ARM::LDMDA_UPD:
3200 case ARM::LDMDB_UPD:
3201 case ARM::LDMIB_UPD:
3203 case ARM::tLDMIA_UPD:
3205 case ARM::t2LDMIA_RET:
3208 case ARM::t2LDMIA_UPD:
3209 case ARM::t2LDMDB_UPD:
3211 DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3216 // We can't seem to determine the result latency of the def, assume it's 2.
3220 switch (UseMCID.getOpcode()) {
3222 UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
3226 case ARM::VSTMDIA_UPD:
3227 case ARM::VSTMDDB_UPD:
3229 case ARM::VSTMSIA_UPD:
3230 case ARM::VSTMSDB_UPD:
3231 UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3238 case ARM::STMIA_UPD:
3239 case ARM::STMDA_UPD:
3240 case ARM::STMDB_UPD:
3241 case ARM::STMIB_UPD:
3242 case ARM::tSTMIA_UPD:
3247 case ARM::t2STMIA_UPD:
3248 case ARM::t2STMDB_UPD:
3249 UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3254 // Assume it's read in the first stage.
3257 UseCycle = DefCycle - UseCycle + 1;
3260 // It's a variable_ops instruction so we can't use DefIdx here. Just use
3261 // first def operand.
3262 if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
3265 } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
3266 UseClass, UseIdx)) {
3274 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
3275 const MachineInstr *MI, unsigned Reg,
3276 unsigned &DefIdx, unsigned &Dist) {
3279 MachineBasicBlock::const_iterator I = MI; ++I;
3280 MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
3281 assert(II->isInsideBundle() && "Empty bundle?");
3284 while (II->isInsideBundle()) {
3285 Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
3292 assert(Idx != -1 && "Cannot find bundled definition!");
3297 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
3298 const MachineInstr *MI, unsigned Reg,
3299 unsigned &UseIdx, unsigned &Dist) {
3302 MachineBasicBlock::const_instr_iterator II = MI; ++II;
3303 assert(II->isInsideBundle() && "Empty bundle?");
3304 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3306 // FIXME: This doesn't properly handle multiple uses.
3308 while (II != E && II->isInsideBundle()) {
3309 Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
3312 if (II->getOpcode() != ARM::t2IT)
3326 /// Return the number of cycles to add to (or subtract from) the static
3327 /// itinerary based on the def opcode and alignment. The caller will ensure that
3328 /// adjusted latency is at least one cycle.
3329 static int adjustDefLatency(const ARMSubtarget &Subtarget,
3330 const MachineInstr *DefMI,
3331 const MCInstrDesc *DefMCID, unsigned DefAlign) {
3333 if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
3334 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3335 // variants are one cycle cheaper.
3336 switch (DefMCID->getOpcode()) {
3340 unsigned ShOpVal = DefMI->getOperand(3).getImm();
3341 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3343 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3350 case ARM::t2LDRSHs: {
3351 // Thumb2 mode: lsl only.
3352 unsigned ShAmt = DefMI->getOperand(3).getImm();
3353 if (ShAmt == 0 || ShAmt == 2)
3358 } else if (Subtarget.isSwift()) {
3359 // FIXME: Properly handle all of the latency adjustments for address
3361 switch (DefMCID->getOpcode()) {
3365 unsigned ShOpVal = DefMI->getOperand(3).getImm();
3366 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3367 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3370 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3371 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3374 ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3381 case ARM::t2LDRSHs: {
3382 // Thumb2 mode: lsl only.
3383 unsigned ShAmt = DefMI->getOperand(3).getImm();
3384 if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
3391 if (DefAlign < 8 && Subtarget.isLikeA9()) {
3392 switch (DefMCID->getOpcode()) {
3398 case ARM::VLD1q8wb_fixed:
3399 case ARM::VLD1q16wb_fixed:
3400 case ARM::VLD1q32wb_fixed:
3401 case ARM::VLD1q64wb_fixed:
3402 case ARM::VLD1q8wb_register:
3403 case ARM::VLD1q16wb_register:
3404 case ARM::VLD1q32wb_register:
3405 case ARM::VLD1q64wb_register:
3412 case ARM::VLD2d8wb_fixed:
3413 case ARM::VLD2d16wb_fixed:
3414 case ARM::VLD2d32wb_fixed:
3415 case ARM::VLD2q8wb_fixed:
3416 case ARM::VLD2q16wb_fixed:
3417 case ARM::VLD2q32wb_fixed:
3418 case ARM::VLD2d8wb_register:
3419 case ARM::VLD2d16wb_register:
3420 case ARM::VLD2d32wb_register:
3421 case ARM::VLD2q8wb_register:
3422 case ARM::VLD2q16wb_register:
3423 case ARM::VLD2q32wb_register:
3428 case ARM::VLD3d8_UPD:
3429 case ARM::VLD3d16_UPD:
3430 case ARM::VLD3d32_UPD:
3431 case ARM::VLD1d64Twb_fixed:
3432 case ARM::VLD1d64Twb_register:
3433 case ARM::VLD3q8_UPD:
3434 case ARM::VLD3q16_UPD:
3435 case ARM::VLD3q32_UPD:
3440 case ARM::VLD4d8_UPD:
3441 case ARM::VLD4d16_UPD:
3442 case ARM::VLD4d32_UPD:
3443 case ARM::VLD1d64Qwb_fixed:
3444 case ARM::VLD1d64Qwb_register:
3445 case ARM::VLD4q8_UPD:
3446 case ARM::VLD4q16_UPD:
3447 case ARM::VLD4q32_UPD:
3448 case ARM::VLD1DUPq8:
3449 case ARM::VLD1DUPq16:
3450 case ARM::VLD1DUPq32:
3451 case ARM::VLD1DUPq8wb_fixed:
3452 case ARM::VLD1DUPq16wb_fixed:
3453 case ARM::VLD1DUPq32wb_fixed:
3454 case ARM::VLD1DUPq8wb_register:
3455 case ARM::VLD1DUPq16wb_register:
3456 case ARM::VLD1DUPq32wb_register:
3457 case ARM::VLD2DUPd8:
3458 case ARM::VLD2DUPd16:
3459 case ARM::VLD2DUPd32:
3460 case ARM::VLD2DUPd8wb_fixed:
3461 case ARM::VLD2DUPd16wb_fixed:
3462 case ARM::VLD2DUPd32wb_fixed:
3463 case ARM::VLD2DUPd8wb_register:
3464 case ARM::VLD2DUPd16wb_register:
3465 case ARM::VLD2DUPd32wb_register:
3466 case ARM::VLD4DUPd8:
3467 case ARM::VLD4DUPd16:
3468 case ARM::VLD4DUPd32:
3469 case ARM::VLD4DUPd8_UPD:
3470 case ARM::VLD4DUPd16_UPD:
3471 case ARM::VLD4DUPd32_UPD:
3473 case ARM::VLD1LNd16:
3474 case ARM::VLD1LNd32:
3475 case ARM::VLD1LNd8_UPD:
3476 case ARM::VLD1LNd16_UPD:
3477 case ARM::VLD1LNd32_UPD:
3479 case ARM::VLD2LNd16:
3480 case ARM::VLD2LNd32:
3481 case ARM::VLD2LNq16:
3482 case ARM::VLD2LNq32:
3483 case ARM::VLD2LNd8_UPD:
3484 case ARM::VLD2LNd16_UPD:
3485 case ARM::VLD2LNd32_UPD:
3486 case ARM::VLD2LNq16_UPD:
3487 case ARM::VLD2LNq32_UPD:
3489 case ARM::VLD4LNd16:
3490 case ARM::VLD4LNd32:
3491 case ARM::VLD4LNq16:
3492 case ARM::VLD4LNq32:
3493 case ARM::VLD4LNd8_UPD:
3494 case ARM::VLD4LNd16_UPD:
3495 case ARM::VLD4LNd32_UPD:
3496 case ARM::VLD4LNq16_UPD:
3497 case ARM::VLD4LNq32_UPD:
3498 // If the address is not 64-bit aligned, the latencies of these
3499 // instructions increases by one.
3510 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3511 const MachineInstr *DefMI, unsigned DefIdx,
3512 const MachineInstr *UseMI,
3513 unsigned UseIdx) const {
3514 // No operand latency. The caller may fall back to getInstrLatency.
3515 if (!ItinData || ItinData->isEmpty())
3518 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
3519 unsigned Reg = DefMO.getReg();
3520 const MCInstrDesc *DefMCID = &DefMI->getDesc();
3521 const MCInstrDesc *UseMCID = &UseMI->getDesc();
3523 unsigned DefAdj = 0;
3524 if (DefMI->isBundle()) {
3525 DefMI = getBundledDefMI(&getRegisterInfo(), DefMI, Reg, DefIdx, DefAdj);
3526 DefMCID = &DefMI->getDesc();
3528 if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
3529 DefMI->isRegSequence() || DefMI->isImplicitDef()) {
3533 unsigned UseAdj = 0;
3534 if (UseMI->isBundle()) {
3536 const MachineInstr *NewUseMI = getBundledUseMI(&getRegisterInfo(), UseMI,
3537 Reg, NewUseIdx, UseAdj);
3543 UseMCID = &UseMI->getDesc();
3546 if (Reg == ARM::CPSR) {
3547 if (DefMI->getOpcode() == ARM::FMSTAT) {
3548 // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
3549 return Subtarget.isLikeA9() ? 1 : 20;
3552 // CPSR set and branch can be paired in the same cycle.
3553 if (UseMI->isBranch())
3556 // Otherwise it takes the instruction latency (generally one).
3557 unsigned Latency = getInstrLatency(ItinData, DefMI);
3559 // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
3560 // its uses. Instructions which are otherwise scheduled between them may
3561 // incur a code size penalty (not able to use the CPSR setting 16-bit
3563 if (Latency > 0 && Subtarget.isThumb2()) {
3564 const MachineFunction *MF = DefMI->getParent()->getParent();
3565 if (MF->getFunction()->getAttributes().
3566 hasAttribute(AttributeSet::FunctionIndex,
3567 Attribute::OptimizeForSize))
3573 if (DefMO.isImplicit() || UseMI->getOperand(UseIdx).isImplicit())
3576 unsigned DefAlign = DefMI->hasOneMemOperand()
3577 ? (*DefMI->memoperands_begin())->getAlignment() : 0;
3578 unsigned UseAlign = UseMI->hasOneMemOperand()
3579 ? (*UseMI->memoperands_begin())->getAlignment() : 0;
3581 // Get the itinerary's latency if possible, and handle variable_ops.
3582 int Latency = getOperandLatency(ItinData, *DefMCID, DefIdx, DefAlign,
3583 *UseMCID, UseIdx, UseAlign);
3584 // Unable to find operand latency. The caller may resort to getInstrLatency.
3588 // Adjust for IT block position.
3589 int Adj = DefAdj + UseAdj;
3591 // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3592 Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
3593 if (Adj >= 0 || (int)Latency > -Adj) {
3594 return Latency + Adj;
3596 // Return the itinerary latency, which may be zero but not less than zero.
3601 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3602 SDNode *DefNode, unsigned DefIdx,
3603 SDNode *UseNode, unsigned UseIdx) const {
3604 if (!DefNode->isMachineOpcode())
3607 const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
3609 if (isZeroCost(DefMCID.Opcode))
3612 if (!ItinData || ItinData->isEmpty())
3613 return DefMCID.mayLoad() ? 3 : 1;
3615 if (!UseNode->isMachineOpcode()) {
3616 int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
3617 if (Subtarget.isLikeA9() || Subtarget.isSwift())
3618 return Latency <= 2 ? 1 : Latency - 1;
3620 return Latency <= 3 ? 1 : Latency - 2;
3623 const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
3624 const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
3625 unsigned DefAlign = !DefMN->memoperands_empty()
3626 ? (*DefMN->memoperands_begin())->getAlignment() : 0;
3627 const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
3628 unsigned UseAlign = !UseMN->memoperands_empty()
3629 ? (*UseMN->memoperands_begin())->getAlignment() : 0;
3630 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
3631 UseMCID, UseIdx, UseAlign);
3634 (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
3635 Subtarget.isCortexA7())) {
3636 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3637 // variants are one cycle cheaper.
3638 switch (DefMCID.getOpcode()) {
3643 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3644 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3646 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3653 case ARM::t2LDRSHs: {
3654 // Thumb2 mode: lsl only.
3656 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3657 if (ShAmt == 0 || ShAmt == 2)
3662 } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
3663 // FIXME: Properly handle all of the latency adjustments for address
3665 switch (DefMCID.getOpcode()) {
3670 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3671 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3673 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3674 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3676 else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3683 case ARM::t2LDRSHs: {
3684 // Thumb2 mode: lsl 0-3 only.
3691 if (DefAlign < 8 && Subtarget.isLikeA9())
3692 switch (DefMCID.getOpcode()) {
3698 case ARM::VLD1q8wb_register:
3699 case ARM::VLD1q16wb_register:
3700 case ARM::VLD1q32wb_register:
3701 case ARM::VLD1q64wb_register:
3702 case ARM::VLD1q8wb_fixed:
3703 case ARM::VLD1q16wb_fixed:
3704 case ARM::VLD1q32wb_fixed:
3705 case ARM::VLD1q64wb_fixed:
3709 case ARM::VLD2q8Pseudo:
3710 case ARM::VLD2q16Pseudo:
3711 case ARM::VLD2q32Pseudo:
3712 case ARM::VLD2d8wb_fixed:
3713 case ARM::VLD2d16wb_fixed:
3714 case ARM::VLD2d32wb_fixed:
3715 case ARM::VLD2q8PseudoWB_fixed:
3716 case ARM::VLD2q16PseudoWB_fixed:
3717 case ARM::VLD2q32PseudoWB_fixed:
3718 case ARM::VLD2d8wb_register:
3719 case ARM::VLD2d16wb_register:
3720 case ARM::VLD2d32wb_register:
3721 case ARM::VLD2q8PseudoWB_register:
3722 case ARM::VLD2q16PseudoWB_register:
3723 case ARM::VLD2q32PseudoWB_register:
3724 case ARM::VLD3d8Pseudo:
3725 case ARM::VLD3d16Pseudo:
3726 case ARM::VLD3d32Pseudo:
3727 case ARM::VLD1d64TPseudo:
3728 case ARM::VLD1d64TPseudoWB_fixed:
3729 case ARM::VLD3d8Pseudo_UPD:
3730 case ARM::VLD3d16Pseudo_UPD:
3731 case ARM::VLD3d32Pseudo_UPD:
3732 case ARM::VLD3q8Pseudo_UPD:
3733 case ARM::VLD3q16Pseudo_UPD:
3734 case ARM::VLD3q32Pseudo_UPD:
3735 case ARM::VLD3q8oddPseudo:
3736 case ARM::VLD3q16oddPseudo:
3737 case ARM::VLD3q32oddPseudo:
3738 case ARM::VLD3q8oddPseudo_UPD:
3739 case ARM::VLD3q16oddPseudo_UPD:
3740 case ARM::VLD3q32oddPseudo_UPD:
3741 case ARM::VLD4d8Pseudo:
3742 case ARM::VLD4d16Pseudo:
3743 case ARM::VLD4d32Pseudo:
3744 case ARM::VLD1d64QPseudo:
3745 case ARM::VLD1d64QPseudoWB_fixed:
3746 case ARM::VLD4d8Pseudo_UPD:
3747 case ARM::VLD4d16Pseudo_UPD:
3748 case ARM::VLD4d32Pseudo_UPD:
3749 case ARM::VLD4q8Pseudo_UPD:
3750 case ARM::VLD4q16Pseudo_UPD:
3751 case ARM::VLD4q32Pseudo_UPD:
3752 case ARM::VLD4q8oddPseudo:
3753 case ARM::VLD4q16oddPseudo:
3754 case ARM::VLD4q32oddPseudo:
3755 case ARM::VLD4q8oddPseudo_UPD:
3756 case ARM::VLD4q16oddPseudo_UPD:
3757 case ARM::VLD4q32oddPseudo_UPD:
3758 case ARM::VLD1DUPq8:
3759 case ARM::VLD1DUPq16:
3760 case ARM::VLD1DUPq32:
3761 case ARM::VLD1DUPq8wb_fixed:
3762 case ARM::VLD1DUPq16wb_fixed:
3763 case ARM::VLD1DUPq32wb_fixed:
3764 case ARM::VLD1DUPq8wb_register:
3765 case ARM::VLD1DUPq16wb_register:
3766 case ARM::VLD1DUPq32wb_register:
3767 case ARM::VLD2DUPd8:
3768 case ARM::VLD2DUPd16:
3769 case ARM::VLD2DUPd32:
3770 case ARM::VLD2DUPd8wb_fixed:
3771 case ARM::VLD2DUPd16wb_fixed:
3772 case ARM::VLD2DUPd32wb_fixed:
3773 case ARM::VLD2DUPd8wb_register:
3774 case ARM::VLD2DUPd16wb_register:
3775 case ARM::VLD2DUPd32wb_register:
3776 case ARM::VLD4DUPd8Pseudo:
3777 case ARM::VLD4DUPd16Pseudo:
3778 case ARM::VLD4DUPd32Pseudo:
3779 case ARM::VLD4DUPd8Pseudo_UPD:
3780 case ARM::VLD4DUPd16Pseudo_UPD:
3781 case ARM::VLD4DUPd32Pseudo_UPD:
3782 case ARM::VLD1LNq8Pseudo:
3783 case ARM::VLD1LNq16Pseudo:
3784 case ARM::VLD1LNq32Pseudo:
3785 case ARM::VLD1LNq8Pseudo_UPD:
3786 case ARM::VLD1LNq16Pseudo_UPD:
3787 case ARM::VLD1LNq32Pseudo_UPD:
3788 case ARM::VLD2LNd8Pseudo:
3789 case ARM::VLD2LNd16Pseudo:
3790 case ARM::VLD2LNd32Pseudo:
3791 case ARM::VLD2LNq16Pseudo:
3792 case ARM::VLD2LNq32Pseudo:
3793 case ARM::VLD2LNd8Pseudo_UPD:
3794 case ARM::VLD2LNd16Pseudo_UPD:
3795 case ARM::VLD2LNd32Pseudo_UPD:
3796 case ARM::VLD2LNq16Pseudo_UPD:
3797 case ARM::VLD2LNq32Pseudo_UPD:
3798 case ARM::VLD4LNd8Pseudo:
3799 case ARM::VLD4LNd16Pseudo:
3800 case ARM::VLD4LNd32Pseudo:
3801 case ARM::VLD4LNq16Pseudo:
3802 case ARM::VLD4LNq32Pseudo:
3803 case ARM::VLD4LNd8Pseudo_UPD:
3804 case ARM::VLD4LNd16Pseudo_UPD:
3805 case ARM::VLD4LNd32Pseudo_UPD:
3806 case ARM::VLD4LNq16Pseudo_UPD:
3807 case ARM::VLD4LNq32Pseudo_UPD:
3808 // If the address is not 64-bit aligned, the latencies of these
3809 // instructions increases by one.
3817 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr *MI) const {
3818 if (MI->isCopyLike() || MI->isInsertSubreg() ||
3819 MI->isRegSequence() || MI->isImplicitDef())
3825 const MCInstrDesc &MCID = MI->getDesc();
3827 if (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR)) {
3828 // When predicated, CPSR is an additional source operand for CPSR updating
3829 // instructions, this apparently increases their latencies.
3835 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3836 const MachineInstr *MI,
3837 unsigned *PredCost) const {
3838 if (MI->isCopyLike() || MI->isInsertSubreg() ||
3839 MI->isRegSequence() || MI->isImplicitDef())
3842 // An instruction scheduler typically runs on unbundled instructions, however
3843 // other passes may query the latency of a bundled instruction.
3844 if (MI->isBundle()) {
3845 unsigned Latency = 0;
3846 MachineBasicBlock::const_instr_iterator I = MI;
3847 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3848 while (++I != E && I->isInsideBundle()) {
3849 if (I->getOpcode() != ARM::t2IT)
3850 Latency += getInstrLatency(ItinData, I, PredCost);
3855 const MCInstrDesc &MCID = MI->getDesc();
3856 if (PredCost && (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR))) {
3857 // When predicated, CPSR is an additional source operand for CPSR updating
3858 // instructions, this apparently increases their latencies.
3861 // Be sure to call getStageLatency for an empty itinerary in case it has a
3862 // valid MinLatency property.
3864 return MI->mayLoad() ? 3 : 1;
3866 unsigned Class = MCID.getSchedClass();
3868 // For instructions with variable uops, use uops as latency.
3869 if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
3870 return getNumMicroOps(ItinData, MI);
3872 // For the common case, fall back on the itinerary's latency.
3873 unsigned Latency = ItinData->getStageLatency(Class);
3875 // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3876 unsigned DefAlign = MI->hasOneMemOperand()
3877 ? (*MI->memoperands_begin())->getAlignment() : 0;
3878 int Adj = adjustDefLatency(Subtarget, MI, &MCID, DefAlign);
3879 if (Adj >= 0 || (int)Latency > -Adj) {
3880 return Latency + Adj;
3885 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3886 SDNode *Node) const {
3887 if (!Node->isMachineOpcode())
3890 if (!ItinData || ItinData->isEmpty())
3893 unsigned Opcode = Node->getMachineOpcode();
3896 return ItinData->getStageLatency(get(Opcode).getSchedClass());
3903 bool ARMBaseInstrInfo::
3904 hasHighOperandLatency(const InstrItineraryData *ItinData,
3905 const MachineRegisterInfo *MRI,
3906 const MachineInstr *DefMI, unsigned DefIdx,
3907 const MachineInstr *UseMI, unsigned UseIdx) const {
3908 unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3909 unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
3910 if (Subtarget.isCortexA8() &&
3911 (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
3912 // CortexA8 VFP instructions are not pipelined.
3915 // Hoist VFP / NEON instructions with 4 or higher latency.
3916 int Latency = computeOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
3918 Latency = getInstrLatency(ItinData, DefMI);
3921 return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
3922 UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
3925 bool ARMBaseInstrInfo::
3926 hasLowDefLatency(const InstrItineraryData *ItinData,
3927 const MachineInstr *DefMI, unsigned DefIdx) const {
3928 if (!ItinData || ItinData->isEmpty())
3931 unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3932 if (DDomain == ARMII::DomainGeneral) {
3933 unsigned DefClass = DefMI->getDesc().getSchedClass();
3934 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3935 return (DefCycle != -1 && DefCycle <= 2);
3940 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI,
3941 StringRef &ErrInfo) const {
3942 if (convertAddSubFlagsOpcode(MI->getOpcode())) {
3943 ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
3949 // LoadStackGuard has so far only been implemented for MachO. Different code
3950 // sequence is needed for other targets.
3951 void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
3952 unsigned LoadImmOpc,
3954 Reloc::Model RM) const {
3955 MachineBasicBlock &MBB = *MI->getParent();
3956 DebugLoc DL = MI->getDebugLoc();
3957 unsigned Reg = MI->getOperand(0).getReg();
3958 const GlobalValue *GV =
3959 cast<GlobalValue>((*MI->memoperands_begin())->getValue());
3960 MachineInstrBuilder MIB;
3962 BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
3963 .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY);
3965 if (Subtarget.GVIsIndirectSymbol(GV, RM)) {
3966 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
3967 MIB.addReg(Reg, RegState::Kill).addImm(0);
3968 unsigned Flag = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant;
3969 MachineMemOperand *MMO = MBB.getParent()->
3970 getMachineMemOperand(MachinePointerInfo::getGOT(), Flag, 4, 4);
3971 MIB.addMemOperand(MMO);
3972 AddDefaultPred(MIB);
3975 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
3976 MIB.addReg(Reg, RegState::Kill).addImm(0);
3977 MIB.setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
3978 AddDefaultPred(MIB);
3982 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
3983 unsigned &AddSubOpc,
3984 bool &NegAcc, bool &HasLane) const {
3985 DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
3986 if (I == MLxEntryMap.end())
3989 const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
3990 MulOpc = Entry.MulOpc;
3991 AddSubOpc = Entry.AddSubOpc;
3992 NegAcc = Entry.NegAcc;
3993 HasLane = Entry.HasLane;
3997 //===----------------------------------------------------------------------===//
3998 // Execution domains.
3999 //===----------------------------------------------------------------------===//
4001 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
4002 // and some can go down both. The vmov instructions go down the VFP pipeline,
4003 // but they can be changed to vorr equivalents that are executed by the NEON
4006 // We use the following execution domain numbering:
4014 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
4016 std::pair<uint16_t, uint16_t>
4017 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const {
4018 // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
4019 // if they are not predicated.
4020 if (MI->getOpcode() == ARM::VMOVD && !isPredicated(MI))
4021 return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
4023 // CortexA9 is particularly picky about mixing the two and wants these
4025 if (Subtarget.isCortexA9() && !isPredicated(MI) &&
4026 (MI->getOpcode() == ARM::VMOVRS ||
4027 MI->getOpcode() == ARM::VMOVSR ||
4028 MI->getOpcode() == ARM::VMOVS))
4029 return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
4031 // No other instructions can be swizzled, so just determine their domain.
4032 unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
4034 if (Domain & ARMII::DomainNEON)
4035 return std::make_pair(ExeNEON, 0);
4037 // Certain instructions can go either way on Cortex-A8.
4038 // Treat them as NEON instructions.
4039 if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
4040 return std::make_pair(ExeNEON, 0);
4042 if (Domain & ARMII::DomainVFP)
4043 return std::make_pair(ExeVFP, 0);
4045 return std::make_pair(ExeGeneric, 0);
4048 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
4049 unsigned SReg, unsigned &Lane) {
4050 unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
4053 if (DReg != ARM::NoRegister)
4057 DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
4059 assert(DReg && "S-register with no D super-register?");
4063 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
4064 /// set ImplicitSReg to a register number that must be marked as implicit-use or
4065 /// zero if no register needs to be defined as implicit-use.
4067 /// If the function cannot determine if an SPR should be marked implicit use or
4068 /// not, it returns false.
4070 /// This function handles cases where an instruction is being modified from taking
4071 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
4072 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
4073 /// lane of the DPR).
4075 /// If the other SPR is defined, an implicit-use of it should be added. Else,
4076 /// (including the case where the DPR itself is defined), it should not.
4078 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
4080 unsigned DReg, unsigned Lane,
4081 unsigned &ImplicitSReg) {
4082 // If the DPR is defined or used already, the other SPR lane will be chained
4083 // correctly, so there is nothing to be done.
4084 if (MI->definesRegister(DReg, TRI) || MI->readsRegister(DReg, TRI)) {
4089 // Otherwise we need to go searching to see if the SPR is set explicitly.
4090 ImplicitSReg = TRI->getSubReg(DReg,
4091 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
4092 MachineBasicBlock::LivenessQueryResult LQR =
4093 MI->getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
4095 if (LQR == MachineBasicBlock::LQR_Live)
4097 else if (LQR == MachineBasicBlock::LQR_Unknown)
4100 // If the register is known not to be live, there is no need to add an
4107 ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const {
4108 unsigned DstReg, SrcReg, DReg;
4110 MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
4111 const TargetRegisterInfo *TRI = &getRegisterInfo();
4112 switch (MI->getOpcode()) {
4114 llvm_unreachable("cannot handle opcode!");
4117 if (Domain != ExeNEON)
4120 // Zap the predicate operands.
4121 assert(!isPredicated(MI) && "Cannot predicate a VORRd");
4123 // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
4124 DstReg = MI->getOperand(0).getReg();
4125 SrcReg = MI->getOperand(1).getReg();
4127 for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4128 MI->RemoveOperand(i-1);
4130 // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
4131 MI->setDesc(get(ARM::VORRd));
4132 AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
4137 if (Domain != ExeNEON)
4139 assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
4141 // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
4142 DstReg = MI->getOperand(0).getReg();
4143 SrcReg = MI->getOperand(1).getReg();
4145 for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4146 MI->RemoveOperand(i-1);
4148 DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
4150 // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
4151 // Note that DSrc has been widened and the other lane may be undef, which
4152 // contaminates the entire register.
4153 MI->setDesc(get(ARM::VGETLNi32));
4154 AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
4155 .addReg(DReg, RegState::Undef)
4158 // The old source should be an implicit use, otherwise we might think it
4159 // was dead before here.
4160 MIB.addReg(SrcReg, RegState::Implicit);
4163 if (Domain != ExeNEON)
4165 assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
4167 // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
4168 DstReg = MI->getOperand(0).getReg();
4169 SrcReg = MI->getOperand(1).getReg();
4171 DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
4173 unsigned ImplicitSReg;
4174 if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
4177 for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4178 MI->RemoveOperand(i-1);
4180 // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
4181 // Again DDst may be undefined at the beginning of this instruction.
4182 MI->setDesc(get(ARM::VSETLNi32));
4183 MIB.addReg(DReg, RegState::Define)
4184 .addReg(DReg, getUndefRegState(!MI->readsRegister(DReg, TRI)))
4187 AddDefaultPred(MIB);
4189 // The narrower destination must be marked as set to keep previous chains
4191 MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
4192 if (ImplicitSReg != 0)
4193 MIB.addReg(ImplicitSReg, RegState::Implicit);
4197 if (Domain != ExeNEON)
4200 // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
4201 DstReg = MI->getOperand(0).getReg();
4202 SrcReg = MI->getOperand(1).getReg();
4204 unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
4205 DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
4206 DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
4208 unsigned ImplicitSReg;
4209 if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
4212 for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4213 MI->RemoveOperand(i-1);
4216 // Destination can be:
4217 // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
4218 MI->setDesc(get(ARM::VDUPLN32d));
4219 MIB.addReg(DDst, RegState::Define)
4220 .addReg(DDst, getUndefRegState(!MI->readsRegister(DDst, TRI)))
4222 AddDefaultPred(MIB);
4224 // Neither the source or the destination are naturally represented any
4225 // more, so add them in manually.
4226 MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
4227 MIB.addReg(SrcReg, RegState::Implicit);
4228 if (ImplicitSReg != 0)
4229 MIB.addReg(ImplicitSReg, RegState::Implicit);
4233 // In general there's no single instruction that can perform an S <-> S
4234 // move in NEON space, but a pair of VEXT instructions *can* do the
4235 // job. It turns out that the VEXTs needed will only use DSrc once, with
4236 // the position based purely on the combination of lane-0 and lane-1
4237 // involved. For example
4238 // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1
4239 // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1
4240 // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1
4241 // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1
4243 // Pattern of the MachineInstrs is:
4244 // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
4245 MachineInstrBuilder NewMIB;
4246 NewMIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4247 get(ARM::VEXTd32), DDst);
4249 // On the first instruction, both DSrc and DDst may be <undef> if present.
4250 // Specifically when the original instruction didn't have them as an
4252 unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
4253 bool CurUndef = !MI->readsRegister(CurReg, TRI);
4254 NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
4256 CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
4257 CurUndef = !MI->readsRegister(CurReg, TRI);
4258 NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
4261 AddDefaultPred(NewMIB);
4263 if (SrcLane == DstLane)
4264 NewMIB.addReg(SrcReg, RegState::Implicit);
4266 MI->setDesc(get(ARM::VEXTd32));
4267 MIB.addReg(DDst, RegState::Define);
4269 // On the second instruction, DDst has definitely been defined above, so
4270 // it is not <undef>. DSrc, if present, can be <undef> as above.
4271 CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
4272 CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
4273 MIB.addReg(CurReg, getUndefRegState(CurUndef));
4275 CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
4276 CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
4277 MIB.addReg(CurReg, getUndefRegState(CurUndef));
4280 AddDefaultPred(MIB);
4282 if (SrcLane != DstLane)
4283 MIB.addReg(SrcReg, RegState::Implicit);
4285 // As before, the original destination is no longer represented, add it
4287 MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
4288 if (ImplicitSReg != 0)
4289 MIB.addReg(ImplicitSReg, RegState::Implicit);
4296 //===----------------------------------------------------------------------===//
4297 // Partial register updates
4298 //===----------------------------------------------------------------------===//
4300 // Swift renames NEON registers with 64-bit granularity. That means any
4301 // instruction writing an S-reg implicitly reads the containing D-reg. The
4302 // problem is mostly avoided by translating f32 operations to v2f32 operations
4303 // on D-registers, but f32 loads are still a problem.
4305 // These instructions can load an f32 into a NEON register:
4307 // VLDRS - Only writes S, partial D update.
4308 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
4309 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
4311 // FCONSTD can be used as a dependency-breaking instruction.
4312 unsigned ARMBaseInstrInfo::
4313 getPartialRegUpdateClearance(const MachineInstr *MI,
4315 const TargetRegisterInfo *TRI) const {
4316 if (!SwiftPartialUpdateClearance ||
4317 !(Subtarget.isSwift() || Subtarget.isCortexA15()))
4320 assert(TRI && "Need TRI instance");
4322 const MachineOperand &MO = MI->getOperand(OpNum);
4325 unsigned Reg = MO.getReg();
4328 switch(MI->getOpcode()) {
4329 // Normal instructions writing only an S-register.
4334 case ARM::VMOVv4i16:
4335 case ARM::VMOVv2i32:
4336 case ARM::VMOVv2f32:
4337 case ARM::VMOVv1i64:
4338 UseOp = MI->findRegisterUseOperandIdx(Reg, false, TRI);
4341 // Explicitly reads the dependency.
4342 case ARM::VLD1LNd32:
4349 // If this instruction actually reads a value from Reg, there is no unwanted
4351 if (UseOp != -1 && MI->getOperand(UseOp).readsReg())
4354 // We must be able to clobber the whole D-reg.
4355 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
4356 // Virtual register must be a foo:ssub_0<def,undef> operand.
4357 if (!MO.getSubReg() || MI->readsVirtualRegister(Reg))
4359 } else if (ARM::SPRRegClass.contains(Reg)) {
4360 // Physical register: MI must define the full D-reg.
4361 unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
4363 if (!DReg || !MI->definesRegister(DReg, TRI))
4367 // MI has an unwanted D-register dependency.
4368 // Avoid defs in the previous N instructrions.
4369 return SwiftPartialUpdateClearance;
4372 // Break a partial register dependency after getPartialRegUpdateClearance
4373 // returned non-zero.
4374 void ARMBaseInstrInfo::
4375 breakPartialRegDependency(MachineBasicBlock::iterator MI,
4377 const TargetRegisterInfo *TRI) const {
4378 assert(MI && OpNum < MI->getDesc().getNumDefs() && "OpNum is not a def");
4379 assert(TRI && "Need TRI instance");
4381 const MachineOperand &MO = MI->getOperand(OpNum);
4382 unsigned Reg = MO.getReg();
4383 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
4384 "Can't break virtual register dependencies.");
4385 unsigned DReg = Reg;
4387 // If MI defines an S-reg, find the corresponding D super-register.
4388 if (ARM::SPRRegClass.contains(Reg)) {
4389 DReg = ARM::D0 + (Reg - ARM::S0) / 2;
4390 assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
4393 assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
4394 assert(MI->definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
4396 // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
4397 // the full D-register by loading the same value to both lanes. The
4398 // instruction is micro-coded with 2 uops, so don't do this until we can
4399 // properly schedule micro-coded instructions. The dispatcher stalls cause
4400 // too big regressions.
4402 // Insert the dependency-breaking FCONSTD before MI.
4403 // 96 is the encoding of 0.5, but the actual value doesn't matter here.
4404 AddDefaultPred(BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4405 get(ARM::FCONSTD), DReg).addImm(96));
4406 MI->addRegisterKilled(DReg, TRI, true);
4409 void ARMBaseInstrInfo::getUnconditionalBranch(
4410 MCInst &Branch, const MCSymbolRefExpr *BranchTarget) const {
4411 if (Subtarget.isThumb())
4412 Branch.setOpcode(ARM::tB);
4413 else if (Subtarget.isThumb2())
4414 Branch.setOpcode(ARM::t2B);
4416 Branch.setOpcode(ARM::Bcc);
4418 Branch.addOperand(MCOperand::CreateExpr(BranchTarget));
4419 Branch.addOperand(MCOperand::CreateImm(ARMCC::AL));
4420 Branch.addOperand(MCOperand::CreateReg(0));
4423 void ARMBaseInstrInfo::getTrap(MCInst &MI) const {
4424 if (Subtarget.isThumb())
4425 MI.setOpcode(ARM::tTRAP);
4426 else if (Subtarget.useNaClTrap())
4427 MI.setOpcode(ARM::TRAPNaCl);
4429 MI.setOpcode(ARM::TRAP);
4432 bool ARMBaseInstrInfo::hasNOP() const {
4433 return (Subtarget.getFeatureBits() & ARM::HasV6T2Ops) != 0;
4436 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
4437 if (MI->getNumOperands() < 4)
4439 unsigned ShOpVal = MI->getOperand(3).getImm();
4440 unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
4441 // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
4442 if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
4443 ((ShImm == 1 || ShImm == 2) &&
4444 ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))