1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the Base ARM implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "ARMBaseInstrInfo.h"
14 #include "ARMBaseRegisterInfo.h"
15 #include "ARMConstantPoolValue.h"
16 #include "ARMFeatures.h"
17 #include "ARMHazardRecognizer.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "MCTargetDesc/ARMBaseInfo.h"
22 #include "MVETailPredUtils.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineMemOperand.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/MachineScheduler.h"
40 #include "llvm/CodeGen/MultiHazardRecognizer.h"
41 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
42 #include "llvm/CodeGen/SelectionDAGNodes.h"
43 #include "llvm/CodeGen/TargetInstrInfo.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSchedule.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCInstrDesc.h"
53 #include "llvm/MC/MCInstrItineraries.h"
54 #include "llvm/Support/BranchProbability.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Target/TargetMachine.h"
62 #include <algorithm>
63 #include <cassert>
64 #include <cstdint>
65 #include <iterator>
66 #include <new>
67 #include <utility>
68 #include <vector>
69
70 using namespace llvm;
71
72 #define DEBUG_TYPE "arm-instrinfo"
73
74 #define GET_INSTRINFO_CTOR_DTOR
75 #include "ARMGenInstrInfo.inc"
76
77 static cl::opt<bool>
78 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
79 cl::desc("Enable ARM 2-addr to 3-addr conv"));
80
81 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
82 struct ARM_MLxEntry {
83 uint16_t MLxOpc; // MLA / MLS opcode
84 uint16_t MulOpc; // Expanded multiplication opcode
85 uint16_t AddSubOpc; // Expanded add / sub opcode
86 bool NegAcc; // True if the acc is negated before the add / sub.
87 bool HasLane; // True if instruction has an extra "lane" operand.
88 };
89
90 static const ARM_MLxEntry ARM_MLxTable[] = {
91 // MLxOpc, MulOpc, AddSubOpc, NegAcc, HasLane
92 // fp scalar ops
93 { ARM::VMLAS, ARM::VMULS, ARM::VADDS, false, false },
94 { ARM::VMLSS, ARM::VMULS, ARM::VSUBS, false, false },
95 { ARM::VMLAD, ARM::VMULD, ARM::VADDD, false, false },
96 { ARM::VMLSD, ARM::VMULD, ARM::VSUBD, false, false },
97 { ARM::VNMLAS, ARM::VNMULS, ARM::VSUBS, true, false },
98 { ARM::VNMLSS, ARM::VMULS, ARM::VSUBS, true, false },
99 { ARM::VNMLAD, ARM::VNMULD, ARM::VSUBD, true, false },
100 { ARM::VNMLSD, ARM::VMULD, ARM::VSUBD, true, false },
101
102 // fp SIMD ops
103 { ARM::VMLAfd, ARM::VMULfd, ARM::VADDfd, false, false },
104 { ARM::VMLSfd, ARM::VMULfd, ARM::VSUBfd, false, false },
105 { ARM::VMLAfq, ARM::VMULfq, ARM::VADDfq, false, false },
106 { ARM::VMLSfq, ARM::VMULfq, ARM::VSUBfq, false, false },
107 { ARM::VMLAslfd, ARM::VMULslfd, ARM::VADDfd, false, true },
108 { ARM::VMLSslfd, ARM::VMULslfd, ARM::VSUBfd, false, true },
109 { ARM::VMLAslfq, ARM::VMULslfq, ARM::VADDfq, false, true },
110 { ARM::VMLSslfq, ARM::VMULslfq, ARM::VSUBfq, false, true },
111 };
112
ARMBaseInstrInfo(const ARMSubtarget & STI)113 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
114 : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
115 Subtarget(STI) {
116 for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
117 if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
118 llvm_unreachable("Duplicated entries?");
119 MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
120 MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
121 }
122 }
123
124 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
125 // currently defaults to no prepass hazard recognizer.
126 ScheduleHazardRecognizer *
CreateTargetHazardRecognizer(const TargetSubtargetInfo * STI,const ScheduleDAG * DAG) const127 ARMBaseInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
128 const ScheduleDAG *DAG) const {
129 if (usePreRAHazardRecognizer()) {
130 const InstrItineraryData *II =
131 static_cast<const ARMSubtarget *>(STI)->getInstrItineraryData();
132 return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
133 }
134 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
135 }
136
137 ScheduleHazardRecognizer *ARMBaseInstrInfo::
CreateTargetPostRAHazardRecognizer(const InstrItineraryData * II,const ScheduleDAG * DAG) const138 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
139 const ScheduleDAG *DAG) const {
140 MultiHazardRecognizer *MHR = new MultiHazardRecognizer();
141
142 if (Subtarget.isThumb2() || Subtarget.hasVFP2Base())
143 MHR->AddHazardRecognizer(std::make_unique<ARMHazardRecognizerFPMLx>());
144
145 auto BHR = TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
146 if (BHR)
147 MHR->AddHazardRecognizer(std::unique_ptr<ScheduleHazardRecognizer>(BHR));
148 return MHR;
149 }
150
convertToThreeAddress(MachineFunction::iterator & MFI,MachineInstr & MI,LiveVariables * LV) const151 MachineInstr *ARMBaseInstrInfo::convertToThreeAddress(
152 MachineFunction::iterator &MFI, MachineInstr &MI, LiveVariables *LV) const {
153 // FIXME: Thumb2 support.
154
155 if (!EnableARM3Addr)
156 return nullptr;
157
158 MachineFunction &MF = *MI.getParent()->getParent();
159 uint64_t TSFlags = MI.getDesc().TSFlags;
160 bool isPre = false;
161 switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
162 default: return nullptr;
163 case ARMII::IndexModePre:
164 isPre = true;
165 break;
166 case ARMII::IndexModePost:
167 break;
168 }
169
170 // Try splitting an indexed load/store to an un-indexed one plus an add/sub
171 // operation.
172 unsigned MemOpc = getUnindexedOpcode(MI.getOpcode());
173 if (MemOpc == 0)
174 return nullptr;
175
176 MachineInstr *UpdateMI = nullptr;
177 MachineInstr *MemMI = nullptr;
178 unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
179 const MCInstrDesc &MCID = MI.getDesc();
180 unsigned NumOps = MCID.getNumOperands();
181 bool isLoad = !MI.mayStore();
182 const MachineOperand &WB = isLoad ? MI.getOperand(1) : MI.getOperand(0);
183 const MachineOperand &Base = MI.getOperand(2);
184 const MachineOperand &Offset = MI.getOperand(NumOps - 3);
185 Register WBReg = WB.getReg();
186 Register BaseReg = Base.getReg();
187 Register OffReg = Offset.getReg();
188 unsigned OffImm = MI.getOperand(NumOps - 2).getImm();
189 ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI.getOperand(NumOps - 1).getImm();
190 switch (AddrMode) {
191 default: llvm_unreachable("Unknown indexed op!");
192 case ARMII::AddrMode2: {
193 bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
194 unsigned Amt = ARM_AM::getAM2Offset(OffImm);
195 if (OffReg == 0) {
196 if (ARM_AM::getSOImmVal(Amt) == -1)
197 // Can't encode it in a so_imm operand. This transformation will
198 // add more than 1 instruction. Abandon!
199 return nullptr;
200 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
201 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
202 .addReg(BaseReg)
203 .addImm(Amt)
204 .add(predOps(Pred))
205 .add(condCodeOp());
206 } else if (Amt != 0) {
207 ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
208 unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
209 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
210 get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
211 .addReg(BaseReg)
212 .addReg(OffReg)
213 .addReg(0)
214 .addImm(SOOpc)
215 .add(predOps(Pred))
216 .add(condCodeOp());
217 } else
218 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
219 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
220 .addReg(BaseReg)
221 .addReg(OffReg)
222 .add(predOps(Pred))
223 .add(condCodeOp());
224 break;
225 }
226 case ARMII::AddrMode3 : {
227 bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
228 unsigned Amt = ARM_AM::getAM3Offset(OffImm);
229 if (OffReg == 0)
230 // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
231 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
232 get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
233 .addReg(BaseReg)
234 .addImm(Amt)
235 .add(predOps(Pred))
236 .add(condCodeOp());
237 else
238 UpdateMI = BuildMI(MF, MI.getDebugLoc(),
239 get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
240 .addReg(BaseReg)
241 .addReg(OffReg)
242 .add(predOps(Pred))
243 .add(condCodeOp());
244 break;
245 }
246 }
247
248 std::vector<MachineInstr*> NewMIs;
249 if (isPre) {
250 if (isLoad)
251 MemMI =
252 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
253 .addReg(WBReg)
254 .addImm(0)
255 .addImm(Pred);
256 else
257 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
258 .addReg(MI.getOperand(1).getReg())
259 .addReg(WBReg)
260 .addReg(0)
261 .addImm(0)
262 .addImm(Pred);
263 NewMIs.push_back(MemMI);
264 NewMIs.push_back(UpdateMI);
265 } else {
266 if (isLoad)
267 MemMI =
268 BuildMI(MF, MI.getDebugLoc(), get(MemOpc), MI.getOperand(0).getReg())
269 .addReg(BaseReg)
270 .addImm(0)
271 .addImm(Pred);
272 else
273 MemMI = BuildMI(MF, MI.getDebugLoc(), get(MemOpc))
274 .addReg(MI.getOperand(1).getReg())
275 .addReg(BaseReg)
276 .addReg(0)
277 .addImm(0)
278 .addImm(Pred);
279 if (WB.isDead())
280 UpdateMI->getOperand(0).setIsDead();
281 NewMIs.push_back(UpdateMI);
282 NewMIs.push_back(MemMI);
283 }
284
285 // Transfer LiveVariables states, kill / dead info.
286 if (LV) {
287 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
288 MachineOperand &MO = MI.getOperand(i);
289 if (MO.isReg() && Register::isVirtualRegister(MO.getReg())) {
290 Register Reg = MO.getReg();
291
292 LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
293 if (MO.isDef()) {
294 MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
295 if (MO.isDead())
296 LV->addVirtualRegisterDead(Reg, *NewMI);
297 }
298 if (MO.isUse() && MO.isKill()) {
299 for (unsigned j = 0; j < 2; ++j) {
300 // Look at the two new MI's in reverse order.
301 MachineInstr *NewMI = NewMIs[j];
302 if (!NewMI->readsRegister(Reg))
303 continue;
304 LV->addVirtualRegisterKilled(Reg, *NewMI);
305 if (VI.removeKill(MI))
306 VI.Kills.push_back(NewMI);
307 break;
308 }
309 }
310 }
311 }
312 }
313
314 MachineBasicBlock::iterator MBBI = MI.getIterator();
315 MFI->insert(MBBI, NewMIs[1]);
316 MFI->insert(MBBI, NewMIs[0]);
317 return NewMIs[0];
318 }
319
320 // Branch analysis.
analyzeBranch(MachineBasicBlock & MBB,MachineBasicBlock * & TBB,MachineBasicBlock * & FBB,SmallVectorImpl<MachineOperand> & Cond,bool AllowModify) const321 bool ARMBaseInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
322 MachineBasicBlock *&TBB,
323 MachineBasicBlock *&FBB,
324 SmallVectorImpl<MachineOperand> &Cond,
325 bool AllowModify) const {
326 TBB = nullptr;
327 FBB = nullptr;
328
329 MachineBasicBlock::instr_iterator I = MBB.instr_end();
330 if (I == MBB.instr_begin())
331 return false; // Empty blocks are easy.
332 --I;
333
334 // Walk backwards from the end of the basic block until the branch is
335 // analyzed or we give up.
336 while (isPredicated(*I) || I->isTerminator() || I->isDebugValue()) {
337 // Flag to be raised on unanalyzeable instructions. This is useful in cases
338 // where we want to clean up on the end of the basic block before we bail
339 // out.
340 bool CantAnalyze = false;
341
342 // Skip over DEBUG values and predicated nonterminators.
343 while (I->isDebugInstr() || !I->isTerminator()) {
344 if (I == MBB.instr_begin())
345 return false;
346 --I;
347 }
348
349 if (isIndirectBranchOpcode(I->getOpcode()) ||
350 isJumpTableBranchOpcode(I->getOpcode())) {
351 // Indirect branches and jump tables can't be analyzed, but we still want
352 // to clean up any instructions at the tail of the basic block.
353 CantAnalyze = true;
354 } else if (isUncondBranchOpcode(I->getOpcode())) {
355 TBB = I->getOperand(0).getMBB();
356 } else if (isCondBranchOpcode(I->getOpcode())) {
357 // Bail out if we encounter multiple conditional branches.
358 if (!Cond.empty())
359 return true;
360
361 assert(!FBB && "FBB should have been null.");
362 FBB = TBB;
363 TBB = I->getOperand(0).getMBB();
364 Cond.push_back(I->getOperand(1));
365 Cond.push_back(I->getOperand(2));
366 } else if (I->isReturn()) {
367 // Returns can't be analyzed, but we should run cleanup.
368 CantAnalyze = true;
369 } else {
370 // We encountered other unrecognized terminator. Bail out immediately.
371 return true;
372 }
373
374 // Cleanup code - to be run for unpredicated unconditional branches and
375 // returns.
376 if (!isPredicated(*I) &&
377 (isUncondBranchOpcode(I->getOpcode()) ||
378 isIndirectBranchOpcode(I->getOpcode()) ||
379 isJumpTableBranchOpcode(I->getOpcode()) ||
380 I->isReturn())) {
381 // Forget any previous condition branch information - it no longer applies.
382 Cond.clear();
383 FBB = nullptr;
384
385 // If we can modify the function, delete everything below this
386 // unconditional branch.
387 if (AllowModify) {
388 MachineBasicBlock::iterator DI = std::next(I);
389 while (DI != MBB.instr_end()) {
390 MachineInstr &InstToDelete = *DI;
391 ++DI;
392 InstToDelete.eraseFromParent();
393 }
394 }
395 }
396
397 if (CantAnalyze) {
398 // We may not be able to analyze the block, but we could still have
399 // an unconditional branch as the last instruction in the block, which
400 // just branches to layout successor. If this is the case, then just
401 // remove it if we're allowed to make modifications.
402 if (AllowModify && !isPredicated(MBB.back()) &&
403 isUncondBranchOpcode(MBB.back().getOpcode()) &&
404 TBB && MBB.isLayoutSuccessor(TBB))
405 removeBranch(MBB);
406 return true;
407 }
408
409 if (I == MBB.instr_begin())
410 return false;
411
412 --I;
413 }
414
415 // We made it past the terminators without bailing out - we must have
416 // analyzed this branch successfully.
417 return false;
418 }
419
removeBranch(MachineBasicBlock & MBB,int * BytesRemoved) const420 unsigned ARMBaseInstrInfo::removeBranch(MachineBasicBlock &MBB,
421 int *BytesRemoved) const {
422 assert(!BytesRemoved && "code size not handled");
423
424 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
425 if (I == MBB.end())
426 return 0;
427
428 if (!isUncondBranchOpcode(I->getOpcode()) &&
429 !isCondBranchOpcode(I->getOpcode()))
430 return 0;
431
432 // Remove the branch.
433 I->eraseFromParent();
434
435 I = MBB.end();
436
437 if (I == MBB.begin()) return 1;
438 --I;
439 if (!isCondBranchOpcode(I->getOpcode()))
440 return 1;
441
442 // Remove the branch.
443 I->eraseFromParent();
444 return 2;
445 }
446
insertBranch(MachineBasicBlock & MBB,MachineBasicBlock * TBB,MachineBasicBlock * FBB,ArrayRef<MachineOperand> Cond,const DebugLoc & DL,int * BytesAdded) const447 unsigned ARMBaseInstrInfo::insertBranch(MachineBasicBlock &MBB,
448 MachineBasicBlock *TBB,
449 MachineBasicBlock *FBB,
450 ArrayRef<MachineOperand> Cond,
451 const DebugLoc &DL,
452 int *BytesAdded) const {
453 assert(!BytesAdded && "code size not handled");
454 ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
455 int BOpc = !AFI->isThumbFunction()
456 ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
457 int BccOpc = !AFI->isThumbFunction()
458 ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
459 bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
460
461 // Shouldn't be a fall through.
462 assert(TBB && "insertBranch must not be told to insert a fallthrough");
463 assert((Cond.size() == 2 || Cond.size() == 0) &&
464 "ARM branch conditions have two components!");
465
466 // For conditional branches, we use addOperand to preserve CPSR flags.
467
468 if (!FBB) {
469 if (Cond.empty()) { // Unconditional branch?
470 if (isThumb)
471 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).add(predOps(ARMCC::AL));
472 else
473 BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
474 } else
475 BuildMI(&MBB, DL, get(BccOpc))
476 .addMBB(TBB)
477 .addImm(Cond[0].getImm())
478 .add(Cond[1]);
479 return 1;
480 }
481
482 // Two-way conditional branch.
483 BuildMI(&MBB, DL, get(BccOpc))
484 .addMBB(TBB)
485 .addImm(Cond[0].getImm())
486 .add(Cond[1]);
487 if (isThumb)
488 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).add(predOps(ARMCC::AL));
489 else
490 BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
491 return 2;
492 }
493
494 bool ARMBaseInstrInfo::
reverseBranchCondition(SmallVectorImpl<MachineOperand> & Cond) const495 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
496 ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
497 Cond[0].setImm(ARMCC::getOppositeCondition(CC));
498 return false;
499 }
500
isPredicated(const MachineInstr & MI) const501 bool ARMBaseInstrInfo::isPredicated(const MachineInstr &MI) const {
502 if (MI.isBundle()) {
503 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
504 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
505 while (++I != E && I->isInsideBundle()) {
506 int PIdx = I->findFirstPredOperandIdx();
507 if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
508 return true;
509 }
510 return false;
511 }
512
513 int PIdx = MI.findFirstPredOperandIdx();
514 return PIdx != -1 && MI.getOperand(PIdx).getImm() != ARMCC::AL;
515 }
516
createMIROperandComment(const MachineInstr & MI,const MachineOperand & Op,unsigned OpIdx,const TargetRegisterInfo * TRI) const517 std::string ARMBaseInstrInfo::createMIROperandComment(
518 const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
519 const TargetRegisterInfo *TRI) const {
520
521 // First, let's see if there is a generic comment for this operand
522 std::string GenericComment =
523 TargetInstrInfo::createMIROperandComment(MI, Op, OpIdx, TRI);
524 if (!GenericComment.empty())
525 return GenericComment;
526
527 // If not, check if we have an immediate operand.
528 if (Op.getType() != MachineOperand::MO_Immediate)
529 return std::string();
530
531 // And print its corresponding condition code if the immediate is a
532 // predicate.
533 int FirstPredOp = MI.findFirstPredOperandIdx();
534 if (FirstPredOp != (int) OpIdx)
535 return std::string();
536
537 std::string CC = "CC::";
538 CC += ARMCondCodeToString((ARMCC::CondCodes)Op.getImm());
539 return CC;
540 }
541
PredicateInstruction(MachineInstr & MI,ArrayRef<MachineOperand> Pred) const542 bool ARMBaseInstrInfo::PredicateInstruction(
543 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
544 unsigned Opc = MI.getOpcode();
545 if (isUncondBranchOpcode(Opc)) {
546 MI.setDesc(get(getMatchingCondBranchOpcode(Opc)));
547 MachineInstrBuilder(*MI.getParent()->getParent(), MI)
548 .addImm(Pred[0].getImm())
549 .addReg(Pred[1].getReg());
550 return true;
551 }
552
553 int PIdx = MI.findFirstPredOperandIdx();
554 if (PIdx != -1) {
555 MachineOperand &PMO = MI.getOperand(PIdx);
556 PMO.setImm(Pred[0].getImm());
557 MI.getOperand(PIdx+1).setReg(Pred[1].getReg());
558
559 // Thumb 1 arithmetic instructions do not set CPSR when executed inside an
560 // IT block. This affects how they are printed.
561 const MCInstrDesc &MCID = MI.getDesc();
562 if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
563 assert(MCID.OpInfo[1].isOptionalDef() && "CPSR def isn't expected operand");
564 assert((MI.getOperand(1).isDead() ||
565 MI.getOperand(1).getReg() != ARM::CPSR) &&
566 "if conversion tried to stop defining used CPSR");
567 MI.getOperand(1).setReg(ARM::NoRegister);
568 }
569
570 return true;
571 }
572 return false;
573 }
574
SubsumesPredicate(ArrayRef<MachineOperand> Pred1,ArrayRef<MachineOperand> Pred2) const575 bool ARMBaseInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
576 ArrayRef<MachineOperand> Pred2) const {
577 if (Pred1.size() > 2 || Pred2.size() > 2)
578 return false;
579
580 ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
581 ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
582 if (CC1 == CC2)
583 return true;
584
585 switch (CC1) {
586 default:
587 return false;
588 case ARMCC::AL:
589 return true;
590 case ARMCC::HS:
591 return CC2 == ARMCC::HI;
592 case ARMCC::LS:
593 return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
594 case ARMCC::GE:
595 return CC2 == ARMCC::GT;
596 case ARMCC::LE:
597 return CC2 == ARMCC::LT;
598 }
599 }
600
ClobbersPredicate(MachineInstr & MI,std::vector<MachineOperand> & Pred,bool SkipDead) const601 bool ARMBaseInstrInfo::ClobbersPredicate(MachineInstr &MI,
602 std::vector<MachineOperand> &Pred,
603 bool SkipDead) const {
604 bool Found = false;
605 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
606 const MachineOperand &MO = MI.getOperand(i);
607 bool ClobbersCPSR = MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR);
608 bool IsCPSR = MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR;
609 if (ClobbersCPSR || IsCPSR) {
610
611 // Filter out T1 instructions that have a dead CPSR,
612 // allowing IT blocks to be generated containing T1 instructions
613 const MCInstrDesc &MCID = MI.getDesc();
614 if (MCID.TSFlags & ARMII::ThumbArithFlagSetting && MO.isDead() &&
615 SkipDead)
616 continue;
617
618 Pred.push_back(MO);
619 Found = true;
620 }
621 }
622
623 return Found;
624 }
625
isCPSRDefined(const MachineInstr & MI)626 bool ARMBaseInstrInfo::isCPSRDefined(const MachineInstr &MI) {
627 for (const auto &MO : MI.operands())
628 if (MO.isReg() && MO.getReg() == ARM::CPSR && MO.isDef() && !MO.isDead())
629 return true;
630 return false;
631 }
632
isEligibleForITBlock(const MachineInstr * MI)633 static bool isEligibleForITBlock(const MachineInstr *MI) {
634 switch (MI->getOpcode()) {
635 default: return true;
636 case ARM::tADC: // ADC (register) T1
637 case ARM::tADDi3: // ADD (immediate) T1
638 case ARM::tADDi8: // ADD (immediate) T2
639 case ARM::tADDrr: // ADD (register) T1
640 case ARM::tAND: // AND (register) T1
641 case ARM::tASRri: // ASR (immediate) T1
642 case ARM::tASRrr: // ASR (register) T1
643 case ARM::tBIC: // BIC (register) T1
644 case ARM::tEOR: // EOR (register) T1
645 case ARM::tLSLri: // LSL (immediate) T1
646 case ARM::tLSLrr: // LSL (register) T1
647 case ARM::tLSRri: // LSR (immediate) T1
648 case ARM::tLSRrr: // LSR (register) T1
649 case ARM::tMUL: // MUL T1
650 case ARM::tMVN: // MVN (register) T1
651 case ARM::tORR: // ORR (register) T1
652 case ARM::tROR: // ROR (register) T1
653 case ARM::tRSB: // RSB (immediate) T1
654 case ARM::tSBC: // SBC (register) T1
655 case ARM::tSUBi3: // SUB (immediate) T1
656 case ARM::tSUBi8: // SUB (immediate) T2
657 case ARM::tSUBrr: // SUB (register) T1
658 return !ARMBaseInstrInfo::isCPSRDefined(*MI);
659 }
660 }
661
662 /// isPredicable - Return true if the specified instruction can be predicated.
663 /// By default, this returns true for every instruction with a
664 /// PredicateOperand.
isPredicable(const MachineInstr & MI) const665 bool ARMBaseInstrInfo::isPredicable(const MachineInstr &MI) const {
666 if (!MI.isPredicable())
667 return false;
668
669 if (MI.isBundle())
670 return false;
671
672 if (!isEligibleForITBlock(&MI))
673 return false;
674
675 const ARMFunctionInfo *AFI =
676 MI.getParent()->getParent()->getInfo<ARMFunctionInfo>();
677
678 // Neon instructions in Thumb2 IT blocks are deprecated, see ARMARM.
679 // In their ARM encoding, they can't be encoded in a conditional form.
680 if ((MI.getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
681 return false;
682
683 if (AFI->isThumb2Function()) {
684 if (getSubtarget().restrictIT())
685 return isV8EligibleForIT(&MI);
686 }
687
688 return true;
689 }
690
691 namespace llvm {
692
IsCPSRDead(const MachineInstr * MI)693 template <> bool IsCPSRDead<MachineInstr>(const MachineInstr *MI) {
694 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
695 const MachineOperand &MO = MI->getOperand(i);
696 if (!MO.isReg() || MO.isUndef() || MO.isUse())
697 continue;
698 if (MO.getReg() != ARM::CPSR)
699 continue;
700 if (!MO.isDead())
701 return false;
702 }
703 // all definitions of CPSR are dead
704 return true;
705 }
706
707 } // end namespace llvm
708
709 /// GetInstSize - Return the size of the specified MachineInstr.
710 ///
getInstSizeInBytes(const MachineInstr & MI) const711 unsigned ARMBaseInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
712 const MachineBasicBlock &MBB = *MI.getParent();
713 const MachineFunction *MF = MBB.getParent();
714 const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
715
716 const MCInstrDesc &MCID = MI.getDesc();
717 if (MCID.getSize())
718 return MCID.getSize();
719
720 switch (MI.getOpcode()) {
721 default:
722 // pseudo-instruction sizes are zero.
723 return 0;
724 case TargetOpcode::BUNDLE:
725 return getInstBundleLength(MI);
726 case ARM::MOVi16_ga_pcrel:
727 case ARM::MOVTi16_ga_pcrel:
728 case ARM::t2MOVi16_ga_pcrel:
729 case ARM::t2MOVTi16_ga_pcrel:
730 return 4;
731 case ARM::MOVi32imm:
732 case ARM::t2MOVi32imm:
733 return 8;
734 case ARM::CONSTPOOL_ENTRY:
735 case ARM::JUMPTABLE_INSTS:
736 case ARM::JUMPTABLE_ADDRS:
737 case ARM::JUMPTABLE_TBB:
738 case ARM::JUMPTABLE_TBH:
739 // If this machine instr is a constant pool entry, its size is recorded as
740 // operand #2.
741 return MI.getOperand(2).getImm();
742 case ARM::Int_eh_sjlj_longjmp:
743 return 16;
744 case ARM::tInt_eh_sjlj_longjmp:
745 return 10;
746 case ARM::tInt_WIN_eh_sjlj_longjmp:
747 return 12;
748 case ARM::Int_eh_sjlj_setjmp:
749 case ARM::Int_eh_sjlj_setjmp_nofp:
750 return 20;
751 case ARM::tInt_eh_sjlj_setjmp:
752 case ARM::t2Int_eh_sjlj_setjmp:
753 case ARM::t2Int_eh_sjlj_setjmp_nofp:
754 return 12;
755 case ARM::SPACE:
756 return MI.getOperand(1).getImm();
757 case ARM::INLINEASM:
758 case ARM::INLINEASM_BR: {
759 // If this machine instr is an inline asm, measure it.
760 unsigned Size = getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
761 if (!MF->getInfo<ARMFunctionInfo>()->isThumbFunction())
762 Size = alignTo(Size, 4);
763 return Size;
764 }
765 }
766 }
767
getInstBundleLength(const MachineInstr & MI) const768 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr &MI) const {
769 unsigned Size = 0;
770 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
771 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
772 while (++I != E && I->isInsideBundle()) {
773 assert(!I->isBundle() && "No nested bundle!");
774 Size += getInstSizeInBytes(*I);
775 }
776 return Size;
777 }
778
copyFromCPSR(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,unsigned DestReg,bool KillSrc,const ARMSubtarget & Subtarget) const779 void ARMBaseInstrInfo::copyFromCPSR(MachineBasicBlock &MBB,
780 MachineBasicBlock::iterator I,
781 unsigned DestReg, bool KillSrc,
782 const ARMSubtarget &Subtarget) const {
783 unsigned Opc = Subtarget.isThumb()
784 ? (Subtarget.isMClass() ? ARM::t2MRS_M : ARM::t2MRS_AR)
785 : ARM::MRS;
786
787 MachineInstrBuilder MIB =
788 BuildMI(MBB, I, I->getDebugLoc(), get(Opc), DestReg);
789
790 // There is only 1 A/R class MRS instruction, and it always refers to
791 // APSR. However, there are lots of other possibilities on M-class cores.
792 if (Subtarget.isMClass())
793 MIB.addImm(0x800);
794
795 MIB.add(predOps(ARMCC::AL))
796 .addReg(ARM::CPSR, RegState::Implicit | getKillRegState(KillSrc));
797 }
798
copyToCPSR(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,unsigned SrcReg,bool KillSrc,const ARMSubtarget & Subtarget) const799 void ARMBaseInstrInfo::copyToCPSR(MachineBasicBlock &MBB,
800 MachineBasicBlock::iterator I,
801 unsigned SrcReg, bool KillSrc,
802 const ARMSubtarget &Subtarget) const {
803 unsigned Opc = Subtarget.isThumb()
804 ? (Subtarget.isMClass() ? ARM::t2MSR_M : ARM::t2MSR_AR)
805 : ARM::MSR;
806
807 MachineInstrBuilder MIB = BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
808
809 if (Subtarget.isMClass())
810 MIB.addImm(0x800);
811 else
812 MIB.addImm(8);
813
814 MIB.addReg(SrcReg, getKillRegState(KillSrc))
815 .add(predOps(ARMCC::AL))
816 .addReg(ARM::CPSR, RegState::Implicit | RegState::Define);
817 }
818
addUnpredicatedMveVpredNOp(MachineInstrBuilder & MIB)819 void llvm::addUnpredicatedMveVpredNOp(MachineInstrBuilder &MIB) {
820 MIB.addImm(ARMVCC::None);
821 MIB.addReg(0);
822 }
823
addUnpredicatedMveVpredROp(MachineInstrBuilder & MIB,Register DestReg)824 void llvm::addUnpredicatedMveVpredROp(MachineInstrBuilder &MIB,
825 Register DestReg) {
826 addUnpredicatedMveVpredNOp(MIB);
827 MIB.addReg(DestReg, RegState::Undef);
828 }
829
addPredicatedMveVpredNOp(MachineInstrBuilder & MIB,unsigned Cond)830 void llvm::addPredicatedMveVpredNOp(MachineInstrBuilder &MIB, unsigned Cond) {
831 MIB.addImm(Cond);
832 MIB.addReg(ARM::VPR, RegState::Implicit);
833 }
834
addPredicatedMveVpredROp(MachineInstrBuilder & MIB,unsigned Cond,unsigned Inactive)835 void llvm::addPredicatedMveVpredROp(MachineInstrBuilder &MIB,
836 unsigned Cond, unsigned Inactive) {
837 addPredicatedMveVpredNOp(MIB, Cond);
838 MIB.addReg(Inactive);
839 }
840
copyPhysReg(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,const DebugLoc & DL,MCRegister DestReg,MCRegister SrcReg,bool KillSrc) const841 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
842 MachineBasicBlock::iterator I,
843 const DebugLoc &DL, MCRegister DestReg,
844 MCRegister SrcReg, bool KillSrc) const {
845 bool GPRDest = ARM::GPRRegClass.contains(DestReg);
846 bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
847
848 if (GPRDest && GPRSrc) {
849 BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
850 .addReg(SrcReg, getKillRegState(KillSrc))
851 .add(predOps(ARMCC::AL))
852 .add(condCodeOp());
853 return;
854 }
855
856 bool SPRDest = ARM::SPRRegClass.contains(DestReg);
857 bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
858
859 unsigned Opc = 0;
860 if (SPRDest && SPRSrc)
861 Opc = ARM::VMOVS;
862 else if (GPRDest && SPRSrc)
863 Opc = ARM::VMOVRS;
864 else if (SPRDest && GPRSrc)
865 Opc = ARM::VMOVSR;
866 else if (ARM::DPRRegClass.contains(DestReg, SrcReg) && Subtarget.hasFP64())
867 Opc = ARM::VMOVD;
868 else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
869 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
870
871 if (Opc) {
872 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
873 MIB.addReg(SrcReg, getKillRegState(KillSrc));
874 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR)
875 MIB.addReg(SrcReg, getKillRegState(KillSrc));
876 if (Opc == ARM::MVE_VORR)
877 addUnpredicatedMveVpredROp(MIB, DestReg);
878 else
879 MIB.add(predOps(ARMCC::AL));
880 return;
881 }
882
883 // Handle register classes that require multiple instructions.
884 unsigned BeginIdx = 0;
885 unsigned SubRegs = 0;
886 int Spacing = 1;
887
888 // Use VORRq when possible.
889 if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
890 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
891 BeginIdx = ARM::qsub_0;
892 SubRegs = 2;
893 } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
894 Opc = Subtarget.hasNEON() ? ARM::VORRq : ARM::MVE_VORR;
895 BeginIdx = ARM::qsub_0;
896 SubRegs = 4;
897 // Fall back to VMOVD.
898 } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
899 Opc = ARM::VMOVD;
900 BeginIdx = ARM::dsub_0;
901 SubRegs = 2;
902 } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
903 Opc = ARM::VMOVD;
904 BeginIdx = ARM::dsub_0;
905 SubRegs = 3;
906 } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
907 Opc = ARM::VMOVD;
908 BeginIdx = ARM::dsub_0;
909 SubRegs = 4;
910 } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
911 Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
912 BeginIdx = ARM::gsub_0;
913 SubRegs = 2;
914 } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
915 Opc = ARM::VMOVD;
916 BeginIdx = ARM::dsub_0;
917 SubRegs = 2;
918 Spacing = 2;
919 } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
920 Opc = ARM::VMOVD;
921 BeginIdx = ARM::dsub_0;
922 SubRegs = 3;
923 Spacing = 2;
924 } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
925 Opc = ARM::VMOVD;
926 BeginIdx = ARM::dsub_0;
927 SubRegs = 4;
928 Spacing = 2;
929 } else if (ARM::DPRRegClass.contains(DestReg, SrcReg) &&
930 !Subtarget.hasFP64()) {
931 Opc = ARM::VMOVS;
932 BeginIdx = ARM::ssub_0;
933 SubRegs = 2;
934 } else if (SrcReg == ARM::CPSR) {
935 copyFromCPSR(MBB, I, DestReg, KillSrc, Subtarget);
936 return;
937 } else if (DestReg == ARM::CPSR) {
938 copyToCPSR(MBB, I, SrcReg, KillSrc, Subtarget);
939 return;
940 } else if (DestReg == ARM::VPR) {
941 assert(ARM::GPRRegClass.contains(SrcReg));
942 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_P0), DestReg)
943 .addReg(SrcReg, getKillRegState(KillSrc))
944 .add(predOps(ARMCC::AL));
945 return;
946 } else if (SrcReg == ARM::VPR) {
947 assert(ARM::GPRRegClass.contains(DestReg));
948 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_P0), DestReg)
949 .addReg(SrcReg, getKillRegState(KillSrc))
950 .add(predOps(ARMCC::AL));
951 return;
952 } else if (DestReg == ARM::FPSCR_NZCV) {
953 assert(ARM::GPRRegClass.contains(SrcReg));
954 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMSR_FPSCR_NZCVQC), DestReg)
955 .addReg(SrcReg, getKillRegState(KillSrc))
956 .add(predOps(ARMCC::AL));
957 return;
958 } else if (SrcReg == ARM::FPSCR_NZCV) {
959 assert(ARM::GPRRegClass.contains(DestReg));
960 BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VMRS_FPSCR_NZCVQC), DestReg)
961 .addReg(SrcReg, getKillRegState(KillSrc))
962 .add(predOps(ARMCC::AL));
963 return;
964 }
965
966 assert(Opc && "Impossible reg-to-reg copy");
967
968 const TargetRegisterInfo *TRI = &getRegisterInfo();
969 MachineInstrBuilder Mov;
970
971 // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
972 if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
973 BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
974 Spacing = -Spacing;
975 }
976 #ifndef NDEBUG
977 SmallSet<unsigned, 4> DstRegs;
978 #endif
979 for (unsigned i = 0; i != SubRegs; ++i) {
980 Register Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
981 Register Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
982 assert(Dst && Src && "Bad sub-register");
983 #ifndef NDEBUG
984 assert(!DstRegs.count(Src) && "destructive vector copy");
985 DstRegs.insert(Dst);
986 #endif
987 Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
988 // VORR (NEON or MVE) takes two source operands.
989 if (Opc == ARM::VORRq || Opc == ARM::MVE_VORR) {
990 Mov.addReg(Src);
991 }
992 // MVE VORR takes predicate operands in place of an ordinary condition.
993 if (Opc == ARM::MVE_VORR)
994 addUnpredicatedMveVpredROp(Mov, Dst);
995 else
996 Mov = Mov.add(predOps(ARMCC::AL));
997 // MOVr can set CC.
998 if (Opc == ARM::MOVr)
999 Mov = Mov.add(condCodeOp());
1000 }
1001 // Add implicit super-register defs and kills to the last instruction.
1002 Mov->addRegisterDefined(DestReg, TRI);
1003 if (KillSrc)
1004 Mov->addRegisterKilled(SrcReg, TRI);
1005 }
1006
1007 Optional<DestSourcePair>
isCopyInstrImpl(const MachineInstr & MI) const1008 ARMBaseInstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
1009 // VMOVRRD is also a copy instruction but it requires
1010 // special way of handling. It is more complex copy version
1011 // and since that we are not considering it. For recognition
1012 // of such instruction isExtractSubregLike MI interface fuction
1013 // could be used.
1014 // VORRq is considered as a move only if two inputs are
1015 // the same register.
1016 if (!MI.isMoveReg() ||
1017 (MI.getOpcode() == ARM::VORRq &&
1018 MI.getOperand(1).getReg() != MI.getOperand(2).getReg()))
1019 return None;
1020 return DestSourcePair{MI.getOperand(0), MI.getOperand(1)};
1021 }
1022
1023 Optional<ParamLoadedValue>
describeLoadedValue(const MachineInstr & MI,Register Reg) const1024 ARMBaseInstrInfo::describeLoadedValue(const MachineInstr &MI,
1025 Register Reg) const {
1026 if (auto DstSrcPair = isCopyInstrImpl(MI)) {
1027 Register DstReg = DstSrcPair->Destination->getReg();
1028
1029 // TODO: We don't handle cases where the forwarding reg is narrower/wider
1030 // than the copy registers. Consider for example:
1031 //
1032 // s16 = VMOVS s0
1033 // s17 = VMOVS s1
1034 // call @callee(d0)
1035 //
1036 // We'd like to describe the call site value of d0 as d8, but this requires
1037 // gathering and merging the descriptions for the two VMOVS instructions.
1038 //
1039 // We also don't handle the reverse situation, where the forwarding reg is
1040 // narrower than the copy destination:
1041 //
1042 // d8 = VMOVD d0
1043 // call @callee(s1)
1044 //
1045 // We need to produce a fragment description (the call site value of s1 is
1046 // /not/ just d8).
1047 if (DstReg != Reg)
1048 return None;
1049 }
1050 return TargetInstrInfo::describeLoadedValue(MI, Reg);
1051 }
1052
1053 const MachineInstrBuilder &
AddDReg(MachineInstrBuilder & MIB,unsigned Reg,unsigned SubIdx,unsigned State,const TargetRegisterInfo * TRI) const1054 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
1055 unsigned SubIdx, unsigned State,
1056 const TargetRegisterInfo *TRI) const {
1057 if (!SubIdx)
1058 return MIB.addReg(Reg, State);
1059
1060 if (Register::isPhysicalRegister(Reg))
1061 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
1062 return MIB.addReg(Reg, State, SubIdx);
1063 }
1064
1065 void ARMBaseInstrInfo::
storeRegToStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,Register SrcReg,bool isKill,int FI,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI) const1066 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1067 Register SrcReg, bool isKill, int FI,
1068 const TargetRegisterClass *RC,
1069 const TargetRegisterInfo *TRI) const {
1070 MachineFunction &MF = *MBB.getParent();
1071 MachineFrameInfo &MFI = MF.getFrameInfo();
1072 Align Alignment = MFI.getObjectAlign(FI);
1073
1074 MachineMemOperand *MMO = MF.getMachineMemOperand(
1075 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOStore,
1076 MFI.getObjectSize(FI), Alignment);
1077
1078 switch (TRI->getSpillSize(*RC)) {
1079 case 2:
1080 if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1081 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRH))
1082 .addReg(SrcReg, getKillRegState(isKill))
1083 .addFrameIndex(FI)
1084 .addImm(0)
1085 .addMemOperand(MMO)
1086 .add(predOps(ARMCC::AL));
1087 } else
1088 llvm_unreachable("Unknown reg class!");
1089 break;
1090 case 4:
1091 if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1092 BuildMI(MBB, I, DebugLoc(), get(ARM::STRi12))
1093 .addReg(SrcReg, getKillRegState(isKill))
1094 .addFrameIndex(FI)
1095 .addImm(0)
1096 .addMemOperand(MMO)
1097 .add(predOps(ARMCC::AL));
1098 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1099 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRS))
1100 .addReg(SrcReg, getKillRegState(isKill))
1101 .addFrameIndex(FI)
1102 .addImm(0)
1103 .addMemOperand(MMO)
1104 .add(predOps(ARMCC::AL));
1105 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1106 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTR_P0_off))
1107 .addReg(SrcReg, getKillRegState(isKill))
1108 .addFrameIndex(FI)
1109 .addImm(0)
1110 .addMemOperand(MMO)
1111 .add(predOps(ARMCC::AL));
1112 } else
1113 llvm_unreachable("Unknown reg class!");
1114 break;
1115 case 8:
1116 if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1117 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTRD))
1118 .addReg(SrcReg, getKillRegState(isKill))
1119 .addFrameIndex(FI)
1120 .addImm(0)
1121 .addMemOperand(MMO)
1122 .add(predOps(ARMCC::AL));
1123 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1124 if (Subtarget.hasV5TEOps()) {
1125 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STRD));
1126 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1127 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1128 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1129 .add(predOps(ARMCC::AL));
1130 } else {
1131 // Fallback to STM instruction, which has existed since the dawn of
1132 // time.
1133 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::STMIA))
1134 .addFrameIndex(FI)
1135 .addMemOperand(MMO)
1136 .add(predOps(ARMCC::AL));
1137 AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
1138 AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
1139 }
1140 } else
1141 llvm_unreachable("Unknown reg class!");
1142 break;
1143 case 16:
1144 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1145 // Use aligned spills if the stack can be realigned.
1146 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
1147 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1q64))
1148 .addFrameIndex(FI)
1149 .addImm(16)
1150 .addReg(SrcReg, getKillRegState(isKill))
1151 .addMemOperand(MMO)
1152 .add(predOps(ARMCC::AL));
1153 } else {
1154 BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMQIA))
1155 .addReg(SrcReg, getKillRegState(isKill))
1156 .addFrameIndex(FI)
1157 .addMemOperand(MMO)
1158 .add(predOps(ARMCC::AL));
1159 }
1160 } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1161 Subtarget.hasMVEIntegerOps()) {
1162 auto MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::MVE_VSTRWU32));
1163 MIB.addReg(SrcReg, getKillRegState(isKill))
1164 .addFrameIndex(FI)
1165 .addImm(0)
1166 .addMemOperand(MMO);
1167 addUnpredicatedMveVpredNOp(MIB);
1168 } else
1169 llvm_unreachable("Unknown reg class!");
1170 break;
1171 case 24:
1172 if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1173 // Use aligned spills if the stack can be realigned.
1174 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1175 Subtarget.hasNEON()) {
1176 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64TPseudo))
1177 .addFrameIndex(FI)
1178 .addImm(16)
1179 .addReg(SrcReg, getKillRegState(isKill))
1180 .addMemOperand(MMO)
1181 .add(predOps(ARMCC::AL));
1182 } else {
1183 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1184 get(ARM::VSTMDIA))
1185 .addFrameIndex(FI)
1186 .add(predOps(ARMCC::AL))
1187 .addMemOperand(MMO);
1188 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1189 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1190 AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1191 }
1192 } else
1193 llvm_unreachable("Unknown reg class!");
1194 break;
1195 case 32:
1196 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1197 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1198 Subtarget.hasNEON()) {
1199 // FIXME: It's possible to only store part of the QQ register if the
1200 // spilled def has a sub-register index.
1201 BuildMI(MBB, I, DebugLoc(), get(ARM::VST1d64QPseudo))
1202 .addFrameIndex(FI)
1203 .addImm(16)
1204 .addReg(SrcReg, getKillRegState(isKill))
1205 .addMemOperand(MMO)
1206 .add(predOps(ARMCC::AL));
1207 } else {
1208 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(),
1209 get(ARM::VSTMDIA))
1210 .addFrameIndex(FI)
1211 .add(predOps(ARMCC::AL))
1212 .addMemOperand(MMO);
1213 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1214 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1215 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1216 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1217 }
1218 } else
1219 llvm_unreachable("Unknown reg class!");
1220 break;
1221 case 64:
1222 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1223 MachineInstrBuilder MIB = BuildMI(MBB, I, DebugLoc(), get(ARM::VSTMDIA))
1224 .addFrameIndex(FI)
1225 .add(predOps(ARMCC::AL))
1226 .addMemOperand(MMO);
1227 MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
1228 MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
1229 MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
1230 MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
1231 MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
1232 MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
1233 MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
1234 AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
1235 } else
1236 llvm_unreachable("Unknown reg class!");
1237 break;
1238 default:
1239 llvm_unreachable("Unknown reg class!");
1240 }
1241 }
1242
isStoreToStackSlot(const MachineInstr & MI,int & FrameIndex) const1243 unsigned ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
1244 int &FrameIndex) const {
1245 switch (MI.getOpcode()) {
1246 default: break;
1247 case ARM::STRrs:
1248 case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
1249 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1250 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1251 MI.getOperand(3).getImm() == 0) {
1252 FrameIndex = MI.getOperand(1).getIndex();
1253 return MI.getOperand(0).getReg();
1254 }
1255 break;
1256 case ARM::STRi12:
1257 case ARM::t2STRi12:
1258 case ARM::tSTRspi:
1259 case ARM::VSTRD:
1260 case ARM::VSTRS:
1261 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1262 MI.getOperand(2).getImm() == 0) {
1263 FrameIndex = MI.getOperand(1).getIndex();
1264 return MI.getOperand(0).getReg();
1265 }
1266 break;
1267 case ARM::VSTR_P0_off:
1268 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1269 MI.getOperand(1).getImm() == 0) {
1270 FrameIndex = MI.getOperand(0).getIndex();
1271 return ARM::P0;
1272 }
1273 break;
1274 case ARM::VST1q64:
1275 case ARM::VST1d64TPseudo:
1276 case ARM::VST1d64QPseudo:
1277 if (MI.getOperand(0).isFI() && MI.getOperand(2).getSubReg() == 0) {
1278 FrameIndex = MI.getOperand(0).getIndex();
1279 return MI.getOperand(2).getReg();
1280 }
1281 break;
1282 case ARM::VSTMQIA:
1283 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1284 FrameIndex = MI.getOperand(1).getIndex();
1285 return MI.getOperand(0).getReg();
1286 }
1287 break;
1288 }
1289
1290 return 0;
1291 }
1292
isStoreToStackSlotPostFE(const MachineInstr & MI,int & FrameIndex) const1293 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr &MI,
1294 int &FrameIndex) const {
1295 SmallVector<const MachineMemOperand *, 1> Accesses;
1296 if (MI.mayStore() && hasStoreToStackSlot(MI, Accesses) &&
1297 Accesses.size() == 1) {
1298 FrameIndex =
1299 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1300 ->getFrameIndex();
1301 return true;
1302 }
1303 return false;
1304 }
1305
1306 void ARMBaseInstrInfo::
loadRegFromStackSlot(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,Register DestReg,int FI,const TargetRegisterClass * RC,const TargetRegisterInfo * TRI) const1307 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
1308 Register DestReg, int FI,
1309 const TargetRegisterClass *RC,
1310 const TargetRegisterInfo *TRI) const {
1311 DebugLoc DL;
1312 if (I != MBB.end()) DL = I->getDebugLoc();
1313 MachineFunction &MF = *MBB.getParent();
1314 MachineFrameInfo &MFI = MF.getFrameInfo();
1315 const Align Alignment = MFI.getObjectAlign(FI);
1316 MachineMemOperand *MMO = MF.getMachineMemOperand(
1317 MachinePointerInfo::getFixedStack(MF, FI), MachineMemOperand::MOLoad,
1318 MFI.getObjectSize(FI), Alignment);
1319
1320 switch (TRI->getSpillSize(*RC)) {
1321 case 2:
1322 if (ARM::HPRRegClass.hasSubClassEq(RC)) {
1323 BuildMI(MBB, I, DL, get(ARM::VLDRH), DestReg)
1324 .addFrameIndex(FI)
1325 .addImm(0)
1326 .addMemOperand(MMO)
1327 .add(predOps(ARMCC::AL));
1328 } else
1329 llvm_unreachable("Unknown reg class!");
1330 break;
1331 case 4:
1332 if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1333 BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
1334 .addFrameIndex(FI)
1335 .addImm(0)
1336 .addMemOperand(MMO)
1337 .add(predOps(ARMCC::AL));
1338 } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1339 BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
1340 .addFrameIndex(FI)
1341 .addImm(0)
1342 .addMemOperand(MMO)
1343 .add(predOps(ARMCC::AL));
1344 } else if (ARM::VCCRRegClass.hasSubClassEq(RC)) {
1345 BuildMI(MBB, I, DL, get(ARM::VLDR_P0_off), DestReg)
1346 .addFrameIndex(FI)
1347 .addImm(0)
1348 .addMemOperand(MMO)
1349 .add(predOps(ARMCC::AL));
1350 } else
1351 llvm_unreachable("Unknown reg class!");
1352 break;
1353 case 8:
1354 if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1355 BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1356 .addFrameIndex(FI)
1357 .addImm(0)
1358 .addMemOperand(MMO)
1359 .add(predOps(ARMCC::AL));
1360 } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1361 MachineInstrBuilder MIB;
1362
1363 if (Subtarget.hasV5TEOps()) {
1364 MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1365 AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1366 AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1367 MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO)
1368 .add(predOps(ARMCC::AL));
1369 } else {
1370 // Fallback to LDM instruction, which has existed since the dawn of
1371 // time.
1372 MIB = BuildMI(MBB, I, DL, get(ARM::LDMIA))
1373 .addFrameIndex(FI)
1374 .addMemOperand(MMO)
1375 .add(predOps(ARMCC::AL));
1376 MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1377 MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1378 }
1379
1380 if (Register::isPhysicalRegister(DestReg))
1381 MIB.addReg(DestReg, RegState::ImplicitDefine);
1382 } else
1383 llvm_unreachable("Unknown reg class!");
1384 break;
1385 case 16:
1386 if (ARM::DPairRegClass.hasSubClassEq(RC) && Subtarget.hasNEON()) {
1387 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF)) {
1388 BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1389 .addFrameIndex(FI)
1390 .addImm(16)
1391 .addMemOperand(MMO)
1392 .add(predOps(ARMCC::AL));
1393 } else {
1394 BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1395 .addFrameIndex(FI)
1396 .addMemOperand(MMO)
1397 .add(predOps(ARMCC::AL));
1398 }
1399 } else if (ARM::QPRRegClass.hasSubClassEq(RC) &&
1400 Subtarget.hasMVEIntegerOps()) {
1401 auto MIB = BuildMI(MBB, I, DL, get(ARM::MVE_VLDRWU32), DestReg);
1402 MIB.addFrameIndex(FI)
1403 .addImm(0)
1404 .addMemOperand(MMO);
1405 addUnpredicatedMveVpredNOp(MIB);
1406 } else
1407 llvm_unreachable("Unknown reg class!");
1408 break;
1409 case 24:
1410 if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1411 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1412 Subtarget.hasNEON()) {
1413 BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1414 .addFrameIndex(FI)
1415 .addImm(16)
1416 .addMemOperand(MMO)
1417 .add(predOps(ARMCC::AL));
1418 } else {
1419 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1420 .addFrameIndex(FI)
1421 .addMemOperand(MMO)
1422 .add(predOps(ARMCC::AL));
1423 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1424 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1425 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1426 if (Register::isPhysicalRegister(DestReg))
1427 MIB.addReg(DestReg, RegState::ImplicitDefine);
1428 }
1429 } else
1430 llvm_unreachable("Unknown reg class!");
1431 break;
1432 case 32:
1433 if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1434 if (Alignment >= 16 && getRegisterInfo().canRealignStack(MF) &&
1435 Subtarget.hasNEON()) {
1436 BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1437 .addFrameIndex(FI)
1438 .addImm(16)
1439 .addMemOperand(MMO)
1440 .add(predOps(ARMCC::AL));
1441 } else {
1442 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1443 .addFrameIndex(FI)
1444 .add(predOps(ARMCC::AL))
1445 .addMemOperand(MMO);
1446 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1447 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1448 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1449 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1450 if (Register::isPhysicalRegister(DestReg))
1451 MIB.addReg(DestReg, RegState::ImplicitDefine);
1452 }
1453 } else
1454 llvm_unreachable("Unknown reg class!");
1455 break;
1456 case 64:
1457 if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1458 MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1459 .addFrameIndex(FI)
1460 .add(predOps(ARMCC::AL))
1461 .addMemOperand(MMO);
1462 MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1463 MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1464 MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1465 MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1466 MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1467 MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1468 MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1469 MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1470 if (Register::isPhysicalRegister(DestReg))
1471 MIB.addReg(DestReg, RegState::ImplicitDefine);
1472 } else
1473 llvm_unreachable("Unknown reg class!");
1474 break;
1475 default:
1476 llvm_unreachable("Unknown regclass!");
1477 }
1478 }
1479
isLoadFromStackSlot(const MachineInstr & MI,int & FrameIndex) const1480 unsigned ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
1481 int &FrameIndex) const {
1482 switch (MI.getOpcode()) {
1483 default: break;
1484 case ARM::LDRrs:
1485 case ARM::t2LDRs: // FIXME: don't use t2LDRs to access frame.
1486 if (MI.getOperand(1).isFI() && MI.getOperand(2).isReg() &&
1487 MI.getOperand(3).isImm() && MI.getOperand(2).getReg() == 0 &&
1488 MI.getOperand(3).getImm() == 0) {
1489 FrameIndex = MI.getOperand(1).getIndex();
1490 return MI.getOperand(0).getReg();
1491 }
1492 break;
1493 case ARM::LDRi12:
1494 case ARM::t2LDRi12:
1495 case ARM::tLDRspi:
1496 case ARM::VLDRD:
1497 case ARM::VLDRS:
1498 if (MI.getOperand(1).isFI() && MI.getOperand(2).isImm() &&
1499 MI.getOperand(2).getImm() == 0) {
1500 FrameIndex = MI.getOperand(1).getIndex();
1501 return MI.getOperand(0).getReg();
1502 }
1503 break;
1504 case ARM::VLDR_P0_off:
1505 if (MI.getOperand(0).isFI() && MI.getOperand(1).isImm() &&
1506 MI.getOperand(1).getImm() == 0) {
1507 FrameIndex = MI.getOperand(0).getIndex();
1508 return ARM::P0;
1509 }
1510 break;
1511 case ARM::VLD1q64:
1512 case ARM::VLD1d8TPseudo:
1513 case ARM::VLD1d16TPseudo:
1514 case ARM::VLD1d32TPseudo:
1515 case ARM::VLD1d64TPseudo:
1516 case ARM::VLD1d8QPseudo:
1517 case ARM::VLD1d16QPseudo:
1518 case ARM::VLD1d32QPseudo:
1519 case ARM::VLD1d64QPseudo:
1520 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1521 FrameIndex = MI.getOperand(1).getIndex();
1522 return MI.getOperand(0).getReg();
1523 }
1524 break;
1525 case ARM::VLDMQIA:
1526 if (MI.getOperand(1).isFI() && MI.getOperand(0).getSubReg() == 0) {
1527 FrameIndex = MI.getOperand(1).getIndex();
1528 return MI.getOperand(0).getReg();
1529 }
1530 break;
1531 }
1532
1533 return 0;
1534 }
1535
isLoadFromStackSlotPostFE(const MachineInstr & MI,int & FrameIndex) const1536 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr &MI,
1537 int &FrameIndex) const {
1538 SmallVector<const MachineMemOperand *, 1> Accesses;
1539 if (MI.mayLoad() && hasLoadFromStackSlot(MI, Accesses) &&
1540 Accesses.size() == 1) {
1541 FrameIndex =
1542 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
1543 ->getFrameIndex();
1544 return true;
1545 }
1546 return false;
1547 }
1548
1549 /// Expands MEMCPY to either LDMIA/STMIA or LDMIA_UPD/STMID_UPD
1550 /// depending on whether the result is used.
expandMEMCPY(MachineBasicBlock::iterator MI) const1551 void ARMBaseInstrInfo::expandMEMCPY(MachineBasicBlock::iterator MI) const {
1552 bool isThumb1 = Subtarget.isThumb1Only();
1553 bool isThumb2 = Subtarget.isThumb2();
1554 const ARMBaseInstrInfo *TII = Subtarget.getInstrInfo();
1555
1556 DebugLoc dl = MI->getDebugLoc();
1557 MachineBasicBlock *BB = MI->getParent();
1558
1559 MachineInstrBuilder LDM, STM;
1560 if (isThumb1 || !MI->getOperand(1).isDead()) {
1561 MachineOperand LDWb(MI->getOperand(1));
1562 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA_UPD
1563 : isThumb1 ? ARM::tLDMIA_UPD
1564 : ARM::LDMIA_UPD))
1565 .add(LDWb);
1566 } else {
1567 LDM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2LDMIA : ARM::LDMIA));
1568 }
1569
1570 if (isThumb1 || !MI->getOperand(0).isDead()) {
1571 MachineOperand STWb(MI->getOperand(0));
1572 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA_UPD
1573 : isThumb1 ? ARM::tSTMIA_UPD
1574 : ARM::STMIA_UPD))
1575 .add(STWb);
1576 } else {
1577 STM = BuildMI(*BB, MI, dl, TII->get(isThumb2 ? ARM::t2STMIA : ARM::STMIA));
1578 }
1579
1580 MachineOperand LDBase(MI->getOperand(3));
1581 LDM.add(LDBase).add(predOps(ARMCC::AL));
1582
1583 MachineOperand STBase(MI->getOperand(2));
1584 STM.add(STBase).add(predOps(ARMCC::AL));
1585
1586 // Sort the scratch registers into ascending order.
1587 const TargetRegisterInfo &TRI = getRegisterInfo();
1588 SmallVector<unsigned, 6> ScratchRegs;
1589 for(unsigned I = 5; I < MI->getNumOperands(); ++I)
1590 ScratchRegs.push_back(MI->getOperand(I).getReg());
1591 llvm::sort(ScratchRegs,
1592 [&TRI](const unsigned &Reg1, const unsigned &Reg2) -> bool {
1593 return TRI.getEncodingValue(Reg1) <
1594 TRI.getEncodingValue(Reg2);
1595 });
1596
1597 for (const auto &Reg : ScratchRegs) {
1598 LDM.addReg(Reg, RegState::Define);
1599 STM.addReg(Reg, RegState::Kill);
1600 }
1601
1602 BB->erase(MI);
1603 }
1604
expandPostRAPseudo(MachineInstr & MI) const1605 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1606 if (MI.getOpcode() == TargetOpcode::LOAD_STACK_GUARD) {
1607 assert(getSubtarget().getTargetTriple().isOSBinFormatMachO() &&
1608 "LOAD_STACK_GUARD currently supported only for MachO.");
1609 expandLoadStackGuard(MI);
1610 MI.getParent()->erase(MI);
1611 return true;
1612 }
1613
1614 if (MI.getOpcode() == ARM::MEMCPY) {
1615 expandMEMCPY(MI);
1616 return true;
1617 }
1618
1619 // This hook gets to expand COPY instructions before they become
1620 // copyPhysReg() calls. Look for VMOVS instructions that can legally be
1621 // widened to VMOVD. We prefer the VMOVD when possible because it may be
1622 // changed into a VORR that can go down the NEON pipeline.
1623 if (!MI.isCopy() || Subtarget.dontWidenVMOVS() || !Subtarget.hasFP64())
1624 return false;
1625
1626 // Look for a copy between even S-registers. That is where we keep floats
1627 // when using NEON v2f32 instructions for f32 arithmetic.
1628 Register DstRegS = MI.getOperand(0).getReg();
1629 Register SrcRegS = MI.getOperand(1).getReg();
1630 if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1631 return false;
1632
1633 const TargetRegisterInfo *TRI = &getRegisterInfo();
1634 unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1635 &ARM::DPRRegClass);
1636 unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1637 &ARM::DPRRegClass);
1638 if (!DstRegD || !SrcRegD)
1639 return false;
1640
1641 // We want to widen this into a DstRegD = VMOVD SrcRegD copy. This is only
1642 // legal if the COPY already defines the full DstRegD, and it isn't a
1643 // sub-register insertion.
1644 if (!MI.definesRegister(DstRegD, TRI) || MI.readsRegister(DstRegD, TRI))
1645 return false;
1646
1647 // A dead copy shouldn't show up here, but reject it just in case.
1648 if (MI.getOperand(0).isDead())
1649 return false;
1650
1651 // All clear, widen the COPY.
1652 LLVM_DEBUG(dbgs() << "widening: " << MI);
1653 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
1654
1655 // Get rid of the old implicit-def of DstRegD. Leave it if it defines a Q-reg
1656 // or some other super-register.
1657 int ImpDefIdx = MI.findRegisterDefOperandIdx(DstRegD);
1658 if (ImpDefIdx != -1)
1659 MI.RemoveOperand(ImpDefIdx);
1660
1661 // Change the opcode and operands.
1662 MI.setDesc(get(ARM::VMOVD));
1663 MI.getOperand(0).setReg(DstRegD);
1664 MI.getOperand(1).setReg(SrcRegD);
1665 MIB.add(predOps(ARMCC::AL));
1666
1667 // We are now reading SrcRegD instead of SrcRegS. This may upset the
1668 // register scavenger and machine verifier, so we need to indicate that we
1669 // are reading an undefined value from SrcRegD, but a proper value from
1670 // SrcRegS.
1671 MI.getOperand(1).setIsUndef();
1672 MIB.addReg(SrcRegS, RegState::Implicit);
1673
1674 // SrcRegD may actually contain an unrelated value in the ssub_1
1675 // sub-register. Don't kill it. Only kill the ssub_0 sub-register.
1676 if (MI.getOperand(1).isKill()) {
1677 MI.getOperand(1).setIsKill(false);
1678 MI.addRegisterKilled(SrcRegS, TRI, true);
1679 }
1680
1681 LLVM_DEBUG(dbgs() << "replaced by: " << MI);
1682 return true;
1683 }
1684
1685 /// Create a copy of a const pool value. Update CPI to the new index and return
1686 /// the label UID.
duplicateCPV(MachineFunction & MF,unsigned & CPI)1687 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1688 MachineConstantPool *MCP = MF.getConstantPool();
1689 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1690
1691 const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1692 assert(MCPE.isMachineConstantPoolEntry() &&
1693 "Expecting a machine constantpool entry!");
1694 ARMConstantPoolValue *ACPV =
1695 static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1696
1697 unsigned PCLabelId = AFI->createPICLabelUId();
1698 ARMConstantPoolValue *NewCPV = nullptr;
1699
1700 // FIXME: The below assumes PIC relocation model and that the function
1701 // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1702 // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1703 // instructions, so that's probably OK, but is PIC always correct when
1704 // we get here?
1705 if (ACPV->isGlobalValue())
1706 NewCPV = ARMConstantPoolConstant::Create(
1707 cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId, ARMCP::CPValue,
1708 4, ACPV->getModifier(), ACPV->mustAddCurrentAddress());
1709 else if (ACPV->isExtSymbol())
1710 NewCPV = ARMConstantPoolSymbol::
1711 Create(MF.getFunction().getContext(),
1712 cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1713 else if (ACPV->isBlockAddress())
1714 NewCPV = ARMConstantPoolConstant::
1715 Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1716 ARMCP::CPBlockAddress, 4);
1717 else if (ACPV->isLSDA())
1718 NewCPV = ARMConstantPoolConstant::Create(&MF.getFunction(), PCLabelId,
1719 ARMCP::CPLSDA, 4);
1720 else if (ACPV->isMachineBasicBlock())
1721 NewCPV = ARMConstantPoolMBB::
1722 Create(MF.getFunction().getContext(),
1723 cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1724 else
1725 llvm_unreachable("Unexpected ARM constantpool value type!!");
1726 CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlign());
1727 return PCLabelId;
1728 }
1729
reMaterialize(MachineBasicBlock & MBB,MachineBasicBlock::iterator I,Register DestReg,unsigned SubIdx,const MachineInstr & Orig,const TargetRegisterInfo & TRI) const1730 void ARMBaseInstrInfo::reMaterialize(MachineBasicBlock &MBB,
1731 MachineBasicBlock::iterator I,
1732 Register DestReg, unsigned SubIdx,
1733 const MachineInstr &Orig,
1734 const TargetRegisterInfo &TRI) const {
1735 unsigned Opcode = Orig.getOpcode();
1736 switch (Opcode) {
1737 default: {
1738 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
1739 MI->substituteRegister(Orig.getOperand(0).getReg(), DestReg, SubIdx, TRI);
1740 MBB.insert(I, MI);
1741 break;
1742 }
1743 case ARM::tLDRpci_pic:
1744 case ARM::t2LDRpci_pic: {
1745 MachineFunction &MF = *MBB.getParent();
1746 unsigned CPI = Orig.getOperand(1).getIndex();
1747 unsigned PCLabelId = duplicateCPV(MF, CPI);
1748 BuildMI(MBB, I, Orig.getDebugLoc(), get(Opcode), DestReg)
1749 .addConstantPoolIndex(CPI)
1750 .addImm(PCLabelId)
1751 .cloneMemRefs(Orig);
1752 break;
1753 }
1754 }
1755 }
1756
1757 MachineInstr &
duplicate(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const MachineInstr & Orig) const1758 ARMBaseInstrInfo::duplicate(MachineBasicBlock &MBB,
1759 MachineBasicBlock::iterator InsertBefore,
1760 const MachineInstr &Orig) const {
1761 MachineInstr &Cloned = TargetInstrInfo::duplicate(MBB, InsertBefore, Orig);
1762 MachineBasicBlock::instr_iterator I = Cloned.getIterator();
1763 for (;;) {
1764 switch (I->getOpcode()) {
1765 case ARM::tLDRpci_pic:
1766 case ARM::t2LDRpci_pic: {
1767 MachineFunction &MF = *MBB.getParent();
1768 unsigned CPI = I->getOperand(1).getIndex();
1769 unsigned PCLabelId = duplicateCPV(MF, CPI);
1770 I->getOperand(1).setIndex(CPI);
1771 I->getOperand(2).setImm(PCLabelId);
1772 break;
1773 }
1774 }
1775 if (!I->isBundledWithSucc())
1776 break;
1777 ++I;
1778 }
1779 return Cloned;
1780 }
1781
produceSameValue(const MachineInstr & MI0,const MachineInstr & MI1,const MachineRegisterInfo * MRI) const1782 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr &MI0,
1783 const MachineInstr &MI1,
1784 const MachineRegisterInfo *MRI) const {
1785 unsigned Opcode = MI0.getOpcode();
1786 if (Opcode == ARM::t2LDRpci ||
1787 Opcode == ARM::t2LDRpci_pic ||
1788 Opcode == ARM::tLDRpci ||
1789 Opcode == ARM::tLDRpci_pic ||
1790 Opcode == ARM::LDRLIT_ga_pcrel ||
1791 Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1792 Opcode == ARM::tLDRLIT_ga_pcrel ||
1793 Opcode == ARM::MOV_ga_pcrel ||
1794 Opcode == ARM::MOV_ga_pcrel_ldr ||
1795 Opcode == ARM::t2MOV_ga_pcrel) {
1796 if (MI1.getOpcode() != Opcode)
1797 return false;
1798 if (MI0.getNumOperands() != MI1.getNumOperands())
1799 return false;
1800
1801 const MachineOperand &MO0 = MI0.getOperand(1);
1802 const MachineOperand &MO1 = MI1.getOperand(1);
1803 if (MO0.getOffset() != MO1.getOffset())
1804 return false;
1805
1806 if (Opcode == ARM::LDRLIT_ga_pcrel ||
1807 Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1808 Opcode == ARM::tLDRLIT_ga_pcrel ||
1809 Opcode == ARM::MOV_ga_pcrel ||
1810 Opcode == ARM::MOV_ga_pcrel_ldr ||
1811 Opcode == ARM::t2MOV_ga_pcrel)
1812 // Ignore the PC labels.
1813 return MO0.getGlobal() == MO1.getGlobal();
1814
1815 const MachineFunction *MF = MI0.getParent()->getParent();
1816 const MachineConstantPool *MCP = MF->getConstantPool();
1817 int CPI0 = MO0.getIndex();
1818 int CPI1 = MO1.getIndex();
1819 const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1820 const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1821 bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1822 bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1823 if (isARMCP0 && isARMCP1) {
1824 ARMConstantPoolValue *ACPV0 =
1825 static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1826 ARMConstantPoolValue *ACPV1 =
1827 static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1828 return ACPV0->hasSameValue(ACPV1);
1829 } else if (!isARMCP0 && !isARMCP1) {
1830 return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1831 }
1832 return false;
1833 } else if (Opcode == ARM::PICLDR) {
1834 if (MI1.getOpcode() != Opcode)
1835 return false;
1836 if (MI0.getNumOperands() != MI1.getNumOperands())
1837 return false;
1838
1839 Register Addr0 = MI0.getOperand(1).getReg();
1840 Register Addr1 = MI1.getOperand(1).getReg();
1841 if (Addr0 != Addr1) {
1842 if (!MRI || !Register::isVirtualRegister(Addr0) ||
1843 !Register::isVirtualRegister(Addr1))
1844 return false;
1845
1846 // This assumes SSA form.
1847 MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1848 MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1849 // Check if the loaded value, e.g. a constantpool of a global address, are
1850 // the same.
1851 if (!produceSameValue(*Def0, *Def1, MRI))
1852 return false;
1853 }
1854
1855 for (unsigned i = 3, e = MI0.getNumOperands(); i != e; ++i) {
1856 // %12 = PICLDR %11, 0, 14, %noreg
1857 const MachineOperand &MO0 = MI0.getOperand(i);
1858 const MachineOperand &MO1 = MI1.getOperand(i);
1859 if (!MO0.isIdenticalTo(MO1))
1860 return false;
1861 }
1862 return true;
1863 }
1864
1865 return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1866 }
1867
1868 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1869 /// determine if two loads are loading from the same base address. It should
1870 /// only return true if the base pointers are the same and the only differences
1871 /// between the two addresses is the offset. It also returns the offsets by
1872 /// reference.
1873 ///
1874 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1875 /// is permanently disabled.
areLoadsFromSameBasePtr(SDNode * Load1,SDNode * Load2,int64_t & Offset1,int64_t & Offset2) const1876 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1877 int64_t &Offset1,
1878 int64_t &Offset2) const {
1879 // Don't worry about Thumb: just ARM and Thumb2.
1880 if (Subtarget.isThumb1Only()) return false;
1881
1882 if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1883 return false;
1884
1885 switch (Load1->getMachineOpcode()) {
1886 default:
1887 return false;
1888 case ARM::LDRi12:
1889 case ARM::LDRBi12:
1890 case ARM::LDRD:
1891 case ARM::LDRH:
1892 case ARM::LDRSB:
1893 case ARM::LDRSH:
1894 case ARM::VLDRD:
1895 case ARM::VLDRS:
1896 case ARM::t2LDRi8:
1897 case ARM::t2LDRBi8:
1898 case ARM::t2LDRDi8:
1899 case ARM::t2LDRSHi8:
1900 case ARM::t2LDRi12:
1901 case ARM::t2LDRBi12:
1902 case ARM::t2LDRSHi12:
1903 break;
1904 }
1905
1906 switch (Load2->getMachineOpcode()) {
1907 default:
1908 return false;
1909 case ARM::LDRi12:
1910 case ARM::LDRBi12:
1911 case ARM::LDRD:
1912 case ARM::LDRH:
1913 case ARM::LDRSB:
1914 case ARM::LDRSH:
1915 case ARM::VLDRD:
1916 case ARM::VLDRS:
1917 case ARM::t2LDRi8:
1918 case ARM::t2LDRBi8:
1919 case ARM::t2LDRSHi8:
1920 case ARM::t2LDRi12:
1921 case ARM::t2LDRBi12:
1922 case ARM::t2LDRSHi12:
1923 break;
1924 }
1925
1926 // Check if base addresses and chain operands match.
1927 if (Load1->getOperand(0) != Load2->getOperand(0) ||
1928 Load1->getOperand(4) != Load2->getOperand(4))
1929 return false;
1930
1931 // Index should be Reg0.
1932 if (Load1->getOperand(3) != Load2->getOperand(3))
1933 return false;
1934
1935 // Determine the offsets.
1936 if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1937 isa<ConstantSDNode>(Load2->getOperand(1))) {
1938 Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1939 Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1940 return true;
1941 }
1942
1943 return false;
1944 }
1945
1946 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1947 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1948 /// be scheduled togther. On some targets if two loads are loading from
1949 /// addresses in the same cache line, it's better if they are scheduled
1950 /// together. This function takes two integers that represent the load offsets
1951 /// from the common base address. It returns true if it decides it's desirable
1952 /// to schedule the two loads together. "NumLoads" is the number of loads that
1953 /// have already been scheduled after Load1.
1954 ///
1955 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1956 /// is permanently disabled.
shouldScheduleLoadsNear(SDNode * Load1,SDNode * Load2,int64_t Offset1,int64_t Offset2,unsigned NumLoads) const1957 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1958 int64_t Offset1, int64_t Offset2,
1959 unsigned NumLoads) const {
1960 // Don't worry about Thumb: just ARM and Thumb2.
1961 if (Subtarget.isThumb1Only()) return false;
1962
1963 assert(Offset2 > Offset1);
1964
1965 if ((Offset2 - Offset1) / 8 > 64)
1966 return false;
1967
1968 // Check if the machine opcodes are different. If they are different
1969 // then we consider them to not be of the same base address,
1970 // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
1971 // In this case, they are considered to be the same because they are different
1972 // encoding forms of the same basic instruction.
1973 if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
1974 !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
1975 Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
1976 (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
1977 Load2->getMachineOpcode() == ARM::t2LDRBi8)))
1978 return false; // FIXME: overly conservative?
1979
1980 // Four loads in a row should be sufficient.
1981 if (NumLoads >= 3)
1982 return false;
1983
1984 return true;
1985 }
1986
isSchedulingBoundary(const MachineInstr & MI,const MachineBasicBlock * MBB,const MachineFunction & MF) const1987 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1988 const MachineBasicBlock *MBB,
1989 const MachineFunction &MF) const {
1990 // Debug info is never a scheduling boundary. It's necessary to be explicit
1991 // due to the special treatment of IT instructions below, otherwise a
1992 // dbg_value followed by an IT will result in the IT instruction being
1993 // considered a scheduling hazard, which is wrong. It should be the actual
1994 // instruction preceding the dbg_value instruction(s), just like it is
1995 // when debug info is not present.
1996 if (MI.isDebugInstr())
1997 return false;
1998
1999 // Terminators and labels can't be scheduled around.
2000 if (MI.isTerminator() || MI.isPosition())
2001 return true;
2002
2003 // INLINEASM_BR can jump to another block
2004 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
2005 return true;
2006
2007 // Treat the start of the IT block as a scheduling boundary, but schedule
2008 // t2IT along with all instructions following it.
2009 // FIXME: This is a big hammer. But the alternative is to add all potential
2010 // true and anti dependencies to IT block instructions as implicit operands
2011 // to the t2IT instruction. The added compile time and complexity does not
2012 // seem worth it.
2013 MachineBasicBlock::const_iterator I = MI;
2014 // Make sure to skip any debug instructions
2015 while (++I != MBB->end() && I->isDebugInstr())
2016 ;
2017 if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
2018 return true;
2019
2020 // Don't attempt to schedule around any instruction that defines
2021 // a stack-oriented pointer, as it's unlikely to be profitable. This
2022 // saves compile time, because it doesn't require every single
2023 // stack slot reference to depend on the instruction that does the
2024 // modification.
2025 // Calls don't actually change the stack pointer, even if they have imp-defs.
2026 // No ARM calling conventions change the stack pointer. (X86 calling
2027 // conventions sometimes do).
2028 if (!MI.isCall() && MI.definesRegister(ARM::SP))
2029 return true;
2030
2031 return false;
2032 }
2033
2034 bool ARMBaseInstrInfo::
isProfitableToIfCvt(MachineBasicBlock & MBB,unsigned NumCycles,unsigned ExtraPredCycles,BranchProbability Probability) const2035 isProfitableToIfCvt(MachineBasicBlock &MBB,
2036 unsigned NumCycles, unsigned ExtraPredCycles,
2037 BranchProbability Probability) const {
2038 if (!NumCycles)
2039 return false;
2040
2041 // If we are optimizing for size, see if the branch in the predecessor can be
2042 // lowered to cbn?z by the constant island lowering pass, and return false if
2043 // so. This results in a shorter instruction sequence.
2044 if (MBB.getParent()->getFunction().hasOptSize()) {
2045 MachineBasicBlock *Pred = *MBB.pred_begin();
2046 if (!Pred->empty()) {
2047 MachineInstr *LastMI = &*Pred->rbegin();
2048 if (LastMI->getOpcode() == ARM::t2Bcc) {
2049 const TargetRegisterInfo *TRI = &getRegisterInfo();
2050 MachineInstr *CmpMI = findCMPToFoldIntoCBZ(LastMI, TRI);
2051 if (CmpMI)
2052 return false;
2053 }
2054 }
2055 }
2056 return isProfitableToIfCvt(MBB, NumCycles, ExtraPredCycles,
2057 MBB, 0, 0, Probability);
2058 }
2059
2060 bool ARMBaseInstrInfo::
isProfitableToIfCvt(MachineBasicBlock & TBB,unsigned TCycles,unsigned TExtra,MachineBasicBlock & FBB,unsigned FCycles,unsigned FExtra,BranchProbability Probability) const2061 isProfitableToIfCvt(MachineBasicBlock &TBB,
2062 unsigned TCycles, unsigned TExtra,
2063 MachineBasicBlock &FBB,
2064 unsigned FCycles, unsigned FExtra,
2065 BranchProbability Probability) const {
2066 if (!TCycles)
2067 return false;
2068
2069 // In thumb code we often end up trading one branch for a IT block, and
2070 // if we are cloning the instruction can increase code size. Prevent
2071 // blocks with multiple predecesors from being ifcvted to prevent this
2072 // cloning.
2073 if (Subtarget.isThumb2() && TBB.getParent()->getFunction().hasMinSize()) {
2074 if (TBB.pred_size() != 1 || FBB.pred_size() != 1)
2075 return false;
2076 }
2077
2078 // Attempt to estimate the relative costs of predication versus branching.
2079 // Here we scale up each component of UnpredCost to avoid precision issue when
2080 // scaling TCycles/FCycles by Probability.
2081 const unsigned ScalingUpFactor = 1024;
2082
2083 unsigned PredCost = (TCycles + FCycles + TExtra + FExtra) * ScalingUpFactor;
2084 unsigned UnpredCost;
2085 if (!Subtarget.hasBranchPredictor()) {
2086 // When we don't have a branch predictor it's always cheaper to not take a
2087 // branch than take it, so we have to take that into account.
2088 unsigned NotTakenBranchCost = 1;
2089 unsigned TakenBranchCost = Subtarget.getMispredictionPenalty();
2090 unsigned TUnpredCycles, FUnpredCycles;
2091 if (!FCycles) {
2092 // Triangle: TBB is the fallthrough
2093 TUnpredCycles = TCycles + NotTakenBranchCost;
2094 FUnpredCycles = TakenBranchCost;
2095 } else {
2096 // Diamond: TBB is the block that is branched to, FBB is the fallthrough
2097 TUnpredCycles = TCycles + TakenBranchCost;
2098 FUnpredCycles = FCycles + NotTakenBranchCost;
2099 // The branch at the end of FBB will disappear when it's predicated, so
2100 // discount it from PredCost.
2101 PredCost -= 1 * ScalingUpFactor;
2102 }
2103 // The total cost is the cost of each path scaled by their probabilites
2104 unsigned TUnpredCost = Probability.scale(TUnpredCycles * ScalingUpFactor);
2105 unsigned FUnpredCost = Probability.getCompl().scale(FUnpredCycles * ScalingUpFactor);
2106 UnpredCost = TUnpredCost + FUnpredCost;
2107 // When predicating assume that the first IT can be folded away but later
2108 // ones cost one cycle each
2109 if (Subtarget.isThumb2() && TCycles + FCycles > 4) {
2110 PredCost += ((TCycles + FCycles - 4) / 4) * ScalingUpFactor;
2111 }
2112 } else {
2113 unsigned TUnpredCost = Probability.scale(TCycles * ScalingUpFactor);
2114 unsigned FUnpredCost =
2115 Probability.getCompl().scale(FCycles * ScalingUpFactor);
2116 UnpredCost = TUnpredCost + FUnpredCost;
2117 UnpredCost += 1 * ScalingUpFactor; // The branch itself
2118 UnpredCost += Subtarget.getMispredictionPenalty() * ScalingUpFactor / 10;
2119 }
2120
2121 return PredCost <= UnpredCost;
2122 }
2123
2124 unsigned
extraSizeToPredicateInstructions(const MachineFunction & MF,unsigned NumInsts) const2125 ARMBaseInstrInfo::extraSizeToPredicateInstructions(const MachineFunction &MF,
2126 unsigned NumInsts) const {
2127 // Thumb2 needs a 2-byte IT instruction to predicate up to 4 instructions.
2128 // ARM has a condition code field in every predicable instruction, using it
2129 // doesn't change code size.
2130 if (!Subtarget.isThumb2())
2131 return 0;
2132
2133 // It's possible that the size of the IT is restricted to a single block.
2134 unsigned MaxInsts = Subtarget.restrictIT() ? 1 : 4;
2135 return divideCeil(NumInsts, MaxInsts) * 2;
2136 }
2137
2138 unsigned
predictBranchSizeForIfCvt(MachineInstr & MI) const2139 ARMBaseInstrInfo::predictBranchSizeForIfCvt(MachineInstr &MI) const {
2140 // If this branch is likely to be folded into the comparison to form a
2141 // CB(N)Z, then removing it won't reduce code size at all, because that will
2142 // just replace the CB(N)Z with a CMP.
2143 if (MI.getOpcode() == ARM::t2Bcc &&
2144 findCMPToFoldIntoCBZ(&MI, &getRegisterInfo()))
2145 return 0;
2146
2147 unsigned Size = getInstSizeInBytes(MI);
2148
2149 // For Thumb2, all branches are 32-bit instructions during the if conversion
2150 // pass, but may be replaced with 16-bit instructions during size reduction.
2151 // Since the branches considered by if conversion tend to be forward branches
2152 // over small basic blocks, they are very likely to be in range for the
2153 // narrow instructions, so we assume the final code size will be half what it
2154 // currently is.
2155 if (Subtarget.isThumb2())
2156 Size /= 2;
2157
2158 return Size;
2159 }
2160
2161 bool
isProfitableToUnpredicate(MachineBasicBlock & TMBB,MachineBasicBlock & FMBB) const2162 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
2163 MachineBasicBlock &FMBB) const {
2164 // Reduce false anti-dependencies to let the target's out-of-order execution
2165 // engine do its thing.
2166 return Subtarget.isProfitableToUnpredicate();
2167 }
2168
2169 /// getInstrPredicate - If instruction is predicated, returns its predicate
2170 /// condition, otherwise returns AL. It also returns the condition code
2171 /// register by reference.
getInstrPredicate(const MachineInstr & MI,Register & PredReg)2172 ARMCC::CondCodes llvm::getInstrPredicate(const MachineInstr &MI,
2173 Register &PredReg) {
2174 int PIdx = MI.findFirstPredOperandIdx();
2175 if (PIdx == -1) {
2176 PredReg = 0;
2177 return ARMCC::AL;
2178 }
2179
2180 PredReg = MI.getOperand(PIdx+1).getReg();
2181 return (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
2182 }
2183
getMatchingCondBranchOpcode(unsigned Opc)2184 unsigned llvm::getMatchingCondBranchOpcode(unsigned Opc) {
2185 if (Opc == ARM::B)
2186 return ARM::Bcc;
2187 if (Opc == ARM::tB)
2188 return ARM::tBcc;
2189 if (Opc == ARM::t2B)
2190 return ARM::t2Bcc;
2191
2192 llvm_unreachable("Unknown unconditional branch opcode!");
2193 }
2194
commuteInstructionImpl(MachineInstr & MI,bool NewMI,unsigned OpIdx1,unsigned OpIdx2) const2195 MachineInstr *ARMBaseInstrInfo::commuteInstructionImpl(MachineInstr &MI,
2196 bool NewMI,
2197 unsigned OpIdx1,
2198 unsigned OpIdx2) const {
2199 switch (MI.getOpcode()) {
2200 case ARM::MOVCCr:
2201 case ARM::t2MOVCCr: {
2202 // MOVCC can be commuted by inverting the condition.
2203 Register PredReg;
2204 ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
2205 // MOVCC AL can't be inverted. Shouldn't happen.
2206 if (CC == ARMCC::AL || PredReg != ARM::CPSR)
2207 return nullptr;
2208 MachineInstr *CommutedMI =
2209 TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2210 if (!CommutedMI)
2211 return nullptr;
2212 // After swapping the MOVCC operands, also invert the condition.
2213 CommutedMI->getOperand(CommutedMI->findFirstPredOperandIdx())
2214 .setImm(ARMCC::getOppositeCondition(CC));
2215 return CommutedMI;
2216 }
2217 }
2218 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
2219 }
2220
2221 /// Identify instructions that can be folded into a MOVCC instruction, and
2222 /// return the defining instruction.
2223 MachineInstr *
canFoldIntoMOVCC(Register Reg,const MachineRegisterInfo & MRI,const TargetInstrInfo * TII) const2224 ARMBaseInstrInfo::canFoldIntoMOVCC(Register Reg, const MachineRegisterInfo &MRI,
2225 const TargetInstrInfo *TII) const {
2226 if (!Reg.isVirtual())
2227 return nullptr;
2228 if (!MRI.hasOneNonDBGUse(Reg))
2229 return nullptr;
2230 MachineInstr *MI = MRI.getVRegDef(Reg);
2231 if (!MI)
2232 return nullptr;
2233 // Check if MI can be predicated and folded into the MOVCC.
2234 if (!isPredicable(*MI))
2235 return nullptr;
2236 // Check if MI has any non-dead defs or physreg uses. This also detects
2237 // predicated instructions which will be reading CPSR.
2238 for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
2239 const MachineOperand &MO = MI->getOperand(i);
2240 // Reject frame index operands, PEI can't handle the predicated pseudos.
2241 if (MO.isFI() || MO.isCPI() || MO.isJTI())
2242 return nullptr;
2243 if (!MO.isReg())
2244 continue;
2245 // MI can't have any tied operands, that would conflict with predication.
2246 if (MO.isTied())
2247 return nullptr;
2248 if (Register::isPhysicalRegister(MO.getReg()))
2249 return nullptr;
2250 if (MO.isDef() && !MO.isDead())
2251 return nullptr;
2252 }
2253 bool DontMoveAcrossStores = true;
2254 if (!MI->isSafeToMove(/* AliasAnalysis = */ nullptr, DontMoveAcrossStores))
2255 return nullptr;
2256 return MI;
2257 }
2258
analyzeSelect(const MachineInstr & MI,SmallVectorImpl<MachineOperand> & Cond,unsigned & TrueOp,unsigned & FalseOp,bool & Optimizable) const2259 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr &MI,
2260 SmallVectorImpl<MachineOperand> &Cond,
2261 unsigned &TrueOp, unsigned &FalseOp,
2262 bool &Optimizable) const {
2263 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2264 "Unknown select instruction");
2265 // MOVCC operands:
2266 // 0: Def.
2267 // 1: True use.
2268 // 2: False use.
2269 // 3: Condition code.
2270 // 4: CPSR use.
2271 TrueOp = 1;
2272 FalseOp = 2;
2273 Cond.push_back(MI.getOperand(3));
2274 Cond.push_back(MI.getOperand(4));
2275 // We can always fold a def.
2276 Optimizable = true;
2277 return false;
2278 }
2279
2280 MachineInstr *
optimizeSelect(MachineInstr & MI,SmallPtrSetImpl<MachineInstr * > & SeenMIs,bool PreferFalse) const2281 ARMBaseInstrInfo::optimizeSelect(MachineInstr &MI,
2282 SmallPtrSetImpl<MachineInstr *> &SeenMIs,
2283 bool PreferFalse) const {
2284 assert((MI.getOpcode() == ARM::MOVCCr || MI.getOpcode() == ARM::t2MOVCCr) &&
2285 "Unknown select instruction");
2286 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2287 MachineInstr *DefMI = canFoldIntoMOVCC(MI.getOperand(2).getReg(), MRI, this);
2288 bool Invert = !DefMI;
2289 if (!DefMI)
2290 DefMI = canFoldIntoMOVCC(MI.getOperand(1).getReg(), MRI, this);
2291 if (!DefMI)
2292 return nullptr;
2293
2294 // Find new register class to use.
2295 MachineOperand FalseReg = MI.getOperand(Invert ? 2 : 1);
2296 Register DestReg = MI.getOperand(0).getReg();
2297 const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
2298 if (!MRI.constrainRegClass(DestReg, PreviousClass))
2299 return nullptr;
2300
2301 // Create a new predicated version of DefMI.
2302 // Rfalse is the first use.
2303 MachineInstrBuilder NewMI =
2304 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), DefMI->getDesc(), DestReg);
2305
2306 // Copy all the DefMI operands, excluding its (null) predicate.
2307 const MCInstrDesc &DefDesc = DefMI->getDesc();
2308 for (unsigned i = 1, e = DefDesc.getNumOperands();
2309 i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
2310 NewMI.add(DefMI->getOperand(i));
2311
2312 unsigned CondCode = MI.getOperand(3).getImm();
2313 if (Invert)
2314 NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
2315 else
2316 NewMI.addImm(CondCode);
2317 NewMI.add(MI.getOperand(4));
2318
2319 // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
2320 if (NewMI->hasOptionalDef())
2321 NewMI.add(condCodeOp());
2322
2323 // The output register value when the predicate is false is an implicit
2324 // register operand tied to the first def.
2325 // The tie makes the register allocator ensure the FalseReg is allocated the
2326 // same register as operand 0.
2327 FalseReg.setImplicit();
2328 NewMI.add(FalseReg);
2329 NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
2330
2331 // Update SeenMIs set: register newly created MI and erase removed DefMI.
2332 SeenMIs.insert(NewMI);
2333 SeenMIs.erase(DefMI);
2334
2335 // If MI is inside a loop, and DefMI is outside the loop, then kill flags on
2336 // DefMI would be invalid when tranferred inside the loop. Checking for a
2337 // loop is expensive, but at least remove kill flags if they are in different
2338 // BBs.
2339 if (DefMI->getParent() != MI.getParent())
2340 NewMI->clearKillInfo();
2341
2342 // The caller will erase MI, but not DefMI.
2343 DefMI->eraseFromParent();
2344 return NewMI;
2345 }
2346
2347 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
2348 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
2349 /// def operand.
2350 ///
2351 /// This will go away once we can teach tblgen how to set the optional CPSR def
2352 /// operand itself.
2353 struct AddSubFlagsOpcodePair {
2354 uint16_t PseudoOpc;
2355 uint16_t MachineOpc;
2356 };
2357
2358 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
2359 {ARM::ADDSri, ARM::ADDri},
2360 {ARM::ADDSrr, ARM::ADDrr},
2361 {ARM::ADDSrsi, ARM::ADDrsi},
2362 {ARM::ADDSrsr, ARM::ADDrsr},
2363
2364 {ARM::SUBSri, ARM::SUBri},
2365 {ARM::SUBSrr, ARM::SUBrr},
2366 {ARM::SUBSrsi, ARM::SUBrsi},
2367 {ARM::SUBSrsr, ARM::SUBrsr},
2368
2369 {ARM::RSBSri, ARM::RSBri},
2370 {ARM::RSBSrsi, ARM::RSBrsi},
2371 {ARM::RSBSrsr, ARM::RSBrsr},
2372
2373 {ARM::tADDSi3, ARM::tADDi3},
2374 {ARM::tADDSi8, ARM::tADDi8},
2375 {ARM::tADDSrr, ARM::tADDrr},
2376 {ARM::tADCS, ARM::tADC},
2377
2378 {ARM::tSUBSi3, ARM::tSUBi3},
2379 {ARM::tSUBSi8, ARM::tSUBi8},
2380 {ARM::tSUBSrr, ARM::tSUBrr},
2381 {ARM::tSBCS, ARM::tSBC},
2382 {ARM::tRSBS, ARM::tRSB},
2383 {ARM::tLSLSri, ARM::tLSLri},
2384
2385 {ARM::t2ADDSri, ARM::t2ADDri},
2386 {ARM::t2ADDSrr, ARM::t2ADDrr},
2387 {ARM::t2ADDSrs, ARM::t2ADDrs},
2388
2389 {ARM::t2SUBSri, ARM::t2SUBri},
2390 {ARM::t2SUBSrr, ARM::t2SUBrr},
2391 {ARM::t2SUBSrs, ARM::t2SUBrs},
2392
2393 {ARM::t2RSBSri, ARM::t2RSBri},
2394 {ARM::t2RSBSrs, ARM::t2RSBrs},
2395 };
2396
convertAddSubFlagsOpcode(unsigned OldOpc)2397 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
2398 for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
2399 if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
2400 return AddSubFlagsOpcodeMap[i].MachineOpc;
2401 return 0;
2402 }
2403
emitARMRegPlusImmediate(MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,const DebugLoc & dl,Register DestReg,Register BaseReg,int NumBytes,ARMCC::CondCodes Pred,Register PredReg,const ARMBaseInstrInfo & TII,unsigned MIFlags)2404 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
2405 MachineBasicBlock::iterator &MBBI,
2406 const DebugLoc &dl, Register DestReg,
2407 Register BaseReg, int NumBytes,
2408 ARMCC::CondCodes Pred, Register PredReg,
2409 const ARMBaseInstrInfo &TII,
2410 unsigned MIFlags) {
2411 if (NumBytes == 0 && DestReg != BaseReg) {
2412 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
2413 .addReg(BaseReg, RegState::Kill)
2414 .add(predOps(Pred, PredReg))
2415 .add(condCodeOp())
2416 .setMIFlags(MIFlags);
2417 return;
2418 }
2419
2420 bool isSub = NumBytes < 0;
2421 if (isSub) NumBytes = -NumBytes;
2422
2423 while (NumBytes) {
2424 unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
2425 unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
2426 assert(ThisVal && "Didn't extract field correctly");
2427
2428 // We will handle these bits from offset, clear them.
2429 NumBytes &= ~ThisVal;
2430
2431 assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
2432
2433 // Build the new ADD / SUB.
2434 unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
2435 BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
2436 .addReg(BaseReg, RegState::Kill)
2437 .addImm(ThisVal)
2438 .add(predOps(Pred, PredReg))
2439 .add(condCodeOp())
2440 .setMIFlags(MIFlags);
2441 BaseReg = DestReg;
2442 }
2443 }
2444
tryFoldSPUpdateIntoPushPop(const ARMSubtarget & Subtarget,MachineFunction & MF,MachineInstr * MI,unsigned NumBytes)2445 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
2446 MachineFunction &MF, MachineInstr *MI,
2447 unsigned NumBytes) {
2448 // This optimisation potentially adds lots of load and store
2449 // micro-operations, it's only really a great benefit to code-size.
2450 if (!Subtarget.hasMinSize())
2451 return false;
2452
2453 // If only one register is pushed/popped, LLVM can use an LDR/STR
2454 // instead. We can't modify those so make sure we're dealing with an
2455 // instruction we understand.
2456 bool IsPop = isPopOpcode(MI->getOpcode());
2457 bool IsPush = isPushOpcode(MI->getOpcode());
2458 if (!IsPush && !IsPop)
2459 return false;
2460
2461 bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
2462 MI->getOpcode() == ARM::VLDMDIA_UPD;
2463 bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
2464 MI->getOpcode() == ARM::tPOP ||
2465 MI->getOpcode() == ARM::tPOP_RET;
2466
2467 assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
2468 MI->getOperand(1).getReg() == ARM::SP)) &&
2469 "trying to fold sp update into non-sp-updating push/pop");
2470
2471 // The VFP push & pop act on D-registers, so we can only fold an adjustment
2472 // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
2473 // if this is violated.
2474 if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
2475 return false;
2476
2477 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
2478 // pred) so the list starts at 4. Thumb1 starts after the predicate.
2479 int RegListIdx = IsT1PushPop ? 2 : 4;
2480
2481 // Calculate the space we'll need in terms of registers.
2482 unsigned RegsNeeded;
2483 const TargetRegisterClass *RegClass;
2484 if (IsVFPPushPop) {
2485 RegsNeeded = NumBytes / 8;
2486 RegClass = &ARM::DPRRegClass;
2487 } else {
2488 RegsNeeded = NumBytes / 4;
2489 RegClass = &ARM::GPRRegClass;
2490 }
2491
2492 // We're going to have to strip all list operands off before
2493 // re-adding them since the order matters, so save the existing ones
2494 // for later.
2495 SmallVector<MachineOperand, 4> RegList;
2496
2497 // We're also going to need the first register transferred by this
2498 // instruction, which won't necessarily be the first register in the list.
2499 unsigned FirstRegEnc = -1;
2500
2501 const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
2502 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i) {
2503 MachineOperand &MO = MI->getOperand(i);
2504 RegList.push_back(MO);
2505
2506 if (MO.isReg() && !MO.isImplicit() &&
2507 TRI->getEncodingValue(MO.getReg()) < FirstRegEnc)
2508 FirstRegEnc = TRI->getEncodingValue(MO.getReg());
2509 }
2510
2511 const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
2512
2513 // Now try to find enough space in the reglist to allocate NumBytes.
2514 for (int CurRegEnc = FirstRegEnc - 1; CurRegEnc >= 0 && RegsNeeded;
2515 --CurRegEnc) {
2516 unsigned CurReg = RegClass->getRegister(CurRegEnc);
2517 if (IsT1PushPop && CurRegEnc > TRI->getEncodingValue(ARM::R7))
2518 continue;
2519 if (!IsPop) {
2520 // Pushing any register is completely harmless, mark the register involved
2521 // as undef since we don't care about its value and must not restore it
2522 // during stack unwinding.
2523 RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
2524 false, false, true));
2525 --RegsNeeded;
2526 continue;
2527 }
2528
2529 // However, we can only pop an extra register if it's not live. For
2530 // registers live within the function we might clobber a return value
2531 // register; the other way a register can be live here is if it's
2532 // callee-saved.
2533 if (isCalleeSavedRegister(CurReg, CSRegs) ||
2534 MI->getParent()->computeRegisterLiveness(TRI, CurReg, MI) !=
2535 MachineBasicBlock::LQR_Dead) {
2536 // VFP pops don't allow holes in the register list, so any skip is fatal
2537 // for our transformation. GPR pops do, so we should just keep looking.
2538 if (IsVFPPushPop)
2539 return false;
2540 else
2541 continue;
2542 }
2543
2544 // Mark the unimportant registers as <def,dead> in the POP.
2545 RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
2546 true));
2547 --RegsNeeded;
2548 }
2549
2550 if (RegsNeeded > 0)
2551 return false;
2552
2553 // Finally we know we can profitably perform the optimisation so go
2554 // ahead: strip all existing registers off and add them back again
2555 // in the right order.
2556 for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
2557 MI->RemoveOperand(i);
2558
2559 // Add the complete list back in.
2560 MachineInstrBuilder MIB(MF, &*MI);
2561 for (int i = RegList.size() - 1; i >= 0; --i)
2562 MIB.add(RegList[i]);
2563
2564 return true;
2565 }
2566
rewriteARMFrameIndex(MachineInstr & MI,unsigned FrameRegIdx,Register FrameReg,int & Offset,const ARMBaseInstrInfo & TII)2567 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
2568 Register FrameReg, int &Offset,
2569 const ARMBaseInstrInfo &TII) {
2570 unsigned Opcode = MI.getOpcode();
2571 const MCInstrDesc &Desc = MI.getDesc();
2572 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
2573 bool isSub = false;
2574
2575 // Memory operands in inline assembly always use AddrMode2.
2576 if (Opcode == ARM::INLINEASM || Opcode == ARM::INLINEASM_BR)
2577 AddrMode = ARMII::AddrMode2;
2578
2579 if (Opcode == ARM::ADDri) {
2580 Offset += MI.getOperand(FrameRegIdx+1).getImm();
2581 if (Offset == 0) {
2582 // Turn it into a move.
2583 MI.setDesc(TII.get(ARM::MOVr));
2584 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2585 MI.RemoveOperand(FrameRegIdx+1);
2586 Offset = 0;
2587 return true;
2588 } else if (Offset < 0) {
2589 Offset = -Offset;
2590 isSub = true;
2591 MI.setDesc(TII.get(ARM::SUBri));
2592 }
2593
2594 // Common case: small offset, fits into instruction.
2595 if (ARM_AM::getSOImmVal(Offset) != -1) {
2596 // Replace the FrameIndex with sp / fp
2597 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2598 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
2599 Offset = 0;
2600 return true;
2601 }
2602
2603 // Otherwise, pull as much of the immedidate into this ADDri/SUBri
2604 // as possible.
2605 unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
2606 unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
2607
2608 // We will handle these bits from offset, clear them.
2609 Offset &= ~ThisImmVal;
2610
2611 // Get the properly encoded SOImmVal field.
2612 assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
2613 "Bit extraction didn't work?");
2614 MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
2615 } else {
2616 unsigned ImmIdx = 0;
2617 int InstrOffs = 0;
2618 unsigned NumBits = 0;
2619 unsigned Scale = 1;
2620 switch (AddrMode) {
2621 case ARMII::AddrMode_i12:
2622 ImmIdx = FrameRegIdx + 1;
2623 InstrOffs = MI.getOperand(ImmIdx).getImm();
2624 NumBits = 12;
2625 break;
2626 case ARMII::AddrMode2:
2627 ImmIdx = FrameRegIdx+2;
2628 InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
2629 if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2630 InstrOffs *= -1;
2631 NumBits = 12;
2632 break;
2633 case ARMII::AddrMode3:
2634 ImmIdx = FrameRegIdx+2;
2635 InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
2636 if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2637 InstrOffs *= -1;
2638 NumBits = 8;
2639 break;
2640 case ARMII::AddrMode4:
2641 case ARMII::AddrMode6:
2642 // Can't fold any offset even if it's zero.
2643 return false;
2644 case ARMII::AddrMode5:
2645 ImmIdx = FrameRegIdx+1;
2646 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2647 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2648 InstrOffs *= -1;
2649 NumBits = 8;
2650 Scale = 4;
2651 break;
2652 case ARMII::AddrMode5FP16:
2653 ImmIdx = FrameRegIdx+1;
2654 InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2655 if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2656 InstrOffs *= -1;
2657 NumBits = 8;
2658 Scale = 2;
2659 break;
2660 case ARMII::AddrModeT2_i7:
2661 case ARMII::AddrModeT2_i7s2:
2662 case ARMII::AddrModeT2_i7s4:
2663 ImmIdx = FrameRegIdx+1;
2664 InstrOffs = MI.getOperand(ImmIdx).getImm();
2665 NumBits = 7;
2666 Scale = (AddrMode == ARMII::AddrModeT2_i7s2 ? 2 :
2667 AddrMode == ARMII::AddrModeT2_i7s4 ? 4 : 1);
2668 break;
2669 default:
2670 llvm_unreachable("Unsupported addressing mode!");
2671 }
2672
2673 Offset += InstrOffs * Scale;
2674 assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
2675 if (Offset < 0) {
2676 Offset = -Offset;
2677 isSub = true;
2678 }
2679
2680 // Attempt to fold address comp. if opcode has offset bits
2681 if (NumBits > 0) {
2682 // Common case: small offset, fits into instruction.
2683 MachineOperand &ImmOp = MI.getOperand(ImmIdx);
2684 int ImmedOffset = Offset / Scale;
2685 unsigned Mask = (1 << NumBits) - 1;
2686 if ((unsigned)Offset <= Mask * Scale) {
2687 // Replace the FrameIndex with sp
2688 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2689 // FIXME: When addrmode2 goes away, this will simplify (like the
2690 // T2 version), as the LDR.i12 versions don't need the encoding
2691 // tricks for the offset value.
2692 if (isSub) {
2693 if (AddrMode == ARMII::AddrMode_i12)
2694 ImmedOffset = -ImmedOffset;
2695 else
2696 ImmedOffset |= 1 << NumBits;
2697 }
2698 ImmOp.ChangeToImmediate(ImmedOffset);
2699 Offset = 0;
2700 return true;
2701 }
2702
2703 // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
2704 ImmedOffset = ImmedOffset & Mask;
2705 if (isSub) {
2706 if (AddrMode == ARMII::AddrMode_i12)
2707 ImmedOffset = -ImmedOffset;
2708 else
2709 ImmedOffset |= 1 << NumBits;
2710 }
2711 ImmOp.ChangeToImmediate(ImmedOffset);
2712 Offset &= ~(Mask*Scale);
2713 }
2714 }
2715
2716 Offset = (isSub) ? -Offset : Offset;
2717 return Offset == 0;
2718 }
2719
2720 /// analyzeCompare - For a comparison instruction, return the source registers
2721 /// in SrcReg and SrcReg2 if having two register operands, and the value it
2722 /// compares against in CmpValue. Return true if the comparison instruction
2723 /// can be analyzed.
analyzeCompare(const MachineInstr & MI,Register & SrcReg,Register & SrcReg2,int & CmpMask,int & CmpValue) const2724 bool ARMBaseInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
2725 Register &SrcReg2, int &CmpMask,
2726 int &CmpValue) const {
2727 switch (MI.getOpcode()) {
2728 default: break;
2729 case ARM::CMPri:
2730 case ARM::t2CMPri:
2731 case ARM::tCMPi8:
2732 SrcReg = MI.getOperand(0).getReg();
2733 SrcReg2 = 0;
2734 CmpMask = ~0;
2735 CmpValue = MI.getOperand(1).getImm();
2736 return true;
2737 case ARM::CMPrr:
2738 case ARM::t2CMPrr:
2739 case ARM::tCMPr:
2740 SrcReg = MI.getOperand(0).getReg();
2741 SrcReg2 = MI.getOperand(1).getReg();
2742 CmpMask = ~0;
2743 CmpValue = 0;
2744 return true;
2745 case ARM::TSTri:
2746 case ARM::t2TSTri:
2747 SrcReg = MI.getOperand(0).getReg();
2748 SrcReg2 = 0;
2749 CmpMask = MI.getOperand(1).getImm();
2750 CmpValue = 0;
2751 return true;
2752 }
2753
2754 return false;
2755 }
2756
2757 /// isSuitableForMask - Identify a suitable 'and' instruction that
2758 /// operates on the given source register and applies the same mask
2759 /// as a 'tst' instruction. Provide a limited look-through for copies.
2760 /// When successful, MI will hold the found instruction.
isSuitableForMask(MachineInstr * & MI,Register SrcReg,int CmpMask,bool CommonUse)2761 static bool isSuitableForMask(MachineInstr *&MI, Register SrcReg,
2762 int CmpMask, bool CommonUse) {
2763 switch (MI->getOpcode()) {
2764 case ARM::ANDri:
2765 case ARM::t2ANDri:
2766 if (CmpMask != MI->getOperand(2).getImm())
2767 return false;
2768 if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2769 return true;
2770 break;
2771 }
2772
2773 return false;
2774 }
2775
2776 /// getCmpToAddCondition - assume the flags are set by CMP(a,b), return
2777 /// the condition code if we modify the instructions such that flags are
2778 /// set by ADD(a,b,X).
getCmpToAddCondition(ARMCC::CondCodes CC)2779 inline static ARMCC::CondCodes getCmpToAddCondition(ARMCC::CondCodes CC) {
2780 switch (CC) {
2781 default: return ARMCC::AL;
2782 case ARMCC::HS: return ARMCC::LO;
2783 case ARMCC::LO: return ARMCC::HS;
2784 case ARMCC::VS: return ARMCC::VS;
2785 case ARMCC::VC: return ARMCC::VC;
2786 }
2787 }
2788
2789 /// isRedundantFlagInstr - check whether the first instruction, whose only
2790 /// purpose is to update flags, can be made redundant.
2791 /// CMPrr can be made redundant by SUBrr if the operands are the same.
2792 /// CMPri can be made redundant by SUBri if the operands are the same.
2793 /// CMPrr(r0, r1) can be made redundant by ADDr[ri](r0, r1, X).
2794 /// This function can be extended later on.
isRedundantFlagInstr(const MachineInstr * CmpI,Register SrcReg,Register SrcReg2,int ImmValue,const MachineInstr * OI,bool & IsThumb1)2795 inline static bool isRedundantFlagInstr(const MachineInstr *CmpI,
2796 Register SrcReg, Register SrcReg2,
2797 int ImmValue, const MachineInstr *OI,
2798 bool &IsThumb1) {
2799 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2800 (OI->getOpcode() == ARM::SUBrr || OI->getOpcode() == ARM::t2SUBrr) &&
2801 ((OI->getOperand(1).getReg() == SrcReg &&
2802 OI->getOperand(2).getReg() == SrcReg2) ||
2803 (OI->getOperand(1).getReg() == SrcReg2 &&
2804 OI->getOperand(2).getReg() == SrcReg))) {
2805 IsThumb1 = false;
2806 return true;
2807 }
2808
2809 if (CmpI->getOpcode() == ARM::tCMPr && OI->getOpcode() == ARM::tSUBrr &&
2810 ((OI->getOperand(2).getReg() == SrcReg &&
2811 OI->getOperand(3).getReg() == SrcReg2) ||
2812 (OI->getOperand(2).getReg() == SrcReg2 &&
2813 OI->getOperand(3).getReg() == SrcReg))) {
2814 IsThumb1 = true;
2815 return true;
2816 }
2817
2818 if ((CmpI->getOpcode() == ARM::CMPri || CmpI->getOpcode() == ARM::t2CMPri) &&
2819 (OI->getOpcode() == ARM::SUBri || OI->getOpcode() == ARM::t2SUBri) &&
2820 OI->getOperand(1).getReg() == SrcReg &&
2821 OI->getOperand(2).getImm() == ImmValue) {
2822 IsThumb1 = false;
2823 return true;
2824 }
2825
2826 if (CmpI->getOpcode() == ARM::tCMPi8 &&
2827 (OI->getOpcode() == ARM::tSUBi8 || OI->getOpcode() == ARM::tSUBi3) &&
2828 OI->getOperand(2).getReg() == SrcReg &&
2829 OI->getOperand(3).getImm() == ImmValue) {
2830 IsThumb1 = true;
2831 return true;
2832 }
2833
2834 if ((CmpI->getOpcode() == ARM::CMPrr || CmpI->getOpcode() == ARM::t2CMPrr) &&
2835 (OI->getOpcode() == ARM::ADDrr || OI->getOpcode() == ARM::t2ADDrr ||
2836 OI->getOpcode() == ARM::ADDri || OI->getOpcode() == ARM::t2ADDri) &&
2837 OI->getOperand(0).isReg() && OI->getOperand(1).isReg() &&
2838 OI->getOperand(0).getReg() == SrcReg &&
2839 OI->getOperand(1).getReg() == SrcReg2) {
2840 IsThumb1 = false;
2841 return true;
2842 }
2843
2844 if (CmpI->getOpcode() == ARM::tCMPr &&
2845 (OI->getOpcode() == ARM::tADDi3 || OI->getOpcode() == ARM::tADDi8 ||
2846 OI->getOpcode() == ARM::tADDrr) &&
2847 OI->getOperand(0).getReg() == SrcReg &&
2848 OI->getOperand(2).getReg() == SrcReg2) {
2849 IsThumb1 = true;
2850 return true;
2851 }
2852
2853 return false;
2854 }
2855
isOptimizeCompareCandidate(MachineInstr * MI,bool & IsThumb1)2856 static bool isOptimizeCompareCandidate(MachineInstr *MI, bool &IsThumb1) {
2857 switch (MI->getOpcode()) {
2858 default: return false;
2859 case ARM::tLSLri:
2860 case ARM::tLSRri:
2861 case ARM::tLSLrr:
2862 case ARM::tLSRrr:
2863 case ARM::tSUBrr:
2864 case ARM::tADDrr:
2865 case ARM::tADDi3:
2866 case ARM::tADDi8:
2867 case ARM::tSUBi3:
2868 case ARM::tSUBi8:
2869 case ARM::tMUL:
2870 case ARM::tADC:
2871 case ARM::tSBC:
2872 case ARM::tRSB:
2873 case ARM::tAND:
2874 case ARM::tORR:
2875 case ARM::tEOR:
2876 case ARM::tBIC:
2877 case ARM::tMVN:
2878 case ARM::tASRri:
2879 case ARM::tASRrr:
2880 case ARM::tROR:
2881 IsThumb1 = true;
2882 LLVM_FALLTHROUGH;
2883 case ARM::RSBrr:
2884 case ARM::RSBri:
2885 case ARM::RSCrr:
2886 case ARM::RSCri:
2887 case ARM::ADDrr:
2888 case ARM::ADDri:
2889 case ARM::ADCrr:
2890 case ARM::ADCri:
2891 case ARM::SUBrr:
2892 case ARM::SUBri:
2893 case ARM::SBCrr:
2894 case ARM::SBCri:
2895 case ARM::t2RSBri:
2896 case ARM::t2ADDrr:
2897 case ARM::t2ADDri:
2898 case ARM::t2ADCrr:
2899 case ARM::t2ADCri:
2900 case ARM::t2SUBrr:
2901 case ARM::t2SUBri:
2902 case ARM::t2SBCrr:
2903 case ARM::t2SBCri:
2904 case ARM::ANDrr:
2905 case ARM::ANDri:
2906 case ARM::t2ANDrr:
2907 case ARM::t2ANDri:
2908 case ARM::ORRrr:
2909 case ARM::ORRri:
2910 case ARM::t2ORRrr:
2911 case ARM::t2ORRri:
2912 case ARM::EORrr:
2913 case ARM::EORri:
2914 case ARM::t2EORrr:
2915 case ARM::t2EORri:
2916 case ARM::t2LSRri:
2917 case ARM::t2LSRrr:
2918 case ARM::t2LSLri:
2919 case ARM::t2LSLrr:
2920 return true;
2921 }
2922 }
2923
2924 /// optimizeCompareInstr - Convert the instruction supplying the argument to the
2925 /// comparison into one that sets the zero bit in the flags register;
2926 /// Remove a redundant Compare instruction if an earlier instruction can set the
2927 /// flags in the same way as Compare.
2928 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2929 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2930 /// condition code of instructions which use the flags.
optimizeCompareInstr(MachineInstr & CmpInstr,Register SrcReg,Register SrcReg2,int CmpMask,int CmpValue,const MachineRegisterInfo * MRI) const2931 bool ARMBaseInstrInfo::optimizeCompareInstr(
2932 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int CmpMask,
2933 int CmpValue, const MachineRegisterInfo *MRI) const {
2934 // Get the unique definition of SrcReg.
2935 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2936 if (!MI) return false;
2937
2938 // Masked compares sometimes use the same register as the corresponding 'and'.
2939 if (CmpMask != ~0) {
2940 if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(*MI)) {
2941 MI = nullptr;
2942 for (MachineRegisterInfo::use_instr_iterator
2943 UI = MRI->use_instr_begin(SrcReg), UE = MRI->use_instr_end();
2944 UI != UE; ++UI) {
2945 if (UI->getParent() != CmpInstr.getParent())
2946 continue;
2947 MachineInstr *PotentialAND = &*UI;
2948 if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2949 isPredicated(*PotentialAND))
2950 continue;
2951 MI = PotentialAND;
2952 break;
2953 }
2954 if (!MI) return false;
2955 }
2956 }
2957
2958 // Get ready to iterate backward from CmpInstr.
2959 MachineBasicBlock::iterator I = CmpInstr, E = MI,
2960 B = CmpInstr.getParent()->begin();
2961
2962 // Early exit if CmpInstr is at the beginning of the BB.
2963 if (I == B) return false;
2964
2965 // There are two possible candidates which can be changed to set CPSR:
2966 // One is MI, the other is a SUB or ADD instruction.
2967 // For CMPrr(r1,r2), we are looking for SUB(r1,r2), SUB(r2,r1), or
2968 // ADDr[ri](r1, r2, X).
2969 // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2970 MachineInstr *SubAdd = nullptr;
2971 if (SrcReg2 != 0)
2972 // MI is not a candidate for CMPrr.
2973 MI = nullptr;
2974 else if (MI->getParent() != CmpInstr.getParent() || CmpValue != 0) {
2975 // Conservatively refuse to convert an instruction which isn't in the same
2976 // BB as the comparison.
2977 // For CMPri w/ CmpValue != 0, a SubAdd may still be a candidate.
2978 // Thus we cannot return here.
2979 if (CmpInstr.getOpcode() == ARM::CMPri ||
2980 CmpInstr.getOpcode() == ARM::t2CMPri ||
2981 CmpInstr.getOpcode() == ARM::tCMPi8)
2982 MI = nullptr;
2983 else
2984 return false;
2985 }
2986
2987 bool IsThumb1 = false;
2988 if (MI && !isOptimizeCompareCandidate(MI, IsThumb1))
2989 return false;
2990
2991 // We also want to do this peephole for cases like this: if (a*b == 0),
2992 // and optimise away the CMP instruction from the generated code sequence:
2993 // MULS, MOVS, MOVS, CMP. Here the MOVS instructions load the boolean values
2994 // resulting from the select instruction, but these MOVS instructions for
2995 // Thumb1 (V6M) are flag setting and are thus preventing this optimisation.
2996 // However, if we only have MOVS instructions in between the CMP and the
2997 // other instruction (the MULS in this example), then the CPSR is dead so we
2998 // can safely reorder the sequence into: MOVS, MOVS, MULS, CMP. We do this
2999 // reordering and then continue the analysis hoping we can eliminate the
3000 // CMP. This peephole works on the vregs, so is still in SSA form. As a
3001 // consequence, the movs won't redefine/kill the MUL operands which would
3002 // make this reordering illegal.
3003 const TargetRegisterInfo *TRI = &getRegisterInfo();
3004 if (MI && IsThumb1) {
3005 --I;
3006 if (I != E && !MI->readsRegister(ARM::CPSR, TRI)) {
3007 bool CanReorder = true;
3008 for (; I != E; --I) {
3009 if (I->getOpcode() != ARM::tMOVi8) {
3010 CanReorder = false;
3011 break;
3012 }
3013 }
3014 if (CanReorder) {
3015 MI = MI->removeFromParent();
3016 E = CmpInstr;
3017 CmpInstr.getParent()->insert(E, MI);
3018 }
3019 }
3020 I = CmpInstr;
3021 E = MI;
3022 }
3023
3024 // Check that CPSR isn't set between the comparison instruction and the one we
3025 // want to change. At the same time, search for SubAdd.
3026 bool SubAddIsThumb1 = false;
3027 do {
3028 const MachineInstr &Instr = *--I;
3029
3030 // Check whether CmpInstr can be made redundant by the current instruction.
3031 if (isRedundantFlagInstr(&CmpInstr, SrcReg, SrcReg2, CmpValue, &Instr,
3032 SubAddIsThumb1)) {
3033 SubAdd = &*I;
3034 break;
3035 }
3036
3037 // Allow E (which was initially MI) to be SubAdd but do not search before E.
3038 if (I == E)
3039 break;
3040
3041 if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
3042 Instr.readsRegister(ARM::CPSR, TRI))
3043 // This instruction modifies or uses CPSR after the one we want to
3044 // change. We can't do this transformation.
3045 return false;
3046
3047 if (I == B) {
3048 // In some cases, we scan the use-list of an instruction for an AND;
3049 // that AND is in the same BB, but may not be scheduled before the
3050 // corresponding TST. In that case, bail out.
3051 //
3052 // FIXME: We could try to reschedule the AND.
3053 return false;
3054 }
3055 } while (true);
3056
3057 // Return false if no candidates exist.
3058 if (!MI && !SubAdd)
3059 return false;
3060
3061 // If we found a SubAdd, use it as it will be closer to the CMP
3062 if (SubAdd) {
3063 MI = SubAdd;
3064 IsThumb1 = SubAddIsThumb1;
3065 }
3066
3067 // We can't use a predicated instruction - it doesn't always write the flags.
3068 if (isPredicated(*MI))
3069 return false;
3070
3071 // Scan forward for the use of CPSR
3072 // When checking against MI: if it's a conditional code that requires
3073 // checking of the V bit or C bit, then this is not safe to do.
3074 // It is safe to remove CmpInstr if CPSR is redefined or killed.
3075 // If we are done with the basic block, we need to check whether CPSR is
3076 // live-out.
3077 SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
3078 OperandsToUpdate;
3079 bool isSafe = false;
3080 I = CmpInstr;
3081 E = CmpInstr.getParent()->end();
3082 while (!isSafe && ++I != E) {
3083 const MachineInstr &Instr = *I;
3084 for (unsigned IO = 0, EO = Instr.getNumOperands();
3085 !isSafe && IO != EO; ++IO) {
3086 const MachineOperand &MO = Instr.getOperand(IO);
3087 if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
3088 isSafe = true;
3089 break;
3090 }
3091 if (!MO.isReg() || MO.getReg() != ARM::CPSR)
3092 continue;
3093 if (MO.isDef()) {
3094 isSafe = true;
3095 break;
3096 }
3097 // Condition code is after the operand before CPSR except for VSELs.
3098 ARMCC::CondCodes CC;
3099 bool IsInstrVSel = true;
3100 switch (Instr.getOpcode()) {
3101 default:
3102 IsInstrVSel = false;
3103 CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
3104 break;
3105 case ARM::VSELEQD:
3106 case ARM::VSELEQS:
3107 case ARM::VSELEQH:
3108 CC = ARMCC::EQ;
3109 break;
3110 case ARM::VSELGTD:
3111 case ARM::VSELGTS:
3112 case ARM::VSELGTH:
3113 CC = ARMCC::GT;
3114 break;
3115 case ARM::VSELGED:
3116 case ARM::VSELGES:
3117 case ARM::VSELGEH:
3118 CC = ARMCC::GE;
3119 break;
3120 case ARM::VSELVSD:
3121 case ARM::VSELVSS:
3122 case ARM::VSELVSH:
3123 CC = ARMCC::VS;
3124 break;
3125 }
3126
3127 if (SubAdd) {
3128 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
3129 // on CMP needs to be updated to be based on SUB.
3130 // If we have ADD(r1, r2, X) and CMP(r1, r2), the condition code also
3131 // needs to be modified.
3132 // Push the condition code operands to OperandsToUpdate.
3133 // If it is safe to remove CmpInstr, the condition code of these
3134 // operands will be modified.
3135 unsigned Opc = SubAdd->getOpcode();
3136 bool IsSub = Opc == ARM::SUBrr || Opc == ARM::t2SUBrr ||
3137 Opc == ARM::SUBri || Opc == ARM::t2SUBri ||
3138 Opc == ARM::tSUBrr || Opc == ARM::tSUBi3 ||
3139 Opc == ARM::tSUBi8;
3140 unsigned OpI = Opc != ARM::tSUBrr ? 1 : 2;
3141 if (!IsSub ||
3142 (SrcReg2 != 0 && SubAdd->getOperand(OpI).getReg() == SrcReg2 &&
3143 SubAdd->getOperand(OpI + 1).getReg() == SrcReg)) {
3144 // VSel doesn't support condition code update.
3145 if (IsInstrVSel)
3146 return false;
3147 // Ensure we can swap the condition.
3148 ARMCC::CondCodes NewCC = (IsSub ? getSwappedCondition(CC) : getCmpToAddCondition(CC));
3149 if (NewCC == ARMCC::AL)
3150 return false;
3151 OperandsToUpdate.push_back(
3152 std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
3153 }
3154 } else {
3155 // No SubAdd, so this is x = <op> y, z; cmp x, 0.
3156 switch (CC) {
3157 case ARMCC::EQ: // Z
3158 case ARMCC::NE: // Z
3159 case ARMCC::MI: // N
3160 case ARMCC::PL: // N
3161 case ARMCC::AL: // none
3162 // CPSR can be used multiple times, we should continue.
3163 break;
3164 case ARMCC::HS: // C
3165 case ARMCC::LO: // C
3166 case ARMCC::VS: // V
3167 case ARMCC::VC: // V
3168 case ARMCC::HI: // C Z
3169 case ARMCC::LS: // C Z
3170 case ARMCC::GE: // N V
3171 case ARMCC::LT: // N V
3172 case ARMCC::GT: // Z N V
3173 case ARMCC::LE: // Z N V
3174 // The instruction uses the V bit or C bit which is not safe.
3175 return false;
3176 }
3177 }
3178 }
3179 }
3180
3181 // If CPSR is not killed nor re-defined, we should check whether it is
3182 // live-out. If it is live-out, do not optimize.
3183 if (!isSafe) {
3184 MachineBasicBlock *MBB = CmpInstr.getParent();
3185 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
3186 SE = MBB->succ_end(); SI != SE; ++SI)
3187 if ((*SI)->isLiveIn(ARM::CPSR))
3188 return false;
3189 }
3190
3191 // Toggle the optional operand to CPSR (if it exists - in Thumb1 we always
3192 // set CPSR so this is represented as an explicit output)
3193 if (!IsThumb1) {
3194 MI->getOperand(5).setReg(ARM::CPSR);
3195 MI->getOperand(5).setIsDef(true);
3196 }
3197 assert(!isPredicated(*MI) && "Can't use flags from predicated instruction");
3198 CmpInstr.eraseFromParent();
3199
3200 // Modify the condition code of operands in OperandsToUpdate.
3201 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
3202 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
3203 for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
3204 OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
3205
3206 MI->clearRegisterDeads(ARM::CPSR);
3207
3208 return true;
3209 }
3210
shouldSink(const MachineInstr & MI) const3211 bool ARMBaseInstrInfo::shouldSink(const MachineInstr &MI) const {
3212 // Do not sink MI if it might be used to optimize a redundant compare.
3213 // We heuristically only look at the instruction immediately following MI to
3214 // avoid potentially searching the entire basic block.
3215 if (isPredicated(MI))
3216 return true;
3217 MachineBasicBlock::const_iterator Next = &MI;
3218 ++Next;
3219 Register SrcReg, SrcReg2;
3220 int CmpMask, CmpValue;
3221 bool IsThumb1;
3222 if (Next != MI.getParent()->end() &&
3223 analyzeCompare(*Next, SrcReg, SrcReg2, CmpMask, CmpValue) &&
3224 isRedundantFlagInstr(&*Next, SrcReg, SrcReg2, CmpValue, &MI, IsThumb1))
3225 return false;
3226 return true;
3227 }
3228
FoldImmediate(MachineInstr & UseMI,MachineInstr & DefMI,Register Reg,MachineRegisterInfo * MRI) const3229 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
3230 Register Reg,
3231 MachineRegisterInfo *MRI) const {
3232 // Fold large immediates into add, sub, or, xor.
3233 unsigned DefOpc = DefMI.getOpcode();
3234 if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
3235 return false;
3236 if (!DefMI.getOperand(1).isImm())
3237 // Could be t2MOVi32imm @xx
3238 return false;
3239
3240 if (!MRI->hasOneNonDBGUse(Reg))
3241 return false;
3242
3243 const MCInstrDesc &DefMCID = DefMI.getDesc();
3244 if (DefMCID.hasOptionalDef()) {
3245 unsigned NumOps = DefMCID.getNumOperands();
3246 const MachineOperand &MO = DefMI.getOperand(NumOps - 1);
3247 if (MO.getReg() == ARM::CPSR && !MO.isDead())
3248 // If DefMI defines CPSR and it is not dead, it's obviously not safe
3249 // to delete DefMI.
3250 return false;
3251 }
3252
3253 const MCInstrDesc &UseMCID = UseMI.getDesc();
3254 if (UseMCID.hasOptionalDef()) {
3255 unsigned NumOps = UseMCID.getNumOperands();
3256 if (UseMI.getOperand(NumOps - 1).getReg() == ARM::CPSR)
3257 // If the instruction sets the flag, do not attempt this optimization
3258 // since it may change the semantics of the code.
3259 return false;
3260 }
3261
3262 unsigned UseOpc = UseMI.getOpcode();
3263 unsigned NewUseOpc = 0;
3264 uint32_t ImmVal = (uint32_t)DefMI.getOperand(1).getImm();
3265 uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
3266 bool Commute = false;
3267 switch (UseOpc) {
3268 default: return false;
3269 case ARM::SUBrr:
3270 case ARM::ADDrr:
3271 case ARM::ORRrr:
3272 case ARM::EORrr:
3273 case ARM::t2SUBrr:
3274 case ARM::t2ADDrr:
3275 case ARM::t2ORRrr:
3276 case ARM::t2EORrr: {
3277 Commute = UseMI.getOperand(2).getReg() != Reg;
3278 switch (UseOpc) {
3279 default: break;
3280 case ARM::ADDrr:
3281 case ARM::SUBrr:
3282 if (UseOpc == ARM::SUBrr && Commute)
3283 return false;
3284
3285 // ADD/SUB are special because they're essentially the same operation, so
3286 // we can handle a larger range of immediates.
3287 if (ARM_AM::isSOImmTwoPartVal(ImmVal))
3288 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::ADDri : ARM::SUBri;
3289 else if (ARM_AM::isSOImmTwoPartVal(-ImmVal)) {
3290 ImmVal = -ImmVal;
3291 NewUseOpc = UseOpc == ARM::ADDrr ? ARM::SUBri : ARM::ADDri;
3292 } else
3293 return false;
3294 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3295 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3296 break;
3297 case ARM::ORRrr:
3298 case ARM::EORrr:
3299 if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
3300 return false;
3301 SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
3302 SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
3303 switch (UseOpc) {
3304 default: break;
3305 case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
3306 case ARM::EORrr: NewUseOpc = ARM::EORri; break;
3307 }
3308 break;
3309 case ARM::t2ADDrr:
3310 case ARM::t2SUBrr: {
3311 if (UseOpc == ARM::t2SUBrr && Commute)
3312 return false;
3313
3314 // ADD/SUB are special because they're essentially the same operation, so
3315 // we can handle a larger range of immediates.
3316 const bool ToSP = DefMI.getOperand(0).getReg() == ARM::SP;
3317 const unsigned t2ADD = ToSP ? ARM::t2ADDspImm : ARM::t2ADDri;
3318 const unsigned t2SUB = ToSP ? ARM::t2SUBspImm : ARM::t2SUBri;
3319 if (ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3320 NewUseOpc = UseOpc == ARM::t2ADDrr ? t2ADD : t2SUB;
3321 else if (ARM_AM::isT2SOImmTwoPartVal(-ImmVal)) {
3322 ImmVal = -ImmVal;
3323 NewUseOpc = UseOpc == ARM::t2ADDrr ? t2SUB : t2ADD;
3324 } else
3325 return false;
3326 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3327 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3328 break;
3329 }
3330 case ARM::t2ORRrr:
3331 case ARM::t2EORrr:
3332 if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
3333 return false;
3334 SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
3335 SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
3336 switch (UseOpc) {
3337 default: break;
3338 case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
3339 case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
3340 }
3341 break;
3342 }
3343 }
3344 }
3345
3346 unsigned OpIdx = Commute ? 2 : 1;
3347 Register Reg1 = UseMI.getOperand(OpIdx).getReg();
3348 bool isKill = UseMI.getOperand(OpIdx).isKill();
3349 const TargetRegisterClass *TRC = MRI->getRegClass(Reg);
3350 Register NewReg = MRI->createVirtualRegister(TRC);
3351 BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(), get(NewUseOpc),
3352 NewReg)
3353 .addReg(Reg1, getKillRegState(isKill))
3354 .addImm(SOImmValV1)
3355 .add(predOps(ARMCC::AL))
3356 .add(condCodeOp());
3357 UseMI.setDesc(get(NewUseOpc));
3358 UseMI.getOperand(1).setReg(NewReg);
3359 UseMI.getOperand(1).setIsKill();
3360 UseMI.getOperand(2).ChangeToImmediate(SOImmValV2);
3361 DefMI.eraseFromParent();
3362 // FIXME: t2ADDrr should be split, as different rulles apply when writing to SP.
3363 // Just as t2ADDri, that was split to [t2ADDri, t2ADDspImm].
3364 // Then the below code will not be needed, as the input/output register
3365 // classes will be rgpr or gprSP.
3366 // For now, we fix the UseMI operand explicitly here:
3367 switch(NewUseOpc){
3368 case ARM::t2ADDspImm:
3369 case ARM::t2SUBspImm:
3370 case ARM::t2ADDri:
3371 case ARM::t2SUBri:
3372 MRI->constrainRegClass(UseMI.getOperand(0).getReg(), TRC);
3373 }
3374 return true;
3375 }
3376
getNumMicroOpsSwiftLdSt(const InstrItineraryData * ItinData,const MachineInstr & MI)3377 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
3378 const MachineInstr &MI) {
3379 switch (MI.getOpcode()) {
3380 default: {
3381 const MCInstrDesc &Desc = MI.getDesc();
3382 int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
3383 assert(UOps >= 0 && "bad # UOps");
3384 return UOps;
3385 }
3386
3387 case ARM::LDRrs:
3388 case ARM::LDRBrs:
3389 case ARM::STRrs:
3390 case ARM::STRBrs: {
3391 unsigned ShOpVal = MI.getOperand(3).getImm();
3392 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3393 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3394 if (!isSub &&
3395 (ShImm == 0 ||
3396 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3397 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3398 return 1;
3399 return 2;
3400 }
3401
3402 case ARM::LDRH:
3403 case ARM::STRH: {
3404 if (!MI.getOperand(2).getReg())
3405 return 1;
3406
3407 unsigned ShOpVal = MI.getOperand(3).getImm();
3408 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3409 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3410 if (!isSub &&
3411 (ShImm == 0 ||
3412 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3413 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3414 return 1;
3415 return 2;
3416 }
3417
3418 case ARM::LDRSB:
3419 case ARM::LDRSH:
3420 return (ARM_AM::getAM3Op(MI.getOperand(3).getImm()) == ARM_AM::sub) ? 3 : 2;
3421
3422 case ARM::LDRSB_POST:
3423 case ARM::LDRSH_POST: {
3424 Register Rt = MI.getOperand(0).getReg();
3425 Register Rm = MI.getOperand(3).getReg();
3426 return (Rt == Rm) ? 4 : 3;
3427 }
3428
3429 case ARM::LDR_PRE_REG:
3430 case ARM::LDRB_PRE_REG: {
3431 Register Rt = MI.getOperand(0).getReg();
3432 Register Rm = MI.getOperand(3).getReg();
3433 if (Rt == Rm)
3434 return 3;
3435 unsigned ShOpVal = MI.getOperand(4).getImm();
3436 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3437 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3438 if (!isSub &&
3439 (ShImm == 0 ||
3440 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3441 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3442 return 2;
3443 return 3;
3444 }
3445
3446 case ARM::STR_PRE_REG:
3447 case ARM::STRB_PRE_REG: {
3448 unsigned ShOpVal = MI.getOperand(4).getImm();
3449 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3450 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3451 if (!isSub &&
3452 (ShImm == 0 ||
3453 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3454 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3455 return 2;
3456 return 3;
3457 }
3458
3459 case ARM::LDRH_PRE:
3460 case ARM::STRH_PRE: {
3461 Register Rt = MI.getOperand(0).getReg();
3462 Register Rm = MI.getOperand(3).getReg();
3463 if (!Rm)
3464 return 2;
3465 if (Rt == Rm)
3466 return 3;
3467 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 3 : 2;
3468 }
3469
3470 case ARM::LDR_POST_REG:
3471 case ARM::LDRB_POST_REG:
3472 case ARM::LDRH_POST: {
3473 Register Rt = MI.getOperand(0).getReg();
3474 Register Rm = MI.getOperand(3).getReg();
3475 return (Rt == Rm) ? 3 : 2;
3476 }
3477
3478 case ARM::LDR_PRE_IMM:
3479 case ARM::LDRB_PRE_IMM:
3480 case ARM::LDR_POST_IMM:
3481 case ARM::LDRB_POST_IMM:
3482 case ARM::STRB_POST_IMM:
3483 case ARM::STRB_POST_REG:
3484 case ARM::STRB_PRE_IMM:
3485 case ARM::STRH_POST:
3486 case ARM::STR_POST_IMM:
3487 case ARM::STR_POST_REG:
3488 case ARM::STR_PRE_IMM:
3489 return 2;
3490
3491 case ARM::LDRSB_PRE:
3492 case ARM::LDRSH_PRE: {
3493 Register Rm = MI.getOperand(3).getReg();
3494 if (Rm == 0)
3495 return 3;
3496 Register Rt = MI.getOperand(0).getReg();
3497 if (Rt == Rm)
3498 return 4;
3499 unsigned ShOpVal = MI.getOperand(4).getImm();
3500 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3501 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3502 if (!isSub &&
3503 (ShImm == 0 ||
3504 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3505 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3506 return 3;
3507 return 4;
3508 }
3509
3510 case ARM::LDRD: {
3511 Register Rt = MI.getOperand(0).getReg();
3512 Register Rn = MI.getOperand(2).getReg();
3513 Register Rm = MI.getOperand(3).getReg();
3514 if (Rm)
3515 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3516 : 3;
3517 return (Rt == Rn) ? 3 : 2;
3518 }
3519
3520 case ARM::STRD: {
3521 Register Rm = MI.getOperand(3).getReg();
3522 if (Rm)
3523 return (ARM_AM::getAM3Op(MI.getOperand(4).getImm()) == ARM_AM::sub) ? 4
3524 : 3;
3525 return 2;
3526 }
3527
3528 case ARM::LDRD_POST:
3529 case ARM::t2LDRD_POST:
3530 return 3;
3531
3532 case ARM::STRD_POST:
3533 case ARM::t2STRD_POST:
3534 return 4;
3535
3536 case ARM::LDRD_PRE: {
3537 Register Rt = MI.getOperand(0).getReg();
3538 Register Rn = MI.getOperand(3).getReg();
3539 Register Rm = MI.getOperand(4).getReg();
3540 if (Rm)
3541 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3542 : 4;
3543 return (Rt == Rn) ? 4 : 3;
3544 }
3545
3546 case ARM::t2LDRD_PRE: {
3547 Register Rt = MI.getOperand(0).getReg();
3548 Register Rn = MI.getOperand(3).getReg();
3549 return (Rt == Rn) ? 4 : 3;
3550 }
3551
3552 case ARM::STRD_PRE: {
3553 Register Rm = MI.getOperand(4).getReg();
3554 if (Rm)
3555 return (ARM_AM::getAM3Op(MI.getOperand(5).getImm()) == ARM_AM::sub) ? 5
3556 : 4;
3557 return 3;
3558 }
3559
3560 case ARM::t2STRD_PRE:
3561 return 3;
3562
3563 case ARM::t2LDR_POST:
3564 case ARM::t2LDRB_POST:
3565 case ARM::t2LDRB_PRE:
3566 case ARM::t2LDRSBi12:
3567 case ARM::t2LDRSBi8:
3568 case ARM::t2LDRSBpci:
3569 case ARM::t2LDRSBs:
3570 case ARM::t2LDRH_POST:
3571 case ARM::t2LDRH_PRE:
3572 case ARM::t2LDRSBT:
3573 case ARM::t2LDRSB_POST:
3574 case ARM::t2LDRSB_PRE:
3575 case ARM::t2LDRSH_POST:
3576 case ARM::t2LDRSH_PRE:
3577 case ARM::t2LDRSHi12:
3578 case ARM::t2LDRSHi8:
3579 case ARM::t2LDRSHpci:
3580 case ARM::t2LDRSHs:
3581 return 2;
3582
3583 case ARM::t2LDRDi8: {
3584 Register Rt = MI.getOperand(0).getReg();
3585 Register Rn = MI.getOperand(2).getReg();
3586 return (Rt == Rn) ? 3 : 2;
3587 }
3588
3589 case ARM::t2STRB_POST:
3590 case ARM::t2STRB_PRE:
3591 case ARM::t2STRBs:
3592 case ARM::t2STRDi8:
3593 case ARM::t2STRH_POST:
3594 case ARM::t2STRH_PRE:
3595 case ARM::t2STRHs:
3596 case ARM::t2STR_POST:
3597 case ARM::t2STR_PRE:
3598 case ARM::t2STRs:
3599 return 2;
3600 }
3601 }
3602
3603 // Return the number of 32-bit words loaded by LDM or stored by STM. If this
3604 // can't be easily determined return 0 (missing MachineMemOperand).
3605 //
3606 // FIXME: The current MachineInstr design does not support relying on machine
3607 // mem operands to determine the width of a memory access. Instead, we expect
3608 // the target to provide this information based on the instruction opcode and
3609 // operands. However, using MachineMemOperand is the best solution now for
3610 // two reasons:
3611 //
3612 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
3613 // operands. This is much more dangerous than using the MachineMemOperand
3614 // sizes because CodeGen passes can insert/remove optional machine operands. In
3615 // fact, it's totally incorrect for preRA passes and appears to be wrong for
3616 // postRA passes as well.
3617 //
3618 // 2) getNumLDMAddresses is only used by the scheduling machine model and any
3619 // machine model that calls this should handle the unknown (zero size) case.
3620 //
3621 // Long term, we should require a target hook that verifies MachineMemOperand
3622 // sizes during MC lowering. That target hook should be local to MC lowering
3623 // because we can't ensure that it is aware of other MI forms. Doing this will
3624 // ensure that MachineMemOperands are correctly propagated through all passes.
getNumLDMAddresses(const MachineInstr & MI) const3625 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr &MI) const {
3626 unsigned Size = 0;
3627 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
3628 E = MI.memoperands_end();
3629 I != E; ++I) {
3630 Size += (*I)->getSize();
3631 }
3632 // FIXME: The scheduler currently can't handle values larger than 16. But
3633 // the values can actually go up to 32 for floating-point load/store
3634 // multiple (VLDMIA etc.). Also, the way this code is reasoning about memory
3635 // operations isn't right; we could end up with "extra" memory operands for
3636 // various reasons, like tail merge merging two memory operations.
3637 return std::min(Size / 4, 16U);
3638 }
3639
getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,unsigned NumRegs)3640 static unsigned getNumMicroOpsSingleIssuePlusExtras(unsigned Opc,
3641 unsigned NumRegs) {
3642 unsigned UOps = 1 + NumRegs; // 1 for address computation.
3643 switch (Opc) {
3644 default:
3645 break;
3646 case ARM::VLDMDIA_UPD:
3647 case ARM::VLDMDDB_UPD:
3648 case ARM::VLDMSIA_UPD:
3649 case ARM::VLDMSDB_UPD:
3650 case ARM::VSTMDIA_UPD:
3651 case ARM::VSTMDDB_UPD:
3652 case ARM::VSTMSIA_UPD:
3653 case ARM::VSTMSDB_UPD:
3654 case ARM::LDMIA_UPD:
3655 case ARM::LDMDA_UPD:
3656 case ARM::LDMDB_UPD:
3657 case ARM::LDMIB_UPD:
3658 case ARM::STMIA_UPD:
3659 case ARM::STMDA_UPD:
3660 case ARM::STMDB_UPD:
3661 case ARM::STMIB_UPD:
3662 case ARM::tLDMIA_UPD:
3663 case ARM::tSTMIA_UPD:
3664 case ARM::t2LDMIA_UPD:
3665 case ARM::t2LDMDB_UPD:
3666 case ARM::t2STMIA_UPD:
3667 case ARM::t2STMDB_UPD:
3668 ++UOps; // One for base register writeback.
3669 break;
3670 case ARM::LDMIA_RET:
3671 case ARM::tPOP_RET:
3672 case ARM::t2LDMIA_RET:
3673 UOps += 2; // One for base reg wb, one for write to pc.
3674 break;
3675 }
3676 return UOps;
3677 }
3678
getNumMicroOps(const InstrItineraryData * ItinData,const MachineInstr & MI) const3679 unsigned ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
3680 const MachineInstr &MI) const {
3681 if (!ItinData || ItinData->isEmpty())
3682 return 1;
3683
3684 const MCInstrDesc &Desc = MI.getDesc();
3685 unsigned Class = Desc.getSchedClass();
3686 int ItinUOps = ItinData->getNumMicroOps(Class);
3687 if (ItinUOps >= 0) {
3688 if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
3689 return getNumMicroOpsSwiftLdSt(ItinData, MI);
3690
3691 return ItinUOps;
3692 }
3693
3694 unsigned Opc = MI.getOpcode();
3695 switch (Opc) {
3696 default:
3697 llvm_unreachable("Unexpected multi-uops instruction!");
3698 case ARM::VLDMQIA:
3699 case ARM::VSTMQIA:
3700 return 2;
3701
3702 // The number of uOps for load / store multiple are determined by the number
3703 // registers.
3704 //
3705 // On Cortex-A8, each pair of register loads / stores can be scheduled on the
3706 // same cycle. The scheduling for the first load / store must be done
3707 // separately by assuming the address is not 64-bit aligned.
3708 //
3709 // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
3710 // is not 64-bit aligned, then AGU would take an extra cycle. For VFP / NEON
3711 // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
3712 case ARM::VLDMDIA:
3713 case ARM::VLDMDIA_UPD:
3714 case ARM::VLDMDDB_UPD:
3715 case ARM::VLDMSIA:
3716 case ARM::VLDMSIA_UPD:
3717 case ARM::VLDMSDB_UPD:
3718 case ARM::VSTMDIA:
3719 case ARM::VSTMDIA_UPD:
3720 case ARM::VSTMDDB_UPD:
3721 case ARM::VSTMSIA:
3722 case ARM::VSTMSIA_UPD:
3723 case ARM::VSTMSDB_UPD: {
3724 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands();
3725 return (NumRegs / 2) + (NumRegs % 2) + 1;
3726 }
3727
3728 case ARM::LDMIA_RET:
3729 case ARM::LDMIA:
3730 case ARM::LDMDA:
3731 case ARM::LDMDB:
3732 case ARM::LDMIB:
3733 case ARM::LDMIA_UPD:
3734 case ARM::LDMDA_UPD:
3735 case ARM::LDMDB_UPD:
3736 case ARM::LDMIB_UPD:
3737 case ARM::STMIA:
3738 case ARM::STMDA:
3739 case ARM::STMDB:
3740 case ARM::STMIB:
3741 case ARM::STMIA_UPD:
3742 case ARM::STMDA_UPD:
3743 case ARM::STMDB_UPD:
3744 case ARM::STMIB_UPD:
3745 case ARM::tLDMIA:
3746 case ARM::tLDMIA_UPD:
3747 case ARM::tSTMIA_UPD:
3748 case ARM::tPOP_RET:
3749 case ARM::tPOP:
3750 case ARM::tPUSH:
3751 case ARM::t2LDMIA_RET:
3752 case ARM::t2LDMIA:
3753 case ARM::t2LDMDB:
3754 case ARM::t2LDMIA_UPD:
3755 case ARM::t2LDMDB_UPD:
3756 case ARM::t2STMIA:
3757 case ARM::t2STMDB:
3758 case ARM::t2STMIA_UPD:
3759 case ARM::t2STMDB_UPD: {
3760 unsigned NumRegs = MI.getNumOperands() - Desc.getNumOperands() + 1;
3761 switch (Subtarget.getLdStMultipleTiming()) {
3762 case ARMSubtarget::SingleIssuePlusExtras:
3763 return getNumMicroOpsSingleIssuePlusExtras(Opc, NumRegs);
3764 case ARMSubtarget::SingleIssue:
3765 // Assume the worst.
3766 return NumRegs;
3767 case ARMSubtarget::DoubleIssue: {
3768 if (NumRegs < 4)
3769 return 2;
3770 // 4 registers would be issued: 2, 2.
3771 // 5 registers would be issued: 2, 2, 1.
3772 unsigned UOps = (NumRegs / 2);
3773 if (NumRegs % 2)
3774 ++UOps;
3775 return UOps;
3776 }
3777 case ARMSubtarget::DoubleIssueCheckUnalignedAccess: {
3778 unsigned UOps = (NumRegs / 2);
3779 // If there are odd number of registers or if it's not 64-bit aligned,
3780 // then it takes an extra AGU (Address Generation Unit) cycle.
3781 if ((NumRegs % 2) || !MI.hasOneMemOperand() ||
3782 (*MI.memoperands_begin())->getAlign() < Align(8))
3783 ++UOps;
3784 return UOps;
3785 }
3786 }
3787 }
3788 }
3789 llvm_unreachable("Didn't find the number of microops");
3790 }
3791
3792 int
getVLDMDefCycle(const InstrItineraryData * ItinData,const MCInstrDesc & DefMCID,unsigned DefClass,unsigned DefIdx,unsigned DefAlign) const3793 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
3794 const MCInstrDesc &DefMCID,
3795 unsigned DefClass,
3796 unsigned DefIdx, unsigned DefAlign) const {
3797 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3798 if (RegNo <= 0)
3799 // Def is the address writeback.
3800 return ItinData->getOperandCycle(DefClass, DefIdx);
3801
3802 int DefCycle;
3803 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3804 // (regno / 2) + (regno % 2) + 1
3805 DefCycle = RegNo / 2 + 1;
3806 if (RegNo % 2)
3807 ++DefCycle;
3808 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3809 DefCycle = RegNo;
3810 bool isSLoad = false;
3811
3812 switch (DefMCID.getOpcode()) {
3813 default: break;
3814 case ARM::VLDMSIA:
3815 case ARM::VLDMSIA_UPD:
3816 case ARM::VLDMSDB_UPD:
3817 isSLoad = true;
3818 break;
3819 }
3820
3821 // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3822 // then it takes an extra cycle.
3823 if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
3824 ++DefCycle;
3825 } else {
3826 // Assume the worst.
3827 DefCycle = RegNo + 2;
3828 }
3829
3830 return DefCycle;
3831 }
3832
3833 int
getLDMDefCycle(const InstrItineraryData * ItinData,const MCInstrDesc & DefMCID,unsigned DefClass,unsigned DefIdx,unsigned DefAlign) const3834 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
3835 const MCInstrDesc &DefMCID,
3836 unsigned DefClass,
3837 unsigned DefIdx, unsigned DefAlign) const {
3838 int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3839 if (RegNo <= 0)
3840 // Def is the address writeback.
3841 return ItinData->getOperandCycle(DefClass, DefIdx);
3842
3843 int DefCycle;
3844 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3845 // 4 registers would be issued: 1, 2, 1.
3846 // 5 registers would be issued: 1, 2, 2.
3847 DefCycle = RegNo / 2;
3848 if (DefCycle < 1)
3849 DefCycle = 1;
3850 // Result latency is issue cycle + 2: E2.
3851 DefCycle += 2;
3852 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3853 DefCycle = (RegNo / 2);
3854 // If there are odd number of registers or if it's not 64-bit aligned,
3855 // then it takes an extra AGU (Address Generation Unit) cycle.
3856 if ((RegNo % 2) || DefAlign < 8)
3857 ++DefCycle;
3858 // Result latency is AGU cycles + 2.
3859 DefCycle += 2;
3860 } else {
3861 // Assume the worst.
3862 DefCycle = RegNo + 2;
3863 }
3864
3865 return DefCycle;
3866 }
3867
3868 int
getVSTMUseCycle(const InstrItineraryData * ItinData,const MCInstrDesc & UseMCID,unsigned UseClass,unsigned UseIdx,unsigned UseAlign) const3869 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
3870 const MCInstrDesc &UseMCID,
3871 unsigned UseClass,
3872 unsigned UseIdx, unsigned UseAlign) const {
3873 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3874 if (RegNo <= 0)
3875 return ItinData->getOperandCycle(UseClass, UseIdx);
3876
3877 int UseCycle;
3878 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3879 // (regno / 2) + (regno % 2) + 1
3880 UseCycle = RegNo / 2 + 1;
3881 if (RegNo % 2)
3882 ++UseCycle;
3883 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3884 UseCycle = RegNo;
3885 bool isSStore = false;
3886
3887 switch (UseMCID.getOpcode()) {
3888 default: break;
3889 case ARM::VSTMSIA:
3890 case ARM::VSTMSIA_UPD:
3891 case ARM::VSTMSDB_UPD:
3892 isSStore = true;
3893 break;
3894 }
3895
3896 // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3897 // then it takes an extra cycle.
3898 if ((isSStore && (RegNo % 2)) || UseAlign < 8)
3899 ++UseCycle;
3900 } else {
3901 // Assume the worst.
3902 UseCycle = RegNo + 2;
3903 }
3904
3905 return UseCycle;
3906 }
3907
3908 int
getSTMUseCycle(const InstrItineraryData * ItinData,const MCInstrDesc & UseMCID,unsigned UseClass,unsigned UseIdx,unsigned UseAlign) const3909 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
3910 const MCInstrDesc &UseMCID,
3911 unsigned UseClass,
3912 unsigned UseIdx, unsigned UseAlign) const {
3913 int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3914 if (RegNo <= 0)
3915 return ItinData->getOperandCycle(UseClass, UseIdx);
3916
3917 int UseCycle;
3918 if (Subtarget.isCortexA8() || Subtarget.isCortexA7()) {
3919 UseCycle = RegNo / 2;
3920 if (UseCycle < 2)
3921 UseCycle = 2;
3922 // Read in E3.
3923 UseCycle += 2;
3924 } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3925 UseCycle = (RegNo / 2);
3926 // If there are odd number of registers or if it's not 64-bit aligned,
3927 // then it takes an extra AGU (Address Generation Unit) cycle.
3928 if ((RegNo % 2) || UseAlign < 8)
3929 ++UseCycle;
3930 } else {
3931 // Assume the worst.
3932 UseCycle = 1;
3933 }
3934 return UseCycle;
3935 }
3936
3937 int
getOperandLatency(const InstrItineraryData * ItinData,const MCInstrDesc & DefMCID,unsigned DefIdx,unsigned DefAlign,const MCInstrDesc & UseMCID,unsigned UseIdx,unsigned UseAlign) const3938 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3939 const MCInstrDesc &DefMCID,
3940 unsigned DefIdx, unsigned DefAlign,
3941 const MCInstrDesc &UseMCID,
3942 unsigned UseIdx, unsigned UseAlign) const {
3943 unsigned DefClass = DefMCID.getSchedClass();
3944 unsigned UseClass = UseMCID.getSchedClass();
3945
3946 if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
3947 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
3948
3949 // This may be a def / use of a variable_ops instruction, the operand
3950 // latency might be determinable dynamically. Let the target try to
3951 // figure it out.
3952 int DefCycle = -1;
3953 bool LdmBypass = false;
3954 switch (DefMCID.getOpcode()) {
3955 default:
3956 DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3957 break;
3958
3959 case ARM::VLDMDIA:
3960 case ARM::VLDMDIA_UPD:
3961 case ARM::VLDMDDB_UPD:
3962 case ARM::VLDMSIA:
3963 case ARM::VLDMSIA_UPD:
3964 case ARM::VLDMSDB_UPD:
3965 DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3966 break;
3967
3968 case ARM::LDMIA_RET:
3969 case ARM::LDMIA:
3970 case ARM::LDMDA:
3971 case ARM::LDMDB:
3972 case ARM::LDMIB:
3973 case ARM::LDMIA_UPD:
3974 case ARM::LDMDA_UPD:
3975 case ARM::LDMDB_UPD:
3976 case ARM::LDMIB_UPD:
3977 case ARM::tLDMIA:
3978 case ARM::tLDMIA_UPD:
3979 case ARM::tPUSH:
3980 case ARM::t2LDMIA_RET:
3981 case ARM::t2LDMIA:
3982 case ARM::t2LDMDB:
3983 case ARM::t2LDMIA_UPD:
3984 case ARM::t2LDMDB_UPD:
3985 LdmBypass = true;
3986 DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3987 break;
3988 }
3989
3990 if (DefCycle == -1)
3991 // We can't seem to determine the result latency of the def, assume it's 2.
3992 DefCycle = 2;
3993
3994 int UseCycle = -1;
3995 switch (UseMCID.getOpcode()) {
3996 default:
3997 UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
3998 break;
3999
4000 case ARM::VSTMDIA:
4001 case ARM::VSTMDIA_UPD:
4002 case ARM::VSTMDDB_UPD:
4003 case ARM::VSTMSIA:
4004 case ARM::VSTMSIA_UPD:
4005 case ARM::VSTMSDB_UPD:
4006 UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
4007 break;
4008
4009 case ARM::STMIA:
4010 case ARM::STMDA:
4011 case ARM::STMDB:
4012 case ARM::STMIB:
4013 case ARM::STMIA_UPD:
4014 case ARM::STMDA_UPD:
4015 case ARM::STMDB_UPD:
4016 case ARM::STMIB_UPD:
4017 case ARM::tSTMIA_UPD:
4018 case ARM::tPOP_RET:
4019 case ARM::tPOP:
4020 case ARM::t2STMIA:
4021 case ARM::t2STMDB:
4022 case ARM::t2STMIA_UPD:
4023 case ARM::t2STMDB_UPD:
4024 UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
4025 break;
4026 }
4027
4028 if (UseCycle == -1)
4029 // Assume it's read in the first stage.
4030 UseCycle = 1;
4031
4032 UseCycle = DefCycle - UseCycle + 1;
4033 if (UseCycle > 0) {
4034 if (LdmBypass) {
4035 // It's a variable_ops instruction so we can't use DefIdx here. Just use
4036 // first def operand.
4037 if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
4038 UseClass, UseIdx))
4039 --UseCycle;
4040 } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
4041 UseClass, UseIdx)) {
4042 --UseCycle;
4043 }
4044 }
4045
4046 return UseCycle;
4047 }
4048
getBundledDefMI(const TargetRegisterInfo * TRI,const MachineInstr * MI,unsigned Reg,unsigned & DefIdx,unsigned & Dist)4049 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
4050 const MachineInstr *MI, unsigned Reg,
4051 unsigned &DefIdx, unsigned &Dist) {
4052 Dist = 0;
4053
4054 MachineBasicBlock::const_iterator I = MI; ++I;
4055 MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
4056 assert(II->isInsideBundle() && "Empty bundle?");
4057
4058 int Idx = -1;
4059 while (II->isInsideBundle()) {
4060 Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
4061 if (Idx != -1)
4062 break;
4063 --II;
4064 ++Dist;
4065 }
4066
4067 assert(Idx != -1 && "Cannot find bundled definition!");
4068 DefIdx = Idx;
4069 return &*II;
4070 }
4071
getBundledUseMI(const TargetRegisterInfo * TRI,const MachineInstr & MI,unsigned Reg,unsigned & UseIdx,unsigned & Dist)4072 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
4073 const MachineInstr &MI, unsigned Reg,
4074 unsigned &UseIdx, unsigned &Dist) {
4075 Dist = 0;
4076
4077 MachineBasicBlock::const_instr_iterator II = ++MI.getIterator();
4078 assert(II->isInsideBundle() && "Empty bundle?");
4079 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4080
4081 // FIXME: This doesn't properly handle multiple uses.
4082 int Idx = -1;
4083 while (II != E && II->isInsideBundle()) {
4084 Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
4085 if (Idx != -1)
4086 break;
4087 if (II->getOpcode() != ARM::t2IT)
4088 ++Dist;
4089 ++II;
4090 }
4091
4092 if (Idx == -1) {
4093 Dist = 0;
4094 return nullptr;
4095 }
4096
4097 UseIdx = Idx;
4098 return &*II;
4099 }
4100
4101 /// Return the number of cycles to add to (or subtract from) the static
4102 /// itinerary based on the def opcode and alignment. The caller will ensure that
4103 /// adjusted latency is at least one cycle.
adjustDefLatency(const ARMSubtarget & Subtarget,const MachineInstr & DefMI,const MCInstrDesc & DefMCID,unsigned DefAlign)4104 static int adjustDefLatency(const ARMSubtarget &Subtarget,
4105 const MachineInstr &DefMI,
4106 const MCInstrDesc &DefMCID, unsigned DefAlign) {
4107 int Adjust = 0;
4108 if (Subtarget.isCortexA8() || Subtarget.isLikeA9() || Subtarget.isCortexA7()) {
4109 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4110 // variants are one cycle cheaper.
4111 switch (DefMCID.getOpcode()) {
4112 default: break;
4113 case ARM::LDRrs:
4114 case ARM::LDRBrs: {
4115 unsigned ShOpVal = DefMI.getOperand(3).getImm();
4116 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4117 if (ShImm == 0 ||
4118 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4119 --Adjust;
4120 break;
4121 }
4122 case ARM::t2LDRs:
4123 case ARM::t2LDRBs:
4124 case ARM::t2LDRHs:
4125 case ARM::t2LDRSHs: {
4126 // Thumb2 mode: lsl only.
4127 unsigned ShAmt = DefMI.getOperand(3).getImm();
4128 if (ShAmt == 0 || ShAmt == 2)
4129 --Adjust;
4130 break;
4131 }
4132 }
4133 } else if (Subtarget.isSwift()) {
4134 // FIXME: Properly handle all of the latency adjustments for address
4135 // writeback.
4136 switch (DefMCID.getOpcode()) {
4137 default: break;
4138 case ARM::LDRrs:
4139 case ARM::LDRBrs: {
4140 unsigned ShOpVal = DefMI.getOperand(3).getImm();
4141 bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
4142 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4143 if (!isSub &&
4144 (ShImm == 0 ||
4145 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4146 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
4147 Adjust -= 2;
4148 else if (!isSub &&
4149 ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4150 --Adjust;
4151 break;
4152 }
4153 case ARM::t2LDRs:
4154 case ARM::t2LDRBs:
4155 case ARM::t2LDRHs:
4156 case ARM::t2LDRSHs: {
4157 // Thumb2 mode: lsl only.
4158 unsigned ShAmt = DefMI.getOperand(3).getImm();
4159 if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
4160 Adjust -= 2;
4161 break;
4162 }
4163 }
4164 }
4165
4166 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment()) {
4167 switch (DefMCID.getOpcode()) {
4168 default: break;
4169 case ARM::VLD1q8:
4170 case ARM::VLD1q16:
4171 case ARM::VLD1q32:
4172 case ARM::VLD1q64:
4173 case ARM::VLD1q8wb_fixed:
4174 case ARM::VLD1q16wb_fixed:
4175 case ARM::VLD1q32wb_fixed:
4176 case ARM::VLD1q64wb_fixed:
4177 case ARM::VLD1q8wb_register:
4178 case ARM::VLD1q16wb_register:
4179 case ARM::VLD1q32wb_register:
4180 case ARM::VLD1q64wb_register:
4181 case ARM::VLD2d8:
4182 case ARM::VLD2d16:
4183 case ARM::VLD2d32:
4184 case ARM::VLD2q8:
4185 case ARM::VLD2q16:
4186 case ARM::VLD2q32:
4187 case ARM::VLD2d8wb_fixed:
4188 case ARM::VLD2d16wb_fixed:
4189 case ARM::VLD2d32wb_fixed:
4190 case ARM::VLD2q8wb_fixed:
4191 case ARM::VLD2q16wb_fixed:
4192 case ARM::VLD2q32wb_fixed:
4193 case ARM::VLD2d8wb_register:
4194 case ARM::VLD2d16wb_register:
4195 case ARM::VLD2d32wb_register:
4196 case ARM::VLD2q8wb_register:
4197 case ARM::VLD2q16wb_register:
4198 case ARM::VLD2q32wb_register:
4199 case ARM::VLD3d8:
4200 case ARM::VLD3d16:
4201 case ARM::VLD3d32:
4202 case ARM::VLD1d64T:
4203 case ARM::VLD3d8_UPD:
4204 case ARM::VLD3d16_UPD:
4205 case ARM::VLD3d32_UPD:
4206 case ARM::VLD1d64Twb_fixed:
4207 case ARM::VLD1d64Twb_register:
4208 case ARM::VLD3q8_UPD:
4209 case ARM::VLD3q16_UPD:
4210 case ARM::VLD3q32_UPD:
4211 case ARM::VLD4d8:
4212 case ARM::VLD4d16:
4213 case ARM::VLD4d32:
4214 case ARM::VLD1d64Q:
4215 case ARM::VLD4d8_UPD:
4216 case ARM::VLD4d16_UPD:
4217 case ARM::VLD4d32_UPD:
4218 case ARM::VLD1d64Qwb_fixed:
4219 case ARM::VLD1d64Qwb_register:
4220 case ARM::VLD4q8_UPD:
4221 case ARM::VLD4q16_UPD:
4222 case ARM::VLD4q32_UPD:
4223 case ARM::VLD1DUPq8:
4224 case ARM::VLD1DUPq16:
4225 case ARM::VLD1DUPq32:
4226 case ARM::VLD1DUPq8wb_fixed:
4227 case ARM::VLD1DUPq16wb_fixed:
4228 case ARM::VLD1DUPq32wb_fixed:
4229 case ARM::VLD1DUPq8wb_register:
4230 case ARM::VLD1DUPq16wb_register:
4231 case ARM::VLD1DUPq32wb_register:
4232 case ARM::VLD2DUPd8:
4233 case ARM::VLD2DUPd16:
4234 case ARM::VLD2DUPd32:
4235 case ARM::VLD2DUPd8wb_fixed:
4236 case ARM::VLD2DUPd16wb_fixed:
4237 case ARM::VLD2DUPd32wb_fixed:
4238 case ARM::VLD2DUPd8wb_register:
4239 case ARM::VLD2DUPd16wb_register:
4240 case ARM::VLD2DUPd32wb_register:
4241 case ARM::VLD4DUPd8:
4242 case ARM::VLD4DUPd16:
4243 case ARM::VLD4DUPd32:
4244 case ARM::VLD4DUPd8_UPD:
4245 case ARM::VLD4DUPd16_UPD:
4246 case ARM::VLD4DUPd32_UPD:
4247 case ARM::VLD1LNd8:
4248 case ARM::VLD1LNd16:
4249 case ARM::VLD1LNd32:
4250 case ARM::VLD1LNd8_UPD:
4251 case ARM::VLD1LNd16_UPD:
4252 case ARM::VLD1LNd32_UPD:
4253 case ARM::VLD2LNd8:
4254 case ARM::VLD2LNd16:
4255 case ARM::VLD2LNd32:
4256 case ARM::VLD2LNq16:
4257 case ARM::VLD2LNq32:
4258 case ARM::VLD2LNd8_UPD:
4259 case ARM::VLD2LNd16_UPD:
4260 case ARM::VLD2LNd32_UPD:
4261 case ARM::VLD2LNq16_UPD:
4262 case ARM::VLD2LNq32_UPD:
4263 case ARM::VLD4LNd8:
4264 case ARM::VLD4LNd16:
4265 case ARM::VLD4LNd32:
4266 case ARM::VLD4LNq16:
4267 case ARM::VLD4LNq32:
4268 case ARM::VLD4LNd8_UPD:
4269 case ARM::VLD4LNd16_UPD:
4270 case ARM::VLD4LNd32_UPD:
4271 case ARM::VLD4LNq16_UPD:
4272 case ARM::VLD4LNq32_UPD:
4273 // If the address is not 64-bit aligned, the latencies of these
4274 // instructions increases by one.
4275 ++Adjust;
4276 break;
4277 }
4278 }
4279 return Adjust;
4280 }
4281
getOperandLatency(const InstrItineraryData * ItinData,const MachineInstr & DefMI,unsigned DefIdx,const MachineInstr & UseMI,unsigned UseIdx) const4282 int ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4283 const MachineInstr &DefMI,
4284 unsigned DefIdx,
4285 const MachineInstr &UseMI,
4286 unsigned UseIdx) const {
4287 // No operand latency. The caller may fall back to getInstrLatency.
4288 if (!ItinData || ItinData->isEmpty())
4289 return -1;
4290
4291 const MachineOperand &DefMO = DefMI.getOperand(DefIdx);
4292 Register Reg = DefMO.getReg();
4293
4294 const MachineInstr *ResolvedDefMI = &DefMI;
4295 unsigned DefAdj = 0;
4296 if (DefMI.isBundle())
4297 ResolvedDefMI =
4298 getBundledDefMI(&getRegisterInfo(), &DefMI, Reg, DefIdx, DefAdj);
4299 if (ResolvedDefMI->isCopyLike() || ResolvedDefMI->isInsertSubreg() ||
4300 ResolvedDefMI->isRegSequence() || ResolvedDefMI->isImplicitDef()) {
4301 return 1;
4302 }
4303
4304 const MachineInstr *ResolvedUseMI = &UseMI;
4305 unsigned UseAdj = 0;
4306 if (UseMI.isBundle()) {
4307 ResolvedUseMI =
4308 getBundledUseMI(&getRegisterInfo(), UseMI, Reg, UseIdx, UseAdj);
4309 if (!ResolvedUseMI)
4310 return -1;
4311 }
4312
4313 return getOperandLatencyImpl(
4314 ItinData, *ResolvedDefMI, DefIdx, ResolvedDefMI->getDesc(), DefAdj, DefMO,
4315 Reg, *ResolvedUseMI, UseIdx, ResolvedUseMI->getDesc(), UseAdj);
4316 }
4317
getOperandLatencyImpl(const InstrItineraryData * ItinData,const MachineInstr & DefMI,unsigned DefIdx,const MCInstrDesc & DefMCID,unsigned DefAdj,const MachineOperand & DefMO,unsigned Reg,const MachineInstr & UseMI,unsigned UseIdx,const MCInstrDesc & UseMCID,unsigned UseAdj) const4318 int ARMBaseInstrInfo::getOperandLatencyImpl(
4319 const InstrItineraryData *ItinData, const MachineInstr &DefMI,
4320 unsigned DefIdx, const MCInstrDesc &DefMCID, unsigned DefAdj,
4321 const MachineOperand &DefMO, unsigned Reg, const MachineInstr &UseMI,
4322 unsigned UseIdx, const MCInstrDesc &UseMCID, unsigned UseAdj) const {
4323 if (Reg == ARM::CPSR) {
4324 if (DefMI.getOpcode() == ARM::FMSTAT) {
4325 // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
4326 return Subtarget.isLikeA9() ? 1 : 20;
4327 }
4328
4329 // CPSR set and branch can be paired in the same cycle.
4330 if (UseMI.isBranch())
4331 return 0;
4332
4333 // Otherwise it takes the instruction latency (generally one).
4334 unsigned Latency = getInstrLatency(ItinData, DefMI);
4335
4336 // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
4337 // its uses. Instructions which are otherwise scheduled between them may
4338 // incur a code size penalty (not able to use the CPSR setting 16-bit
4339 // instructions).
4340 if (Latency > 0 && Subtarget.isThumb2()) {
4341 const MachineFunction *MF = DefMI.getParent()->getParent();
4342 // FIXME: Use Function::hasOptSize().
4343 if (MF->getFunction().hasFnAttribute(Attribute::OptimizeForSize))
4344 --Latency;
4345 }
4346 return Latency;
4347 }
4348
4349 if (DefMO.isImplicit() || UseMI.getOperand(UseIdx).isImplicit())
4350 return -1;
4351
4352 unsigned DefAlign = DefMI.hasOneMemOperand()
4353 ? (*DefMI.memoperands_begin())->getAlign().value()
4354 : 0;
4355 unsigned UseAlign = UseMI.hasOneMemOperand()
4356 ? (*UseMI.memoperands_begin())->getAlign().value()
4357 : 0;
4358
4359 // Get the itinerary's latency if possible, and handle variable_ops.
4360 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign, UseMCID,
4361 UseIdx, UseAlign);
4362 // Unable to find operand latency. The caller may resort to getInstrLatency.
4363 if (Latency < 0)
4364 return Latency;
4365
4366 // Adjust for IT block position.
4367 int Adj = DefAdj + UseAdj;
4368
4369 // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4370 Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
4371 if (Adj >= 0 || (int)Latency > -Adj) {
4372 return Latency + Adj;
4373 }
4374 // Return the itinerary latency, which may be zero but not less than zero.
4375 return Latency;
4376 }
4377
4378 int
getOperandLatency(const InstrItineraryData * ItinData,SDNode * DefNode,unsigned DefIdx,SDNode * UseNode,unsigned UseIdx) const4379 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
4380 SDNode *DefNode, unsigned DefIdx,
4381 SDNode *UseNode, unsigned UseIdx) const {
4382 if (!DefNode->isMachineOpcode())
4383 return 1;
4384
4385 const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
4386
4387 if (isZeroCost(DefMCID.Opcode))
4388 return 0;
4389
4390 if (!ItinData || ItinData->isEmpty())
4391 return DefMCID.mayLoad() ? 3 : 1;
4392
4393 if (!UseNode->isMachineOpcode()) {
4394 int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
4395 int Adj = Subtarget.getPreISelOperandLatencyAdjustment();
4396 int Threshold = 1 + Adj;
4397 return Latency <= Threshold ? 1 : Latency - Adj;
4398 }
4399
4400 const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
4401 auto *DefMN = cast<MachineSDNode>(DefNode);
4402 unsigned DefAlign = !DefMN->memoperands_empty()
4403 ? (*DefMN->memoperands_begin())->getAlign().value()
4404 : 0;
4405 auto *UseMN = cast<MachineSDNode>(UseNode);
4406 unsigned UseAlign = !UseMN->memoperands_empty()
4407 ? (*UseMN->memoperands_begin())->getAlign().value()
4408 : 0;
4409 int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
4410 UseMCID, UseIdx, UseAlign);
4411
4412 if (Latency > 1 &&
4413 (Subtarget.isCortexA8() || Subtarget.isLikeA9() ||
4414 Subtarget.isCortexA7())) {
4415 // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
4416 // variants are one cycle cheaper.
4417 switch (DefMCID.getOpcode()) {
4418 default: break;
4419 case ARM::LDRrs:
4420 case ARM::LDRBrs: {
4421 unsigned ShOpVal =
4422 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4423 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4424 if (ShImm == 0 ||
4425 (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4426 --Latency;
4427 break;
4428 }
4429 case ARM::t2LDRs:
4430 case ARM::t2LDRBs:
4431 case ARM::t2LDRHs:
4432 case ARM::t2LDRSHs: {
4433 // Thumb2 mode: lsl only.
4434 unsigned ShAmt =
4435 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4436 if (ShAmt == 0 || ShAmt == 2)
4437 --Latency;
4438 break;
4439 }
4440 }
4441 } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
4442 // FIXME: Properly handle all of the latency adjustments for address
4443 // writeback.
4444 switch (DefMCID.getOpcode()) {
4445 default: break;
4446 case ARM::LDRrs:
4447 case ARM::LDRBrs: {
4448 unsigned ShOpVal =
4449 cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
4450 unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
4451 if (ShImm == 0 ||
4452 ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
4453 ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
4454 Latency -= 2;
4455 else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
4456 --Latency;
4457 break;
4458 }
4459 case ARM::t2LDRs:
4460 case ARM::t2LDRBs:
4461 case ARM::t2LDRHs:
4462 case ARM::t2LDRSHs:
4463 // Thumb2 mode: lsl 0-3 only.
4464 Latency -= 2;
4465 break;
4466 }
4467 }
4468
4469 if (DefAlign < 8 && Subtarget.checkVLDnAccessAlignment())
4470 switch (DefMCID.getOpcode()) {
4471 default: break;
4472 case ARM::VLD1q8:
4473 case ARM::VLD1q16:
4474 case ARM::VLD1q32:
4475 case ARM::VLD1q64:
4476 case ARM::VLD1q8wb_register:
4477 case ARM::VLD1q16wb_register:
4478 case ARM::VLD1q32wb_register:
4479 case ARM::VLD1q64wb_register:
4480 case ARM::VLD1q8wb_fixed:
4481 case ARM::VLD1q16wb_fixed:
4482 case ARM::VLD1q32wb_fixed:
4483 case ARM::VLD1q64wb_fixed:
4484 case ARM::VLD2d8:
4485 case ARM::VLD2d16:
4486 case ARM::VLD2d32:
4487 case ARM::VLD2q8Pseudo:
4488 case ARM::VLD2q16Pseudo:
4489 case ARM::VLD2q32Pseudo:
4490 case ARM::VLD2d8wb_fixed:
4491 case ARM::VLD2d16wb_fixed:
4492 case ARM::VLD2d32wb_fixed:
4493 case ARM::VLD2q8PseudoWB_fixed:
4494 case ARM::VLD2q16PseudoWB_fixed:
4495 case ARM::VLD2q32PseudoWB_fixed:
4496 case ARM::VLD2d8wb_register:
4497 case ARM::VLD2d16wb_register:
4498 case ARM::VLD2d32wb_register:
4499 case ARM::VLD2q8PseudoWB_register:
4500 case ARM::VLD2q16PseudoWB_register:
4501 case ARM::VLD2q32PseudoWB_register:
4502 case ARM::VLD3d8Pseudo:
4503 case ARM::VLD3d16Pseudo:
4504 case ARM::VLD3d32Pseudo:
4505 case ARM::VLD1d8TPseudo:
4506 case ARM::VLD1d16TPseudo:
4507 case ARM::VLD1d32TPseudo:
4508 case ARM::VLD1d64TPseudo:
4509 case ARM::VLD1d64TPseudoWB_fixed:
4510 case ARM::VLD1d64TPseudoWB_register:
4511 case ARM::VLD3d8Pseudo_UPD:
4512 case ARM::VLD3d16Pseudo_UPD:
4513 case ARM::VLD3d32Pseudo_UPD:
4514 case ARM::VLD3q8Pseudo_UPD:
4515 case ARM::VLD3q16Pseudo_UPD:
4516 case ARM::VLD3q32Pseudo_UPD:
4517 case ARM::VLD3q8oddPseudo:
4518 case ARM::VLD3q16oddPseudo:
4519 case ARM::VLD3q32oddPseudo:
4520 case ARM::VLD3q8oddPseudo_UPD:
4521 case ARM::VLD3q16oddPseudo_UPD:
4522 case ARM::VLD3q32oddPseudo_UPD:
4523 case ARM::VLD4d8Pseudo:
4524 case ARM::VLD4d16Pseudo:
4525 case ARM::VLD4d32Pseudo:
4526 case ARM::VLD1d8QPseudo:
4527 case ARM::VLD1d16QPseudo:
4528 case ARM::VLD1d32QPseudo:
4529 case ARM::VLD1d64QPseudo:
4530 case ARM::VLD1d64QPseudoWB_fixed:
4531 case ARM::VLD1d64QPseudoWB_register:
4532 case ARM::VLD1q8HighQPseudo:
4533 case ARM::VLD1q8LowQPseudo_UPD:
4534 case ARM::VLD1q8HighTPseudo:
4535 case ARM::VLD1q8LowTPseudo_UPD:
4536 case ARM::VLD1q16HighQPseudo:
4537 case ARM::VLD1q16LowQPseudo_UPD:
4538 case ARM::VLD1q16HighTPseudo:
4539 case ARM::VLD1q16LowTPseudo_UPD:
4540 case ARM::VLD1q32HighQPseudo:
4541 case ARM::VLD1q32LowQPseudo_UPD:
4542 case ARM::VLD1q32HighTPseudo:
4543 case ARM::VLD1q32LowTPseudo_UPD:
4544 case ARM::VLD1q64HighQPseudo:
4545 case ARM::VLD1q64LowQPseudo_UPD:
4546 case ARM::VLD1q64HighTPseudo:
4547 case ARM::VLD1q64LowTPseudo_UPD:
4548 case ARM::VLD4d8Pseudo_UPD:
4549 case ARM::VLD4d16Pseudo_UPD:
4550 case ARM::VLD4d32Pseudo_UPD:
4551 case ARM::VLD4q8Pseudo_UPD:
4552 case ARM::VLD4q16Pseudo_UPD:
4553 case ARM::VLD4q32Pseudo_UPD:
4554 case ARM::VLD4q8oddPseudo:
4555 case ARM::VLD4q16oddPseudo:
4556 case ARM::VLD4q32oddPseudo:
4557 case ARM::VLD4q8oddPseudo_UPD:
4558 case ARM::VLD4q16oddPseudo_UPD:
4559 case ARM::VLD4q32oddPseudo_UPD:
4560 case ARM::VLD1DUPq8:
4561 case ARM::VLD1DUPq16:
4562 case ARM::VLD1DUPq32:
4563 case ARM::VLD1DUPq8wb_fixed:
4564 case ARM::VLD1DUPq16wb_fixed:
4565 case ARM::VLD1DUPq32wb_fixed:
4566 case ARM::VLD1DUPq8wb_register:
4567 case ARM::VLD1DUPq16wb_register:
4568 case ARM::VLD1DUPq32wb_register:
4569 case ARM::VLD2DUPd8:
4570 case ARM::VLD2DUPd16:
4571 case ARM::VLD2DUPd32:
4572 case ARM::VLD2DUPd8wb_fixed:
4573 case ARM::VLD2DUPd16wb_fixed:
4574 case ARM::VLD2DUPd32wb_fixed:
4575 case ARM::VLD2DUPd8wb_register:
4576 case ARM::VLD2DUPd16wb_register:
4577 case ARM::VLD2DUPd32wb_register:
4578 case ARM::VLD2DUPq8EvenPseudo:
4579 case ARM::VLD2DUPq8OddPseudo:
4580 case ARM::VLD2DUPq16EvenPseudo:
4581 case ARM::VLD2DUPq16OddPseudo:
4582 case ARM::VLD2DUPq32EvenPseudo:
4583 case ARM::VLD2DUPq32OddPseudo:
4584 case ARM::VLD3DUPq8EvenPseudo:
4585 case ARM::VLD3DUPq8OddPseudo:
4586 case ARM::VLD3DUPq16EvenPseudo:
4587 case ARM::VLD3DUPq16OddPseudo:
4588 case ARM::VLD3DUPq32EvenPseudo:
4589 case ARM::VLD3DUPq32OddPseudo:
4590 case ARM::VLD4DUPd8Pseudo:
4591 case ARM::VLD4DUPd16Pseudo:
4592 case ARM::VLD4DUPd32Pseudo:
4593 case ARM::VLD4DUPd8Pseudo_UPD:
4594 case ARM::VLD4DUPd16Pseudo_UPD:
4595 case ARM::VLD4DUPd32Pseudo_UPD:
4596 case ARM::VLD4DUPq8EvenPseudo:
4597 case ARM::VLD4DUPq8OddPseudo:
4598 case ARM::VLD4DUPq16EvenPseudo:
4599 case ARM::VLD4DUPq16OddPseudo:
4600 case ARM::VLD4DUPq32EvenPseudo:
4601 case ARM::VLD4DUPq32OddPseudo:
4602 case ARM::VLD1LNq8Pseudo:
4603 case ARM::VLD1LNq16Pseudo:
4604 case ARM::VLD1LNq32Pseudo:
4605 case ARM::VLD1LNq8Pseudo_UPD:
4606 case ARM::VLD1LNq16Pseudo_UPD:
4607 case ARM::VLD1LNq32Pseudo_UPD:
4608 case ARM::VLD2LNd8Pseudo:
4609 case ARM::VLD2LNd16Pseudo:
4610 case ARM::VLD2LNd32Pseudo:
4611 case ARM::VLD2LNq16Pseudo:
4612 case ARM::VLD2LNq32Pseudo:
4613 case ARM::VLD2LNd8Pseudo_UPD:
4614 case ARM::VLD2LNd16Pseudo_UPD:
4615 case ARM::VLD2LNd32Pseudo_UPD:
4616 case ARM::VLD2LNq16Pseudo_UPD:
4617 case ARM::VLD2LNq32Pseudo_UPD:
4618 case ARM::VLD4LNd8Pseudo:
4619 case ARM::VLD4LNd16Pseudo:
4620 case ARM::VLD4LNd32Pseudo:
4621 case ARM::VLD4LNq16Pseudo:
4622 case ARM::VLD4LNq32Pseudo:
4623 case ARM::VLD4LNd8Pseudo_UPD:
4624 case ARM::VLD4LNd16Pseudo_UPD:
4625 case ARM::VLD4LNd32Pseudo_UPD:
4626 case ARM::VLD4LNq16Pseudo_UPD:
4627 case ARM::VLD4LNq32Pseudo_UPD:
4628 // If the address is not 64-bit aligned, the latencies of these
4629 // instructions increases by one.
4630 ++Latency;
4631 break;
4632 }
4633
4634 return Latency;
4635 }
4636
getPredicationCost(const MachineInstr & MI) const4637 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr &MI) const {
4638 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4639 MI.isImplicitDef())
4640 return 0;
4641
4642 if (MI.isBundle())
4643 return 0;
4644
4645 const MCInstrDesc &MCID = MI.getDesc();
4646
4647 if (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4648 !Subtarget.cheapPredicableCPSRDef())) {
4649 // When predicated, CPSR is an additional source operand for CPSR updating
4650 // instructions, this apparently increases their latencies.
4651 return 1;
4652 }
4653 return 0;
4654 }
4655
getInstrLatency(const InstrItineraryData * ItinData,const MachineInstr & MI,unsigned * PredCost) const4656 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4657 const MachineInstr &MI,
4658 unsigned *PredCost) const {
4659 if (MI.isCopyLike() || MI.isInsertSubreg() || MI.isRegSequence() ||
4660 MI.isImplicitDef())
4661 return 1;
4662
4663 // An instruction scheduler typically runs on unbundled instructions, however
4664 // other passes may query the latency of a bundled instruction.
4665 if (MI.isBundle()) {
4666 unsigned Latency = 0;
4667 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
4668 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
4669 while (++I != E && I->isInsideBundle()) {
4670 if (I->getOpcode() != ARM::t2IT)
4671 Latency += getInstrLatency(ItinData, *I, PredCost);
4672 }
4673 return Latency;
4674 }
4675
4676 const MCInstrDesc &MCID = MI.getDesc();
4677 if (PredCost && (MCID.isCall() || (MCID.hasImplicitDefOfPhysReg(ARM::CPSR) &&
4678 !Subtarget.cheapPredicableCPSRDef()))) {
4679 // When predicated, CPSR is an additional source operand for CPSR updating
4680 // instructions, this apparently increases their latencies.
4681 *PredCost = 1;
4682 }
4683 // Be sure to call getStageLatency for an empty itinerary in case it has a
4684 // valid MinLatency property.
4685 if (!ItinData)
4686 return MI.mayLoad() ? 3 : 1;
4687
4688 unsigned Class = MCID.getSchedClass();
4689
4690 // For instructions with variable uops, use uops as latency.
4691 if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
4692 return getNumMicroOps(ItinData, MI);
4693
4694 // For the common case, fall back on the itinerary's latency.
4695 unsigned Latency = ItinData->getStageLatency(Class);
4696
4697 // Adjust for dynamic def-side opcode variants not captured by the itinerary.
4698 unsigned DefAlign =
4699 MI.hasOneMemOperand() ? (*MI.memoperands_begin())->getAlign().value() : 0;
4700 int Adj = adjustDefLatency(Subtarget, MI, MCID, DefAlign);
4701 if (Adj >= 0 || (int)Latency > -Adj) {
4702 return Latency + Adj;
4703 }
4704 return Latency;
4705 }
4706
getInstrLatency(const InstrItineraryData * ItinData,SDNode * Node) const4707 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
4708 SDNode *Node) const {
4709 if (!Node->isMachineOpcode())
4710 return 1;
4711
4712 if (!ItinData || ItinData->isEmpty())
4713 return 1;
4714
4715 unsigned Opcode = Node->getMachineOpcode();
4716 switch (Opcode) {
4717 default:
4718 return ItinData->getStageLatency(get(Opcode).getSchedClass());
4719 case ARM::VLDMQIA:
4720 case ARM::VSTMQIA:
4721 return 2;
4722 }
4723 }
4724
hasHighOperandLatency(const TargetSchedModel & SchedModel,const MachineRegisterInfo * MRI,const MachineInstr & DefMI,unsigned DefIdx,const MachineInstr & UseMI,unsigned UseIdx) const4725 bool ARMBaseInstrInfo::hasHighOperandLatency(const TargetSchedModel &SchedModel,
4726 const MachineRegisterInfo *MRI,
4727 const MachineInstr &DefMI,
4728 unsigned DefIdx,
4729 const MachineInstr &UseMI,
4730 unsigned UseIdx) const {
4731 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4732 unsigned UDomain = UseMI.getDesc().TSFlags & ARMII::DomainMask;
4733 if (Subtarget.nonpipelinedVFP() &&
4734 (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
4735 return true;
4736
4737 // Hoist VFP / NEON instructions with 4 or higher latency.
4738 unsigned Latency =
4739 SchedModel.computeOperandLatency(&DefMI, DefIdx, &UseMI, UseIdx);
4740 if (Latency <= 3)
4741 return false;
4742 return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
4743 UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
4744 }
4745
hasLowDefLatency(const TargetSchedModel & SchedModel,const MachineInstr & DefMI,unsigned DefIdx) const4746 bool ARMBaseInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
4747 const MachineInstr &DefMI,
4748 unsigned DefIdx) const {
4749 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
4750 if (!ItinData || ItinData->isEmpty())
4751 return false;
4752
4753 unsigned DDomain = DefMI.getDesc().TSFlags & ARMII::DomainMask;
4754 if (DDomain == ARMII::DomainGeneral) {
4755 unsigned DefClass = DefMI.getDesc().getSchedClass();
4756 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
4757 return (DefCycle != -1 && DefCycle <= 2);
4758 }
4759 return false;
4760 }
4761
verifyInstruction(const MachineInstr & MI,StringRef & ErrInfo) const4762 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr &MI,
4763 StringRef &ErrInfo) const {
4764 if (convertAddSubFlagsOpcode(MI.getOpcode())) {
4765 ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
4766 return false;
4767 }
4768 if (MI.getOpcode() == ARM::tMOVr && !Subtarget.hasV6Ops()) {
4769 // Make sure we don't generate a lo-lo mov that isn't supported.
4770 if (!ARM::hGPRRegClass.contains(MI.getOperand(0).getReg()) &&
4771 !ARM::hGPRRegClass.contains(MI.getOperand(1).getReg())) {
4772 ErrInfo = "Non-flag-setting Thumb1 mov is v6-only";
4773 return false;
4774 }
4775 }
4776 if (MI.getOpcode() == ARM::tPUSH ||
4777 MI.getOpcode() == ARM::tPOP ||
4778 MI.getOpcode() == ARM::tPOP_RET) {
4779 for (int i = 2, e = MI.getNumOperands(); i < e; ++i) {
4780 if (MI.getOperand(i).isImplicit() ||
4781 !MI.getOperand(i).isReg())
4782 continue;
4783 Register Reg = MI.getOperand(i).getReg();
4784 if (Reg < ARM::R0 || Reg > ARM::R7) {
4785 if (!(MI.getOpcode() == ARM::tPUSH && Reg == ARM::LR) &&
4786 !(MI.getOpcode() == ARM::tPOP_RET && Reg == ARM::PC)) {
4787 ErrInfo = "Unsupported register in Thumb1 push/pop";
4788 return false;
4789 }
4790 }
4791 }
4792 }
4793 return true;
4794 }
4795
4796 // LoadStackGuard has so far only been implemented for MachO. Different code
4797 // sequence is needed for other targets.
expandLoadStackGuardBase(MachineBasicBlock::iterator MI,unsigned LoadImmOpc,unsigned LoadOpc) const4798 void ARMBaseInstrInfo::expandLoadStackGuardBase(MachineBasicBlock::iterator MI,
4799 unsigned LoadImmOpc,
4800 unsigned LoadOpc) const {
4801 assert(!Subtarget.isROPI() && !Subtarget.isRWPI() &&
4802 "ROPI/RWPI not currently supported with stack guard");
4803
4804 MachineBasicBlock &MBB = *MI->getParent();
4805 DebugLoc DL = MI->getDebugLoc();
4806 Register Reg = MI->getOperand(0).getReg();
4807 const GlobalValue *GV =
4808 cast<GlobalValue>((*MI->memoperands_begin())->getValue());
4809 MachineInstrBuilder MIB;
4810
4811 BuildMI(MBB, MI, DL, get(LoadImmOpc), Reg)
4812 .addGlobalAddress(GV, 0, ARMII::MO_NONLAZY);
4813
4814 if (Subtarget.isGVIndirectSymbol(GV)) {
4815 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4816 MIB.addReg(Reg, RegState::Kill).addImm(0);
4817 auto Flags = MachineMemOperand::MOLoad |
4818 MachineMemOperand::MODereferenceable |
4819 MachineMemOperand::MOInvariant;
4820 MachineMemOperand *MMO = MBB.getParent()->getMachineMemOperand(
4821 MachinePointerInfo::getGOT(*MBB.getParent()), Flags, 4, Align(4));
4822 MIB.addMemOperand(MMO).add(predOps(ARMCC::AL));
4823 }
4824
4825 MIB = BuildMI(MBB, MI, DL, get(LoadOpc), Reg);
4826 MIB.addReg(Reg, RegState::Kill)
4827 .addImm(0)
4828 .cloneMemRefs(*MI)
4829 .add(predOps(ARMCC::AL));
4830 }
4831
4832 bool
isFpMLxInstruction(unsigned Opcode,unsigned & MulOpc,unsigned & AddSubOpc,bool & NegAcc,bool & HasLane) const4833 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
4834 unsigned &AddSubOpc,
4835 bool &NegAcc, bool &HasLane) const {
4836 DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
4837 if (I == MLxEntryMap.end())
4838 return false;
4839
4840 const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
4841 MulOpc = Entry.MulOpc;
4842 AddSubOpc = Entry.AddSubOpc;
4843 NegAcc = Entry.NegAcc;
4844 HasLane = Entry.HasLane;
4845 return true;
4846 }
4847
4848 //===----------------------------------------------------------------------===//
4849 // Execution domains.
4850 //===----------------------------------------------------------------------===//
4851 //
4852 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
4853 // and some can go down both. The vmov instructions go down the VFP pipeline,
4854 // but they can be changed to vorr equivalents that are executed by the NEON
4855 // pipeline.
4856 //
4857 // We use the following execution domain numbering:
4858 //
4859 enum ARMExeDomain {
4860 ExeGeneric = 0,
4861 ExeVFP = 1,
4862 ExeNEON = 2
4863 };
4864
4865 //
4866 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
4867 //
4868 std::pair<uint16_t, uint16_t>
getExecutionDomain(const MachineInstr & MI) const4869 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr &MI) const {
4870 // If we don't have access to NEON instructions then we won't be able
4871 // to swizzle anything to the NEON domain. Check to make sure.
4872 if (Subtarget.hasNEON()) {
4873 // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
4874 // if they are not predicated.
4875 if (MI.getOpcode() == ARM::VMOVD && !isPredicated(MI))
4876 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4877
4878 // CortexA9 is particularly picky about mixing the two and wants these
4879 // converted.
4880 if (Subtarget.useNEONForFPMovs() && !isPredicated(MI) &&
4881 (MI.getOpcode() == ARM::VMOVRS || MI.getOpcode() == ARM::VMOVSR ||
4882 MI.getOpcode() == ARM::VMOVS))
4883 return std::make_pair(ExeVFP, (1 << ExeVFP) | (1 << ExeNEON));
4884 }
4885 // No other instructions can be swizzled, so just determine their domain.
4886 unsigned Domain = MI.getDesc().TSFlags & ARMII::DomainMask;
4887
4888 if (Domain & ARMII::DomainNEON)
4889 return std::make_pair(ExeNEON, 0);
4890
4891 // Certain instructions can go either way on Cortex-A8.
4892 // Treat them as NEON instructions.
4893 if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
4894 return std::make_pair(ExeNEON, 0);
4895
4896 if (Domain & ARMII::DomainVFP)
4897 return std::make_pair(ExeVFP, 0);
4898
4899 return std::make_pair(ExeGeneric, 0);
4900 }
4901
getCorrespondingDRegAndLane(const TargetRegisterInfo * TRI,unsigned SReg,unsigned & Lane)4902 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
4903 unsigned SReg, unsigned &Lane) {
4904 unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
4905 Lane = 0;
4906
4907 if (DReg != ARM::NoRegister)
4908 return DReg;
4909
4910 Lane = 1;
4911 DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
4912
4913 assert(DReg && "S-register with no D super-register?");
4914 return DReg;
4915 }
4916
4917 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
4918 /// set ImplicitSReg to a register number that must be marked as implicit-use or
4919 /// zero if no register needs to be defined as implicit-use.
4920 ///
4921 /// If the function cannot determine if an SPR should be marked implicit use or
4922 /// not, it returns false.
4923 ///
4924 /// This function handles cases where an instruction is being modified from taking
4925 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
4926 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
4927 /// lane of the DPR).
4928 ///
4929 /// If the other SPR is defined, an implicit-use of it should be added. Else,
4930 /// (including the case where the DPR itself is defined), it should not.
4931 ///
getImplicitSPRUseForDPRUse(const TargetRegisterInfo * TRI,MachineInstr & MI,unsigned DReg,unsigned Lane,unsigned & ImplicitSReg)4932 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
4933 MachineInstr &MI, unsigned DReg,
4934 unsigned Lane, unsigned &ImplicitSReg) {
4935 // If the DPR is defined or used already, the other SPR lane will be chained
4936 // correctly, so there is nothing to be done.
4937 if (MI.definesRegister(DReg, TRI) || MI.readsRegister(DReg, TRI)) {
4938 ImplicitSReg = 0;
4939 return true;
4940 }
4941
4942 // Otherwise we need to go searching to see if the SPR is set explicitly.
4943 ImplicitSReg = TRI->getSubReg(DReg,
4944 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
4945 MachineBasicBlock::LivenessQueryResult LQR =
4946 MI.getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
4947
4948 if (LQR == MachineBasicBlock::LQR_Live)
4949 return true;
4950 else if (LQR == MachineBasicBlock::LQR_Unknown)
4951 return false;
4952
4953 // If the register is known not to be live, there is no need to add an
4954 // implicit-use.
4955 ImplicitSReg = 0;
4956 return true;
4957 }
4958
setExecutionDomain(MachineInstr & MI,unsigned Domain) const4959 void ARMBaseInstrInfo::setExecutionDomain(MachineInstr &MI,
4960 unsigned Domain) const {
4961 unsigned DstReg, SrcReg, DReg;
4962 unsigned Lane;
4963 MachineInstrBuilder MIB(*MI.getParent()->getParent(), MI);
4964 const TargetRegisterInfo *TRI = &getRegisterInfo();
4965 switch (MI.getOpcode()) {
4966 default:
4967 llvm_unreachable("cannot handle opcode!");
4968 break;
4969 case ARM::VMOVD:
4970 if (Domain != ExeNEON)
4971 break;
4972
4973 // Zap the predicate operands.
4974 assert(!isPredicated(MI) && "Cannot predicate a VORRd");
4975
4976 // Make sure we've got NEON instructions.
4977 assert(Subtarget.hasNEON() && "VORRd requires NEON");
4978
4979 // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
4980 DstReg = MI.getOperand(0).getReg();
4981 SrcReg = MI.getOperand(1).getReg();
4982
4983 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
4984 MI.RemoveOperand(i - 1);
4985
4986 // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
4987 MI.setDesc(get(ARM::VORRd));
4988 MIB.addReg(DstReg, RegState::Define)
4989 .addReg(SrcReg)
4990 .addReg(SrcReg)
4991 .add(predOps(ARMCC::AL));
4992 break;
4993 case ARM::VMOVRS:
4994 if (Domain != ExeNEON)
4995 break;
4996 assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
4997
4998 // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
4999 DstReg = MI.getOperand(0).getReg();
5000 SrcReg = MI.getOperand(1).getReg();
5001
5002 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5003 MI.RemoveOperand(i - 1);
5004
5005 DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
5006
5007 // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
5008 // Note that DSrc has been widened and the other lane may be undef, which
5009 // contaminates the entire register.
5010 MI.setDesc(get(ARM::VGETLNi32));
5011 MIB.addReg(DstReg, RegState::Define)
5012 .addReg(DReg, RegState::Undef)
5013 .addImm(Lane)
5014 .add(predOps(ARMCC::AL));
5015
5016 // The old source should be an implicit use, otherwise we might think it
5017 // was dead before here.
5018 MIB.addReg(SrcReg, RegState::Implicit);
5019 break;
5020 case ARM::VMOVSR: {
5021 if (Domain != ExeNEON)
5022 break;
5023 assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
5024
5025 // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
5026 DstReg = MI.getOperand(0).getReg();
5027 SrcReg = MI.getOperand(1).getReg();
5028
5029 DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
5030
5031 unsigned ImplicitSReg;
5032 if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
5033 break;
5034
5035 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5036 MI.RemoveOperand(i - 1);
5037
5038 // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
5039 // Again DDst may be undefined at the beginning of this instruction.
5040 MI.setDesc(get(ARM::VSETLNi32));
5041 MIB.addReg(DReg, RegState::Define)
5042 .addReg(DReg, getUndefRegState(!MI.readsRegister(DReg, TRI)))
5043 .addReg(SrcReg)
5044 .addImm(Lane)
5045 .add(predOps(ARMCC::AL));
5046
5047 // The narrower destination must be marked as set to keep previous chains
5048 // in place.
5049 MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5050 if (ImplicitSReg != 0)
5051 MIB.addReg(ImplicitSReg, RegState::Implicit);
5052 break;
5053 }
5054 case ARM::VMOVS: {
5055 if (Domain != ExeNEON)
5056 break;
5057
5058 // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
5059 DstReg = MI.getOperand(0).getReg();
5060 SrcReg = MI.getOperand(1).getReg();
5061
5062 unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
5063 DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
5064 DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
5065
5066 unsigned ImplicitSReg;
5067 if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
5068 break;
5069
5070 for (unsigned i = MI.getDesc().getNumOperands(); i; --i)
5071 MI.RemoveOperand(i - 1);
5072
5073 if (DSrc == DDst) {
5074 // Destination can be:
5075 // %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
5076 MI.setDesc(get(ARM::VDUPLN32d));
5077 MIB.addReg(DDst, RegState::Define)
5078 .addReg(DDst, getUndefRegState(!MI.readsRegister(DDst, TRI)))
5079 .addImm(SrcLane)
5080 .add(predOps(ARMCC::AL));
5081
5082 // Neither the source or the destination are naturally represented any
5083 // more, so add them in manually.
5084 MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
5085 MIB.addReg(SrcReg, RegState::Implicit);
5086 if (ImplicitSReg != 0)
5087 MIB.addReg(ImplicitSReg, RegState::Implicit);
5088 break;
5089 }
5090
5091 // In general there's no single instruction that can perform an S <-> S
5092 // move in NEON space, but a pair of VEXT instructions *can* do the
5093 // job. It turns out that the VEXTs needed will only use DSrc once, with
5094 // the position based purely on the combination of lane-0 and lane-1
5095 // involved. For example
5096 // vmov s0, s2 -> vext.32 d0, d0, d1, #1 vext.32 d0, d0, d0, #1
5097 // vmov s1, s3 -> vext.32 d0, d1, d0, #1 vext.32 d0, d0, d0, #1
5098 // vmov s0, s3 -> vext.32 d0, d0, d0, #1 vext.32 d0, d1, d0, #1
5099 // vmov s1, s2 -> vext.32 d0, d0, d0, #1 vext.32 d0, d0, d1, #1
5100 //
5101 // Pattern of the MachineInstrs is:
5102 // %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
5103 MachineInstrBuilder NewMIB;
5104 NewMIB = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::VEXTd32),
5105 DDst);
5106
5107 // On the first instruction, both DSrc and DDst may be undef if present.
5108 // Specifically when the original instruction didn't have them as an
5109 // <imp-use>.
5110 unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
5111 bool CurUndef = !MI.readsRegister(CurReg, TRI);
5112 NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
5113
5114 CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
5115 CurUndef = !MI.readsRegister(CurReg, TRI);
5116 NewMIB.addReg(CurReg, getUndefRegState(CurUndef))
5117 .addImm(1)
5118 .add(predOps(ARMCC::AL));
5119
5120 if (SrcLane == DstLane)
5121 NewMIB.addReg(SrcReg, RegState::Implicit);
5122
5123 MI.setDesc(get(ARM::VEXTd32));
5124 MIB.addReg(DDst, RegState::Define);
5125
5126 // On the second instruction, DDst has definitely been defined above, so
5127 // it is not undef. DSrc, if present, can be undef as above.
5128 CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
5129 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5130 MIB.addReg(CurReg, getUndefRegState(CurUndef));
5131
5132 CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
5133 CurUndef = CurReg == DSrc && !MI.readsRegister(CurReg, TRI);
5134 MIB.addReg(CurReg, getUndefRegState(CurUndef))
5135 .addImm(1)
5136 .add(predOps(ARMCC::AL));
5137
5138 if (SrcLane != DstLane)
5139 MIB.addReg(SrcReg, RegState::Implicit);
5140
5141 // As before, the original destination is no longer represented, add it
5142 // implicitly.
5143 MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
5144 if (ImplicitSReg != 0)
5145 MIB.addReg(ImplicitSReg, RegState::Implicit);
5146 break;
5147 }
5148 }
5149 }
5150
5151 //===----------------------------------------------------------------------===//
5152 // Partial register updates
5153 //===----------------------------------------------------------------------===//
5154 //
5155 // Swift renames NEON registers with 64-bit granularity. That means any
5156 // instruction writing an S-reg implicitly reads the containing D-reg. The
5157 // problem is mostly avoided by translating f32 operations to v2f32 operations
5158 // on D-registers, but f32 loads are still a problem.
5159 //
5160 // These instructions can load an f32 into a NEON register:
5161 //
5162 // VLDRS - Only writes S, partial D update.
5163 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
5164 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
5165 //
5166 // FCONSTD can be used as a dependency-breaking instruction.
getPartialRegUpdateClearance(const MachineInstr & MI,unsigned OpNum,const TargetRegisterInfo * TRI) const5167 unsigned ARMBaseInstrInfo::getPartialRegUpdateClearance(
5168 const MachineInstr &MI, unsigned OpNum,
5169 const TargetRegisterInfo *TRI) const {
5170 auto PartialUpdateClearance = Subtarget.getPartialUpdateClearance();
5171 if (!PartialUpdateClearance)
5172 return 0;
5173
5174 assert(TRI && "Need TRI instance");
5175
5176 const MachineOperand &MO = MI.getOperand(OpNum);
5177 if (MO.readsReg())
5178 return 0;
5179 Register Reg = MO.getReg();
5180 int UseOp = -1;
5181
5182 switch (MI.getOpcode()) {
5183 // Normal instructions writing only an S-register.
5184 case ARM::VLDRS:
5185 case ARM::FCONSTS:
5186 case ARM::VMOVSR:
5187 case ARM::VMOVv8i8:
5188 case ARM::VMOVv4i16:
5189 case ARM::VMOVv2i32:
5190 case ARM::VMOVv2f32:
5191 case ARM::VMOVv1i64:
5192 UseOp = MI.findRegisterUseOperandIdx(Reg, false, TRI);
5193 break;
5194
5195 // Explicitly reads the dependency.
5196 case ARM::VLD1LNd32:
5197 UseOp = 3;
5198 break;
5199 default:
5200 return 0;
5201 }
5202
5203 // If this instruction actually reads a value from Reg, there is no unwanted
5204 // dependency.
5205 if (UseOp != -1 && MI.getOperand(UseOp).readsReg())
5206 return 0;
5207
5208 // We must be able to clobber the whole D-reg.
5209 if (Register::isVirtualRegister(Reg)) {
5210 // Virtual register must be a def undef foo:ssub_0 operand.
5211 if (!MO.getSubReg() || MI.readsVirtualRegister(Reg))
5212 return 0;
5213 } else if (ARM::SPRRegClass.contains(Reg)) {
5214 // Physical register: MI must define the full D-reg.
5215 unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
5216 &ARM::DPRRegClass);
5217 if (!DReg || !MI.definesRegister(DReg, TRI))
5218 return 0;
5219 }
5220
5221 // MI has an unwanted D-register dependency.
5222 // Avoid defs in the previous N instructrions.
5223 return PartialUpdateClearance;
5224 }
5225
5226 // Break a partial register dependency after getPartialRegUpdateClearance
5227 // returned non-zero.
breakPartialRegDependency(MachineInstr & MI,unsigned OpNum,const TargetRegisterInfo * TRI) const5228 void ARMBaseInstrInfo::breakPartialRegDependency(
5229 MachineInstr &MI, unsigned OpNum, const TargetRegisterInfo *TRI) const {
5230 assert(OpNum < MI.getDesc().getNumDefs() && "OpNum is not a def");
5231 assert(TRI && "Need TRI instance");
5232
5233 const MachineOperand &MO = MI.getOperand(OpNum);
5234 Register Reg = MO.getReg();
5235 assert(Register::isPhysicalRegister(Reg) &&
5236 "Can't break virtual register dependencies.");
5237 unsigned DReg = Reg;
5238
5239 // If MI defines an S-reg, find the corresponding D super-register.
5240 if (ARM::SPRRegClass.contains(Reg)) {
5241 DReg = ARM::D0 + (Reg - ARM::S0) / 2;
5242 assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
5243 }
5244
5245 assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
5246 assert(MI.definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
5247
5248 // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
5249 // the full D-register by loading the same value to both lanes. The
5250 // instruction is micro-coded with 2 uops, so don't do this until we can
5251 // properly schedule micro-coded instructions. The dispatcher stalls cause
5252 // too big regressions.
5253
5254 // Insert the dependency-breaking FCONSTD before MI.
5255 // 96 is the encoding of 0.5, but the actual value doesn't matter here.
5256 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), get(ARM::FCONSTD), DReg)
5257 .addImm(96)
5258 .add(predOps(ARMCC::AL));
5259 MI.addRegisterKilled(DReg, TRI, true);
5260 }
5261
hasNOP() const5262 bool ARMBaseInstrInfo::hasNOP() const {
5263 return Subtarget.getFeatureBits()[ARM::HasV6KOps];
5264 }
5265
isSwiftFastImmShift(const MachineInstr * MI) const5266 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
5267 if (MI->getNumOperands() < 4)
5268 return true;
5269 unsigned ShOpVal = MI->getOperand(3).getImm();
5270 unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
5271 // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
5272 if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
5273 ((ShImm == 1 || ShImm == 2) &&
5274 ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
5275 return true;
5276
5277 return false;
5278 }
5279
getRegSequenceLikeInputs(const MachineInstr & MI,unsigned DefIdx,SmallVectorImpl<RegSubRegPairAndIdx> & InputRegs) const5280 bool ARMBaseInstrInfo::getRegSequenceLikeInputs(
5281 const MachineInstr &MI, unsigned DefIdx,
5282 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
5283 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5284 assert(MI.isRegSequenceLike() && "Invalid kind of instruction");
5285
5286 switch (MI.getOpcode()) {
5287 case ARM::VMOVDRR:
5288 // dX = VMOVDRR rY, rZ
5289 // is the same as:
5290 // dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1
5291 // Populate the InputRegs accordingly.
5292 // rY
5293 const MachineOperand *MOReg = &MI.getOperand(1);
5294 if (!MOReg->isUndef())
5295 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5296 MOReg->getSubReg(), ARM::ssub_0));
5297 // rZ
5298 MOReg = &MI.getOperand(2);
5299 if (!MOReg->isUndef())
5300 InputRegs.push_back(RegSubRegPairAndIdx(MOReg->getReg(),
5301 MOReg->getSubReg(), ARM::ssub_1));
5302 return true;
5303 }
5304 llvm_unreachable("Target dependent opcode missing");
5305 }
5306
getExtractSubregLikeInputs(const MachineInstr & MI,unsigned DefIdx,RegSubRegPairAndIdx & InputReg) const5307 bool ARMBaseInstrInfo::getExtractSubregLikeInputs(
5308 const MachineInstr &MI, unsigned DefIdx,
5309 RegSubRegPairAndIdx &InputReg) const {
5310 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5311 assert(MI.isExtractSubregLike() && "Invalid kind of instruction");
5312
5313 switch (MI.getOpcode()) {
5314 case ARM::VMOVRRD:
5315 // rX, rY = VMOVRRD dZ
5316 // is the same as:
5317 // rX = EXTRACT_SUBREG dZ, ssub_0
5318 // rY = EXTRACT_SUBREG dZ, ssub_1
5319 const MachineOperand &MOReg = MI.getOperand(2);
5320 if (MOReg.isUndef())
5321 return false;
5322 InputReg.Reg = MOReg.getReg();
5323 InputReg.SubReg = MOReg.getSubReg();
5324 InputReg.SubIdx = DefIdx == 0 ? ARM::ssub_0 : ARM::ssub_1;
5325 return true;
5326 }
5327 llvm_unreachable("Target dependent opcode missing");
5328 }
5329
getInsertSubregLikeInputs(const MachineInstr & MI,unsigned DefIdx,RegSubRegPair & BaseReg,RegSubRegPairAndIdx & InsertedReg) const5330 bool ARMBaseInstrInfo::getInsertSubregLikeInputs(
5331 const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg,
5332 RegSubRegPairAndIdx &InsertedReg) const {
5333 assert(DefIdx < MI.getDesc().getNumDefs() && "Invalid definition index");
5334 assert(MI.isInsertSubregLike() && "Invalid kind of instruction");
5335
5336 switch (MI.getOpcode()) {
5337 case ARM::VSETLNi32:
5338 // dX = VSETLNi32 dY, rZ, imm
5339 const MachineOperand &MOBaseReg = MI.getOperand(1);
5340 const MachineOperand &MOInsertedReg = MI.getOperand(2);
5341 if (MOInsertedReg.isUndef())
5342 return false;
5343 const MachineOperand &MOIndex = MI.getOperand(3);
5344 BaseReg.Reg = MOBaseReg.getReg();
5345 BaseReg.SubReg = MOBaseReg.getSubReg();
5346
5347 InsertedReg.Reg = MOInsertedReg.getReg();
5348 InsertedReg.SubReg = MOInsertedReg.getSubReg();
5349 InsertedReg.SubIdx = MOIndex.getImm() == 0 ? ARM::ssub_0 : ARM::ssub_1;
5350 return true;
5351 }
5352 llvm_unreachable("Target dependent opcode missing");
5353 }
5354
5355 std::pair<unsigned, unsigned>
decomposeMachineOperandsTargetFlags(unsigned TF) const5356 ARMBaseInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
5357 const unsigned Mask = ARMII::MO_OPTION_MASK;
5358 return std::make_pair(TF & Mask, TF & ~Mask);
5359 }
5360
5361 ArrayRef<std::pair<unsigned, const char *>>
getSerializableDirectMachineOperandTargetFlags() const5362 ARMBaseInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
5363 using namespace ARMII;
5364
5365 static const std::pair<unsigned, const char *> TargetFlags[] = {
5366 {MO_LO16, "arm-lo16"}, {MO_HI16, "arm-hi16"}};
5367 return makeArrayRef(TargetFlags);
5368 }
5369
5370 ArrayRef<std::pair<unsigned, const char *>>
getSerializableBitmaskMachineOperandTargetFlags() const5371 ARMBaseInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
5372 using namespace ARMII;
5373
5374 static const std::pair<unsigned, const char *> TargetFlags[] = {
5375 {MO_COFFSTUB, "arm-coffstub"},
5376 {MO_GOT, "arm-got"},
5377 {MO_SBREL, "arm-sbrel"},
5378 {MO_DLLIMPORT, "arm-dllimport"},
5379 {MO_SECREL, "arm-secrel"},
5380 {MO_NONLAZY, "arm-nonlazy"}};
5381 return makeArrayRef(TargetFlags);
5382 }
5383
isAddImmediate(const MachineInstr & MI,Register Reg) const5384 Optional<RegImmPair> ARMBaseInstrInfo::isAddImmediate(const MachineInstr &MI,
5385 Register Reg) const {
5386 int Sign = 1;
5387 unsigned Opcode = MI.getOpcode();
5388 int64_t Offset = 0;
5389
5390 // TODO: Handle cases where Reg is a super- or sub-register of the
5391 // destination register.
5392 const MachineOperand &Op0 = MI.getOperand(0);
5393 if (!Op0.isReg() || Reg != Op0.getReg())
5394 return None;
5395
5396 // We describe SUBri or ADDri instructions.
5397 if (Opcode == ARM::SUBri)
5398 Sign = -1;
5399 else if (Opcode != ARM::ADDri)
5400 return None;
5401
5402 // TODO: Third operand can be global address (usually some string). Since
5403 // strings can be relocated we cannot calculate their offsets for
5404 // now.
5405 if (!MI.getOperand(1).isReg() || !MI.getOperand(2).isImm())
5406 return None;
5407
5408 Offset = MI.getOperand(2).getImm() * Sign;
5409 return RegImmPair{MI.getOperand(1).getReg(), Offset};
5410 }
5411
registerDefinedBetween(unsigned Reg,MachineBasicBlock::iterator From,MachineBasicBlock::iterator To,const TargetRegisterInfo * TRI)5412 bool llvm::registerDefinedBetween(unsigned Reg,
5413 MachineBasicBlock::iterator From,
5414 MachineBasicBlock::iterator To,
5415 const TargetRegisterInfo *TRI) {
5416 for (auto I = From; I != To; ++I)
5417 if (I->modifiesRegister(Reg, TRI))
5418 return true;
5419 return false;
5420 }
5421
findCMPToFoldIntoCBZ(MachineInstr * Br,const TargetRegisterInfo * TRI)5422 MachineInstr *llvm::findCMPToFoldIntoCBZ(MachineInstr *Br,
5423 const TargetRegisterInfo *TRI) {
5424 // Search backwards to the instruction that defines CSPR. This may or not
5425 // be a CMP, we check that after this loop. If we find another instruction
5426 // that reads cpsr, we return nullptr.
5427 MachineBasicBlock::iterator CmpMI = Br;
5428 while (CmpMI != Br->getParent()->begin()) {
5429 --CmpMI;
5430 if (CmpMI->modifiesRegister(ARM::CPSR, TRI))
5431 break;
5432 if (CmpMI->readsRegister(ARM::CPSR, TRI))
5433 break;
5434 }
5435
5436 // Check that this inst is a CMP r[0-7], #0 and that the register
5437 // is not redefined between the cmp and the br.
5438 if (CmpMI->getOpcode() != ARM::tCMPi8 && CmpMI->getOpcode() != ARM::t2CMPri)
5439 return nullptr;
5440 Register Reg = CmpMI->getOperand(0).getReg();
5441 Register PredReg;
5442 ARMCC::CondCodes Pred = getInstrPredicate(*CmpMI, PredReg);
5443 if (Pred != ARMCC::AL || CmpMI->getOperand(1).getImm() != 0)
5444 return nullptr;
5445 if (!isARMLowRegister(Reg))
5446 return nullptr;
5447 if (registerDefinedBetween(Reg, CmpMI->getNextNode(), Br, TRI))
5448 return nullptr;
5449
5450 return &*CmpMI;
5451 }
5452
ConstantMaterializationCost(unsigned Val,const ARMSubtarget * Subtarget,bool ForCodesize)5453 unsigned llvm::ConstantMaterializationCost(unsigned Val,
5454 const ARMSubtarget *Subtarget,
5455 bool ForCodesize) {
5456 if (Subtarget->isThumb()) {
5457 if (Val <= 255) // MOV
5458 return ForCodesize ? 2 : 1;
5459 if (Subtarget->hasV6T2Ops() && (Val <= 0xffff || // MOV
5460 ARM_AM::getT2SOImmVal(Val) != -1 || // MOVW
5461 ARM_AM::getT2SOImmVal(~Val) != -1)) // MVN
5462 return ForCodesize ? 4 : 1;
5463 if (Val <= 510) // MOV + ADDi8
5464 return ForCodesize ? 4 : 2;
5465 if (~Val <= 255) // MOV + MVN
5466 return ForCodesize ? 4 : 2;
5467 if (ARM_AM::isThumbImmShiftedVal(Val)) // MOV + LSL
5468 return ForCodesize ? 4 : 2;
5469 } else {
5470 if (ARM_AM::getSOImmVal(Val) != -1) // MOV
5471 return ForCodesize ? 4 : 1;
5472 if (ARM_AM::getSOImmVal(~Val) != -1) // MVN
5473 return ForCodesize ? 4 : 1;
5474 if (Subtarget->hasV6T2Ops() && Val <= 0xffff) // MOVW
5475 return ForCodesize ? 4 : 1;
5476 if (ARM_AM::isSOImmTwoPartVal(Val)) // two instrs
5477 return ForCodesize ? 8 : 2;
5478 if (ARM_AM::isSOImmTwoPartValNeg(Val)) // two instrs
5479 return ForCodesize ? 8 : 2;
5480 }
5481 if (Subtarget->useMovt()) // MOVW + MOVT
5482 return ForCodesize ? 8 : 2;
5483 return ForCodesize ? 8 : 3; // Literal pool load
5484 }
5485
HasLowerConstantMaterializationCost(unsigned Val1,unsigned Val2,const ARMSubtarget * Subtarget,bool ForCodesize)5486 bool llvm::HasLowerConstantMaterializationCost(unsigned Val1, unsigned Val2,
5487 const ARMSubtarget *Subtarget,
5488 bool ForCodesize) {
5489 // Check with ForCodesize
5490 unsigned Cost1 = ConstantMaterializationCost(Val1, Subtarget, ForCodesize);
5491 unsigned Cost2 = ConstantMaterializationCost(Val2, Subtarget, ForCodesize);
5492 if (Cost1 < Cost2)
5493 return true;
5494 if (Cost1 > Cost2)
5495 return false;
5496
5497 // If they are equal, try with !ForCodesize
5498 return ConstantMaterializationCost(Val1, Subtarget, !ForCodesize) <
5499 ConstantMaterializationCost(Val2, Subtarget, !ForCodesize);
5500 }
5501
5502 /// Constants defining how certain sequences should be outlined.
5503 /// This encompasses how an outlined function should be called, and what kind of
5504 /// frame should be emitted for that outlined function.
5505 ///
5506 /// \p MachineOutlinerTailCall implies that the function is being created from
5507 /// a sequence of instructions ending in a return.
5508 ///
5509 /// That is,
5510 ///
5511 /// I1 OUTLINED_FUNCTION:
5512 /// I2 --> B OUTLINED_FUNCTION I1
5513 /// BX LR I2
5514 /// BX LR
5515 ///
5516 /// +-------------------------+--------+-----+
5517 /// | | Thumb2 | ARM |
5518 /// +-------------------------+--------+-----+
5519 /// | Call overhead in Bytes | 4 | 4 |
5520 /// | Frame overhead in Bytes | 0 | 0 |
5521 /// | Stack fixup required | No | No |
5522 /// +-------------------------+--------+-----+
5523 ///
5524 /// \p MachineOutlinerThunk implies that the function is being created from
5525 /// a sequence of instructions ending in a call. The outlined function is
5526 /// called with a BL instruction, and the outlined function tail-calls the
5527 /// original call destination.
5528 ///
5529 /// That is,
5530 ///
5531 /// I1 OUTLINED_FUNCTION:
5532 /// I2 --> BL OUTLINED_FUNCTION I1
5533 /// BL f I2
5534 /// B f
5535 ///
5536 /// +-------------------------+--------+-----+
5537 /// | | Thumb2 | ARM |
5538 /// +-------------------------+--------+-----+
5539 /// | Call overhead in Bytes | 4 | 4 |
5540 /// | Frame overhead in Bytes | 0 | 0 |
5541 /// | Stack fixup required | No | No |
5542 /// +-------------------------+--------+-----+
5543 ///
5544 /// \p MachineOutlinerNoLRSave implies that the function should be called using
5545 /// a BL instruction, but doesn't require LR to be saved and restored. This
5546 /// happens when LR is known to be dead.
5547 ///
5548 /// That is,
5549 ///
5550 /// I1 OUTLINED_FUNCTION:
5551 /// I2 --> BL OUTLINED_FUNCTION I1
5552 /// I3 I2
5553 /// I3
5554 /// BX LR
5555 ///
5556 /// +-------------------------+--------+-----+
5557 /// | | Thumb2 | ARM |
5558 /// +-------------------------+--------+-----+
5559 /// | Call overhead in Bytes | 4 | 4 |
5560 /// | Frame overhead in Bytes | 4 | 4 |
5561 /// | Stack fixup required | No | No |
5562 /// +-------------------------+--------+-----+
5563 ///
5564 /// \p MachineOutlinerRegSave implies that the function should be called with a
5565 /// save and restore of LR to an available register. This allows us to avoid
5566 /// stack fixups. Note that this outlining variant is compatible with the
5567 /// NoLRSave case.
5568 ///
5569 /// That is,
5570 ///
5571 /// I1 Save LR OUTLINED_FUNCTION:
5572 /// I2 --> BL OUTLINED_FUNCTION I1
5573 /// I3 Restore LR I2
5574 /// I3
5575 /// BX LR
5576 ///
5577 /// +-------------------------+--------+-----+
5578 /// | | Thumb2 | ARM |
5579 /// +-------------------------+--------+-----+
5580 /// | Call overhead in Bytes | 8 | 12 |
5581 /// | Frame overhead in Bytes | 2 | 4 |
5582 /// | Stack fixup required | No | No |
5583 /// +-------------------------+--------+-----+
5584 ///
5585 /// \p MachineOutlinerDefault implies that the function should be called with
5586 /// a save and restore of LR to the stack.
5587 ///
5588 /// That is,
5589 ///
5590 /// I1 Save LR OUTLINED_FUNCTION:
5591 /// I2 --> BL OUTLINED_FUNCTION I1
5592 /// I3 Restore LR I2
5593 /// I3
5594 /// BX LR
5595 ///
5596 /// +-------------------------+--------+-----+
5597 /// | | Thumb2 | ARM |
5598 /// +-------------------------+--------+-----+
5599 /// | Call overhead in Bytes | 8 | 12 |
5600 /// | Frame overhead in Bytes | 2 | 4 |
5601 /// | Stack fixup required | Yes | Yes |
5602 /// +-------------------------+--------+-----+
5603
5604 enum MachineOutlinerClass {
5605 MachineOutlinerTailCall,
5606 MachineOutlinerThunk,
5607 MachineOutlinerNoLRSave,
5608 MachineOutlinerRegSave,
5609 MachineOutlinerDefault
5610 };
5611
5612 enum MachineOutlinerMBBFlags {
5613 LRUnavailableSomewhere = 0x2,
5614 HasCalls = 0x4,
5615 UnsafeRegsDead = 0x8
5616 };
5617
5618 struct OutlinerCosts {
5619 const int CallTailCall;
5620 const int FrameTailCall;
5621 const int CallThunk;
5622 const int FrameThunk;
5623 const int CallNoLRSave;
5624 const int FrameNoLRSave;
5625 const int CallRegSave;
5626 const int FrameRegSave;
5627 const int CallDefault;
5628 const int FrameDefault;
5629 const int SaveRestoreLROnStack;
5630
OutlinerCostsOutlinerCosts5631 OutlinerCosts(const ARMSubtarget &target)
5632 : CallTailCall(target.isThumb() ? 4 : 4),
5633 FrameTailCall(target.isThumb() ? 0 : 0),
5634 CallThunk(target.isThumb() ? 4 : 4),
5635 FrameThunk(target.isThumb() ? 0 : 0),
5636 CallNoLRSave(target.isThumb() ? 4 : 4),
5637 FrameNoLRSave(target.isThumb() ? 4 : 4),
5638 CallRegSave(target.isThumb() ? 8 : 12),
5639 FrameRegSave(target.isThumb() ? 2 : 4),
5640 CallDefault(target.isThumb() ? 8 : 12),
5641 FrameDefault(target.isThumb() ? 2 : 4),
5642 SaveRestoreLROnStack(target.isThumb() ? 8 : 8) {}
5643 };
5644
5645 unsigned
findRegisterToSaveLRTo(const outliner::Candidate & C) const5646 ARMBaseInstrInfo::findRegisterToSaveLRTo(const outliner::Candidate &C) const {
5647 assert(C.LRUWasSet && "LRU wasn't set?");
5648 MachineFunction *MF = C.getMF();
5649 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo *>(
5650 MF->getSubtarget().getRegisterInfo());
5651
5652 BitVector regsReserved = ARI->getReservedRegs(*MF);
5653 // Check if there is an available register across the sequence that we can
5654 // use.
5655 for (unsigned Reg : ARM::rGPRRegClass) {
5656 if (!(Reg < regsReserved.size() && regsReserved.test(Reg)) &&
5657 Reg != ARM::LR && // LR is not reserved, but don't use it.
5658 Reg != ARM::R12 && // R12 is not guaranteed to be preserved.
5659 C.LRU.available(Reg) && C.UsedInSequence.available(Reg))
5660 return Reg;
5661 }
5662
5663 // No suitable register. Return 0.
5664 return 0u;
5665 }
5666
5667 // Compute liveness of LR at the point after the interval [I, E), which
5668 // denotes a *backward* iteration through instructions. Used only for return
5669 // basic blocks, which do not end with a tail call.
isLRAvailable(const TargetRegisterInfo & TRI,MachineBasicBlock::reverse_iterator I,MachineBasicBlock::reverse_iterator E)5670 static bool isLRAvailable(const TargetRegisterInfo &TRI,
5671 MachineBasicBlock::reverse_iterator I,
5672 MachineBasicBlock::reverse_iterator E) {
5673 // At the end of the function LR dead.
5674 bool Live = false;
5675 for (; I != E; ++I) {
5676 const MachineInstr &MI = *I;
5677
5678 // Check defs of LR.
5679 if (MI.modifiesRegister(ARM::LR, &TRI))
5680 Live = false;
5681
5682 // Check uses of LR.
5683 unsigned Opcode = MI.getOpcode();
5684 if (Opcode == ARM::BX_RET || Opcode == ARM::MOVPCLR ||
5685 Opcode == ARM::SUBS_PC_LR || Opcode == ARM::tBX_RET ||
5686 Opcode == ARM::tBXNS_RET) {
5687 // These instructions use LR, but it's not an (explicit or implicit)
5688 // operand.
5689 Live = true;
5690 continue;
5691 }
5692 if (MI.readsRegister(ARM::LR, &TRI))
5693 Live = true;
5694 }
5695 return !Live;
5696 }
5697
getOutliningCandidateInfo(std::vector<outliner::Candidate> & RepeatedSequenceLocs) const5698 outliner::OutlinedFunction ARMBaseInstrInfo::getOutliningCandidateInfo(
5699 std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
5700 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
5701 unsigned SequenceSize =
5702 std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
5703 [this](unsigned Sum, const MachineInstr &MI) {
5704 return Sum + getInstSizeInBytes(MI);
5705 });
5706
5707 // Properties about candidate MBBs that hold for all of them.
5708 unsigned FlagsSetInAll = 0xF;
5709
5710 // Compute liveness information for each candidate, and set FlagsSetInAll.
5711 const TargetRegisterInfo &TRI = getRegisterInfo();
5712 std::for_each(
5713 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
5714 [&FlagsSetInAll](outliner::Candidate &C) { FlagsSetInAll &= C.Flags; });
5715
5716 // According to the ARM Procedure Call Standard, the following are
5717 // undefined on entry/exit from a function call:
5718 //
5719 // * Register R12(IP),
5720 // * Condition codes (and thus the CPSR register)
5721 //
5722 // Since we control the instructions which are part of the outlined regions
5723 // we don't need to be fully compliant with the AAPCS, but we have to
5724 // guarantee that if a veneer is inserted at link time the code is still
5725 // correct. Because of this, we can't outline any sequence of instructions
5726 // where one of these registers is live into/across it. Thus, we need to
5727 // delete those candidates.
5728 auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
5729 // If the unsafe registers in this block are all dead, then we don't need
5730 // to compute liveness here.
5731 if (C.Flags & UnsafeRegsDead)
5732 return false;
5733 C.initLRU(TRI);
5734 LiveRegUnits LRU = C.LRU;
5735 return (!LRU.available(ARM::R12) || !LRU.available(ARM::CPSR));
5736 };
5737
5738 // Are there any candidates where those registers are live?
5739 if (!(FlagsSetInAll & UnsafeRegsDead)) {
5740 // Erase every candidate that violates the restrictions above. (It could be
5741 // true that we have viable candidates, so it's not worth bailing out in
5742 // the case that, say, 1 out of 20 candidates violate the restructions.)
5743 RepeatedSequenceLocs.erase(std::remove_if(RepeatedSequenceLocs.begin(),
5744 RepeatedSequenceLocs.end(),
5745 CantGuaranteeValueAcrossCall),
5746 RepeatedSequenceLocs.end());
5747
5748 // If the sequence doesn't have enough candidates left, then we're done.
5749 if (RepeatedSequenceLocs.size() < 2)
5750 return outliner::OutlinedFunction();
5751 }
5752
5753 // At this point, we have only "safe" candidates to outline. Figure out
5754 // frame + call instruction information.
5755
5756 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
5757
5758 // Helper lambda which sets call information for every candidate.
5759 auto SetCandidateCallInfo =
5760 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
5761 for (outliner::Candidate &C : RepeatedSequenceLocs)
5762 C.setCallInfo(CallID, NumBytesForCall);
5763 };
5764
5765 OutlinerCosts Costs(Subtarget);
5766 unsigned FrameID = MachineOutlinerDefault;
5767 unsigned NumBytesToCreateFrame = Costs.FrameDefault;
5768
5769 // If the last instruction in any candidate is a terminator, then we should
5770 // tail call all of the candidates.
5771 if (RepeatedSequenceLocs[0].back()->isTerminator()) {
5772 FrameID = MachineOutlinerTailCall;
5773 NumBytesToCreateFrame = Costs.FrameTailCall;
5774 SetCandidateCallInfo(MachineOutlinerTailCall, Costs.CallTailCall);
5775 } else if (LastInstrOpcode == ARM::BL || LastInstrOpcode == ARM::BLX ||
5776 LastInstrOpcode == ARM::tBL || LastInstrOpcode == ARM::tBLXr ||
5777 LastInstrOpcode == ARM::tBLXi) {
5778 FrameID = MachineOutlinerThunk;
5779 NumBytesToCreateFrame = Costs.FrameThunk;
5780 SetCandidateCallInfo(MachineOutlinerThunk, Costs.CallThunk);
5781 } else {
5782 // We need to decide how to emit calls + frames. We can always emit the same
5783 // frame if we don't need to save to the stack. If we have to save to the
5784 // stack, then we need a different frame.
5785 unsigned NumBytesNoStackCalls = 0;
5786 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
5787
5788 for (outliner::Candidate &C : RepeatedSequenceLocs) {
5789 C.initLRU(TRI);
5790 // LR liveness is overestimated in return blocks, unless they end with a
5791 // tail call.
5792 const auto Last = C.getMBB()->rbegin();
5793 const bool LRIsAvailable =
5794 C.getMBB()->isReturnBlock() && !Last->isCall()
5795 ? isLRAvailable(TRI, Last,
5796 (MachineBasicBlock::reverse_iterator)C.front())
5797 : C.LRU.available(ARM::LR);
5798 if (LRIsAvailable) {
5799 FrameID = MachineOutlinerNoLRSave;
5800 NumBytesNoStackCalls += Costs.CallNoLRSave;
5801 C.setCallInfo(MachineOutlinerNoLRSave, Costs.CallNoLRSave);
5802 CandidatesWithoutStackFixups.push_back(C);
5803 }
5804
5805 // Is an unused register available? If so, we won't modify the stack, so
5806 // we can outline with the same frame type as those that don't save LR.
5807 else if (findRegisterToSaveLRTo(C)) {
5808 FrameID = MachineOutlinerRegSave;
5809 NumBytesNoStackCalls += Costs.CallRegSave;
5810 C.setCallInfo(MachineOutlinerRegSave, Costs.CallRegSave);
5811 CandidatesWithoutStackFixups.push_back(C);
5812 }
5813
5814 // Is SP used in the sequence at all? If not, we don't have to modify
5815 // the stack, so we are guaranteed to get the same frame.
5816 else if (C.UsedInSequence.available(ARM::SP)) {
5817 NumBytesNoStackCalls += Costs.CallDefault;
5818 C.setCallInfo(MachineOutlinerDefault, Costs.CallDefault);
5819 SetCandidateCallInfo(MachineOutlinerDefault, Costs.CallDefault);
5820 CandidatesWithoutStackFixups.push_back(C);
5821 } else
5822 return outliner::OutlinedFunction();
5823 }
5824
5825 // Does every candidate's MBB contain a call? If so, then we might have a
5826 // call in the range.
5827 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
5828 // check if the range contains a call. These require a save + restore of
5829 // the link register.
5830 if (std::any_of(FirstCand.front(), FirstCand.back(),
5831 [](const MachineInstr &MI) { return MI.isCall(); }))
5832 NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
5833
5834 // Handle the last instruction separately. If it is tail call, then the
5835 // last instruction is a call, we don't want to save + restore in this
5836 // case. However, it could be possible that the last instruction is a
5837 // call without it being valid to tail call this sequence. We should
5838 // consider this as well.
5839 else if (FrameID != MachineOutlinerThunk &&
5840 FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
5841 NumBytesToCreateFrame += Costs.SaveRestoreLROnStack;
5842 }
5843 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
5844 }
5845
5846 return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
5847 NumBytesToCreateFrame, FrameID);
5848 }
5849
isFunctionSafeToOutlineFrom(MachineFunction & MF,bool OutlineFromLinkOnceODRs) const5850 bool ARMBaseInstrInfo::isFunctionSafeToOutlineFrom(
5851 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
5852 const Function &F = MF.getFunction();
5853
5854 // Can F be deduplicated by the linker? If it can, don't outline from it.
5855 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
5856 return false;
5857
5858 // Don't outline from functions with section markings; the program could
5859 // expect that all the code is in the named section.
5860 // FIXME: Allow outlining from multiple functions with the same section
5861 // marking.
5862 if (F.hasSection())
5863 return false;
5864
5865 // FIXME: Thumb1 outlining is not handled
5866 if (MF.getInfo<ARMFunctionInfo>()->isThumb1OnlyFunction())
5867 return false;
5868
5869 // It's safe to outline from MF.
5870 return true;
5871 }
5872
isMBBSafeToOutlineFrom(MachineBasicBlock & MBB,unsigned & Flags) const5873 bool ARMBaseInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
5874 unsigned &Flags) const {
5875 // Check if LR is available through all of the MBB. If it's not, then set
5876 // a flag.
5877 assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
5878 "Suitable Machine Function for outlining must track liveness");
5879
5880 LiveRegUnits LRU(getRegisterInfo());
5881
5882 std::for_each(MBB.rbegin(), MBB.rend(),
5883 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); });
5884
5885 // Check if each of the unsafe registers are available...
5886 bool R12AvailableInBlock = LRU.available(ARM::R12);
5887 bool CPSRAvailableInBlock = LRU.available(ARM::CPSR);
5888
5889 // If all of these are dead (and not live out), we know we don't have to check
5890 // them later.
5891 if (R12AvailableInBlock && CPSRAvailableInBlock)
5892 Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
5893
5894 // Now, add the live outs to the set.
5895 LRU.addLiveOuts(MBB);
5896
5897 // If any of these registers is available in the MBB, but also a live out of
5898 // the block, then we know outlining is unsafe.
5899 if (R12AvailableInBlock && !LRU.available(ARM::R12))
5900 return false;
5901 if (CPSRAvailableInBlock && !LRU.available(ARM::CPSR))
5902 return false;
5903
5904 // Check if there's a call inside this MachineBasicBlock. If there is, then
5905 // set a flag.
5906 if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
5907 Flags |= MachineOutlinerMBBFlags::HasCalls;
5908
5909 // LR liveness is overestimated in return blocks.
5910
5911 bool LRIsAvailable =
5912 MBB.isReturnBlock() && !MBB.back().isCall()
5913 ? isLRAvailable(getRegisterInfo(), MBB.rbegin(), MBB.rend())
5914 : LRU.available(ARM::LR);
5915 if (!LRIsAvailable)
5916 Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
5917
5918 return true;
5919 }
5920
5921 outliner::InstrType
getOutliningType(MachineBasicBlock::iterator & MIT,unsigned Flags) const5922 ARMBaseInstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
5923 unsigned Flags) const {
5924 MachineInstr &MI = *MIT;
5925 const TargetRegisterInfo *TRI = &getRegisterInfo();
5926
5927 // Be conservative with inline ASM
5928 if (MI.isInlineAsm())
5929 return outliner::InstrType::Illegal;
5930
5931 // Don't allow debug values to impact outlining type.
5932 if (MI.isDebugInstr() || MI.isIndirectDebugValue())
5933 return outliner::InstrType::Invisible;
5934
5935 // At this point, KILL or IMPLICIT_DEF instructions don't really tell us much
5936 // so we can go ahead and skip over them.
5937 if (MI.isKill() || MI.isImplicitDef())
5938 return outliner::InstrType::Invisible;
5939
5940 // PIC instructions contain labels, outlining them would break offset
5941 // computing. unsigned Opc = MI.getOpcode();
5942 unsigned Opc = MI.getOpcode();
5943 if (Opc == ARM::tPICADD || Opc == ARM::PICADD || Opc == ARM::PICSTR ||
5944 Opc == ARM::PICSTRB || Opc == ARM::PICSTRH || Opc == ARM::PICLDR ||
5945 Opc == ARM::PICLDRB || Opc == ARM::PICLDRH || Opc == ARM::PICLDRSB ||
5946 Opc == ARM::PICLDRSH || Opc == ARM::t2LDRpci_pic ||
5947 Opc == ARM::t2MOVi16_ga_pcrel || Opc == ARM::t2MOVTi16_ga_pcrel ||
5948 Opc == ARM::t2MOV_ga_pcrel)
5949 return outliner::InstrType::Illegal;
5950
5951 // Be conservative with ARMv8.1 MVE instructions.
5952 if (Opc == ARM::t2BF_LabelPseudo || Opc == ARM::t2DoLoopStart ||
5953 Opc == ARM::t2DoLoopStartTP || Opc == ARM::t2WhileLoopStart ||
5954 Opc == ARM::t2LoopDec || Opc == ARM::t2LoopEnd)
5955 return outliner::InstrType::Illegal;
5956
5957 const MCInstrDesc &MCID = MI.getDesc();
5958 uint64_t MIFlags = MCID.TSFlags;
5959 if ((MIFlags & ARMII::DomainMask) == ARMII::DomainMVE)
5960 return outliner::InstrType::Illegal;
5961
5962 // Is this a terminator for a basic block?
5963 if (MI.isTerminator()) {
5964 // Don't outline if the branch is not unconditional.
5965 if (isPredicated(MI))
5966 return outliner::InstrType::Illegal;
5967
5968 // Is this the end of a function?
5969 if (MI.getParent()->succ_empty())
5970 return outliner::InstrType::Legal;
5971
5972 // It's not, so don't outline it.
5973 return outliner::InstrType::Illegal;
5974 }
5975
5976 // Make sure none of the operands are un-outlinable.
5977 for (const MachineOperand &MOP : MI.operands()) {
5978 if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
5979 MOP.isTargetIndex())
5980 return outliner::InstrType::Illegal;
5981 }
5982
5983 // Don't outline if link register or program counter value are used.
5984 if (MI.readsRegister(ARM::LR, TRI) || MI.readsRegister(ARM::PC, TRI))
5985 return outliner::InstrType::Illegal;
5986
5987 if (MI.isCall()) {
5988 // Get the function associated with the call. Look at each operand and find
5989 // the one that represents the calle and get its name.
5990 const Function *Callee = nullptr;
5991 for (const MachineOperand &MOP : MI.operands()) {
5992 if (MOP.isGlobal()) {
5993 Callee = dyn_cast<Function>(MOP.getGlobal());
5994 break;
5995 }
5996 }
5997
5998 // Dont't outline calls to "mcount" like functions, in particular Linux
5999 // kernel function tracing relies on it.
6000 if (Callee &&
6001 (Callee->getName() == "\01__gnu_mcount_nc" ||
6002 Callee->getName() == "\01mcount" || Callee->getName() == "__mcount"))
6003 return outliner::InstrType::Illegal;
6004
6005 // If we don't know anything about the callee, assume it depends on the
6006 // stack layout of the caller. In that case, it's only legal to outline
6007 // as a tail-call. Explicitly list the call instructions we know about so
6008 // we don't get unexpected results with call pseudo-instructions.
6009 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
6010 if (Opc == ARM::BL || Opc == ARM::tBL || Opc == ARM::BLX ||
6011 Opc == ARM::tBLXr || Opc == ARM::tBLXi)
6012 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
6013
6014 if (!Callee)
6015 return UnknownCallOutlineType;
6016
6017 // We have a function we have information about. Check if it's something we
6018 // can safely outline.
6019 MachineFunction *MF = MI.getParent()->getParent();
6020 MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
6021
6022 // We don't know what's going on with the callee at all. Don't touch it.
6023 if (!CalleeMF)
6024 return UnknownCallOutlineType;
6025
6026 // Check if we know anything about the callee saves on the function. If we
6027 // don't, then don't touch it, since that implies that we haven't computed
6028 // anything about its stack frame yet.
6029 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
6030 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
6031 MFI.getNumObjects() > 0)
6032 return UnknownCallOutlineType;
6033
6034 // At this point, we can say that CalleeMF ought to not pass anything on the
6035 // stack. Therefore, we can outline it.
6036 return outliner::InstrType::Legal;
6037 }
6038
6039 // Since calls are handled, don't touch LR or PC
6040 if (MI.modifiesRegister(ARM::LR, TRI) || MI.modifiesRegister(ARM::PC, TRI))
6041 return outliner::InstrType::Illegal;
6042
6043 // Does this use the stack?
6044 if (MI.modifiesRegister(ARM::SP, TRI) || MI.readsRegister(ARM::SP, TRI)) {
6045 // True if there is no chance that any outlined candidate from this range
6046 // could require stack fixups. That is, both
6047 // * LR is available in the range (No save/restore around call)
6048 // * The range doesn't include calls (No save/restore in outlined frame)
6049 // are true.
6050 // FIXME: This is very restrictive; the flags check the whole block,
6051 // not just the bit we will try to outline.
6052 bool MightNeedStackFixUp =
6053 (Flags & (MachineOutlinerMBBFlags::LRUnavailableSomewhere |
6054 MachineOutlinerMBBFlags::HasCalls));
6055
6056 if (!MightNeedStackFixUp)
6057 return outliner::InstrType::Legal;
6058
6059 return outliner::InstrType::Illegal;
6060 }
6061
6062 // Be conservative with IT blocks.
6063 if (MI.readsRegister(ARM::ITSTATE, TRI) ||
6064 MI.modifiesRegister(ARM::ITSTATE, TRI))
6065 return outliner::InstrType::Illegal;
6066
6067 // Don't outline positions.
6068 if (MI.isPosition())
6069 return outliner::InstrType::Illegal;
6070
6071 return outliner::InstrType::Legal;
6072 }
6073
saveLROnStack(MachineBasicBlock & MBB,MachineBasicBlock::iterator It) const6074 void ARMBaseInstrInfo::saveLROnStack(MachineBasicBlock &MBB,
6075 MachineBasicBlock::iterator It) const {
6076 unsigned Opc = Subtarget.isThumb() ? ARM::t2STR_PRE : ARM::STR_PRE_IMM;
6077 int Align = -Subtarget.getStackAlignment().value();
6078 BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::SP)
6079 .addReg(ARM::LR, RegState::Kill)
6080 .addReg(ARM::SP)
6081 .addImm(Align)
6082 .add(predOps(ARMCC::AL));
6083 }
6084
emitCFIForLRSaveOnStack(MachineBasicBlock & MBB,MachineBasicBlock::iterator It) const6085 void ARMBaseInstrInfo::emitCFIForLRSaveOnStack(
6086 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6087 MachineFunction &MF = *MBB.getParent();
6088 const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6089 unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6090 int Align = Subtarget.getStackAlignment().value();
6091 // Add a CFI saying the stack was moved down.
6092 int64_t StackPosEntry =
6093 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, Align));
6094 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6095 .addCFIIndex(StackPosEntry)
6096 .setMIFlags(MachineInstr::FrameSetup);
6097
6098 // Add a CFI saying that the LR that we want to find is now higher than
6099 // before.
6100 int64_t LRPosEntry =
6101 MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfLR, -Align));
6102 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6103 .addCFIIndex(LRPosEntry)
6104 .setMIFlags(MachineInstr::FrameSetup);
6105 }
6106
emitCFIForLRSaveToReg(MachineBasicBlock & MBB,MachineBasicBlock::iterator It,Register Reg) const6107 void ARMBaseInstrInfo::emitCFIForLRSaveToReg(MachineBasicBlock &MBB,
6108 MachineBasicBlock::iterator It,
6109 Register Reg) const {
6110 MachineFunction &MF = *MBB.getParent();
6111 const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6112 unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6113 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
6114
6115 int64_t LRPosEntry = MF.addFrameInst(
6116 MCCFIInstruction::createRegister(nullptr, DwarfLR, DwarfReg));
6117 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6118 .addCFIIndex(LRPosEntry)
6119 .setMIFlags(MachineInstr::FrameSetup);
6120 }
6121
restoreLRFromStack(MachineBasicBlock & MBB,MachineBasicBlock::iterator It) const6122 void ARMBaseInstrInfo::restoreLRFromStack(
6123 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6124 unsigned Opc = Subtarget.isThumb() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6125 MachineInstrBuilder MIB = BuildMI(MBB, It, DebugLoc(), get(Opc), ARM::LR)
6126 .addReg(ARM::SP, RegState::Define)
6127 .addReg(ARM::SP);
6128 if (!Subtarget.isThumb())
6129 MIB.addReg(0);
6130 MIB.addImm(Subtarget.getStackAlignment().value()).add(predOps(ARMCC::AL));
6131 }
6132
emitCFIForLRRestoreFromStack(MachineBasicBlock & MBB,MachineBasicBlock::iterator It) const6133 void ARMBaseInstrInfo::emitCFIForLRRestoreFromStack(
6134 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6135 // Now stack has moved back up...
6136 MachineFunction &MF = *MBB.getParent();
6137 const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6138 unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6139 int64_t StackPosEntry =
6140 MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
6141 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6142 .addCFIIndex(StackPosEntry)
6143 .setMIFlags(MachineInstr::FrameDestroy);
6144
6145 // ... and we have restored LR.
6146 int64_t LRPosEntry =
6147 MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
6148 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6149 .addCFIIndex(LRPosEntry)
6150 .setMIFlags(MachineInstr::FrameDestroy);
6151 }
6152
emitCFIForLRRestoreFromReg(MachineBasicBlock & MBB,MachineBasicBlock::iterator It) const6153 void ARMBaseInstrInfo::emitCFIForLRRestoreFromReg(
6154 MachineBasicBlock &MBB, MachineBasicBlock::iterator It) const {
6155 MachineFunction &MF = *MBB.getParent();
6156 const MCRegisterInfo *MRI = Subtarget.getRegisterInfo();
6157 unsigned DwarfLR = MRI->getDwarfRegNum(ARM::LR, true);
6158
6159 int64_t LRPosEntry =
6160 MF.addFrameInst(MCCFIInstruction::createRestore(nullptr, DwarfLR));
6161 BuildMI(MBB, It, DebugLoc(), get(ARM::CFI_INSTRUCTION))
6162 .addCFIIndex(LRPosEntry)
6163 .setMIFlags(MachineInstr::FrameDestroy);
6164 }
6165
buildOutlinedFrame(MachineBasicBlock & MBB,MachineFunction & MF,const outliner::OutlinedFunction & OF) const6166 void ARMBaseInstrInfo::buildOutlinedFrame(
6167 MachineBasicBlock &MBB, MachineFunction &MF,
6168 const outliner::OutlinedFunction &OF) const {
6169 // For thunk outlining, rewrite the last instruction from a call to a
6170 // tail-call.
6171 if (OF.FrameConstructionID == MachineOutlinerThunk) {
6172 MachineInstr *Call = &*--MBB.instr_end();
6173 bool isThumb = Subtarget.isThumb();
6174 unsigned FuncOp = isThumb ? 2 : 0;
6175 unsigned Opc = Call->getOperand(FuncOp).isReg()
6176 ? isThumb ? ARM::tTAILJMPr : ARM::TAILJMPr
6177 : isThumb ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd
6178 : ARM::tTAILJMPdND
6179 : ARM::TAILJMPd;
6180 MachineInstrBuilder MIB = BuildMI(MBB, MBB.end(), DebugLoc(), get(Opc))
6181 .add(Call->getOperand(FuncOp));
6182 if (isThumb && !Call->getOperand(FuncOp).isReg())
6183 MIB.add(predOps(ARMCC::AL));
6184 Call->eraseFromParent();
6185 }
6186
6187 // Is there a call in the outlined range?
6188 auto IsNonTailCall = [](MachineInstr &MI) {
6189 return MI.isCall() && !MI.isReturn();
6190 };
6191 if (std::any_of(MBB.instr_begin(), MBB.instr_end(), IsNonTailCall)) {
6192 MachineBasicBlock::iterator It = MBB.begin();
6193 MachineBasicBlock::iterator Et = MBB.end();
6194
6195 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
6196 OF.FrameConstructionID == MachineOutlinerThunk)
6197 Et = std::prev(MBB.end());
6198
6199 // We have to save and restore LR, we need to add it to the liveins if it
6200 // is not already part of the set. This is suffient since outlined
6201 // functions only have one block.
6202 if (!MBB.isLiveIn(ARM::LR))
6203 MBB.addLiveIn(ARM::LR);
6204
6205 // Insert a save before the outlined region
6206 saveLROnStack(MBB, It);
6207 emitCFIForLRSaveOnStack(MBB, It);
6208
6209 // Insert a restore before the terminator for the function. Restore LR.
6210 restoreLRFromStack(MBB, Et);
6211 emitCFIForLRRestoreFromStack(MBB, Et);
6212 }
6213
6214 // If this is a tail call outlined function, then there's already a return.
6215 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
6216 OF.FrameConstructionID == MachineOutlinerThunk)
6217 return;
6218
6219 // Here we have to insert the return ourselves. Get the correct opcode from
6220 // current feature set.
6221 BuildMI(MBB, MBB.end(), DebugLoc(), get(Subtarget.getReturnOpcode()))
6222 .add(predOps(ARMCC::AL));
6223 }
6224
insertOutlinedCall(Module & M,MachineBasicBlock & MBB,MachineBasicBlock::iterator & It,MachineFunction & MF,const outliner::Candidate & C) const6225 MachineBasicBlock::iterator ARMBaseInstrInfo::insertOutlinedCall(
6226 Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
6227 MachineFunction &MF, const outliner::Candidate &C) const {
6228 MachineInstrBuilder MIB;
6229 MachineBasicBlock::iterator CallPt;
6230 unsigned Opc;
6231 bool isThumb = Subtarget.isThumb();
6232
6233 // Are we tail calling?
6234 if (C.CallConstructionID == MachineOutlinerTailCall) {
6235 // If yes, then we can just branch to the label.
6236 Opc = isThumb
6237 ? Subtarget.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND
6238 : ARM::TAILJMPd;
6239 MIB = BuildMI(MF, DebugLoc(), get(Opc))
6240 .addGlobalAddress(M.getNamedValue(MF.getName()));
6241 if (isThumb)
6242 MIB.add(predOps(ARMCC::AL));
6243 It = MBB.insert(It, MIB);
6244 return It;
6245 }
6246
6247 // Create the call instruction.
6248 Opc = isThumb ? ARM::tBL : ARM::BL;
6249 MachineInstrBuilder CallMIB = BuildMI(MF, DebugLoc(), get(Opc));
6250 if (isThumb)
6251 CallMIB.add(predOps(ARMCC::AL));
6252 CallMIB.addGlobalAddress(M.getNamedValue(MF.getName()));
6253
6254 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
6255 C.CallConstructionID == MachineOutlinerThunk) {
6256 // No, so just insert the call.
6257 It = MBB.insert(It, CallMIB);
6258 return It;
6259 }
6260
6261 const ARMFunctionInfo &AFI = *C.getMF()->getInfo<ARMFunctionInfo>();
6262 // Can we save to a register?
6263 if (C.CallConstructionID == MachineOutlinerRegSave) {
6264 unsigned Reg = findRegisterToSaveLRTo(C);
6265 assert(Reg != 0 && "No callee-saved register available?");
6266
6267 // Save and restore LR from that register.
6268 copyPhysReg(MBB, It, DebugLoc(), Reg, ARM::LR, true);
6269 if (!AFI.isLRSpilled())
6270 emitCFIForLRSaveToReg(MBB, It, Reg);
6271 CallPt = MBB.insert(It, CallMIB);
6272 copyPhysReg(MBB, It, DebugLoc(), ARM::LR, Reg, true);
6273 if (!AFI.isLRSpilled())
6274 emitCFIForLRRestoreFromReg(MBB, It);
6275 It--;
6276 return CallPt;
6277 }
6278 // We have the default case. Save and restore from SP.
6279 saveLROnStack(MBB, It);
6280 if (!AFI.isLRSpilled())
6281 emitCFIForLRSaveOnStack(MBB, It);
6282 CallPt = MBB.insert(It, CallMIB);
6283 restoreLRFromStack(MBB, It);
6284 if (!AFI.isLRSpilled())
6285 emitCFIForLRRestoreFromStack(MBB, It);
6286 It--;
6287 return CallPt;
6288 }
6289
shouldOutlineFromFunctionByDefault(MachineFunction & MF) const6290 bool ARMBaseInstrInfo::shouldOutlineFromFunctionByDefault(
6291 MachineFunction &MF) const {
6292 return Subtarget.isMClass() && MF.getFunction().hasMinSize();
6293 }
6294
isReallyTriviallyReMaterializable(const MachineInstr & MI,AAResults * AA) const6295 bool ARMBaseInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
6296 AAResults *AA) const {
6297 // Try hard to rematerialize any VCTPs because if we spill P0, it will block
6298 // the tail predication conversion. This means that the element count
6299 // register has to be live for longer, but that has to be better than
6300 // spill/restore and VPT predication.
6301 return isVCTP(&MI) && !isPredicated(MI);
6302 }
6303