LLVM 24.0.0git
AArch64InstrInfo.cpp
Go to the documentation of this file.
1//===- AArch64InstrInfo.cpp - AArch64 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 AArch64 implementation of the TargetInstrInfo class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "AArch64InstrInfo.h"
14#include "AArch64ExpandImm.h"
16#include "AArch64PointerAuth.h"
17#include "AArch64Subtarget.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
45#include "llvm/IR/DebugLoc.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/Module.h"
48#include "llvm/MC/MCAsmInfo.h"
49#include "llvm/MC/MCInst.h"
51#include "llvm/MC/MCInstrDesc.h"
55#include "llvm/Support/LEB128.h"
59#include <cassert>
60#include <cstdint>
61#include <iterator>
62#include <utility>
63
64using namespace llvm;
65
66#define GET_INSTRINFO_CTOR_DTOR
67#include "AArch64GenInstrInfo.inc"
68
69#define DEBUG_TYPE "AArch64InstrInfo"
70
71STATISTIC(NumCopyInstrs, "Number of COPY instructions expanded");
72STATISTIC(NumZCRegMoveInstrsGPR, "Number of zero-cycle GPR register move "
73 "instructions expanded from canonical COPY");
74STATISTIC(NumZCRegMoveInstrsFPR, "Number of zero-cycle FPR register move "
75 "instructions expanded from canonical COPY");
76STATISTIC(NumZCZeroingInstrsGPR, "Number of zero-cycle GPR zeroing "
77 "instructions expanded from canonical COPY");
78// NumZCZeroingInstrsFPR is counted at AArch64AsmPrinter
79
81 : AArch64GenInstrInfo(STI, RI, AArch64::ADJCALLSTACKDOWN,
82 AArch64::ADJCALLSTACKUP, AArch64::CATCHRET),
83 RI(STI.getTargetTriple(), STI.getHwMode()), Subtarget(STI) {}
84
85/// Return the maximum number of bytes of code the specified instruction may be
86/// after LFI rewriting. If the instruction is not rewritten, std::nullopt is
87/// returned (use default sizing).
88///
89/// NOTE: the size estimates here must be kept in sync with the rewrites in
90/// AArch64MCLFIRewriter.cpp. Sizes may be overestimates of the rewritten
91/// instruction sequences.
92static std::optional<unsigned> getLFIInstSizeInBytes(const MachineInstr &MI) {
93 switch (MI.getOpcode()) {
94 case AArch64::SVC:
95 // SVC expands to 4 instructions.
96 return 16;
97 case AArch64::BR:
98 case AArch64::BLR:
99 // Indirect branches/calls expand to 2 instructions (guard + br/blr).
100 return 8;
101 case AArch64::RET:
102 // RET through another register expands to 2 instructions (guard + ret).
103 if (MI.getOperand(0).getReg() != AArch64::LR)
104 return 8;
105 return std::nullopt;
106 case AArch64::RETAA:
107 case AArch64::RETAB:
108 // Authenticated returns expand to 3 instructions (authenticate + guard +
109 // ret). Any deferred LR guard is discarded, so the flush allowance added
110 // by getInstSizeInBytes is an overestimate here.
111 return 12;
112 case AArch64::BRAA:
113 case AArch64::BRAAZ:
114 case AArch64::BRAB:
115 case AArch64::BRABZ:
116 case AArch64::BLRAA:
117 case AArch64::BLRAAZ:
118 case AArch64::BLRAB:
119 case AArch64::BLRABZ:
120 // Authenticated branches/calls expand to 3 instructions (authenticate +
121 // guard + branch).
122 return 12;
123 case AArch64::BRA:
124 case AArch64::BLRA:
125 // Up to 2 instructions to materialize the discriminator (mov + movk),
126 // followed by an authenticated branch/call that expands to 3 instructions
127 // (authenticate + guard + branch).
128 return 20;
129 case AArch64::TLSDESC_CALLSEQ:
130 // adrp + ldr + add + blr, where the ldr and blr each gain a guard.
131 return 24;
132 case AArch64::TLSDESC_AUTH_CALLSEQ:
133 // adrp + ldr + add + blraa, where the ldr gains a guard and the blraa
134 // expands to 3 instructions (authenticate + guard + blr).
135 return 28;
136 case AArch64::AUTIASP:
137 case AArch64::AUTIBSP:
138 case AArch64::AUTIAZ:
139 case AArch64::AUTIBZ:
140 case AArch64::XPACLRI:
141 // Authenticating LR expands to the instruction plus a deferred LR guard.
142 return 8;
143 case AArch64::SYSxt:
144 // VA-based DC/IC ops (op1=3, Cn=7, op2=1) expand to 2 instructions.
145 if (MI.getOperand(0).getImm() == 3 && MI.getOperand(1).getImm() == 7 &&
146 MI.getOperand(3).getImm() == 1)
147 return 8;
148 return std::nullopt;
149 default:
150 break;
151 }
152
153 // Detect instructions that explicitly define SP or LR.
154 bool ModifiesLR = false;
155 bool ModifiesSP = false;
156 for (const MachineOperand &MO : MI.defs()) {
157 if (!MO.isReg())
158 continue;
159 if (MO.getReg() == AArch64::LR)
160 ModifiesLR = true;
161 else if (MO.getReg() == AArch64::SP)
162 ModifiesSP = true;
163 }
164
165 // Memory accesses expand to a base-register guard plus the rewritten access
166 // (8 bytes), with an extra base-register update for pre/post-index forms (12
167 // bytes total). If the access also defines LR, an LR mask is appended (+4
168 // bytes). Depending on additional optimizations that the rewriter performs,
169 // this may be an overestimate.
170 if (MI.mayLoadOrStore()) {
171 unsigned Size = isLFIPrePostMemAccess(MI.getOpcode()) ? 12 : 8;
172 if (ModifiesLR)
173 Size += 4;
174 return Size;
175 }
176
177 // Non memory operations that modify LR or SP expand to 2 instructions.
178 if (ModifiesSP || ModifiesLR)
179 return 8;
180
181 // Default case: instructions that don't cause expansion.
182 // - TP accesses in LFI are a single load/store, so no expansion.
183 // - All remaining instructions are not rewritten.
184 return std::nullopt;
185}
186
187/// GetInstSize - Return the number of bytes of code the specified
188/// instruction may be. This returns the maximum number of bytes.
190 const MCInstrDesc &Desc = MI.getDesc();
191 if (!Desc.isPseudo() && !Subtarget.isLFI()) {
192 assert(Desc.getSize() == 4 && "Unexpected instruction size");
193 return 4;
194 }
195
196 unsigned NumBytes = getInstSizeInBytesNoGuard(MI);
197
198 // The LFI rewriter may flush a deferred LR guard (1 instruction) before any
199 // control-flow instruction. Bundles are skipped because their size is the
200 // sum of the bundled instructions, which already include this.
201 if (Subtarget.isLFI() && !MI.isBundle() &&
202 (MI.isCall() || MI.isBranch() || MI.isReturn()))
203 NumBytes += 4;
204
205 return NumBytes;
206}
207
208unsigned
209AArch64InstrInfo::getInstSizeInBytesNoGuard(const MachineInstr &MI) const {
210 const MCInstrDesc &Desc = MI.getDesc();
211 const MachineBasicBlock &MBB = *MI.getParent();
212 const MachineFunction *MF = MBB.getParent();
213 const Function &F = MF->getFunction();
214 const MCAsmInfo &MAI = MF->getTarget().getMCAsmInfo();
215
216 {
217 auto Op = MI.getOpcode();
218 if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
219 return getInlineAsmLength(MI.getOperand(0).getSymbolName(), MAI);
220 }
221
222 // Meta-instructions emit no code.
223 if (MI.isMetaInstruction())
224 return 0;
225
226 // FIXME: We currently only handle pseudoinstructions that don't get expanded
227 // before the assembly printer.
228 unsigned NumBytes = 0;
229
230 // LFI rewriter expansions that supersede normal sizing.
231 const auto &STI = MF->getSubtarget<AArch64Subtarget>();
232 if (STI.isLFI())
233 if (auto Size = getLFIInstSizeInBytes(MI))
234 return *Size;
235
236 if (!MI.isBundle() && isTailCallReturnInst(MI)) {
237 NumBytes = Desc.getSize() ? Desc.getSize() : 4;
238
239 if (STI.isLFI()) {
240 unsigned Opc = MI.getOpcode();
241 if (Opc == AArch64::AUTH_TCRETURN || Opc == AArch64::AUTH_TCRETURN_BTI) {
242 // The braa/brab expands to 3 instructions (authenticate + guard + br).
243 NumBytes += 8;
244 } else if (MI.getOperand(0).isReg()) {
245 // Indirect tail calls expand to 2 instructions (guard + br).
246 NumBytes += 4;
247 }
248 }
249
250 const auto *MFI = MF->getInfo<AArch64FunctionInfo>();
251 if (!MFI->shouldSignReturnAddress(*MF))
252 return NumBytes;
253
254 auto Method = STI.getAuthenticatedLRCheckMethod(*MF);
255 NumBytes += AArch64PAuth::getCheckerSizeInBytes(Method);
256 return NumBytes;
257 }
258
259 // Size should be preferably set in
260 // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
261 // Specific cases handle instructions of variable sizes
262 switch (Desc.getOpcode()) {
263 default:
264 if (Desc.getSize())
265 return Desc.getSize();
266
267 // Anything not explicitly designated otherwise (i.e. pseudo-instructions
268 // with fixed constant size but not specified in .td file) is a normal
269 // 4-byte insn.
270 NumBytes = 4;
271 break;
272 case TargetOpcode::STACKMAP:
273 // The upper bound for a stackmap intrinsic is the full length of its shadow
274 NumBytes = StackMapOpers(&MI).getNumPatchBytes();
275 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
276 break;
277 case TargetOpcode::PATCHPOINT:
278 // The size of the patchpoint intrinsic is the number of bytes requested
279 NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
280 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
281 break;
282 case TargetOpcode::STATEPOINT:
283 NumBytes = StatepointOpers(&MI).getNumPatchBytes();
284 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
285 // No patch bytes means a normal call inst is emitted
286 if (NumBytes == 0)
287 NumBytes = 4;
288 break;
289 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
290 // If `patchable-function-entry` is set, PATCHABLE_FUNCTION_ENTER
291 // instructions are expanded to the specified number of NOPs. Otherwise,
292 // they are expanded to 36-byte XRay sleds.
293 NumBytes =
294 F.getFnAttributeAsParsedInteger("patchable-function-entry", 9) * 4;
295 break;
296 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
297 case TargetOpcode::PATCHABLE_TAIL_CALL:
298 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
299 // An XRay sled can be 4 bytes of alignment plus a 32-byte block.
300 NumBytes = 36;
301 break;
302 case TargetOpcode::PATCHABLE_EVENT_CALL:
303 // EVENT_CALL XRay sleds are exactly 6 instructions long (no alignment).
304 NumBytes = 24;
305 break;
306
307 case AArch64::SPACE:
308 NumBytes = MI.getOperand(1).getImm();
309 break;
310 case AArch64::MOVaddr:
311 case AArch64::MOVaddrJT:
312 case AArch64::MOVaddrCP:
313 case AArch64::MOVaddrBA:
314 case AArch64::MOVaddrTLS:
315 case AArch64::MOVaddrEXT: {
316 // Use the same logic as the pseudo expansion to count instructions.
319 MI.getOperand(1).getTargetFlags(),
320 Subtarget.isTargetMachO(), Insn);
321 NumBytes = Insn.size() * 4;
322 break;
323 }
324
325 case AArch64::MOVi32imm:
326 case AArch64::MOVi64imm: {
327 // Use the same logic as the pseudo expansion to count instructions.
328 unsigned BitSize = Desc.getOpcode() == AArch64::MOVi32imm ? 32 : 64;
330 AArch64_IMM::expandMOVImm(MI.getOperand(1).getImm(), BitSize, Insn);
331 NumBytes = Insn.size() * 4;
332 break;
333 }
334
335 case TargetOpcode::BUNDLE:
336 NumBytes = getInstBundleSize(MI);
337 break;
338 }
339
340 return NumBytes;
341}
342
345 // Block ends with fall-through condbranch.
346 switch (LastInst->getOpcode()) {
347 default:
348 llvm_unreachable("Unknown branch instruction?");
349 case AArch64::Bcc:
350 Target = LastInst->getOperand(1).getMBB();
351 Cond.push_back(LastInst->getOperand(0));
352 break;
353 case AArch64::CBZW:
354 case AArch64::CBZX:
355 case AArch64::CBNZW:
356 case AArch64::CBNZX:
357 Target = LastInst->getOperand(1).getMBB();
358 Cond.push_back(MachineOperand::CreateImm(-1));
359 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
360 Cond.push_back(LastInst->getOperand(0));
361 break;
362 case AArch64::TBZW:
363 case AArch64::TBZX:
364 case AArch64::TBNZW:
365 case AArch64::TBNZX:
366 Target = LastInst->getOperand(2).getMBB();
367 Cond.push_back(MachineOperand::CreateImm(-1));
368 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
369 Cond.push_back(LastInst->getOperand(0));
370 Cond.push_back(LastInst->getOperand(1));
371 break;
372 case AArch64::CBWPri:
373 case AArch64::CBXPri:
374 case AArch64::CBWPrr:
375 case AArch64::CBXPrr:
376 Target = LastInst->getOperand(3).getMBB();
377 Cond.push_back(MachineOperand::CreateImm(-1));
378 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
379 Cond.push_back(LastInst->getOperand(0));
380 Cond.push_back(LastInst->getOperand(1));
381 Cond.push_back(LastInst->getOperand(2));
382 break;
383 case AArch64::CBBAssertExt:
384 case AArch64::CBHAssertExt:
385 Target = LastInst->getOperand(3).getMBB();
386 Cond.push_back(MachineOperand::CreateImm(-1)); // -1
387 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); // Opc
388 Cond.push_back(LastInst->getOperand(0)); // Cond
389 Cond.push_back(LastInst->getOperand(1)); // Op0
390 Cond.push_back(LastInst->getOperand(2)); // Op1
391 Cond.push_back(LastInst->getOperand(4)); // Ext0
392 Cond.push_back(LastInst->getOperand(5)); // Ext1
393 break;
394 }
395}
396
397static unsigned getBranchDisplacementBits(const AArch64Options &CLOpts,
398 unsigned Opc) {
399 switch (Opc) {
400 default:
401 llvm_unreachable("unexpected opcode!");
402 case AArch64::B:
403 return CLOpts.b_offset_bits;
404 case AArch64::TBNZW:
405 case AArch64::TBZW:
406 case AArch64::TBNZX:
407 case AArch64::TBZX:
408 return CLOpts.tbz_offset_bits;
409 case AArch64::CBNZW:
410 case AArch64::CBZW:
411 case AArch64::CBNZX:
412 case AArch64::CBZX:
413 return CLOpts.cbz_offset_bits;
414 case AArch64::Bcc:
415 return CLOpts.bcc_offset_bits;
416 case AArch64::CBWPri:
417 case AArch64::CBXPri:
418 case AArch64::CBBAssertExt:
419 case AArch64::CBHAssertExt:
420 case AArch64::CBWPrr:
421 case AArch64::CBXPrr:
422 return CLOpts.cb_offset_bits;
423 }
424}
425
427 int64_t BrOffset) const {
428 unsigned Bits = getBranchDisplacementBits(Subtarget.getCLOpts(), BranchOp);
429 assert(Bits >= 3 && "max branch displacement must be enough to jump"
430 "over conditional branch expansion");
431 return isIntN(Bits, BrOffset / 4);
432}
433
436 switch (MI.getOpcode()) {
437 default:
438 llvm_unreachable("unexpected opcode!");
439 case AArch64::B:
440 return MI.getOperand(0).getMBB();
441 case AArch64::TBZW:
442 case AArch64::TBNZW:
443 case AArch64::TBZX:
444 case AArch64::TBNZX:
445 return MI.getOperand(2).getMBB();
446 case AArch64::CBZW:
447 case AArch64::CBNZW:
448 case AArch64::CBZX:
449 case AArch64::CBNZX:
450 case AArch64::Bcc:
451 return MI.getOperand(1).getMBB();
452 case AArch64::CBWPri:
453 case AArch64::CBXPri:
454 case AArch64::CBBAssertExt:
455 case AArch64::CBHAssertExt:
456 case AArch64::CBWPrr:
457 case AArch64::CBXPrr:
458 return MI.getOperand(3).getMBB();
459 }
460}
461
463 MachineBasicBlock &NewDestBB,
464 MachineBasicBlock &RestoreBB,
465 const DebugLoc &DL,
466 int64_t BrOffset,
467 RegScavenger *RS) const {
468 assert(RS && "RegScavenger required for long branching");
469 assert(MBB.empty() &&
470 "new block should be inserted for expanding unconditional branch");
471 assert(MBB.pred_size() == 1);
472 assert(RestoreBB.empty() &&
473 "restore block should be inserted for restoring clobbered registers");
474
475 auto buildIndirectBranch = [&](Register Reg, MachineBasicBlock &DestBB) {
476 // Offsets outside of the signed 33-bit range are not supported for ADRP +
477 // ADD.
478 if (!isInt<33>(BrOffset))
480 "Branch offsets outside of the signed 33-bit range not supported");
481
482 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADRP), Reg)
483 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGE);
484 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADDXri), Reg)
485 .addReg(Reg)
486 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
487 .addImm(0);
488 BuildMI(MBB, MBB.end(), DL, get(AArch64::BR)).addReg(Reg);
489 };
490
491 RS->enterBasicBlockEnd(MBB);
492 // If X16 is unused, we can rely on the linker to insert a range extension
493 // thunk if NewDestBB is out of range of a single B instruction.
494 constexpr Register Reg = AArch64::X16;
495 if (!RS->isRegUsed(Reg)) {
496 insertUnconditionalBranch(MBB, &NewDestBB, DL);
497 RS->setRegUsed(Reg);
498 return;
499 }
500
501 // In a cold block without BTI, insert the indirect branch if a register is
502 // free. Skip this if BTI is enabled to avoid inserting a BTI at the target,
503 // prioritizing a dynamic cost in cold code over a static cost in hot code.
504 AArch64FunctionInfo *AFI = MBB.getParent()->getInfo<AArch64FunctionInfo>();
505 bool HasBTI = AFI && AFI->branchTargetEnforcement();
506 if (MBB.getSectionID() == MBBSectionID::ColdSectionID && !HasBTI) {
507 Register Scavenged = RS->FindUnusedReg(&AArch64::GPR64RegClass);
508 if (Scavenged.isValid()) {
509 buildIndirectBranch(Scavenged, NewDestBB);
510 RS->setRegUsed(Scavenged);
511 return;
512 }
513 }
514
515 // Note: Spilling X16 briefly moves the stack pointer, making it incompatible
516 // with red zones.
517 if (!AFI || AFI->hasRedZone().value_or(true))
519 "Unable to insert indirect branch inside function that has red zone");
520
521 // Otherwise, spill X16 and defer range extension to the linker.
522 BuildMI(MBB, MBB.end(), DL, get(AArch64::STRXpre))
523 .addReg(AArch64::SP, RegState::Define)
524 .addReg(Reg)
525 .addReg(AArch64::SP)
526 .addImm(-16);
527
528 BuildMI(MBB, MBB.end(), DL, get(AArch64::B)).addMBB(&RestoreBB);
529
530 BuildMI(RestoreBB, RestoreBB.end(), DL, get(AArch64::LDRXpost))
531 .addReg(AArch64::SP, RegState::Define)
533 .addReg(AArch64::SP)
534 .addImm(16);
535}
536
537// Branch analysis.
540 MachineBasicBlock *&FBB,
542 bool AllowModify) const {
543 // If the block has no terminators, it just falls into the block after it.
544 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
545 if (I == MBB.end())
546 return false;
547
548 // Skip over SpeculationBarrierEndBB terminators
549 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
550 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
551 --I;
552 }
553
554 if (!isUnpredicatedTerminator(*I))
555 return false;
556
557 // Get the last instruction in the block.
558 MachineInstr *LastInst = &*I;
559
560 // If there is only one terminator instruction, process it.
561 unsigned LastOpc = LastInst->getOpcode();
562 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
563 if (isUncondBranchOpcode(LastOpc)) {
564 TBB = LastInst->getOperand(0).getMBB();
565 return false;
566 }
567 if (isCondBranchOpcode(LastOpc)) {
568 // Block ends with fall-through condbranch.
569 parseCondBranch(LastInst, TBB, Cond);
570 return false;
571 }
572 return true; // Can't handle indirect branch.
573 }
574
575 // Get the instruction before it if it is a terminator.
576 MachineInstr *SecondLastInst = &*I;
577 unsigned SecondLastOpc = SecondLastInst->getOpcode();
578
579 // If AllowModify is true and the block ends with two or more unconditional
580 // branches, delete all but the first unconditional branch.
581 if (AllowModify && isUncondBranchOpcode(LastOpc)) {
582 while (isUncondBranchOpcode(SecondLastOpc)) {
583 LastInst->eraseFromParent();
584 LastInst = SecondLastInst;
585 LastOpc = LastInst->getOpcode();
586 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
587 // Return now the only terminator is an unconditional branch.
588 TBB = LastInst->getOperand(0).getMBB();
589 return false;
590 }
591 SecondLastInst = &*I;
592 SecondLastOpc = SecondLastInst->getOpcode();
593 }
594 }
595
596 // If we're allowed to modify and the block ends in a unconditional branch
597 // which could simply fallthrough, remove the branch. (Note: This case only
598 // matters when we can't understand the whole sequence, otherwise it's also
599 // handled by BranchFolding.cpp.)
600 if (AllowModify && isUncondBranchOpcode(LastOpc) &&
601 MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
602 LastInst->eraseFromParent();
603 LastInst = SecondLastInst;
604 LastOpc = LastInst->getOpcode();
605 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
606 assert(!isUncondBranchOpcode(LastOpc) &&
607 "unreachable unconditional branches removed above");
608
609 if (isCondBranchOpcode(LastOpc)) {
610 // Block ends with fall-through condbranch.
611 parseCondBranch(LastInst, TBB, Cond);
612 return false;
613 }
614 return true; // Can't handle indirect branch.
615 }
616 SecondLastInst = &*I;
617 SecondLastOpc = SecondLastInst->getOpcode();
618 }
619
620 // If there are three terminators, we don't know what sort of block this is.
621 if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
622 return true;
623
624 // If the block ends with a B and a Bcc, handle it.
625 if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
626 parseCondBranch(SecondLastInst, TBB, Cond);
627 FBB = LastInst->getOperand(0).getMBB();
628 return false;
629 }
630
631 // If the block ends with two unconditional branches, handle it. The second
632 // one is not executed, so remove it.
633 if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
634 TBB = SecondLastInst->getOperand(0).getMBB();
635 I = LastInst;
636 if (AllowModify)
637 I->eraseFromParent();
638 return false;
639 }
640
641 // ...likewise if it ends with an indirect branch followed by an unconditional
642 // branch.
643 if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
644 I = LastInst;
645 if (AllowModify)
646 I->eraseFromParent();
647 return true;
648 }
649
650 // Otherwise, can't handle this.
651 return true;
652}
653
655 MachineBranchPredicate &MBP,
656 bool AllowModify) const {
657 // Use analyzeBranch to validate the branch pattern.
658 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
660 if (analyzeBranch(MBB, TBB, FBB, Cond, AllowModify))
661 return true;
662
663 // analyzeBranch returns success with empty Cond for unconditional branches.
664 if (Cond.empty())
665 return true;
666
667 MBP.TrueDest = TBB;
668 assert(MBP.TrueDest && "expected!");
669 MBP.FalseDest = FBB ? FBB : MBB.getNextNode();
670
671 MBP.ConditionDef = nullptr;
672 MBP.SingleUseCondition = false;
673
674 // Find the conditional branch. After analyzeBranch succeeds with non-empty
675 // Cond, there's exactly one conditional branch - either last (fallthrough)
676 // or second-to-last (followed by unconditional B).
677 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
678 if (I == MBB.end())
679 return true;
680
681 if (isUncondBranchOpcode(I->getOpcode())) {
682 if (I == MBB.begin())
683 return true;
684 --I;
685 }
686
687 MachineInstr *CondBranch = &*I;
688 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
689
690 switch (CondBranch->getOpcode()) {
691 default:
692 return true;
693
694 case AArch64::Bcc:
695 // Bcc takes the NZCV flag as the operand to branch on, walk up the
696 // instruction stream to find the last instruction to define NZCV.
698 if (MI.modifiesRegister(AArch64::NZCV, /*TRI=*/nullptr)) {
699 MBP.ConditionDef = &MI;
700 break;
701 }
702 }
703 return false;
704
705 case AArch64::CBZW:
706 case AArch64::CBZX:
707 case AArch64::CBNZW:
708 case AArch64::CBNZX: {
709 MBP.LHS = CondBranch->getOperand(0);
710 MBP.RHS = MachineOperand::CreateImm(0);
711 unsigned Opc = CondBranch->getOpcode();
712 MBP.Predicate = (Opc == AArch64::CBNZX || Opc == AArch64::CBNZW)
713 ? MachineBranchPredicate::PRED_NE
714 : MachineBranchPredicate::PRED_EQ;
715 Register CondReg = MBP.LHS.getReg();
716 if (CondReg.isVirtual())
717 MBP.ConditionDef = MRI.getVRegDef(CondReg);
718 return false;
719 }
720
721 case AArch64::TBZW:
722 case AArch64::TBZX:
723 case AArch64::TBNZW:
724 case AArch64::TBNZX: {
725 Register CondReg = CondBranch->getOperand(0).getReg();
726 if (CondReg.isVirtual())
727 MBP.ConditionDef = MRI.getVRegDef(CondReg);
728 return false;
729 }
730 }
731}
732
735 if (Cond[0].getImm() != -1) {
736 // Regular Bcc
739 } else {
740 // Folded compare-and-branch
741 switch (Cond[1].getImm()) {
742 default:
743 llvm_unreachable("Unknown conditional branch!");
744 case AArch64::CBZW:
745 Cond[1].setImm(AArch64::CBNZW);
746 break;
747 case AArch64::CBNZW:
748 Cond[1].setImm(AArch64::CBZW);
749 break;
750 case AArch64::CBZX:
751 Cond[1].setImm(AArch64::CBNZX);
752 break;
753 case AArch64::CBNZX:
754 Cond[1].setImm(AArch64::CBZX);
755 break;
756 case AArch64::TBZW:
757 Cond[1].setImm(AArch64::TBNZW);
758 break;
759 case AArch64::TBNZW:
760 Cond[1].setImm(AArch64::TBZW);
761 break;
762 case AArch64::TBZX:
763 Cond[1].setImm(AArch64::TBNZX);
764 break;
765 case AArch64::TBNZX:
766 Cond[1].setImm(AArch64::TBZX);
767 break;
768
769 // Cond is { -1, Opcode, CC, Op0, Op1, ... }
770 case AArch64::CBWPri:
771 case AArch64::CBXPri:
772 case AArch64::CBBAssertExt:
773 case AArch64::CBHAssertExt:
774 case AArch64::CBWPrr:
775 case AArch64::CBXPrr: {
776 // Pseudos using standard 4bit Arm condition codes
778 static_cast<AArch64CC::CondCode>(Cond[2].getImm());
780 }
781 }
782 }
783
784 return false;
785}
786
788 int *BytesRemoved) const {
789 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
790 if (I == MBB.end())
791 return 0;
792
793 if (!isUncondBranchOpcode(I->getOpcode()) &&
794 !isCondBranchOpcode(I->getOpcode()))
795 return 0;
796
797 // Remove the branch.
798 I->eraseFromParent();
799
800 I = MBB.end();
801
802 if (I == MBB.begin()) {
803 if (BytesRemoved)
804 *BytesRemoved = 4;
805 return 1;
806 }
807 --I;
808 if (!isCondBranchOpcode(I->getOpcode())) {
809 if (BytesRemoved)
810 *BytesRemoved = 4;
811 return 1;
812 }
813
814 // Remove the branch.
815 I->eraseFromParent();
816 if (BytesRemoved)
817 *BytesRemoved = 8;
818
819 return 2;
820}
821
822void AArch64InstrInfo::instantiateCondBranch(
825 if (Cond[0].getImm() != -1) {
826 // Regular Bcc
827 BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
828 } else {
829 // Folded compare-and-branch
830 // Note that we use addOperand instead of addReg to keep the flags.
831
832 // cbz, cbnz
833 const MachineInstrBuilder MIB =
834 BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
835
836 // tbz/tbnz
837 if (Cond.size() > 3)
838 MIB.add(Cond[3]);
839
840 // cb
841 if (Cond.size() > 4)
842 MIB.add(Cond[4]);
843
844 MIB.addMBB(TBB);
845
846 // cb[b,h]
847 if (Cond.size() > 5) {
848 MIB.addImm(Cond[5].getImm());
849 MIB.addImm(Cond[6].getImm());
850 }
851 }
852}
853
856 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
857 // Shouldn't be a fall through.
858 assert(TBB && "insertBranch must not be told to insert a fallthrough");
859
860 if (!FBB) {
861 if (Cond.empty()) // Unconditional branch?
862 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
863 else
864 instantiateCondBranch(MBB, DL, TBB, Cond);
865
866 if (BytesAdded)
867 *BytesAdded = 4;
868
869 return 1;
870 }
871
872 // Two-way conditional branch.
873 instantiateCondBranch(MBB, DL, TBB, Cond);
874 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
875
876 if (BytesAdded)
877 *BytesAdded = 8;
878
879 return 2;
880}
881
882#ifndef NDEBUG
884 switch (Ext) {
885 default:
886 return false;
887 case AArch64_AM::UXTB:
888 case AArch64_AM::SXTB:
889 return Opc == AArch64::CBBAssertExt;
890 case AArch64_AM::UXTH:
891 case AArch64_AM::SXTH:
892 return Opc == AArch64::CBHAssertExt;
893 }
894}
895#endif
896
900 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
901
902 // Parse the condition code, see parseCondBranch() above.
904 switch (Cond.size()) {
905 default:
906 llvm_unreachable("Unknown condition opcode in Cond");
907 case 1: // b.cc
909 break;
910 case 3: { // cbz/cbnz
911 // We must insert a compare against 0.
912 bool Is64Bit;
913 switch (Cond[1].getImm()) {
914 default:
915 llvm_unreachable("Unknown branch opcode in Cond");
916 case AArch64::CBZW:
917 Is64Bit = false;
919 break;
920 case AArch64::CBZX:
921 Is64Bit = true;
923 break;
924 case AArch64::CBNZW:
925 Is64Bit = false;
927 break;
928 case AArch64::CBNZX:
929 Is64Bit = true;
931 break;
932 }
933 Register SrcReg = Cond[2].getReg();
934 if (Is64Bit) {
935 // cmp reg, #0 is actually subs xzr, reg, #0.
936 MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
937 BuildMI(MBB, MI, DL, get(AArch64::SUBSXri), AArch64::XZR)
938 .addReg(SrcReg)
939 .addImm(0)
940 .addImm(0);
941 } else {
942 MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
943 BuildMI(MBB, MI, DL, get(AArch64::SUBSWri), AArch64::WZR)
944 .addReg(SrcReg)
945 .addImm(0)
946 .addImm(0);
947 }
948 } break;
949 case 4: { // tbz/tbnz
950 // We must insert a tst instruction.
951 switch (Cond[1].getImm()) {
952 default:
953 llvm_unreachable("Unknown branch opcode in Cond");
954 case AArch64::TBZW:
955 case AArch64::TBZX:
957 break;
958 case AArch64::TBNZW:
959 case AArch64::TBNZX:
961 break;
962 }
963 // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
964 if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
965 BuildMI(MBB, MI, DL, get(AArch64::ANDSWri), AArch64::WZR)
966 .addReg(Cond[2].getReg())
967 .addImm(
969 else
970 BuildMI(MBB, MI, DL, get(AArch64::ANDSXri), AArch64::XZR)
971 .addReg(Cond[2].getReg())
972 .addImm(
974 } break;
975 case 5: { // cb
976 // We must insert a cmp, that is a subs
977 // 0 1 2 3 4
978 // Cond is { -1, Opcode, CC, Op0, Op1 }
979 unsigned SubsOpc, SubsDestReg;
980 bool IsImm = false;
981 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
982 switch (Cond[1].getImm()) {
983 default:
984 llvm_unreachable("Unknown branch opcode in Cond");
985 case AArch64::CBWPri:
986 SubsOpc = AArch64::SUBSWri;
987 SubsDestReg = AArch64::WZR;
988 IsImm = true;
989 break;
990 case AArch64::CBXPri:
991 SubsOpc = AArch64::SUBSXri;
992 SubsDestReg = AArch64::XZR;
993 IsImm = true;
994 break;
995 case AArch64::CBWPrr:
996 SubsOpc = AArch64::SUBSWrr;
997 SubsDestReg = AArch64::WZR;
998 IsImm = false;
999 break;
1000 case AArch64::CBXPrr:
1001 SubsOpc = AArch64::SUBSXrr;
1002 SubsDestReg = AArch64::XZR;
1003 IsImm = false;
1004 break;
1005 }
1006
1007 if (IsImm) {
1008 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
1009 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
1010 .addReg(Cond[3].getReg())
1011 .addImm(Cond[4].getImm())
1012 .addImm(0);
1013 } else {
1014 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
1015 MRI.constrainRegClass(Cond[4].getReg(), getRegClass(get(SubsOpc), 2));
1016 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
1017 .addReg(Cond[3].getReg())
1018 .addReg(Cond[4].getReg());
1019 }
1020 } break;
1021 case 7: { // cb[b,h]
1022 // We must insert a cmp, that is a subs, but also zero- or sign-extensions
1023 // that have been folded. For the first operand we codegen an explicit
1024 // extension, for the second operand we fold the extension into cmp.
1025 // 0 1 2 3 4 5 6
1026 // Cond is { -1, Opcode, CC, Op0, Op1, Ext0, Ext1 }
1027
1028 // We need a new register for the now explicitly extended register
1029 Register Reg = Cond[3].getReg();
1031 unsigned ExtOpc;
1032 unsigned ExtBits;
1033 AArch64_AM::ShiftExtendType ExtendType =
1035 assert(isValidCBExtend(Cond[1].getImm(), ExtendType) &&
1036 "Unexpected compare-and-branch instruction for extend type");
1037 switch (ExtendType) {
1038 default:
1039 llvm_unreachable("Unknown shift-extend for CB instruction");
1040 case AArch64_AM::SXTB:
1041 ExtOpc = AArch64::SBFMWri;
1042 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1043 break;
1044 case AArch64_AM::SXTH:
1045 ExtOpc = AArch64::SBFMWri;
1046 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1047 break;
1048 case AArch64_AM::UXTB:
1049 ExtOpc = AArch64::ANDWri;
1050 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1051 break;
1052 case AArch64_AM::UXTH:
1053 ExtOpc = AArch64::ANDWri;
1054 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1055 break;
1056 }
1057
1058 // Build the explicit extension of the first operand
1059 Reg = MRI.createVirtualRegister(&AArch64::GPR32commonRegClass);
1061 BuildMI(MBB, MI, DL, get(ExtOpc), Reg).addReg(Cond[3].getReg());
1062 if (ExtOpc != AArch64::ANDWri)
1063 MBBI.addImm(0);
1064 MBBI.addImm(ExtBits);
1065 }
1066
1067 // Now, subs with an extended second operand
1069 MRI.constrainRegClass(Reg, &AArch64::GPR32commonRegClass);
1070 AArch64_AM::ShiftExtendType ExtendType =
1072 assert(isValidCBExtend(Cond[1].getImm(), ExtendType) &&
1073 "Unexpected compare-and-branch instruction for extend type");
1074 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrx), AArch64::WZR)
1075 .addReg(Reg)
1076 .addReg(Cond[4].getReg())
1077 .addImm(AArch64_AM::getArithExtendImm(ExtendType, 0));
1078 } // If no extension is needed, just a regular subs
1079 else {
1080 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrr), AArch64::WZR)
1081 .addReg(Reg)
1082 .addReg(Cond[4].getReg());
1083 }
1084
1085 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
1086 } break;
1087 }
1088 return CC;
1089}
1090
1092 const TargetInstrInfo &TII) {
1093 for (MachineInstr &MI : MBB->terminators()) {
1094 unsigned Opc = MI.getOpcode();
1095 switch (Opc) {
1096 case AArch64::CBZW:
1097 case AArch64::CBZX:
1098 case AArch64::TBZW:
1099 case AArch64::TBZX:
1100 // CBZ/TBZ with WZR/XZR -> unconditional B
1101 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1102 MI.getOperand(0).getReg() == AArch64::XZR) {
1103 DEBUG_WITH_TYPE("optimizeTerminators",
1104 dbgs() << "Removing always taken branch: " << MI);
1105 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1106 SmallVector<MachineBasicBlock *> Succs(MBB->successors());
1107 for (auto *S : Succs)
1108 if (S != Target)
1109 MBB->removeSuccessor(S);
1110 DebugLoc DL = MI.getDebugLoc();
1111 while (MBB->rbegin() != &MI)
1112 MBB->rbegin()->eraseFromParent();
1113 MI.eraseFromParent();
1114 BuildMI(MBB, DL, TII.get(AArch64::B)).addMBB(Target);
1115 return true;
1116 }
1117 break;
1118 case AArch64::CBNZW:
1119 case AArch64::CBNZX:
1120 case AArch64::TBNZW:
1121 case AArch64::TBNZX:
1122 // CBNZ/TBNZ with WZR/XZR -> never taken, remove branch and successor
1123 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1124 MI.getOperand(0).getReg() == AArch64::XZR) {
1125 DEBUG_WITH_TYPE("optimizeTerminators",
1126 dbgs() << "Removing never taken branch: " << MI);
1127 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1128 MI.getParent()->removeSuccessor(Target);
1129 MI.eraseFromParent();
1130 return true;
1131 }
1132 break;
1133 }
1134 }
1135 return false;
1136}
1137
1138// Find the original register that VReg is copied from.
1139static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
1140 while (Register::isVirtualRegister(VReg)) {
1141 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1142 if (!DefMI || !DefMI->isFullCopy())
1143 return VReg;
1144 VReg = DefMI->getOperand(1).getReg();
1145 }
1146 return VReg;
1147}
1148
1149// Determine if VReg is defined by an instruction that can be folded into a
1150// csel instruction. If so, return the folded opcode, and the replacement
1151// register.
1152static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
1153 unsigned *NewReg = nullptr) {
1154 VReg = removeCopies(MRI, VReg);
1155 if (!Register::isVirtualRegister(VReg))
1156 return 0;
1157
1158 bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
1159 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1160 if (!DefMI)
1161 return 0;
1162 unsigned Opc = 0;
1163 unsigned SrcReg = 0;
1164 switch (DefMI->getOpcode()) {
1165 case AArch64::SUBREG_TO_REG:
1166 // Check for the following way to define an 64-bit immediate:
1167 // %0:gpr32 = MOVi32imm 1
1168 // %1:gpr64 = SUBREG_TO_REG %0:gpr32, %subreg.sub_32
1169 if (!DefMI->getOperand(1).isReg())
1170 return 0;
1171 if (!DefMI->getOperand(2).isImm() ||
1172 DefMI->getOperand(2).getImm() != AArch64::sub_32)
1173 return 0;
1174 DefMI = MRI.getVRegDef(DefMI->getOperand(1).getReg());
1175 if (DefMI->getOpcode() != AArch64::MOVi32imm)
1176 return 0;
1177 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1178 return 0;
1179 assert(Is64Bit);
1180 SrcReg = AArch64::XZR;
1181 Opc = AArch64::CSINCXr;
1182 break;
1183
1184 case AArch64::MOVi32imm:
1185 case AArch64::MOVi64imm:
1186 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1187 return 0;
1188 SrcReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1189 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1190 break;
1191
1192 case AArch64::ADDSXri:
1193 case AArch64::ADDSWri:
1194 // if NZCV is used, do not fold.
1195 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1196 true) == -1)
1197 return 0;
1198 // fall-through to ADDXri and ADDWri.
1199 [[fallthrough]];
1200 case AArch64::ADDXri:
1201 case AArch64::ADDWri:
1202 // add x, 1 -> csinc.
1203 if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
1204 DefMI->getOperand(3).getImm() != 0)
1205 return 0;
1206 SrcReg = DefMI->getOperand(1).getReg();
1207 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1208 break;
1209
1210 case AArch64::ORNXrr:
1211 case AArch64::ORNWrr: {
1212 // not x -> csinv, represented as orn dst, xzr, src.
1213 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1214 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1215 return 0;
1216 SrcReg = DefMI->getOperand(2).getReg();
1217 Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
1218 break;
1219 }
1220
1221 case AArch64::SUBSXrr:
1222 case AArch64::SUBSWrr:
1223 // if NZCV is used, do not fold.
1224 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1225 true) == -1)
1226 return 0;
1227 // fall-through to SUBXrr and SUBWrr.
1228 [[fallthrough]];
1229 case AArch64::SUBXrr:
1230 case AArch64::SUBWrr: {
1231 // neg x -> csneg, represented as sub dst, xzr, src.
1232 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1233 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1234 return 0;
1235 SrcReg = DefMI->getOperand(2).getReg();
1236 Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
1237 break;
1238 }
1239 default:
1240 return 0;
1241 }
1242 assert(Opc && SrcReg && "Missing parameters");
1243
1244 if (NewReg)
1245 *NewReg = SrcReg;
1246 return Opc;
1247}
1248
1251 Register DstReg, Register TrueReg,
1252 Register FalseReg,
1253 SelectExpansion &Exp) const {
1254 // Check register classes.
1255 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1256 const TargetRegisterClass *RC =
1257 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1258 if (!RC)
1259 return false;
1260
1261 // Also need to check the dest regclass, in case we're trying to optimize
1262 // something like:
1263 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
1264 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
1265 return false;
1266
1267 // Expanding cbz/tbz requires a flag setting instruction in addition to the
1268 // select, adding an extra cycle of latency on the condition.
1269 unsigned ExtraCondLat = Cond.size() != 1;
1270 Exp.NumInsts = 1 + ExtraCondLat;
1271 if (ExtraCondLat)
1272 Exp.ClobberedPhysRegs.push_back(AArch64::NZCV);
1273
1274 // GPRs are handled by csel.
1275 // FIXME: Fold in x+1, -x, and ~x when applicable.
1276 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
1277 AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
1278 // Single-cycle csel, csinc, csinv, and csneg.
1279 Exp.CondCycles = 1 + ExtraCondLat;
1280 Exp.TrueCycles = Exp.FalseCycles = 1;
1281 if (canFoldIntoCSel(MRI, TrueReg))
1282 Exp.TrueCycles = 0;
1283 else if (canFoldIntoCSel(MRI, FalseReg))
1284 Exp.FalseCycles = 0;
1285 return true;
1286 }
1287
1288 // Scalar floating point is handled by fcsel.
1289 // FIXME: Form fabs, fmin, and fmax when applicable.
1290 if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
1291 AArch64::FPR32RegClass.hasSubClassEq(RC)) {
1292 Exp.CondCycles = 5 + ExtraCondLat;
1293 Exp.TrueCycles = Exp.FalseCycles = 2;
1294 return true;
1295 }
1296
1297 // No single conditional move for a 128-bit vector, but we can emit a sequence
1298 // of csetm (~1), dup (~5, cross domain), bsl (~2).
1299 if (AArch64::FPR128RegClass.hasSubClassEq(RC) &&
1300 Subtarget.isNeonAvailable() &&
1301 !MBB.getParent()->getFunction().hasMinSize()) {
1302 Exp.CondCycles = 8 + ExtraCondLat;
1303 Exp.TrueCycles = Exp.FalseCycles = 2;
1304 Exp.NumInsts = 3 + ExtraCondLat;
1305 return true;
1306 }
1307
1308 return false;
1309}
1310
1313 const DebugLoc &DL, Register DstReg,
1315 Register TrueReg, Register FalseReg) const {
1316
1317 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1319
1320 // A 128-bit vector has no conditional move so blend the operands with a mask
1321 // built from the flags.
1322 if (MRI.constrainRegClass(DstReg, &AArch64::FPR128RegClass)) {
1323 assert(Subtarget.isNeonAvailable() && "Expected NEON for a vector select");
1324 MRI.constrainRegClass(TrueReg, &AArch64::FPR128RegClass);
1325 MRI.constrainRegClass(FalseReg, &AArch64::FPR128RegClass);
1326 Register CondSet = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1327 BuildMI(MBB, I, DL, get(AArch64::CSINVXr), CondSet)
1328 .addReg(AArch64::XZR)
1329 .addReg(AArch64::XZR)
1331 Register Mask = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
1332 BuildMI(MBB, I, DL, get(AArch64::DUPv2i64gpr), Mask).addReg(CondSet);
1333 BuildMI(MBB, I, DL, get(AArch64::BSPv16i8), DstReg)
1334 .addReg(Mask)
1335 .addReg(TrueReg)
1336 .addReg(FalseReg);
1337 return;
1338 }
1339
1340 unsigned Opc = 0;
1341 const TargetRegisterClass *RC = nullptr;
1342 bool TryFold = false;
1343 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
1344 RC = &AArch64::GPR64RegClass;
1345 Opc = AArch64::CSELXr;
1346 TryFold = true;
1347 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
1348 RC = &AArch64::GPR32RegClass;
1349 Opc = AArch64::CSELWr;
1350 TryFold = true;
1351 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
1352 RC = &AArch64::FPR64RegClass;
1353 Opc = AArch64::FCSELDrrr;
1354 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
1355 RC = &AArch64::FPR32RegClass;
1356 Opc = AArch64::FCSELSrrr;
1357 }
1358 assert(RC && "Unsupported regclass");
1359
1360 // Try folding simple instructions into the csel.
1361 if (TryFold) {
1362 unsigned NewReg = 0;
1363 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewReg);
1364 if (FoldedOpc) {
1365 // The folded opcodes csinc, csinc and csneg apply the operation to
1366 // FalseReg, so we need to invert the condition.
1368 TrueReg = FalseReg;
1369 } else
1370 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewReg);
1371
1372 // Fold the operation. Leave any dead instructions for DCE to clean up.
1373 if (FoldedOpc) {
1374 FalseReg = NewReg;
1375 Opc = FoldedOpc;
1376 }
1377 }
1378
1379 // Pull all virtual register into the appropriate class.
1380 MRI.constrainRegClass(TrueReg, RC);
1381 // FalseReg might be WZR or XZR if the folded operand is a literal 1.
1382 assert(
1383 (FalseReg.isVirtual() || FalseReg == AArch64::WZR ||
1384 FalseReg == AArch64::XZR) &&
1385 "FalseReg was folded into a non-virtual register other than WZR or XZR");
1386 if (FalseReg.isVirtual())
1387 MRI.constrainRegClass(FalseReg, RC);
1388
1389 // Insert the csel.
1390 BuildMI(MBB, I, DL, get(Opc), DstReg)
1391 .addReg(TrueReg)
1392 .addReg(FalseReg)
1393 .addImm(CC);
1394}
1395
1396// Return true if Imm can be loaded into a register by a "cheap" sequence of
1397// instructions. For now, "cheap" means at most two instructions.
1398static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize) {
1399 if (BitSize == 32)
1400 return true;
1401
1402 assert(BitSize == 64 && "Only bit sizes of 32 or 64 allowed");
1403 uint64_t Imm = static_cast<uint64_t>(MI.getOperand(1).getImm());
1405 AArch64_IMM::expandMOVImm(Imm, BitSize, Is);
1406
1407 return Is.size() <= 2;
1408}
1409
1410// Check if a COPY instruction is cheap.
1411static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI) {
1412 assert(MI.isCopy() && "Expected COPY instruction");
1413 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1414
1415 // Cross-bank copies (e.g., between GPR and FPR) are expensive on AArch64,
1416 // typically requiring an FMOV instruction with a 2-6 cycle latency.
1417 auto GetRegClass = [&](Register Reg) -> const TargetRegisterClass * {
1418 if (Reg.isVirtual())
1419 return MRI.getRegClass(Reg);
1420 if (Reg.isPhysical())
1421 return RI.getMinimalPhysRegClass(Reg);
1422 return nullptr;
1423 };
1424 const TargetRegisterClass *DstRC = GetRegClass(MI.getOperand(0).getReg());
1425 const TargetRegisterClass *SrcRC = GetRegClass(MI.getOperand(1).getReg());
1426 if (DstRC && SrcRC && !RI.getCommonSubClass(DstRC, SrcRC))
1427 return false;
1428
1429 return MI.isAsCheapAsAMove();
1430}
1431
1432// FIXME: this implementation should be micro-architecture dependent, so a
1433// micro-architecture target hook should be introduced here in future.
1435 if (Subtarget.hasExynosCheapAsMoveHandling()) {
1436 if (isExynosCheapAsMove(MI))
1437 return true;
1438 return MI.isAsCheapAsAMove();
1439 }
1440
1441 switch (MI.getOpcode()) {
1442 default:
1443 return MI.isAsCheapAsAMove();
1444
1445 case TargetOpcode::COPY:
1446 return isCheapCopy(MI, RI);
1447
1448 case AArch64::ADDWrs:
1449 case AArch64::ADDXrs:
1450 case AArch64::SUBWrs:
1451 case AArch64::SUBXrs:
1452 return Subtarget.hasALULSLFast() && MI.getOperand(3).getImm() <= 4;
1453
1454 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
1455 // ORRXri, it is as cheap as MOV.
1456 // Likewise if it can be expanded to MOVZ/MOVN/MOVK.
1457 case AArch64::MOVi32imm:
1458 return isCheapImmediate(MI, 32);
1459 case AArch64::MOVi64imm:
1460 return isCheapImmediate(MI, 64);
1461 }
1462}
1463
1464bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
1465 switch (MI.getOpcode()) {
1466 default:
1467 return false;
1468
1469 case AArch64::ADDWrs:
1470 case AArch64::ADDXrs:
1471 case AArch64::ADDSWrs:
1472 case AArch64::ADDSXrs: {
1473 unsigned Imm = MI.getOperand(3).getImm();
1474 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1475 if (ShiftVal == 0)
1476 return true;
1477 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
1478 }
1479
1480 case AArch64::ADDWrx:
1481 case AArch64::ADDXrx:
1482 case AArch64::ADDXrx64:
1483 case AArch64::ADDSWrx:
1484 case AArch64::ADDSXrx:
1485 case AArch64::ADDSXrx64: {
1486 unsigned Imm = MI.getOperand(3).getImm();
1488 default:
1489 return false;
1490 case AArch64_AM::UXTB:
1491 case AArch64_AM::UXTH:
1492 case AArch64_AM::UXTW:
1493 case AArch64_AM::UXTX:
1495 }
1496 }
1497
1498 case AArch64::SUBWrs:
1499 case AArch64::SUBSWrs: {
1500 unsigned Imm = MI.getOperand(3).getImm();
1501 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1502 return ShiftVal == 0 ||
1503 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
1504 }
1505
1506 case AArch64::SUBXrs:
1507 case AArch64::SUBSXrs: {
1508 unsigned Imm = MI.getOperand(3).getImm();
1509 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1510 return ShiftVal == 0 ||
1511 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
1512 }
1513
1514 case AArch64::SUBWrx:
1515 case AArch64::SUBXrx:
1516 case AArch64::SUBXrx64:
1517 case AArch64::SUBSWrx:
1518 case AArch64::SUBSXrx:
1519 case AArch64::SUBSXrx64: {
1520 unsigned Imm = MI.getOperand(3).getImm();
1522 default:
1523 return false;
1524 case AArch64_AM::UXTB:
1525 case AArch64_AM::UXTH:
1526 case AArch64_AM::UXTW:
1527 case AArch64_AM::UXTX:
1529 }
1530 }
1531
1532 case AArch64::LDRBBroW:
1533 case AArch64::LDRBBroX:
1534 case AArch64::LDRBroW:
1535 case AArch64::LDRBroX:
1536 case AArch64::LDRDroW:
1537 case AArch64::LDRDroX:
1538 case AArch64::LDRHHroW:
1539 case AArch64::LDRHHroX:
1540 case AArch64::LDRHroW:
1541 case AArch64::LDRHroX:
1542 case AArch64::LDRQroW:
1543 case AArch64::LDRQroX:
1544 case AArch64::LDRSBWroW:
1545 case AArch64::LDRSBWroX:
1546 case AArch64::LDRSBXroW:
1547 case AArch64::LDRSBXroX:
1548 case AArch64::LDRSHWroW:
1549 case AArch64::LDRSHWroX:
1550 case AArch64::LDRSHXroW:
1551 case AArch64::LDRSHXroX:
1552 case AArch64::LDRSWroW:
1553 case AArch64::LDRSWroX:
1554 case AArch64::LDRSroW:
1555 case AArch64::LDRSroX:
1556 case AArch64::LDRWroW:
1557 case AArch64::LDRWroX:
1558 case AArch64::LDRXroW:
1559 case AArch64::LDRXroX:
1560 case AArch64::PRFMroW:
1561 case AArch64::PRFMroX:
1562 case AArch64::STRBBroW:
1563 case AArch64::STRBBroX:
1564 case AArch64::STRBroW:
1565 case AArch64::STRBroX:
1566 case AArch64::STRDroW:
1567 case AArch64::STRDroX:
1568 case AArch64::STRHHroW:
1569 case AArch64::STRHHroX:
1570 case AArch64::STRHroW:
1571 case AArch64::STRHroX:
1572 case AArch64::STRQroW:
1573 case AArch64::STRQroX:
1574 case AArch64::STRSroW:
1575 case AArch64::STRSroX:
1576 case AArch64::STRWroW:
1577 case AArch64::STRWroX:
1578 case AArch64::STRXroW:
1579 case AArch64::STRXroX: {
1580 unsigned IsSigned = MI.getOperand(3).getImm();
1581 return !IsSigned;
1582 }
1583 }
1584}
1585
1586bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
1587 unsigned Opc = MI.getOpcode();
1588 switch (Opc) {
1589 default:
1590 return false;
1591 case AArch64::SEH_StartProc:
1592 case AArch64::SEH_EndProc:
1593 case AArch64::SEH_EndC:
1594 case AArch64::SEH_StackAlloc:
1595 case AArch64::SEH_SaveFPLR:
1596 case AArch64::SEH_SaveFPLR_X:
1597 case AArch64::SEH_SaveReg:
1598 case AArch64::SEH_SaveReg_X:
1599 case AArch64::SEH_SaveRegP:
1600 case AArch64::SEH_SaveRegP_X:
1601 case AArch64::SEH_SaveFReg:
1602 case AArch64::SEH_SaveFReg_X:
1603 case AArch64::SEH_SaveFRegP:
1604 case AArch64::SEH_SaveFRegP_X:
1605 case AArch64::SEH_SetFP:
1606 case AArch64::SEH_AddFP:
1607 case AArch64::SEH_Nop:
1608 case AArch64::SEH_PrologEnd:
1609 case AArch64::SEH_EpilogStart:
1610 case AArch64::SEH_EpilogEnd:
1611 case AArch64::SEH_PACSignLR:
1612 case AArch64::SEH_SaveAnyRegI:
1613 case AArch64::SEH_SaveAnyRegIP:
1614 case AArch64::SEH_SaveAnyRegQ:
1615 case AArch64::SEH_SaveAnyRegQX:
1616 case AArch64::SEH_SaveAnyRegQP:
1617 case AArch64::SEH_SaveAnyRegQPX:
1618 case AArch64::SEH_AllocZ:
1619 case AArch64::SEH_SaveZReg:
1620 case AArch64::SEH_SavePReg:
1621 return true;
1622 }
1623}
1624
1626 Register &SrcReg, Register &DstReg,
1627 unsigned &SubIdx) const {
1628 switch (MI.getOpcode()) {
1629 default:
1630 return false;
1631 case AArch64::SBFMXri: // aka sxtw
1632 case AArch64::UBFMXri: // aka uxtw
1633 // Check for the 32 -> 64 bit extension case, these instructions can do
1634 // much more.
1635 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1636 return false;
1637 // This is a signed or unsigned 32 -> 64 bit extension.
1638 SrcReg = MI.getOperand(1).getReg();
1639 DstReg = MI.getOperand(0).getReg();
1640 SubIdx = AArch64::sub_32;
1641 return true;
1642 }
1643}
1644
1646 const MachineInstr &MIa, const MachineInstr &MIb) const {
1647 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1648 int64_t OffsetA = 0, OffsetB = 0;
1649 TypeSize WidthA(0, false), WidthB(0, false);
1650 bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1651
1652 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1653 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1654
1657 return false;
1658
1659 // Retrieve the base, offset from the base and width. Width
1660 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
1661 // base are identical, and the offset of a lower memory access +
1662 // the width doesn't overlap the offset of a higher memory access,
1663 // then the memory accesses are different.
1664 // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1665 // are assumed to have the same scale (vscale).
1666 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1667 WidthA) &&
1668 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1669 WidthB)) {
1670 if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1671 OffsetAIsScalable == OffsetBIsScalable) {
1672 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1673 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1674 TypeSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1675 if (LowWidth.isScalable() == OffsetAIsScalable &&
1676 LowOffset + (int)LowWidth.getKnownMinValue() <= HighOffset)
1677 return true;
1678 }
1679 }
1680 return false;
1681}
1682
1684 const MachineBasicBlock *MBB,
1685 const MachineFunction &MF) const {
1687 return true;
1688
1689 // Do not move an instruction that can be recognized as a branch target.
1690 if (hasBTISemantics(MI))
1691 return true;
1692
1693 switch (MI.getOpcode()) {
1694 case AArch64::PAUTH_EPILOGUE:
1695 // Keep authentication after the other epilogue instructions and close to
1696 // the return, allowing them to combine into an authenticated return.
1697 return true;
1698 case AArch64::HINT:
1699 // CSDB hints are scheduling barriers.
1700 if (MI.getOperand(0).getImm() == 0x14)
1701 return true;
1702 break;
1703 case AArch64::DSB:
1704 case AArch64::ISB:
1705 // DSB and ISB also are scheduling barriers.
1706 return true;
1707 case AArch64::MSRpstatesvcrImm1:
1708 // SMSTART and SMSTOP are also scheduling barriers.
1709 return true;
1710 default:;
1711 }
1712 if (isSEHInstruction(MI))
1713 return true;
1714 // Skip debug instructions and pseudo probes so they do not change
1715 // scheduling regions.
1716 auto Next = next_nodbg(MI.getIterator(), MBB->instr_end());
1717 return Next != MBB->instr_end() && Next->isCFIInstruction();
1718}
1719
1720/// analyzeCompare - For a comparison instruction, return the source registers
1721/// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1722/// Return true if the comparison instruction can be analyzed.
1724 Register &SrcReg2, int64_t &CmpMask,
1725 int64_t &CmpValue) const {
1726 // The first operand can be a frame index where we'd normally expect a
1727 // register.
1728 // FIXME: Pass subregisters out of analyzeCompare
1729 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1730 if (!MI.getOperand(1).isReg() || MI.getOperand(1).getSubReg())
1731 return false;
1732
1733 switch (MI.getOpcode()) {
1734 default:
1735 break;
1736 case AArch64::PTEST_PP:
1737 case AArch64::PTEST_PP_ANY:
1738 case AArch64::PTEST_PP_FIRST:
1739 SrcReg = MI.getOperand(0).getReg();
1740 SrcReg2 = MI.getOperand(1).getReg();
1741 if (MI.getOperand(2).getSubReg())
1742 return false;
1743
1744 // Not sure about the mask and value for now...
1745 CmpMask = ~0;
1746 CmpValue = 0;
1747 return true;
1748 case AArch64::SUBSWrr:
1749 case AArch64::SUBSWrs:
1750 case AArch64::SUBSWrx:
1751 case AArch64::SUBSXrr:
1752 case AArch64::SUBSXrs:
1753 case AArch64::SUBSXrx:
1754 case AArch64::ADDSWrr:
1755 case AArch64::ADDSWrs:
1756 case AArch64::ADDSWrx:
1757 case AArch64::ADDSXrr:
1758 case AArch64::ADDSXrs:
1759 case AArch64::ADDSXrx:
1760 // Replace SUBSWrr with SUBWrr if NZCV is not used.
1761 SrcReg = MI.getOperand(1).getReg();
1762 SrcReg2 = MI.getOperand(2).getReg();
1763
1764 // FIXME: Pass subregisters out of analyzeCompare
1765 if (MI.getOperand(2).getSubReg())
1766 return false;
1767
1768 CmpMask = ~0;
1769 CmpValue = 0;
1770 return true;
1771 case AArch64::SUBSWri:
1772 case AArch64::ADDSWri:
1773 case AArch64::SUBSXri:
1774 case AArch64::ADDSXri:
1775 SrcReg = MI.getOperand(1).getReg();
1776 SrcReg2 = 0;
1777 CmpMask = ~0;
1778 CmpValue = MI.getOperand(2).getImm();
1779 return true;
1780 case AArch64::ANDSWri:
1781 case AArch64::ANDSXri:
1782 // ANDS does not use the same encoding scheme as the others xxxS
1783 // instructions.
1784 SrcReg = MI.getOperand(1).getReg();
1785 SrcReg2 = 0;
1786 CmpMask = ~0;
1788 MI.getOperand(2).getImm(),
1789 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1790 return true;
1791 }
1792
1793 return false;
1794}
1795
1797 MachineBasicBlock *MBB = Instr.getParent();
1798 assert(MBB && "Can't get MachineBasicBlock here");
1799 MachineFunction *MF = MBB->getParent();
1800 assert(MF && "Can't get MachineFunction here");
1804
1805 for (const auto &[OpIdx, MO] : enumerate(Instr.operands())) {
1806 if (!MO.isReg() || !MO.getReg().isVirtual())
1807 continue;
1808
1809 Register Reg = MO.getReg();
1810 const TargetRegisterClass *NewRC = Instr.getRegClassConstraintEffect(
1811 OpIdx, MRI->getRegClass(Reg), TII, TRI);
1812 if (!NewRC || !MRI->constrainRegClass(Reg, NewRC))
1813 llvm_unreachable("Operand register classes are incompatible");
1814 }
1815}
1816
1817/// Return the opcode that does not set flags when possible - otherwise
1818/// return the original opcode. The caller is responsible to do the actual
1819/// substitution and legality checking.
1821 // Don't convert all compare instructions, because for some the zero register
1822 // encoding becomes the sp register.
1823 bool MIDefinesZeroReg = false;
1824 if (MI.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
1825 MI.definesRegister(AArch64::XZR, /*TRI=*/nullptr))
1826 MIDefinesZeroReg = true;
1827
1828 switch (MI.getOpcode()) {
1829 default:
1830 return MI.getOpcode();
1831 case AArch64::ADDSWrr:
1832 return AArch64::ADDWrr;
1833 case AArch64::ADDSWri:
1834 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1835 case AArch64::ADDSWrs:
1836 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1837 case AArch64::ADDSWrx:
1838 return AArch64::ADDWrx;
1839 case AArch64::ADDSXrr:
1840 return AArch64::ADDXrr;
1841 case AArch64::ADDSXri:
1842 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1843 case AArch64::ADDSXrs:
1844 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1845 case AArch64::ADDSXrx:
1846 return AArch64::ADDXrx;
1847 case AArch64::SUBSWrr:
1848 return AArch64::SUBWrr;
1849 case AArch64::SUBSWri:
1850 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1851 case AArch64::SUBSWrs:
1852 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1853 case AArch64::SUBSWrx:
1854 return AArch64::SUBWrx;
1855 case AArch64::SUBSXrr:
1856 return AArch64::SUBXrr;
1857 case AArch64::SUBSXri:
1858 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1859 case AArch64::SUBSXrs:
1860 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1861 case AArch64::SUBSXrx:
1862 return AArch64::SUBXrx;
1863 }
1864}
1865
1866enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1867
1868/// True when condition flags are accessed (either by writing or reading)
1869/// on the instruction trace starting at From and ending at To.
1870///
1871/// Note: If From and To are from different blocks it's assumed CC are accessed
1872/// on the path.
1875 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1876 // Early exit if To is at the beginning of the BB.
1877 if (To == To->getParent()->begin())
1878 return true;
1879
1880 // Check whether the instructions are in the same basic block
1881 // If not, assume the condition flags might get modified somewhere.
1882 if (To->getParent() != From->getParent())
1883 return true;
1884
1885 // From must be above To.
1886 assert(std::any_of(
1887 ++To.getReverse(), To->getParent()->rend(),
1888 [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1889
1890 // We iterate backward starting at \p To until we hit \p From.
1891 for (const MachineInstr &Instr :
1893 if (((AccessToCheck & AK_Write) &&
1894 Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1895 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1896 return true;
1897 }
1898 return false;
1899}
1900
1901std::optional<unsigned>
1902AArch64InstrInfo::canRemovePTestInstr(MachineInstr *PTest, MachineInstr *Mask,
1904 const MachineRegisterInfo *MRI) const {
1905 unsigned MaskOpcode = Mask->getOpcode();
1906 unsigned PredOpcode = Pred->getOpcode();
1907 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1908 bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1909
1910 if (PredIsWhileLike) {
1911 // For PTEST(PG, PG), PTEST is redundant when PG is the result of a WHILEcc
1912 // instruction and the condition is "any" since WHILcc does an implicit
1913 // PTEST(ALL, PG) check and PG is always a subset of ALL.
1914 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1915 return PredOpcode;
1916
1917 // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
1918 // redundant since WHILE performs an implicit PTEST with an all active
1919 // mask.
1920 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1921 getElementSizeForOpcode(MaskOpcode) ==
1922 getElementSizeForOpcode(PredOpcode))
1923 return PredOpcode;
1924
1925 // For PTEST_FIRST(PTRUE_ALL, WHILE), the PTEST_FIRST is redundant since
1926 // WHILEcc performs an implicit PTEST with an all active mask, setting
1927 // the N flag as the PTEST_FIRST would.
1928 if (PTest->getOpcode() == AArch64::PTEST_PP_FIRST &&
1929 isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31)
1930 return PredOpcode;
1931
1932 return {};
1933 }
1934
1935 if (PredIsPTestLike) {
1936 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1937 // instruction that sets the flags as PTEST would and the condition is
1938 // "any" since PG is always a subset of the governing predicate of the
1939 // ptest-like instruction.
1940 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1941 return PredOpcode;
1942
1943 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1944
1945 // If the PTEST like instruction's general predicate is not `Mask`, attempt
1946 // to look through a copy and try again. This is because some instructions
1947 // take a predicate whose register class is a subset of its result class.
1948 if (Mask != PTestLikeMask && PTestLikeMask->isFullCopy() &&
1949 PTestLikeMask->getOperand(1).getReg().isVirtual())
1950 PTestLikeMask =
1951 MRI->getUniqueVRegDef(PTestLikeMask->getOperand(1).getReg());
1952
1953 // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
1954 // the element size matches and either the PTEST_LIKE instruction uses
1955 // the same all active mask or the condition is "any".
1956 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1957 getElementSizeForOpcode(MaskOpcode) ==
1958 getElementSizeForOpcode(PredOpcode)) {
1959 if (Mask == PTestLikeMask || PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1960 return PredOpcode;
1961 }
1962
1963 // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
1964 // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
1965 // on 8-bit predicates like the PTEST. Otherwise, for instructions like
1966 // compare that also support 16/32/64-bit predicates, the implicit PTEST
1967 // performed by the compare could consider fewer lanes for these element
1968 // sizes.
1969 //
1970 // For example, consider
1971 //
1972 // ptrue p0.b ; P0=1111-1111-1111-1111
1973 // index z0.s, #0, #1 ; Z0=<0,1,2,3>
1974 // index z1.s, #1, #1 ; Z1=<1,2,3,4>
1975 // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
1976 // ; ^ last active
1977 // ptest p0, p1.b ; P1=0001-0001-0001-0001
1978 // ; ^ last active
1979 //
1980 // where the compare generates a canonical all active 32-bit predicate
1981 // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
1982 // active flag, whereas the PTEST instruction with the same mask doesn't.
1983 // For PTEST_ANY this doesn't apply as the flags in this case would be
1984 // identical regardless of element size.
1985 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1986 if (Mask == PTestLikeMask && (PredElementSize == AArch64::ElementSizeB ||
1987 PTest->getOpcode() == AArch64::PTEST_PP_ANY))
1988 return PredOpcode;
1989
1990 return {};
1991 }
1992
1993 // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
1994 // opcode so the PTEST becomes redundant.
1995 switch (PredOpcode) {
1996 case AArch64::AND_PPzPP:
1997 case AArch64::BIC_PPzPP:
1998 case AArch64::EOR_PPzPP:
1999 case AArch64::NAND_PPzPP:
2000 case AArch64::NOR_PPzPP:
2001 case AArch64::ORN_PPzPP:
2002 case AArch64::ORR_PPzPP:
2003 case AArch64::BRKA_PPzP:
2004 case AArch64::BRKPA_PPzPP:
2005 case AArch64::BRKB_PPzP:
2006 case AArch64::BRKPB_PPzPP:
2007 case AArch64::RDFFR_PPz: {
2008 // Check to see if our mask is the same. If not the resulting flag bits
2009 // may be different and we can't remove the ptest.
2010 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
2011 if (Mask != PredMask)
2012 return {};
2013 break;
2014 }
2015 case AArch64::BRKN_PPzP: {
2016 // BRKN uses an all active implicit mask to set flags unlike the other
2017 // flag-setting instructions.
2018 // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
2019 if ((MaskOpcode != AArch64::PTRUE_B) ||
2020 (Mask->getOperand(1).getImm() != 31))
2021 return {};
2022 break;
2023 }
2024 case AArch64::PTRUE_B:
2025 // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
2026 break;
2027 default:
2028 // Bail out if we don't recognize the input
2029 return {};
2030 }
2031
2032 return convertToFlagSettingOpc(PredOpcode);
2033}
2034
2035/// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
2036/// operation which could set the flags in an identical manner
2037bool AArch64InstrInfo::optimizePTestInstr(
2038 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
2039 const MachineRegisterInfo *MRI) const {
2040 auto *Mask = MRI->getUniqueVRegDef(MaskReg);
2041 auto *Pred = MRI->getUniqueVRegDef(PredReg);
2042
2043 if (Pred->isCopy() && PTest->getOpcode() == AArch64::PTEST_PP_FIRST) {
2044 // Instructions which return a multi-vector (e.g. WHILECC_x2) require copies
2045 // before the branch to extract each subregister.
2046 auto Op = Pred->getOperand(1);
2047 if (Op.isReg() && Op.getReg().isVirtual() &&
2048 Op.getSubReg() == AArch64::psub0)
2049 Pred = MRI->getUniqueVRegDef(Op.getReg());
2050 }
2051
2052 unsigned PredOpcode = Pred->getOpcode();
2053 auto NewOp = canRemovePTestInstr(PTest, Mask, Pred, MRI);
2054 if (!NewOp)
2055 return false;
2056
2057 const TargetRegisterInfo *TRI = &getRegisterInfo();
2058
2059 // If another instruction between Pred and PTest accesses flags, don't remove
2060 // the ptest or update the earlier instruction to modify them.
2062 return false;
2063
2064 // If we pass all the checks, it's safe to remove the PTEST and use the flags
2065 // as they are prior to PTEST. Sometimes this requires the tested PTEST
2066 // operand to be replaced with an equivalent instruction that also sets the
2067 // flags.
2068 PTest->eraseFromParent();
2069 if (*NewOp != PredOpcode) {
2070 Pred->setDesc(get(*NewOp));
2072 Pred->addRegisterDefined(AArch64::NZCV, TRI);
2073 }
2074
2075 // Ensure that the flags def is live.
2076 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
2077 unsigned i = 0, e = Pred->getNumOperands();
2078 for (; i != e; ++i) {
2079 MachineOperand &MO = Pred->getOperand(i);
2080 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
2081 MO.setIsDead(false);
2082 break;
2083 }
2084 }
2085 }
2086 return true;
2087}
2088
2089/// Try to optimize a compare instruction. A compare instruction is an
2090/// instruction which produces AArch64::NZCV. It can be truly compare
2091/// instruction
2092/// when there are no uses of its destination register.
2093///
2094/// The following steps are tried in order:
2095/// 1. Convert CmpInstr into an unconditional version.
2096/// 2. Remove CmpInstr if above there is an instruction producing a needed
2097/// condition code or an instruction which can be converted into such an
2098/// instruction.
2099/// Only comparison with zero is supported.
2101 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
2102 int64_t CmpValue, const MachineRegisterInfo *MRI) const {
2103 assert(CmpInstr.getParent());
2104 assert(MRI);
2105
2106 // Replace SUBSWrr with SUBWrr if NZCV is not used.
2107 int DeadNZCVIdx =
2108 CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
2109 if (DeadNZCVIdx != -1) {
2110 if (CmpInstr.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
2111 CmpInstr.definesRegister(AArch64::XZR, /*TRI=*/nullptr)) {
2112 CmpInstr.eraseFromParent();
2113 return true;
2114 }
2115 unsigned Opc = CmpInstr.getOpcode();
2116 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
2117 if (NewOpc == Opc)
2118 return false;
2119 const MCInstrDesc &MCID = get(NewOpc);
2120 CmpInstr.setDesc(MCID);
2121 CmpInstr.removeOperand(DeadNZCVIdx);
2122 updateOperandRegClass(CmpInstr);
2123 return true;
2124 }
2125
2126 if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
2127 CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY ||
2128 CmpInstr.getOpcode() == AArch64::PTEST_PP_FIRST)
2129 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
2130
2131 if (SrcReg2 != 0)
2132 return false;
2133
2134 // CmpInstr is a Compare instruction if destination register is not used.
2135 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
2136 return false;
2137
2138 if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
2139 return true;
2140 return (CmpValue == 0 || CmpValue == 1) &&
2141 removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
2142}
2143
2144/// Get opcode of S version of Instr.
2145/// If Instr is S version its opcode is returned.
2146/// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
2147/// or we are not interested in it.
2148static unsigned sForm(MachineInstr &Instr) {
2149 switch (Instr.getOpcode()) {
2150 default:
2151 return AArch64::INSTRUCTION_LIST_END;
2152
2153 case AArch64::ADDSWrr:
2154 case AArch64::ADDSWri:
2155 case AArch64::ADDSXrr:
2156 case AArch64::ADDSXri:
2157 case AArch64::ADDSWrx:
2158 case AArch64::ADDSXrx:
2159 case AArch64::ADDSWrs:
2160 case AArch64::ADDSXrs:
2161 case AArch64::SUBSWrr:
2162 case AArch64::SUBSWri:
2163 case AArch64::SUBSWrx:
2164 case AArch64::SUBSWrs:
2165 case AArch64::SUBSXrr:
2166 case AArch64::SUBSXri:
2167 case AArch64::SUBSXrx:
2168 case AArch64::SUBSXrs:
2169 case AArch64::ANDSWri:
2170 case AArch64::ANDSWrr:
2171 case AArch64::ANDSWrs:
2172 case AArch64::ANDSXri:
2173 case AArch64::ANDSXrr:
2174 case AArch64::ANDSXrs:
2175 case AArch64::BICSWrr:
2176 case AArch64::BICSXrr:
2177 case AArch64::BICSWrs:
2178 case AArch64::BICSXrs:
2179 case AArch64::ADCSWr:
2180 case AArch64::ADCSXr:
2181 case AArch64::SBCSWr:
2182 case AArch64::SBCSXr:
2183 return Instr.getOpcode();
2184
2185 case AArch64::ADDWrr:
2186 return AArch64::ADDSWrr;
2187 case AArch64::ADDWri:
2188 return AArch64::ADDSWri;
2189 case AArch64::ADDXrr:
2190 return AArch64::ADDSXrr;
2191 case AArch64::ADDXri:
2192 return AArch64::ADDSXri;
2193 case AArch64::ADDWrx:
2194 return AArch64::ADDSWrx;
2195 case AArch64::ADDXrx:
2196 return AArch64::ADDSXrx;
2197 case AArch64::ADDWrs:
2198 return AArch64::ADDSWrs;
2199 case AArch64::ADDXrs:
2200 return AArch64::ADDSXrs;
2201 case AArch64::ADCWr:
2202 return AArch64::ADCSWr;
2203 case AArch64::ADCXr:
2204 return AArch64::ADCSXr;
2205 case AArch64::SUBWrr:
2206 return AArch64::SUBSWrr;
2207 case AArch64::SUBWri:
2208 return AArch64::SUBSWri;
2209 case AArch64::SUBXrr:
2210 return AArch64::SUBSXrr;
2211 case AArch64::SUBXri:
2212 return AArch64::SUBSXri;
2213 case AArch64::SUBWrx:
2214 return AArch64::SUBSWrx;
2215 case AArch64::SUBXrx:
2216 return AArch64::SUBSXrx;
2217 case AArch64::SUBWrs:
2218 return AArch64::SUBSWrs;
2219 case AArch64::SUBXrs:
2220 return AArch64::SUBSXrs;
2221 case AArch64::SBCWr:
2222 return AArch64::SBCSWr;
2223 case AArch64::SBCXr:
2224 return AArch64::SBCSXr;
2225 case AArch64::ANDWri:
2226 return AArch64::ANDSWri;
2227 case AArch64::ANDXri:
2228 return AArch64::ANDSXri;
2229 case AArch64::ANDWrr:
2230 return AArch64::ANDSWrr;
2231 case AArch64::ANDWrs:
2232 return AArch64::ANDSWrs;
2233 case AArch64::ANDXrr:
2234 return AArch64::ANDSXrr;
2235 case AArch64::ANDXrs:
2236 return AArch64::ANDSXrs;
2237 case AArch64::BICWrr:
2238 return AArch64::BICSWrr;
2239 case AArch64::BICXrr:
2240 return AArch64::BICSXrr;
2241 case AArch64::BICWrs:
2242 return AArch64::BICSWrs;
2243 case AArch64::BICXrs:
2244 return AArch64::BICSXrs;
2245 }
2246}
2247
2248/// Check if AArch64::NZCV should be alive in successors of MBB.
2250 for (auto *BB : MBB->successors())
2251 if (BB->isLiveIn(AArch64::NZCV))
2252 return true;
2253 return false;
2254}
2255
2256/// \returns The condition code operand index for \p Instr if it is a branch
2257/// or select and -1 otherwise.
2258int AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
2259 const MachineInstr &Instr) {
2260 switch (Instr.getOpcode()) {
2261 default:
2262 return -1;
2263
2264 case AArch64::Bcc: {
2265 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2266 assert(Idx >= 2);
2267 return Idx - 2;
2268 }
2269
2270 case AArch64::CSINVWr:
2271 case AArch64::CSINVXr:
2272 case AArch64::CSINCWr:
2273 case AArch64::CSINCXr:
2274 case AArch64::CSELWr:
2275 case AArch64::CSELXr:
2276 case AArch64::CSNEGWr:
2277 case AArch64::CSNEGXr:
2278 case AArch64::FCSELSrrr:
2279 case AArch64::FCSELDrrr: {
2280 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2281 assert(Idx >= 1);
2282 return Idx - 1;
2283 }
2284 }
2285}
2286
2287/// Find a condition code used by the instruction.
2288/// Returns AArch64CC::Invalid if either the instruction does not use condition
2289/// codes or we don't optimize CmpInstr in the presence of such instructions.
2291 int CCIdx =
2292 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(Instr);
2293 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
2294 Instr.getOperand(CCIdx).getImm())
2296}
2297
2300 UsedNZCV UsedFlags;
2301 switch (CC) {
2302 default:
2303 break;
2304
2305 case AArch64CC::EQ: // Z set
2306 case AArch64CC::NE: // Z clear
2307 UsedFlags.Z = true;
2308 break;
2309
2310 case AArch64CC::HI: // Z clear and C set
2311 case AArch64CC::LS: // Z set or C clear
2312 UsedFlags.Z = true;
2313 [[fallthrough]];
2314 case AArch64CC::HS: // C set
2315 case AArch64CC::LO: // C clear
2316 UsedFlags.C = true;
2317 break;
2318
2319 case AArch64CC::MI: // N set
2320 case AArch64CC::PL: // N clear
2321 UsedFlags.N = true;
2322 break;
2323
2324 case AArch64CC::VS: // V set
2325 case AArch64CC::VC: // V clear
2326 UsedFlags.V = true;
2327 break;
2328
2329 case AArch64CC::GT: // Z clear, N and V the same
2330 case AArch64CC::LE: // Z set, N and V differ
2331 UsedFlags.Z = true;
2332 [[fallthrough]];
2333 case AArch64CC::GE: // N and V the same
2334 case AArch64CC::LT: // N and V differ
2335 UsedFlags.N = true;
2336 UsedFlags.V = true;
2337 break;
2338 }
2339 return UsedFlags;
2340}
2341
2342/// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
2343/// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
2344/// \returns std::nullopt otherwise.
2345///
2346/// Collect instructions using that flags in \p CCUseInstrs if provided.
2347std::optional<UsedNZCV>
2349 const TargetRegisterInfo &TRI,
2350 SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
2351 MachineBasicBlock *CmpParent = CmpInstr.getParent();
2352 if (MI.getParent() != CmpParent)
2353 return std::nullopt;
2354
2355 if (areCFlagsAliveInSuccessors(CmpParent))
2356 return std::nullopt;
2357
2358 UsedNZCV NZCVUsedAfterCmp;
2360 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
2361 if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
2363 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
2364 return std::nullopt;
2365 NZCVUsedAfterCmp |= getUsedNZCV(CC);
2366 if (CCUseInstrs)
2367 CCUseInstrs->push_back(&Instr);
2368 }
2369 if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
2370 break;
2371 }
2372 return NZCVUsedAfterCmp;
2373}
2374
2375static bool isADDSRegImm(unsigned Opcode) {
2376 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
2377}
2378
2379static bool isSUBSRegImm(unsigned Opcode) {
2380 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
2381}
2382
2384 unsigned Opc = sForm(MI);
2385 switch (Opc) {
2386 case AArch64::ANDSWri:
2387 case AArch64::ANDSWrr:
2388 case AArch64::ANDSWrs:
2389 case AArch64::ANDSXri:
2390 case AArch64::ANDSXrr:
2391 case AArch64::ANDSXrs:
2392 case AArch64::BICSWrr:
2393 case AArch64::BICSXrr:
2394 case AArch64::BICSWrs:
2395 case AArch64::BICSXrs:
2396 return true;
2397 default:
2398 return false;
2399 }
2400}
2401
2402/// Check if CmpInstr can be substituted by MI.
2403///
2404/// CmpInstr can be substituted:
2405/// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2406/// - and, MI and CmpInstr are from the same MachineBB
2407/// - and, condition flags are not alive in successors of the CmpInstr parent
2408/// - and, if MI opcode is the S form there must be no defs of flags between
2409/// MI and CmpInstr
2410/// or if MI opcode is not the S form there must be neither defs of flags
2411/// nor uses of flags between MI and CmpInstr.
2412/// - and, C is not used after CmpInstr; CmpInstr's C is from adds/subs #0 on
2413/// SrcReg and can differ from MI (e.g. carry out of ADCS/SBCS).
2414/// - and, V is not used after CmpInstr unless MI is AND/BIC (V cleared) or MI
2415/// has NoSWrap (overflow is poison and the fold is still safe).
2417 const TargetRegisterInfo &TRI) {
2418 // MI is an opcode sForm maps (add/sub/adc/sbc/and/bic and their S forms).
2419 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
2420
2421 const unsigned CmpOpcode = CmpInstr.getOpcode();
2422 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
2423 return false;
2424
2425 assert((CmpInstr.getOperand(2).isImm() &&
2426 CmpInstr.getOperand(2).getImm() == 0) &&
2427 "Caller guarantees that CmpInstr compares with constant 0");
2428
2429 std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
2430 if (!NZVCUsed || NZVCUsed->C)
2431 return false;
2432
2433 // CmpInstr is ADDS/SUBS with immediate 0 on SrcReg (compare SrcReg to zero).
2434 // After the fold, users see NZCV from MI (or its S form), not from CmpInstr.
2435 // N/Z match CmpInstr for the value in SrcReg; C/V need not match in general
2436 // (e.g. ADCS vs adds #0), so we require C unused after CmpInstr and gate V
2437 // as below. NoSWrap makes signed overflow poison; AND/BIC clear V.
2438 if (NZVCUsed->V && !MI.getFlag(MachineInstr::NoSWrap) && !isANDOpcode(MI))
2439 return false;
2440
2441 AccessKind AccessToCheck = AK_Write;
2442 if (sForm(MI) != MI.getOpcode())
2443 AccessToCheck = AK_All;
2444 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
2445}
2446
2447/// Substitute an instruction comparing to zero with another instruction
2448/// which produces needed condition flags.
2449///
2450/// Return true on success.
2451bool AArch64InstrInfo::substituteCmpToZero(
2452 MachineInstr &CmpInstr, unsigned SrcReg,
2453 const MachineRegisterInfo &MRI) const {
2454 // Get the unique definition of SrcReg.
2455 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2456 if (!MI)
2457 return false;
2458
2459 const TargetRegisterInfo &TRI = getRegisterInfo();
2460
2461 unsigned NewOpc = sForm(*MI);
2462 if (NewOpc == AArch64::INSTRUCTION_LIST_END)
2463 return false;
2464
2465 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
2466 return false;
2467
2468 // Update the instruction to set NZCV.
2469 MI->setDesc(get(NewOpc));
2470 CmpInstr.eraseFromParent();
2472 MI->addRegisterDefined(AArch64::NZCV, &TRI);
2473 return true;
2474}
2475
2476/// \returns True if \p CmpInstr can be removed.
2477///
2478/// \p IsInvertCC is true if, after removing \p CmpInstr, condition
2479/// codes used in \p CCUseInstrs must be inverted.
2481 int CmpValue, const TargetRegisterInfo &TRI,
2483 bool &IsInvertCC) {
2484 assert((CmpValue == 0 || CmpValue == 1) &&
2485 "Only comparisons to 0 or 1 considered for removal!");
2486
2487 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
2488 unsigned MIOpc = MI.getOpcode();
2489 if (MIOpc == AArch64::CSINCWr) {
2490 if (MI.getOperand(1).getReg() != AArch64::WZR ||
2491 MI.getOperand(2).getReg() != AArch64::WZR)
2492 return false;
2493 } else if (MIOpc == AArch64::CSINCXr) {
2494 if (MI.getOperand(1).getReg() != AArch64::XZR ||
2495 MI.getOperand(2).getReg() != AArch64::XZR)
2496 return false;
2497 } else {
2498 return false;
2499 }
2501 if (MICC == AArch64CC::Invalid)
2502 return false;
2503
2504 // NZCV needs to be defined
2505 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) != -1)
2506 return false;
2507
2508 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
2509 const unsigned CmpOpcode = CmpInstr.getOpcode();
2510 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
2511 if (CmpValue && !IsSubsRegImm)
2512 return false;
2513 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
2514 return false;
2515
2516 // MI conditions allowed: eq, ne, mi, pl
2517 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
2518 if (MIUsedNZCV.C || MIUsedNZCV.V)
2519 return false;
2520
2521 std::optional<UsedNZCV> NZCVUsedAfterCmp =
2522 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
2523 // Condition flags are not used in CmpInstr basic block successors and only
2524 // Z or N flags allowed to be used after CmpInstr within its basic block
2525 if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
2526 return false;
2527 // Z or N flag used after CmpInstr must correspond to the flag used in MI
2528 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
2529 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
2530 return false;
2531 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
2532 if (MIUsedNZCV.N && !CmpValue)
2533 return false;
2534
2535 // There must be no defs of flags between MI and CmpInstr
2536 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
2537 return false;
2538
2539 // Condition code is inverted in the following cases:
2540 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2541 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
2542 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
2543 (!CmpValue && MICC == AArch64CC::NE);
2544 return true;
2545}
2546
2547/// Remove comparison in csinc-cmp sequence
2548///
2549/// Examples:
2550/// 1. \code
2551/// csinc w9, wzr, wzr, ne
2552/// cmp w9, #0
2553/// b.eq
2554/// \endcode
2555/// to
2556/// \code
2557/// csinc w9, wzr, wzr, ne
2558/// b.ne
2559/// \endcode
2560///
2561/// 2. \code
2562/// csinc x2, xzr, xzr, mi
2563/// cmp x2, #1
2564/// b.pl
2565/// \endcode
2566/// to
2567/// \code
2568/// csinc x2, xzr, xzr, mi
2569/// b.pl
2570/// \endcode
2571///
2572/// \param CmpInstr comparison instruction
2573/// \return True when comparison removed
2574bool AArch64InstrInfo::removeCmpToZeroOrOne(
2575 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
2576 const MachineRegisterInfo &MRI) const {
2577 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2578 if (!MI)
2579 return false;
2580 const TargetRegisterInfo &TRI = getRegisterInfo();
2581 SmallVector<MachineInstr *, 4> CCUseInstrs;
2582 bool IsInvertCC = false;
2583 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
2584 IsInvertCC))
2585 return false;
2586 // Make transformation
2587 CmpInstr.eraseFromParent();
2588 if (IsInvertCC) {
2589 // Invert condition codes in CmpInstr CC users
2590 for (MachineInstr *CCUseInstr : CCUseInstrs) {
2591 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
2592 assert(Idx >= 0 && "Unexpected instruction using CC.");
2593 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
2595 static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
2596 CCOperand.setImm(CCUse);
2597 }
2598 }
2599 return true;
2600}
2601
2602bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2603 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
2604 MI.getOpcode() != AArch64::CATCHRET &&
2605 MI.getOpcode() != AArch64::STACK_GUARD_UNMIX)
2606 return false;
2607
2608 MachineBasicBlock &MBB = *MI.getParent();
2609 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
2610 auto TRI = Subtarget.getRegisterInfo();
2611 DebugLoc DL = MI.getDebugLoc();
2612
2613 if (MI.getOpcode() == AArch64::STACK_GUARD_UNMIX) {
2614 // Expand STACK_GUARD_UNMIX to: sub Rd, fp, Rs
2615 // This computes FP - stored_mixed_value to unmix the cookie
2616 Register DstReg = MI.getOperand(0).getReg();
2617 Register SrcReg = MI.getOperand(1).getReg();
2618
2619 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), DstReg)
2620 .addReg(AArch64::FP)
2621 .addReg(SrcReg);
2622
2623 MBB.erase(MI);
2624 return true;
2625 }
2626
2627 if (MI.getOpcode() == AArch64::CATCHRET) {
2628 // Skip to the first instruction before the epilog.
2629 const TargetInstrInfo *TII =
2631 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
2633 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
2634 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
2635 FirstEpilogSEH != MBB.begin())
2636 FirstEpilogSEH = std::prev(FirstEpilogSEH);
2637 if (FirstEpilogSEH != MBB.begin())
2638 FirstEpilogSEH = std::next(FirstEpilogSEH);
2639 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
2640 .addReg(AArch64::X0, RegState::Define)
2641 .addMBB(TargetMBB, AArch64II::MO_PAGE);
2642 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
2643 .addReg(AArch64::X0, RegState::Define)
2644 .addReg(AArch64::X0)
2646 .addImm(0);
2647 TargetMBB->setMachineBlockAddressTaken();
2648 return true;
2649 }
2650
2651 Register Reg = MI.getOperand(0).getReg();
2653 if (M.getStackProtectorGuard() == "sysreg") {
2654 const AArch64SysReg::SysReg *SrcReg =
2655 AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
2656 if (!SrcReg)
2657 report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
2658
2659 // mrs xN, sysreg
2660 BuildMI(MBB, MI, DL, get(AArch64::MRS))
2662 .addImm(SrcReg->Encoding);
2663 int Offset = M.getStackProtectorGuardOffset();
2664 if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
2665 // ldr xN, [xN, #offset]
2666 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2667 .addDef(Reg)
2669 .addImm(Offset / 8);
2670 } else if (Offset >= -256 && Offset <= 255) {
2671 // ldur xN, [xN, #offset]
2672 BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
2673 .addDef(Reg)
2675 .addImm(Offset);
2676 } else if (Offset >= -4095 && Offset <= 4095) {
2677 if (Offset > 0) {
2678 // add xN, xN, #offset
2679 BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
2680 .addDef(Reg)
2682 .addImm(Offset)
2683 .addImm(0);
2684 } else {
2685 // sub xN, xN, #offset
2686 BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
2687 .addDef(Reg)
2689 .addImm(-Offset)
2690 .addImm(0);
2691 }
2692 // ldr xN, [xN]
2693 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2694 .addDef(Reg)
2696 .addImm(0);
2697 } else {
2698 // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
2699 // than 23760.
2700 // It might be nice to use AArch64::MOVi32imm here, which would get
2701 // expanded in PreSched2 after PostRA, but our lone scratch Reg already
2702 // contains the MRS result. findScratchNonCalleeSaveRegister() in
2703 // AArch64FrameLowering might help us find such a scratch register
2704 // though. If we failed to find a scratch register, we could emit a
2705 // stream of add instructions to build up the immediate. Or, we could try
2706 // to insert a AArch64::MOVi32imm before register allocation so that we
2707 // didn't need to scavenge for a scratch register.
2708 report_fatal_error("Unable to encode Stack Protector Guard Offset");
2709 }
2710 MBB.erase(MI);
2711 return true;
2712 }
2713
2714 const GlobalValue *GV =
2715 cast<GlobalValue>((*MI.memoperands_begin())->getValue());
2716 const TargetMachine &TM = MBB.getParent()->getTarget();
2717 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
2718 const unsigned char MO_NC = AArch64II::MO_NC;
2719
2720 unsigned GuardWidth = M.getStackProtectorGuardValueWidth().value_or(
2721 Subtarget.isTargetILP32() ? 4 : 8);
2722 if (GuardWidth != 4 && GuardWidth != 8)
2723 report_fatal_error("Unsupported stack protector value width");
2724 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2725 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
2726 .addGlobalAddress(GV, 0, OpFlags);
2727 if (GuardWidth == 4) {
2728 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2729 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2730 .addDef(Reg32)
2732 .addImm(0)
2733 .addMemOperand(*MI.memoperands_begin())
2735 } else {
2736 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2738 .addImm(0)
2739 .addMemOperand(*MI.memoperands_begin());
2740 }
2741 } else if (TM.getCodeModel() == CodeModel::Large) {
2742 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
2743 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
2744 .addImm(0);
2745 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2747 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
2748 .addImm(16);
2749 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2751 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
2752 .addImm(32);
2753 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2756 .addImm(48);
2757 if (GuardWidth == 4) {
2758 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2759 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2760 .addDef(Reg32)
2762 .addImm(0)
2763 .addMemOperand(*MI.memoperands_begin())
2765 } else {
2766 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2768 .addImm(0)
2769 .addMemOperand(*MI.memoperands_begin());
2770 }
2771 } else {
2772 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
2773 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
2774 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2775 if (GuardWidth == 4) {
2776 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2777 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2778 .addDef(Reg32)
2780 .addGlobalAddress(GV, 0, LoFlags)
2781 .addMemOperand(*MI.memoperands_begin())
2783 } else {
2784 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2786 .addGlobalAddress(GV, 0, LoFlags)
2787 .addMemOperand(*MI.memoperands_begin());
2788 }
2789 }
2790 // To match MSVC. Unlike x86_64 which uses xor instruction to mix the cookie,
2791 // we use sub instruction to mix the cookie on aarch64.
2792 // The mixing happens here in expandPostRAPseudo (after RA) to ensure we use
2793 // the final frame pointer value.
2794 if (Subtarget.getTargetTriple().isOSMSVCRT())
2795 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), Reg)
2796 .addReg(AArch64::FP)
2798
2799 MBB.erase(MI);
2800
2801 return true;
2802}
2803
2804// Return true if this instruction simply sets its single destination register
2805// to zero. This is equivalent to a register rename of the zero-register.
2807 switch (MI.getOpcode()) {
2808 default:
2809 break;
2810 case AArch64::MOVZWi:
2811 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2812 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2813 assert(MI.getDesc().getNumOperands() == 3 &&
2814 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2815 return true;
2816 }
2817 break;
2818 case AArch64::ANDWri: // and Rd, Rzr, #imm
2819 return MI.getOperand(1).getReg() == AArch64::WZR;
2820 case AArch64::ANDXri:
2821 return MI.getOperand(1).getReg() == AArch64::XZR;
2822 case TargetOpcode::COPY:
2823 return MI.getOperand(1).getReg() == AArch64::WZR;
2824 }
2825 return false;
2826}
2827
2828// Return true if this instruction simply renames a general register without
2829// modifying bits.
2831 switch (MI.getOpcode()) {
2832 default:
2833 break;
2834 case TargetOpcode::COPY: {
2835 // GPR32 copies will by lowered to ORRXrs
2836 Register DstReg = MI.getOperand(0).getReg();
2837 return DstReg.isPhysical() && (AArch64::GPR32RegClass.contains(DstReg) ||
2838 AArch64::GPR64RegClass.contains(DstReg));
2839 }
2840 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2841 if (MI.getOperand(1).getReg() == AArch64::XZR) {
2842 assert(MI.getDesc().getNumOperands() == 4 &&
2843 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2844 return true;
2845 }
2846 break;
2847 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2848 if (MI.getOperand(2).getImm() == 0) {
2849 assert(MI.getDesc().getNumOperands() == 4 &&
2850 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2851 return true;
2852 }
2853 break;
2854 }
2855 return false;
2856}
2857
2858// Return true if this instruction simply renames a general register without
2859// modifying bits.
2861 switch (MI.getOpcode()) {
2862 default:
2863 break;
2864 case TargetOpcode::COPY: {
2865 Register DstReg = MI.getOperand(0).getReg();
2866 return DstReg.isPhysical() && AArch64::FPR128RegClass.contains(DstReg);
2867 }
2868 case AArch64::ORRv16i8:
2869 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2870 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2871 "invalid ORRv16i8 operands");
2872 return true;
2873 }
2874 break;
2875 }
2876 return false;
2877}
2878
2879static bool isFrameLoadOpcode(int Opcode) {
2880 switch (Opcode) {
2881 default:
2882 return false;
2883 case AArch64::LDRWui:
2884 case AArch64::LDRXui:
2885 case AArch64::LDRBui:
2886 case AArch64::LDRHui:
2887 case AArch64::LDRSui:
2888 case AArch64::LDRDui:
2889 case AArch64::LDRQui:
2890 case AArch64::LDR_PXI:
2891 return true;
2892 }
2893}
2894
2896 int &FrameIndex) const {
2897 if (!isFrameLoadOpcode(MI.getOpcode()))
2898 return Register();
2899
2900 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2901 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2902 FrameIndex = MI.getOperand(1).getIndex();
2903 return MI.getOperand(0).getReg();
2904 }
2905 return Register();
2906}
2907
2908static bool isFrameStoreOpcode(int Opcode) {
2909 switch (Opcode) {
2910 default:
2911 return false;
2912 case AArch64::STRWui:
2913 case AArch64::STRXui:
2914 case AArch64::STRBui:
2915 case AArch64::STRHui:
2916 case AArch64::STRSui:
2917 case AArch64::STRDui:
2918 case AArch64::STRQui:
2919 case AArch64::STR_PXI:
2920 return true;
2921 }
2922}
2923
2925 int &FrameIndex) const {
2926 if (!isFrameStoreOpcode(MI.getOpcode()))
2927 return Register();
2928
2929 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2930 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2931 FrameIndex = MI.getOperand(1).getIndex();
2932 return MI.getOperand(0).getReg();
2933 }
2934 return Register();
2935}
2936
2938 int &FrameIndex) const {
2939 if (!isFrameStoreOpcode(MI.getOpcode()))
2940 return Register();
2941
2942 if (Register Reg = isStoreToStackSlot(MI, FrameIndex))
2943 return Reg;
2944
2946 if (hasStoreToStackSlot(MI, Accesses)) {
2947 if (Accesses.size() > 1)
2948 return Register();
2949
2950 FrameIndex =
2951 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2952 ->getFrameIndex();
2953 return MI.getOperand(0).getReg();
2954 }
2955 return Register();
2956}
2957
2959 int &FrameIndex) const {
2960 if (!isFrameLoadOpcode(MI.getOpcode()))
2961 return Register();
2962
2963 if (Register Reg = isLoadFromStackSlot(MI, FrameIndex))
2964 return Reg;
2965
2967 if (hasLoadFromStackSlot(MI, Accesses)) {
2968 if (Accesses.size() > 1)
2969 return Register();
2970
2971 FrameIndex =
2972 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2973 ->getFrameIndex();
2974 return MI.getOperand(0).getReg();
2975 }
2976 return Register();
2977}
2978
2979/// Check all MachineMemOperands for a hint to suppress pairing.
2981 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2982 return MMO->getFlags() & MOSuppressPair;
2983 });
2984}
2985
2986/// Set a flag on the first MachineMemOperand to suppress pairing.
2988 if (MI.memoperands_empty())
2989 return;
2990 (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2991}
2992
2993/// Check all MachineMemOperands for a hint that the load/store is strided.
2995 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2996 return MMO->getFlags() & MOStridedAccess;
2997 });
2998}
2999
3001 switch (Opc) {
3002 default:
3003 return false;
3004 case AArch64::STURSi:
3005 case AArch64::STRSpre:
3006 case AArch64::STURDi:
3007 case AArch64::STRDpre:
3008 case AArch64::STURQi:
3009 case AArch64::STRQpre:
3010 case AArch64::STURBBi:
3011 case AArch64::STURHHi:
3012 case AArch64::STURWi:
3013 case AArch64::STRWpre:
3014 case AArch64::STURXi:
3015 case AArch64::STRXpre:
3016 case AArch64::LDURSi:
3017 case AArch64::LDRSpre:
3018 case AArch64::LDURDi:
3019 case AArch64::LDRDpre:
3020 case AArch64::LDURQi:
3021 case AArch64::LDRQpre:
3022 case AArch64::LDURWi:
3023 case AArch64::LDRWpre:
3024 case AArch64::LDURXi:
3025 case AArch64::LDRXpre:
3026 case AArch64::LDRSWpre:
3027 case AArch64::LDURSWi:
3028 case AArch64::LDURHHi:
3029 case AArch64::LDURBBi:
3030 case AArch64::LDURSBWi:
3031 case AArch64::LDURSHWi:
3032 return true;
3033 }
3034}
3035
3036std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
3037 switch (Opc) {
3038 default: return {};
3039 case AArch64::PRFMui: return AArch64::PRFUMi;
3040 case AArch64::LDRXui: return AArch64::LDURXi;
3041 case AArch64::LDRWui: return AArch64::LDURWi;
3042 case AArch64::LDRBui: return AArch64::LDURBi;
3043 case AArch64::LDRHui: return AArch64::LDURHi;
3044 case AArch64::LDRSui: return AArch64::LDURSi;
3045 case AArch64::LDRDui: return AArch64::LDURDi;
3046 case AArch64::LDRQui: return AArch64::LDURQi;
3047 case AArch64::LDRBBui: return AArch64::LDURBBi;
3048 case AArch64::LDRHHui: return AArch64::LDURHHi;
3049 case AArch64::LDRSBXui: return AArch64::LDURSBXi;
3050 case AArch64::LDRSBWui: return AArch64::LDURSBWi;
3051 case AArch64::LDRSHXui: return AArch64::LDURSHXi;
3052 case AArch64::LDRSHWui: return AArch64::LDURSHWi;
3053 case AArch64::LDRSWui: return AArch64::LDURSWi;
3054 case AArch64::STRXui: return AArch64::STURXi;
3055 case AArch64::STRWui: return AArch64::STURWi;
3056 case AArch64::STRBui: return AArch64::STURBi;
3057 case AArch64::STRHui: return AArch64::STURHi;
3058 case AArch64::STRSui: return AArch64::STURSi;
3059 case AArch64::STRDui: return AArch64::STURDi;
3060 case AArch64::STRQui: return AArch64::STURQi;
3061 case AArch64::STRBBui: return AArch64::STURBBi;
3062 case AArch64::STRHHui: return AArch64::STURHHi;
3063 }
3064}
3065
3067 switch (Opc) {
3068 default:
3069 llvm_unreachable("Unhandled Opcode in getLoadStoreImmIdx");
3070 case AArch64::ADDG:
3071 case AArch64::LDAPURBi:
3072 case AArch64::LDAPURHi:
3073 case AArch64::LDAPURi:
3074 case AArch64::LDAPURSBWi:
3075 case AArch64::LDAPURSBXi:
3076 case AArch64::LDAPURSHWi:
3077 case AArch64::LDAPURSHXi:
3078 case AArch64::LDAPURSWi:
3079 case AArch64::LDAPURXi:
3080 case AArch64::LDR_PPXI:
3081 case AArch64::LDR_PXI:
3082 case AArch64::LDR_ZXI:
3083 case AArch64::LDR_ZZXI:
3084 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
3085 case AArch64::LDR_ZZZXI:
3086 case AArch64::LDR_ZZZZXI:
3087 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
3088 case AArch64::LDRBBui:
3089 case AArch64::LDRBui:
3090 case AArch64::LDRDui:
3091 case AArch64::LDRHHui:
3092 case AArch64::LDRHui:
3093 case AArch64::LDRQui:
3094 case AArch64::LDRSBWui:
3095 case AArch64::LDRSBXui:
3096 case AArch64::LDRSHWui:
3097 case AArch64::LDRSHXui:
3098 case AArch64::LDRSui:
3099 case AArch64::LDRSWui:
3100 case AArch64::LDRWui:
3101 case AArch64::LDRXui:
3102 case AArch64::LDURBBi:
3103 case AArch64::LDURBi:
3104 case AArch64::LDURDi:
3105 case AArch64::LDURHHi:
3106 case AArch64::LDURHi:
3107 case AArch64::LDURQi:
3108 case AArch64::LDURSBWi:
3109 case AArch64::LDURSBXi:
3110 case AArch64::LDURSHWi:
3111 case AArch64::LDURSHXi:
3112 case AArch64::LDURSi:
3113 case AArch64::LDURSWi:
3114 case AArch64::LDURWi:
3115 case AArch64::LDURXi:
3116 case AArch64::PRFMui:
3117 case AArch64::PRFUMi:
3118 case AArch64::ST2Gi:
3119 case AArch64::STGi:
3120 case AArch64::STLURBi:
3121 case AArch64::STLURHi:
3122 case AArch64::STLURWi:
3123 case AArch64::STLURXi:
3124 case AArch64::StoreSwiftAsyncContext:
3125 case AArch64::STR_PPXI:
3126 case AArch64::STR_PXI:
3127 case AArch64::STR_ZXI:
3128 case AArch64::STR_ZZXI:
3129 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
3130 case AArch64::STR_ZZZXI:
3131 case AArch64::STR_ZZZZXI:
3132 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
3133 case AArch64::STRBBui:
3134 case AArch64::STRBui:
3135 case AArch64::STRDui:
3136 case AArch64::STRHHui:
3137 case AArch64::STRHui:
3138 case AArch64::STRQui:
3139 case AArch64::STRSui:
3140 case AArch64::STRWui:
3141 case AArch64::STRXui:
3142 case AArch64::STURBBi:
3143 case AArch64::STURBi:
3144 case AArch64::STURDi:
3145 case AArch64::STURHHi:
3146 case AArch64::STURHi:
3147 case AArch64::STURQi:
3148 case AArch64::STURSi:
3149 case AArch64::STURWi:
3150 case AArch64::STURXi:
3151 case AArch64::STZ2Gi:
3152 case AArch64::STZGi:
3153 case AArch64::TAGPstack:
3154 case AArch64::ATOMIC_STORE_HINT_Bi:
3155 case AArch64::ATOMIC_STORE_HINT_Hi:
3156 case AArch64::ATOMIC_STORE_HINT_Wi:
3157 case AArch64::ATOMIC_STORE_HINT_Si:
3158 case AArch64::ATOMIC_STORE_HINT_Xi:
3159 case AArch64::ATOMIC_STORE_HINT_Di:
3160 case AArch64::ATOMIC_STORE_HINT_Bui:
3161 case AArch64::ATOMIC_STORE_HINT_Hui:
3162 case AArch64::ATOMIC_STORE_HINT_Wui:
3163 case AArch64::ATOMIC_STORE_HINT_Sui:
3164 case AArch64::ATOMIC_STORE_HINT_Xui:
3165 case AArch64::ATOMIC_STORE_HINT_Dui:
3166 return 2;
3167 case AArch64::LD1B_D_IMM:
3168 case AArch64::LD1B_H_IMM:
3169 case AArch64::LD1B_IMM:
3170 case AArch64::LD1B_S_IMM:
3171 case AArch64::LD1D_IMM:
3172 case AArch64::LD1H_D_IMM:
3173 case AArch64::LD1H_IMM:
3174 case AArch64::LD1H_S_IMM:
3175 case AArch64::LD1RB_D_IMM:
3176 case AArch64::LD1RB_H_IMM:
3177 case AArch64::LD1RB_IMM:
3178 case AArch64::LD1RB_S_IMM:
3179 case AArch64::LD1RD_IMM:
3180 case AArch64::LD1RH_D_IMM:
3181 case AArch64::LD1RH_IMM:
3182 case AArch64::LD1RH_S_IMM:
3183 case AArch64::LD1RSB_D_IMM:
3184 case AArch64::LD1RSB_H_IMM:
3185 case AArch64::LD1RSB_S_IMM:
3186 case AArch64::LD1RSH_D_IMM:
3187 case AArch64::LD1RSH_S_IMM:
3188 case AArch64::LD1RSW_IMM:
3189 case AArch64::LD1RW_D_IMM:
3190 case AArch64::LD1RW_IMM:
3191 case AArch64::LD1SB_D_IMM:
3192 case AArch64::LD1SB_H_IMM:
3193 case AArch64::LD1SB_S_IMM:
3194 case AArch64::LD1SH_D_IMM:
3195 case AArch64::LD1SH_S_IMM:
3196 case AArch64::LD1SW_D_IMM:
3197 case AArch64::LD1W_D_IMM:
3198 case AArch64::LD1W_IMM:
3199 case AArch64::LD2B_IMM:
3200 case AArch64::LD2D_IMM:
3201 case AArch64::LD2H_IMM:
3202 case AArch64::LD2W_IMM:
3203 case AArch64::LD3B_IMM:
3204 case AArch64::LD3D_IMM:
3205 case AArch64::LD3H_IMM:
3206 case AArch64::LD3W_IMM:
3207 case AArch64::LD4B_IMM:
3208 case AArch64::LD4D_IMM:
3209 case AArch64::LD4H_IMM:
3210 case AArch64::LD4W_IMM:
3211 case AArch64::LDG:
3212 case AArch64::LDNF1B_D_IMM:
3213 case AArch64::LDNF1B_H_IMM:
3214 case AArch64::LDNF1B_IMM:
3215 case AArch64::LDNF1B_S_IMM:
3216 case AArch64::LDNF1D_IMM:
3217 case AArch64::LDNF1H_D_IMM:
3218 case AArch64::LDNF1H_IMM:
3219 case AArch64::LDNF1H_S_IMM:
3220 case AArch64::LDNF1SB_D_IMM:
3221 case AArch64::LDNF1SB_H_IMM:
3222 case AArch64::LDNF1SB_S_IMM:
3223 case AArch64::LDNF1SH_D_IMM:
3224 case AArch64::LDNF1SH_S_IMM:
3225 case AArch64::LDNF1SW_D_IMM:
3226 case AArch64::LDNF1W_D_IMM:
3227 case AArch64::LDNF1W_IMM:
3228 case AArch64::LDNPDi:
3229 case AArch64::LDNPQi:
3230 case AArch64::LDNPSi:
3231 case AArch64::LDNPWi:
3232 case AArch64::LDNPXi:
3233 case AArch64::LDNT1B_ZRI:
3234 case AArch64::LDNT1D_ZRI:
3235 case AArch64::LDNT1H_ZRI:
3236 case AArch64::LDNT1W_ZRI:
3237 case AArch64::LDPDi:
3238 case AArch64::LDPQi:
3239 case AArch64::LDPSi:
3240 case AArch64::LDPWi:
3241 case AArch64::LDPXi:
3242 case AArch64::LDRBBpost:
3243 case AArch64::LDRBBpre:
3244 case AArch64::LDRBpost:
3245 case AArch64::LDRBpre:
3246 case AArch64::LDRDpost:
3247 case AArch64::LDRDpre:
3248 case AArch64::LDRHHpost:
3249 case AArch64::LDRHHpre:
3250 case AArch64::LDRHpost:
3251 case AArch64::LDRHpre:
3252 case AArch64::LDRQpost:
3253 case AArch64::LDRQpre:
3254 case AArch64::LDRSpost:
3255 case AArch64::LDRSpre:
3256 case AArch64::LDRWpost:
3257 case AArch64::LDRWpre:
3258 case AArch64::LDRXpost:
3259 case AArch64::LDRXpre:
3260 case AArch64::ST1B_D_IMM:
3261 case AArch64::ST1B_H_IMM:
3262 case AArch64::ST1B_IMM:
3263 case AArch64::ST1B_S_IMM:
3264 case AArch64::ST1D_IMM:
3265 case AArch64::ST1H_D_IMM:
3266 case AArch64::ST1H_IMM:
3267 case AArch64::ST1H_S_IMM:
3268 case AArch64::ST1W_D_IMM:
3269 case AArch64::ST1W_IMM:
3270 case AArch64::ST2B_IMM:
3271 case AArch64::ST2D_IMM:
3272 case AArch64::ST2H_IMM:
3273 case AArch64::ST2W_IMM:
3274 case AArch64::ST3B_IMM:
3275 case AArch64::ST3D_IMM:
3276 case AArch64::ST3H_IMM:
3277 case AArch64::ST3W_IMM:
3278 case AArch64::ST4B_IMM:
3279 case AArch64::ST4D_IMM:
3280 case AArch64::ST4H_IMM:
3281 case AArch64::ST4W_IMM:
3282 case AArch64::STGPi:
3283 case AArch64::STGPreIndex:
3284 case AArch64::STZGPreIndex:
3285 case AArch64::ST2GPreIndex:
3286 case AArch64::STZ2GPreIndex:
3287 case AArch64::STGPostIndex:
3288 case AArch64::STZGPostIndex:
3289 case AArch64::ST2GPostIndex:
3290 case AArch64::STZ2GPostIndex:
3291 case AArch64::STNPDi:
3292 case AArch64::STNPQi:
3293 case AArch64::STNPSi:
3294 case AArch64::STNPWi:
3295 case AArch64::STNPXi:
3296 case AArch64::STNT1B_ZRI:
3297 case AArch64::STNT1D_ZRI:
3298 case AArch64::STNT1H_ZRI:
3299 case AArch64::STNT1W_ZRI:
3300 case AArch64::STPDi:
3301 case AArch64::STPQi:
3302 case AArch64::STPSi:
3303 case AArch64::STPWi:
3304 case AArch64::STPXi:
3305 case AArch64::STRBBpost:
3306 case AArch64::STRBBpre:
3307 case AArch64::STRBpost:
3308 case AArch64::STRBpre:
3309 case AArch64::STRDpost:
3310 case AArch64::STRDpre:
3311 case AArch64::STRHHpost:
3312 case AArch64::STRHHpre:
3313 case AArch64::STRHpost:
3314 case AArch64::STRHpre:
3315 case AArch64::STRQpost:
3316 case AArch64::STRQpre:
3317 case AArch64::STRSpost:
3318 case AArch64::STRSpre:
3319 case AArch64::STRWpost:
3320 case AArch64::STRWpre:
3321 case AArch64::STRXpost:
3322 case AArch64::STRXpre:
3323 case AArch64::LD1B_2Z_IMM:
3324 case AArch64::LD1B_2Z_STRIDED_IMM:
3325 case AArch64::LD1H_2Z_IMM:
3326 case AArch64::LD1H_2Z_STRIDED_IMM:
3327 case AArch64::LD1W_2Z_IMM:
3328 case AArch64::LD1W_2Z_STRIDED_IMM:
3329 case AArch64::LD1D_2Z_IMM:
3330 case AArch64::LD1D_2Z_STRIDED_IMM:
3331 case AArch64::LD1B_4Z_IMM:
3332 case AArch64::LD1B_4Z_STRIDED_IMM:
3333 case AArch64::LD1H_4Z_IMM:
3334 case AArch64::LD1H_4Z_STRIDED_IMM:
3335 case AArch64::LD1W_4Z_IMM:
3336 case AArch64::LD1W_4Z_STRIDED_IMM:
3337 case AArch64::LD1D_4Z_IMM:
3338 case AArch64::LD1D_4Z_STRIDED_IMM:
3339 case AArch64::LD1B_2Z_IMM_PSEUDO:
3340 case AArch64::LD1H_2Z_IMM_PSEUDO:
3341 case AArch64::LD1W_2Z_IMM_PSEUDO:
3342 case AArch64::LD1D_2Z_IMM_PSEUDO:
3343 case AArch64::LD1B_4Z_IMM_PSEUDO:
3344 case AArch64::LD1H_4Z_IMM_PSEUDO:
3345 case AArch64::LD1W_4Z_IMM_PSEUDO:
3346 case AArch64::LD1D_4Z_IMM_PSEUDO:
3347 case AArch64::ST1B_2Z_IMM:
3348 case AArch64::ST1B_2Z_STRIDED_IMM:
3349 case AArch64::ST1H_2Z_IMM:
3350 case AArch64::ST1H_2Z_STRIDED_IMM:
3351 case AArch64::ST1W_2Z_IMM:
3352 case AArch64::ST1W_2Z_STRIDED_IMM:
3353 case AArch64::ST1D_2Z_IMM:
3354 case AArch64::ST1D_2Z_STRIDED_IMM:
3355 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
3356 case AArch64::LDNT1B_2Z_IMM:
3357 case AArch64::LDNT1B_2Z_STRIDED_IMM:
3358 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
3359 case AArch64::LDNT1H_2Z_IMM:
3360 case AArch64::LDNT1H_2Z_STRIDED_IMM:
3361 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
3362 case AArch64::LDNT1W_2Z_IMM:
3363 case AArch64::LDNT1W_2Z_STRIDED_IMM:
3364 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
3365 case AArch64::LDNT1D_2Z_IMM:
3366 case AArch64::LDNT1D_2Z_STRIDED_IMM:
3367 case AArch64::STNT1B_2Z_IMM:
3368 case AArch64::STNT1B_2Z_STRIDED_IMM:
3369 case AArch64::STNT1H_2Z_IMM:
3370 case AArch64::STNT1H_2Z_STRIDED_IMM:
3371 case AArch64::STNT1W_2Z_IMM:
3372 case AArch64::STNT1W_2Z_STRIDED_IMM:
3373 case AArch64::STNT1D_2Z_IMM:
3374 case AArch64::STNT1D_2Z_STRIDED_IMM:
3375 case AArch64::ST1B_2Z_IMM_PSEUDO:
3376 case AArch64::ST1H_2Z_IMM_PSEUDO:
3377 case AArch64::ST1W_2Z_IMM_PSEUDO:
3378 case AArch64::ST1D_2Z_IMM_PSEUDO:
3379 case AArch64::STNT1B_2Z_IMM_PSEUDO:
3380 case AArch64::STNT1H_2Z_IMM_PSEUDO:
3381 case AArch64::STNT1W_2Z_IMM_PSEUDO:
3382 case AArch64::STNT1D_2Z_IMM_PSEUDO:
3383 case AArch64::ST1B_4Z_IMM:
3384 case AArch64::ST1B_4Z_STRIDED_IMM:
3385 case AArch64::ST1H_4Z_IMM:
3386 case AArch64::ST1H_4Z_STRIDED_IMM:
3387 case AArch64::ST1W_4Z_IMM:
3388 case AArch64::ST1W_4Z_STRIDED_IMM:
3389 case AArch64::ST1D_4Z_IMM:
3390 case AArch64::ST1D_4Z_STRIDED_IMM:
3391 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
3392 case AArch64::LDNT1B_4Z_IMM:
3393 case AArch64::LDNT1B_4Z_STRIDED_IMM:
3394 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
3395 case AArch64::LDNT1H_4Z_IMM:
3396 case AArch64::LDNT1H_4Z_STRIDED_IMM:
3397 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
3398 case AArch64::LDNT1W_4Z_IMM:
3399 case AArch64::LDNT1W_4Z_STRIDED_IMM:
3400 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
3401 case AArch64::LDNT1D_4Z_IMM:
3402 case AArch64::LDNT1D_4Z_STRIDED_IMM:
3403 case AArch64::STNT1B_4Z_IMM:
3404 case AArch64::STNT1B_4Z_STRIDED_IMM:
3405 case AArch64::STNT1H_4Z_IMM:
3406 case AArch64::STNT1H_4Z_STRIDED_IMM:
3407 case AArch64::STNT1W_4Z_IMM:
3408 case AArch64::STNT1W_4Z_STRIDED_IMM:
3409 case AArch64::STNT1D_4Z_IMM:
3410 case AArch64::STNT1D_4Z_STRIDED_IMM:
3411 case AArch64::ST1B_4Z_IMM_PSEUDO:
3412 case AArch64::ST1H_4Z_IMM_PSEUDO:
3413 case AArch64::ST1W_4Z_IMM_PSEUDO:
3414 case AArch64::ST1D_4Z_IMM_PSEUDO:
3415 case AArch64::STNT1B_4Z_IMM_PSEUDO:
3416 case AArch64::STNT1H_4Z_IMM_PSEUDO:
3417 case AArch64::STNT1W_4Z_IMM_PSEUDO:
3418 case AArch64::STNT1D_4Z_IMM_PSEUDO:
3419 return 3;
3420 case AArch64::LDPDpost:
3421 case AArch64::LDPDpre:
3422 case AArch64::LDPQpost:
3423 case AArch64::LDPQpre:
3424 case AArch64::LDPSpost:
3425 case AArch64::LDPSpre:
3426 case AArch64::LDPWpost:
3427 case AArch64::LDPWpre:
3428 case AArch64::LDPXpost:
3429 case AArch64::LDPXpre:
3430 case AArch64::STGPpre:
3431 case AArch64::STGPpost:
3432 case AArch64::STPDpost:
3433 case AArch64::STPDpre:
3434 case AArch64::STPQpost:
3435 case AArch64::STPQpre:
3436 case AArch64::STPSpost:
3437 case AArch64::STPSpre:
3438 case AArch64::STPWpost:
3439 case AArch64::STPWpre:
3440 case AArch64::STPXpost:
3441 case AArch64::STPXpre:
3442 return 4;
3443 }
3444}
3445
3447 switch (MI.getOpcode()) {
3448 default:
3449 return false;
3450 // Scaled instructions.
3451 case AArch64::STRSui:
3452 case AArch64::STRDui:
3453 case AArch64::STRQui:
3454 case AArch64::STRXui:
3455 case AArch64::STRWui:
3456 case AArch64::LDRSui:
3457 case AArch64::LDRDui:
3458 case AArch64::LDRQui:
3459 case AArch64::LDRXui:
3460 case AArch64::LDRWui:
3461 case AArch64::LDRSWui:
3462 // Unscaled instructions.
3463 case AArch64::STURSi:
3464 case AArch64::STRSpre:
3465 case AArch64::STURDi:
3466 case AArch64::STRDpre:
3467 case AArch64::STURQi:
3468 case AArch64::STRQpre:
3469 case AArch64::STURWi:
3470 case AArch64::STRWpre:
3471 case AArch64::STURXi:
3472 case AArch64::STRXpre:
3473 case AArch64::LDURSi:
3474 case AArch64::LDRSpre:
3475 case AArch64::LDURDi:
3476 case AArch64::LDRDpre:
3477 case AArch64::LDURQi:
3478 case AArch64::LDRQpre:
3479 case AArch64::LDURWi:
3480 case AArch64::LDRWpre:
3481 case AArch64::LDURXi:
3482 case AArch64::LDRXpre:
3483 case AArch64::LDURSWi:
3484 case AArch64::LDRSWpre:
3485 // SVE instructions.
3486 case AArch64::LDR_ZXI:
3487 case AArch64::STR_ZXI:
3488 return true;
3489 }
3490}
3491
3493 switch (MI.getOpcode()) {
3494 default:
3495 assert((!MI.isCall() || !MI.isReturn()) &&
3496 "Unexpected instruction - was a new tail call opcode introduced?");
3497 return false;
3498 case AArch64::TCRETURNdi:
3499 case AArch64::TCRETURNri:
3500 case AArch64::TCRETURNrix16x17:
3501 case AArch64::TCRETURNrix17:
3502 case AArch64::TCRETURNrinotx16:
3503 case AArch64::TCRETURNriALL:
3504 case AArch64::AUTH_TCRETURN:
3505 case AArch64::AUTH_TCRETURN_BTI:
3506 return true;
3507 }
3508}
3509
3511 switch (Opc) {
3512 default:
3513 llvm_unreachable("Opcode has no flag setting equivalent!");
3514 // 32-bit cases:
3515 case AArch64::ADDWri:
3516 return AArch64::ADDSWri;
3517 case AArch64::ADDWrr:
3518 return AArch64::ADDSWrr;
3519 case AArch64::ADDWrs:
3520 return AArch64::ADDSWrs;
3521 case AArch64::ADDWrx:
3522 return AArch64::ADDSWrx;
3523 case AArch64::ANDWri:
3524 return AArch64::ANDSWri;
3525 case AArch64::ANDWrr:
3526 return AArch64::ANDSWrr;
3527 case AArch64::ANDWrs:
3528 return AArch64::ANDSWrs;
3529 case AArch64::BICWrr:
3530 return AArch64::BICSWrr;
3531 case AArch64::BICWrs:
3532 return AArch64::BICSWrs;
3533 case AArch64::SUBWri:
3534 return AArch64::SUBSWri;
3535 case AArch64::SUBWrr:
3536 return AArch64::SUBSWrr;
3537 case AArch64::SUBWrs:
3538 return AArch64::SUBSWrs;
3539 case AArch64::SUBWrx:
3540 return AArch64::SUBSWrx;
3541 // 64-bit cases:
3542 case AArch64::ADDXri:
3543 return AArch64::ADDSXri;
3544 case AArch64::ADDXrr:
3545 return AArch64::ADDSXrr;
3546 case AArch64::ADDXrs:
3547 return AArch64::ADDSXrs;
3548 case AArch64::ADDXrx:
3549 return AArch64::ADDSXrx;
3550 case AArch64::ANDXri:
3551 return AArch64::ANDSXri;
3552 case AArch64::ANDXrr:
3553 return AArch64::ANDSXrr;
3554 case AArch64::ANDXrs:
3555 return AArch64::ANDSXrs;
3556 case AArch64::BICXrr:
3557 return AArch64::BICSXrr;
3558 case AArch64::BICXrs:
3559 return AArch64::BICSXrs;
3560 case AArch64::SUBXri:
3561 return AArch64::SUBSXri;
3562 case AArch64::SUBXrr:
3563 return AArch64::SUBSXrr;
3564 case AArch64::SUBXrs:
3565 return AArch64::SUBSXrs;
3566 case AArch64::SUBXrx:
3567 return AArch64::SUBSXrx;
3568 // SVE instructions:
3569 case AArch64::AND_PPzPP:
3570 return AArch64::ANDS_PPzPP;
3571 case AArch64::BIC_PPzPP:
3572 return AArch64::BICS_PPzPP;
3573 case AArch64::EOR_PPzPP:
3574 return AArch64::EORS_PPzPP;
3575 case AArch64::NAND_PPzPP:
3576 return AArch64::NANDS_PPzPP;
3577 case AArch64::NOR_PPzPP:
3578 return AArch64::NORS_PPzPP;
3579 case AArch64::ORN_PPzPP:
3580 return AArch64::ORNS_PPzPP;
3581 case AArch64::ORR_PPzPP:
3582 return AArch64::ORRS_PPzPP;
3583 case AArch64::BRKA_PPzP:
3584 return AArch64::BRKAS_PPzP;
3585 case AArch64::BRKPA_PPzPP:
3586 return AArch64::BRKPAS_PPzPP;
3587 case AArch64::BRKB_PPzP:
3588 return AArch64::BRKBS_PPzP;
3589 case AArch64::BRKPB_PPzPP:
3590 return AArch64::BRKPBS_PPzPP;
3591 case AArch64::BRKN_PPzP:
3592 return AArch64::BRKNS_PPzP;
3593 case AArch64::RDFFR_PPz:
3594 return AArch64::RDFFRS_PPz;
3595 case AArch64::PTRUE_B:
3596 return AArch64::PTRUES_B;
3597 }
3598}
3599
3600// Is this a candidate for ld/st merging or pairing? For example, we don't
3601// touch volatiles or load/stores that have a hint to avoid pair formation.
3603
3604 bool IsPreLdSt = isPreLdSt(MI);
3605
3606 // If this is a volatile load/store, don't mess with it.
3607 if (MI.hasOrderedMemoryRef())
3608 return false;
3609
3610 // Make sure this is a reg/fi+imm (as opposed to an address reloc).
3611 // For Pre-inc LD/ST, the operand is shifted by one.
3612 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
3613 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
3614 "Expected a reg or frame index operand.");
3615
3616 // For Pre-indexed addressing quadword instructions, the third operand is the
3617 // immediate value.
3618 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
3619
3620 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
3621 return false;
3622
3623 // Can't merge/pair if the instruction modifies the base register.
3624 // e.g., ldr x0, [x0]
3625 // This case will never occur with an FI base.
3626 // However, if the instruction is an LDR<S,D,Q,W,X,SW>pre or
3627 // STR<S,D,Q,W,X>pre, it can be merged.
3628 // For example:
3629 // ldr q0, [x11, #32]!
3630 // ldr q1, [x11, #16]
3631 // to
3632 // ldp q0, q1, [x11, #32]!
3633 if (MI.getOperand(1).isReg() && !IsPreLdSt) {
3634 Register BaseReg = MI.getOperand(1).getReg();
3636 if (MI.modifiesRegister(BaseReg, TRI))
3637 return false;
3638 }
3639
3640 // Pairing SVE fills/spills is only valid for little-endian targets that
3641 // implement VLS 128.
3642 switch (MI.getOpcode()) {
3643 default:
3644 break;
3645 case AArch64::LDR_ZXI:
3646 case AArch64::STR_ZXI:
3647 if (!Subtarget.isLittleEndian() ||
3648 Subtarget.getSVEVectorSizeInBits() != 128)
3649 return false;
3650 }
3651
3652 // Check if this load/store has a hint to avoid pair formation.
3653 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
3655 return false;
3656
3657 // Do not pair any callee-save store/reload instructions in the
3658 // prologue/epilogue if the CFI information encoded the operations as separate
3659 // instructions, as that will cause the size of the actual prologue to mismatch
3660 // with the prologue size recorded in the Windows CFI.
3661 if ((MI.getFlag(MachineInstr::FrameSetup) ||
3662 MI.getFlag(MachineInstr::FrameDestroy)) &&
3663 MI.getMF()->needsWinCFI())
3664 return false;
3665
3666 // On some CPUs quad load/store pairs are slower than two single load/stores.
3667 if (Subtarget.isPaired128Slow()) {
3668 switch (MI.getOpcode()) {
3669 default:
3670 break;
3671 case AArch64::LDURQi:
3672 case AArch64::STURQi:
3673 case AArch64::LDRQui:
3674 case AArch64::STRQui:
3675 return false;
3676 }
3677 }
3678
3679 return true;
3680}
3681
3684 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const {
3685 if (!LdSt.mayLoadOrStore())
3686 return false;
3687
3688 const MachineOperand *BaseOp;
3689 TypeSize WidthN(0, false);
3690 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
3691 WidthN))
3692 return false;
3693 // The maximum vscale is 16 under AArch64, return the maximal extent for the
3694 // vector.
3695 Width = LocationSize::precise(WidthN);
3696 BaseOps.push_back(BaseOp);
3697 return true;
3698}
3699
3700std::optional<ExtAddrMode>
3702 const MachineOperand *Base; // Filled with the base operand of MI.
3703 int64_t Offset; // Filled with the offset of MI.
3704 bool OffsetIsScalable;
3705 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable))
3706 return std::nullopt;
3707
3708 if (!Base->isReg())
3709 return std::nullopt;
3710 ExtAddrMode AM;
3711 AM.BaseReg = Base->getReg();
3712 AM.Displacement = Offset;
3713 AM.ScaledReg = 0;
3714 AM.Scale = 0;
3715 return AM;
3716}
3717
3719 Register Reg,
3720 const MachineInstr &AddrI,
3721 ExtAddrMode &AM) const {
3722 // Filter out instructions into which we cannot fold.
3723 unsigned NumBytes;
3724 int64_t OffsetScale = 1;
3725 switch (MemI.getOpcode()) {
3726 default:
3727 return false;
3728
3729 case AArch64::LDURQi:
3730 case AArch64::STURQi:
3731 NumBytes = 16;
3732 break;
3733
3734 case AArch64::LDURDi:
3735 case AArch64::STURDi:
3736 case AArch64::LDURXi:
3737 case AArch64::STURXi:
3738 NumBytes = 8;
3739 break;
3740
3741 case AArch64::LDURSi:
3742 case AArch64::STURSi:
3743 case AArch64::LDURWi:
3744 case AArch64::LDURSWi:
3745 case AArch64::STURWi:
3746 NumBytes = 4;
3747 break;
3748
3749 case AArch64::LDURHi:
3750 case AArch64::STURHi:
3751 case AArch64::LDURHHi:
3752 case AArch64::STURHHi:
3753 case AArch64::LDURSHXi:
3754 case AArch64::LDURSHWi:
3755 NumBytes = 2;
3756 break;
3757
3758 case AArch64::LDRBroX:
3759 case AArch64::LDRBBroX:
3760 case AArch64::LDRSBXroX:
3761 case AArch64::LDRSBWroX:
3762 case AArch64::STRBroX:
3763 case AArch64::STRBBroX:
3764 case AArch64::LDURBi:
3765 case AArch64::LDURBBi:
3766 case AArch64::LDURSBXi:
3767 case AArch64::LDURSBWi:
3768 case AArch64::STURBi:
3769 case AArch64::STURBBi:
3770 case AArch64::LDRBui:
3771 case AArch64::LDRBBui:
3772 case AArch64::LDRSBXui:
3773 case AArch64::LDRSBWui:
3774 case AArch64::STRBui:
3775 case AArch64::STRBBui:
3776 NumBytes = 1;
3777 break;
3778
3779 case AArch64::LDRQroX:
3780 case AArch64::STRQroX:
3781 case AArch64::LDRQui:
3782 case AArch64::STRQui:
3783 NumBytes = 16;
3784 OffsetScale = 16;
3785 break;
3786
3787 case AArch64::LDRDroX:
3788 case AArch64::STRDroX:
3789 case AArch64::LDRXroX:
3790 case AArch64::STRXroX:
3791 case AArch64::LDRDui:
3792 case AArch64::STRDui:
3793 case AArch64::LDRXui:
3794 case AArch64::STRXui:
3795 NumBytes = 8;
3796 OffsetScale = 8;
3797 break;
3798
3799 case AArch64::LDRSroX:
3800 case AArch64::STRSroX:
3801 case AArch64::LDRWroX:
3802 case AArch64::LDRSWroX:
3803 case AArch64::STRWroX:
3804 case AArch64::LDRSui:
3805 case AArch64::STRSui:
3806 case AArch64::LDRWui:
3807 case AArch64::LDRSWui:
3808 case AArch64::STRWui:
3809 NumBytes = 4;
3810 OffsetScale = 4;
3811 break;
3812
3813 case AArch64::LDRHroX:
3814 case AArch64::STRHroX:
3815 case AArch64::LDRHHroX:
3816 case AArch64::STRHHroX:
3817 case AArch64::LDRSHXroX:
3818 case AArch64::LDRSHWroX:
3819 case AArch64::LDRHui:
3820 case AArch64::STRHui:
3821 case AArch64::LDRHHui:
3822 case AArch64::STRHHui:
3823 case AArch64::LDRSHXui:
3824 case AArch64::LDRSHWui:
3825 NumBytes = 2;
3826 OffsetScale = 2;
3827 break;
3828 }
3829
3830 // Check the fold operand is not the loaded/stored value.
3831 const MachineOperand &BaseRegOp = MemI.getOperand(0);
3832 if (BaseRegOp.isReg() && BaseRegOp.getReg() == Reg)
3833 return false;
3834
3835 // Handle memory instructions with a [Reg, Reg] addressing mode.
3836 if (MemI.getOperand(2).isReg()) {
3837 // Bail if the addressing mode already includes extension of the offset
3838 // register.
3839 if (MemI.getOperand(3).getImm())
3840 return false;
3841
3842 // Check if we actually have a scaled offset.
3843 if (MemI.getOperand(4).getImm() == 0)
3844 OffsetScale = 1;
3845
3846 // If the address instructions is folded into the base register, then the
3847 // addressing mode must not have a scale. Then we can swap the base and the
3848 // scaled registers.
3849 if (MemI.getOperand(1).getReg() == Reg && OffsetScale != 1)
3850 return false;
3851
3852 switch (AddrI.getOpcode()) {
3853 default:
3854 return false;
3855
3856 case AArch64::SBFMXri:
3857 // sxtw Xa, Wm
3858 // ldr Xd, [Xn, Xa, lsl #N]
3859 // ->
3860 // ldr Xd, [Xn, Wm, sxtw #N]
3861 if (AddrI.getOperand(2).getImm() != 0 ||
3862 AddrI.getOperand(3).getImm() != 31)
3863 return false;
3864
3865 AM.BaseReg = MemI.getOperand(1).getReg();
3866 if (AM.BaseReg == Reg)
3867 AM.BaseReg = MemI.getOperand(2).getReg();
3868 AM.ScaledReg = AddrI.getOperand(1).getReg();
3869 AM.Scale = OffsetScale;
3870 AM.Displacement = 0;
3872 return true;
3873
3874 case TargetOpcode::SUBREG_TO_REG: {
3875 // mov Wa, Wm
3876 // ldr Xd, [Xn, Xa, lsl #N]
3877 // ->
3878 // ldr Xd, [Xn, Wm, uxtw #N]
3879
3880 // Zero-extension looks like an ORRWrs followed by a SUBREG_TO_REG.
3881 if (AddrI.getOperand(2).getImm() != AArch64::sub_32)
3882 return false;
3883
3884 const MachineRegisterInfo &MRI = AddrI.getMF()->getRegInfo();
3885 Register OffsetReg = AddrI.getOperand(1).getReg();
3886 if (!OffsetReg.isVirtual() || !MRI.hasOneNonDBGUse(OffsetReg))
3887 return false;
3888
3889 const MachineInstr &DefMI = *MRI.getVRegDef(OffsetReg);
3890 if (DefMI.getOpcode() != AArch64::ORRWrs ||
3891 DefMI.getOperand(1).getReg() != AArch64::WZR ||
3892 DefMI.getOperand(3).getImm() != 0)
3893 return false;
3894
3895 AM.BaseReg = MemI.getOperand(1).getReg();
3896 if (AM.BaseReg == Reg)
3897 AM.BaseReg = MemI.getOperand(2).getReg();
3898 AM.ScaledReg = DefMI.getOperand(2).getReg();
3899 AM.Scale = OffsetScale;
3900 AM.Displacement = 0;
3902 return true;
3903 }
3904 }
3905 }
3906
3907 // Handle memory instructions with a [Reg, #Imm] addressing mode.
3908
3909 // Check we are not breaking a potential conversion to an LDP.
3910 auto validateOffsetForLDP = [](unsigned NumBytes, int64_t OldOffset,
3911 int64_t NewOffset) -> bool {
3912 int64_t MinOffset, MaxOffset;
3913 switch (NumBytes) {
3914 default:
3915 return true;
3916 case 4:
3917 MinOffset = -256;
3918 MaxOffset = 252;
3919 break;
3920 case 8:
3921 MinOffset = -512;
3922 MaxOffset = 504;
3923 break;
3924 case 16:
3925 MinOffset = -1024;
3926 MaxOffset = 1008;
3927 break;
3928 }
3929 return OldOffset < MinOffset || OldOffset > MaxOffset ||
3930 (NewOffset >= MinOffset && NewOffset <= MaxOffset);
3931 };
3932 auto canFoldAddSubImmIntoAddrMode = [&](int64_t Disp) -> bool {
3933 int64_t OldOffset = MemI.getOperand(2).getImm() * OffsetScale;
3934 int64_t NewOffset = OldOffset + Disp;
3935 if (!isLegalAddressingMode(NumBytes, NewOffset, /* Scale */ 0))
3936 return false;
3937 // If the old offset would fit into an LDP, but the new offset wouldn't,
3938 // bail out.
3939 if (!validateOffsetForLDP(NumBytes, OldOffset, NewOffset))
3940 return false;
3941 AM.BaseReg = AddrI.getOperand(1).getReg();
3942 AM.ScaledReg = 0;
3943 AM.Scale = 0;
3944 AM.Displacement = NewOffset;
3946 return true;
3947 };
3948
3949 auto canFoldAddRegIntoAddrMode =
3950 [&](int64_t Scale,
3952 if (MemI.getOperand(2).getImm() != 0)
3953 return false;
3954 if ((unsigned)Scale != Scale)
3955 return false;
3956 if (!isLegalAddressingMode(NumBytes, /* Offset */ 0, Scale))
3957 return false;
3958 AM.BaseReg = AddrI.getOperand(1).getReg();
3959 AM.ScaledReg = AddrI.getOperand(2).getReg();
3960 AM.Scale = Scale;
3961 AM.Displacement = 0;
3962 AM.Form = Form;
3963 return true;
3964 };
3965
3966 auto avoidSlowSTRQ = [&](const MachineInstr &MemI) {
3967 unsigned Opcode = MemI.getOpcode();
3968 return (Opcode == AArch64::STURQi || Opcode == AArch64::STRQui) &&
3969 Subtarget.isSTRQroSlow();
3970 };
3971
3972 int64_t Disp = 0;
3973 const bool OptSize = MemI.getMF()->getFunction().hasOptSize();
3974 switch (AddrI.getOpcode()) {
3975 default:
3976 return false;
3977
3978 case AArch64::ADDXri:
3979 // add Xa, Xn, #N
3980 // ldr Xd, [Xa, #M]
3981 // ->
3982 // ldr Xd, [Xn, #N'+M]
3983 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3984 return canFoldAddSubImmIntoAddrMode(Disp);
3985
3986 case AArch64::SUBXri:
3987 // sub Xa, Xn, #N
3988 // ldr Xd, [Xa, #M]
3989 // ->
3990 // ldr Xd, [Xn, #N'+M]
3991 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3992 return canFoldAddSubImmIntoAddrMode(-Disp);
3993
3994 case AArch64::ADDXrs: {
3995 // add Xa, Xn, Xm, lsl #N
3996 // ldr Xd, [Xa]
3997 // ->
3998 // ldr Xd, [Xn, Xm, lsl #N]
3999
4000 // Don't fold the add if the result would be slower, unless optimising for
4001 // size.
4002 unsigned Shift = static_cast<unsigned>(AddrI.getOperand(3).getImm());
4004 return false;
4005 Shift = AArch64_AM::getShiftValue(Shift);
4006 if (!OptSize) {
4007 if (Shift != 2 && Shift != 3 && Subtarget.hasAddrLSLSlow14())
4008 return false;
4009 if (avoidSlowSTRQ(MemI))
4010 return false;
4011 }
4012 return canFoldAddRegIntoAddrMode(1ULL << Shift);
4013 }
4014
4015 case AArch64::ADDXrr:
4016 // add Xa, Xn, Xm
4017 // ldr Xd, [Xa]
4018 // ->
4019 // ldr Xd, [Xn, Xm, lsl #0]
4020
4021 // Don't fold the add if the result would be slower, unless optimising for
4022 // size.
4023 if (!OptSize && avoidSlowSTRQ(MemI))
4024 return false;
4025 return canFoldAddRegIntoAddrMode(1);
4026
4027 case AArch64::ADDXrx:
4028 // add Xa, Xn, Wm, {s,u}xtw #N
4029 // ldr Xd, [Xa]
4030 // ->
4031 // ldr Xd, [Xn, Wm, {s,u}xtw #N]
4032
4033 // Don't fold the add if the result would be slower, unless optimising for
4034 // size.
4035 if (!OptSize && avoidSlowSTRQ(MemI))
4036 return false;
4037
4038 // Can fold only sign-/zero-extend of a word.
4039 unsigned Imm = static_cast<unsigned>(AddrI.getOperand(3).getImm());
4041 if (Extend != AArch64_AM::UXTW && Extend != AArch64_AM::SXTW)
4042 return false;
4043
4044 return canFoldAddRegIntoAddrMode(
4048 }
4049}
4050
4051// Given an opcode for an instruction with a [Reg, #Imm] addressing mode,
4052// return the opcode of an instruction performing the same operation, but using
4053// the [Reg, Reg] addressing mode.
4054static unsigned regOffsetOpcode(unsigned Opcode) {
4055 switch (Opcode) {
4056 default:
4057 llvm_unreachable("Address folding not implemented for instruction");
4058
4059 case AArch64::LDURQi:
4060 case AArch64::LDRQui:
4061 return AArch64::LDRQroX;
4062 case AArch64::STURQi:
4063 case AArch64::STRQui:
4064 return AArch64::STRQroX;
4065 case AArch64::LDURDi:
4066 case AArch64::LDRDui:
4067 return AArch64::LDRDroX;
4068 case AArch64::STURDi:
4069 case AArch64::STRDui:
4070 return AArch64::STRDroX;
4071 case AArch64::LDURXi:
4072 case AArch64::LDRXui:
4073 return AArch64::LDRXroX;
4074 case AArch64::STURXi:
4075 case AArch64::STRXui:
4076 return AArch64::STRXroX;
4077 case AArch64::LDURSi:
4078 case AArch64::LDRSui:
4079 return AArch64::LDRSroX;
4080 case AArch64::STURSi:
4081 case AArch64::STRSui:
4082 return AArch64::STRSroX;
4083 case AArch64::LDURWi:
4084 case AArch64::LDRWui:
4085 return AArch64::LDRWroX;
4086 case AArch64::LDURSWi:
4087 case AArch64::LDRSWui:
4088 return AArch64::LDRSWroX;
4089 case AArch64::STURWi:
4090 case AArch64::STRWui:
4091 return AArch64::STRWroX;
4092 case AArch64::LDURHi:
4093 case AArch64::LDRHui:
4094 return AArch64::LDRHroX;
4095 case AArch64::STURHi:
4096 case AArch64::STRHui:
4097 return AArch64::STRHroX;
4098 case AArch64::LDURHHi:
4099 case AArch64::LDRHHui:
4100 return AArch64::LDRHHroX;
4101 case AArch64::STURHHi:
4102 case AArch64::STRHHui:
4103 return AArch64::STRHHroX;
4104 case AArch64::LDURSHXi:
4105 case AArch64::LDRSHXui:
4106 return AArch64::LDRSHXroX;
4107 case AArch64::LDURSHWi:
4108 case AArch64::LDRSHWui:
4109 return AArch64::LDRSHWroX;
4110 case AArch64::LDURBi:
4111 case AArch64::LDRBui:
4112 return AArch64::LDRBroX;
4113 case AArch64::LDURBBi:
4114 case AArch64::LDRBBui:
4115 return AArch64::LDRBBroX;
4116 case AArch64::LDURSBXi:
4117 case AArch64::LDRSBXui:
4118 return AArch64::LDRSBXroX;
4119 case AArch64::LDURSBWi:
4120 case AArch64::LDRSBWui:
4121 return AArch64::LDRSBWroX;
4122 case AArch64::STURBi:
4123 case AArch64::STRBui:
4124 return AArch64::STRBroX;
4125 case AArch64::STURBBi:
4126 case AArch64::STRBBui:
4127 return AArch64::STRBBroX;
4128 }
4129}
4130
4131// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4132// the opcode of an instruction performing the same operation, but using the
4133// [Reg, #Imm] addressing mode with scaled offset.
4134unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale) {
4135 switch (Opcode) {
4136 default:
4137 llvm_unreachable("Address folding not implemented for instruction");
4138
4139 case AArch64::LDURQi:
4140 Scale = 16;
4141 return AArch64::LDRQui;
4142 case AArch64::STURQi:
4143 Scale = 16;
4144 return AArch64::STRQui;
4145 case AArch64::LDURDi:
4146 Scale = 8;
4147 return AArch64::LDRDui;
4148 case AArch64::STURDi:
4149 Scale = 8;
4150 return AArch64::STRDui;
4151 case AArch64::LDURXi:
4152 Scale = 8;
4153 return AArch64::LDRXui;
4154 case AArch64::STURXi:
4155 Scale = 8;
4156 return AArch64::STRXui;
4157 case AArch64::LDURSi:
4158 Scale = 4;
4159 return AArch64::LDRSui;
4160 case AArch64::STURSi:
4161 Scale = 4;
4162 return AArch64::STRSui;
4163 case AArch64::LDURWi:
4164 Scale = 4;
4165 return AArch64::LDRWui;
4166 case AArch64::LDURSWi:
4167 Scale = 4;
4168 return AArch64::LDRSWui;
4169 case AArch64::STURWi:
4170 Scale = 4;
4171 return AArch64::STRWui;
4172 case AArch64::LDURHi:
4173 Scale = 2;
4174 return AArch64::LDRHui;
4175 case AArch64::STURHi:
4176 Scale = 2;
4177 return AArch64::STRHui;
4178 case AArch64::LDURHHi:
4179 Scale = 2;
4180 return AArch64::LDRHHui;
4181 case AArch64::STURHHi:
4182 Scale = 2;
4183 return AArch64::STRHHui;
4184 case AArch64::LDURSHXi:
4185 Scale = 2;
4186 return AArch64::LDRSHXui;
4187 case AArch64::LDURSHWi:
4188 Scale = 2;
4189 return AArch64::LDRSHWui;
4190 case AArch64::LDURBi:
4191 Scale = 1;
4192 return AArch64::LDRBui;
4193 case AArch64::LDURBBi:
4194 Scale = 1;
4195 return AArch64::LDRBBui;
4196 case AArch64::LDURSBXi:
4197 Scale = 1;
4198 return AArch64::LDRSBXui;
4199 case AArch64::LDURSBWi:
4200 Scale = 1;
4201 return AArch64::LDRSBWui;
4202 case AArch64::STURBi:
4203 Scale = 1;
4204 return AArch64::STRBui;
4205 case AArch64::STURBBi:
4206 Scale = 1;
4207 return AArch64::STRBBui;
4208 case AArch64::LDRQui:
4209 case AArch64::STRQui:
4210 Scale = 16;
4211 return Opcode;
4212 case AArch64::LDRDui:
4213 case AArch64::STRDui:
4214 case AArch64::LDRXui:
4215 case AArch64::STRXui:
4216 Scale = 8;
4217 return Opcode;
4218 case AArch64::LDRSui:
4219 case AArch64::STRSui:
4220 case AArch64::LDRWui:
4221 case AArch64::LDRSWui:
4222 case AArch64::STRWui:
4223 Scale = 4;
4224 return Opcode;
4225 case AArch64::LDRHui:
4226 case AArch64::STRHui:
4227 case AArch64::LDRHHui:
4228 case AArch64::STRHHui:
4229 case AArch64::LDRSHXui:
4230 case AArch64::LDRSHWui:
4231 Scale = 2;
4232 return Opcode;
4233 case AArch64::LDRBui:
4234 case AArch64::LDRBBui:
4235 case AArch64::LDRSBXui:
4236 case AArch64::LDRSBWui:
4237 case AArch64::STRBui:
4238 case AArch64::STRBBui:
4239 Scale = 1;
4240 return Opcode;
4241 }
4242}
4243
4244// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4245// the opcode of an instruction performing the same operation, but using the
4246// [Reg, #Imm] addressing mode with unscaled offset.
4247unsigned unscaledOffsetOpcode(unsigned Opcode) {
4248 switch (Opcode) {
4249 default:
4250 llvm_unreachable("Address folding not implemented for instruction");
4251
4252 case AArch64::LDURQi:
4253 case AArch64::STURQi:
4254 case AArch64::LDURDi:
4255 case AArch64::STURDi:
4256 case AArch64::LDURXi:
4257 case AArch64::STURXi:
4258 case AArch64::LDURSi:
4259 case AArch64::STURSi:
4260 case AArch64::LDURWi:
4261 case AArch64::LDURSWi:
4262 case AArch64::STURWi:
4263 case AArch64::LDURHi:
4264 case AArch64::STURHi:
4265 case AArch64::LDURHHi:
4266 case AArch64::STURHHi:
4267 case AArch64::LDURSHXi:
4268 case AArch64::LDURSHWi:
4269 case AArch64::LDURBi:
4270 case AArch64::STURBi:
4271 case AArch64::LDURBBi:
4272 case AArch64::STURBBi:
4273 case AArch64::LDURSBWi:
4274 case AArch64::LDURSBXi:
4275 return Opcode;
4276 case AArch64::LDRQui:
4277 return AArch64::LDURQi;
4278 case AArch64::STRQui:
4279 return AArch64::STURQi;
4280 case AArch64::LDRDui:
4281 return AArch64::LDURDi;
4282 case AArch64::STRDui:
4283 return AArch64::STURDi;
4284 case AArch64::LDRXui:
4285 return AArch64::LDURXi;
4286 case AArch64::STRXui:
4287 return AArch64::STURXi;
4288 case AArch64::LDRSui:
4289 return AArch64::LDURSi;
4290 case AArch64::STRSui:
4291 return AArch64::STURSi;
4292 case AArch64::LDRWui:
4293 return AArch64::LDURWi;
4294 case AArch64::LDRSWui:
4295 return AArch64::LDURSWi;
4296 case AArch64::STRWui:
4297 return AArch64::STURWi;
4298 case AArch64::LDRHui:
4299 return AArch64::LDURHi;
4300 case AArch64::STRHui:
4301 return AArch64::STURHi;
4302 case AArch64::LDRHHui:
4303 return AArch64::LDURHHi;
4304 case AArch64::STRHHui:
4305 return AArch64::STURHHi;
4306 case AArch64::LDRSHXui:
4307 return AArch64::LDURSHXi;
4308 case AArch64::LDRSHWui:
4309 return AArch64::LDURSHWi;
4310 case AArch64::LDRBBui:
4311 return AArch64::LDURBBi;
4312 case AArch64::LDRBui:
4313 return AArch64::LDURBi;
4314 case AArch64::STRBBui:
4315 return AArch64::STURBBi;
4316 case AArch64::STRBui:
4317 return AArch64::STURBi;
4318 case AArch64::LDRSBWui:
4319 return AArch64::LDURSBWi;
4320 case AArch64::LDRSBXui:
4321 return AArch64::LDURSBXi;
4322 }
4323}
4324
4325// Given the opcode of a memory load/store instruction, return the opcode of an
4326// instruction performing the same operation, but using
4327// the [Reg, Reg, {s,u}xtw #N] addressing mode with sign-/zero-extend of the
4328// offset register.
4329static unsigned offsetExtendOpcode(unsigned Opcode) {
4330 switch (Opcode) {
4331 default:
4332 llvm_unreachable("Address folding not implemented for instruction");
4333
4334 case AArch64::LDRQroX:
4335 case AArch64::LDURQi:
4336 case AArch64::LDRQui:
4337 return AArch64::LDRQroW;
4338 case AArch64::STRQroX:
4339 case AArch64::STURQi:
4340 case AArch64::STRQui:
4341 return AArch64::STRQroW;
4342 case AArch64::LDRDroX:
4343 case AArch64::LDURDi:
4344 case AArch64::LDRDui:
4345 return AArch64::LDRDroW;
4346 case AArch64::STRDroX:
4347 case AArch64::STURDi:
4348 case AArch64::STRDui:
4349 return AArch64::STRDroW;
4350 case AArch64::LDRXroX:
4351 case AArch64::LDURXi:
4352 case AArch64::LDRXui:
4353 return AArch64::LDRXroW;
4354 case AArch64::STRXroX:
4355 case AArch64::STURXi:
4356 case AArch64::STRXui:
4357 return AArch64::STRXroW;
4358 case AArch64::LDRSroX:
4359 case AArch64::LDURSi:
4360 case AArch64::LDRSui:
4361 return AArch64::LDRSroW;
4362 case AArch64::STRSroX:
4363 case AArch64::STURSi:
4364 case AArch64::STRSui:
4365 return AArch64::STRSroW;
4366 case AArch64::LDRWroX:
4367 case AArch64::LDURWi:
4368 case AArch64::LDRWui:
4369 return AArch64::LDRWroW;
4370 case AArch64::LDRSWroX:
4371 case AArch64::LDURSWi:
4372 case AArch64::LDRSWui:
4373 return AArch64::LDRSWroW;
4374 case AArch64::STRWroX:
4375 case AArch64::STURWi:
4376 case AArch64::STRWui:
4377 return AArch64::STRWroW;
4378 case AArch64::LDRHroX:
4379 case AArch64::LDURHi:
4380 case AArch64::LDRHui:
4381 return AArch64::LDRHroW;
4382 case AArch64::STRHroX:
4383 case AArch64::STURHi:
4384 case AArch64::STRHui:
4385 return AArch64::STRHroW;
4386 case AArch64::LDRHHroX:
4387 case AArch64::LDURHHi:
4388 case AArch64::LDRHHui:
4389 return AArch64::LDRHHroW;
4390 case AArch64::STRHHroX:
4391 case AArch64::STURHHi:
4392 case AArch64::STRHHui:
4393 return AArch64::STRHHroW;
4394 case AArch64::LDRSHXroX:
4395 case AArch64::LDURSHXi:
4396 case AArch64::LDRSHXui:
4397 return AArch64::LDRSHXroW;
4398 case AArch64::LDRSHWroX:
4399 case AArch64::LDURSHWi:
4400 case AArch64::LDRSHWui:
4401 return AArch64::LDRSHWroW;
4402 case AArch64::LDRBroX:
4403 case AArch64::LDURBi:
4404 case AArch64::LDRBui:
4405 return AArch64::LDRBroW;
4406 case AArch64::LDRBBroX:
4407 case AArch64::LDURBBi:
4408 case AArch64::LDRBBui:
4409 return AArch64::LDRBBroW;
4410 case AArch64::LDRSBXroX:
4411 case AArch64::LDURSBXi:
4412 case AArch64::LDRSBXui:
4413 return AArch64::LDRSBXroW;
4414 case AArch64::LDRSBWroX:
4415 case AArch64::LDURSBWi:
4416 case AArch64::LDRSBWui:
4417 return AArch64::LDRSBWroW;
4418 case AArch64::STRBroX:
4419 case AArch64::STURBi:
4420 case AArch64::STRBui:
4421 return AArch64::STRBroW;
4422 case AArch64::STRBBroX:
4423 case AArch64::STURBBi:
4424 case AArch64::STRBBui:
4425 return AArch64::STRBBroW;
4426 }
4427}
4428
4430 const ExtAddrMode &AM) const {
4431
4432 const DebugLoc &DL = MemI.getDebugLoc();
4433 MachineBasicBlock &MBB = *MemI.getParent();
4435
4437 if (AM.ScaledReg) {
4438 // The new instruction will be in the form `ldr Rt, [Xn, Xm, lsl #imm]`.
4439 unsigned Opcode = regOffsetOpcode(MemI.getOpcode());
4440 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4441 auto B = BuildMI(MBB, MemI, DL, get(Opcode))
4442 .addReg(MemI.getOperand(0).getReg(),
4443 getDefRegState(MemI.mayLoad()))
4444 .addReg(AM.BaseReg)
4445 .addReg(AM.ScaledReg)
4446 .addImm(0)
4447 .addImm(AM.Scale > 1)
4448 .setMemRefs(MemI.memoperands())
4449 .setMIFlags(MemI.getFlags());
4450 return B.getInstr();
4451 }
4452
4453 assert(AM.ScaledReg == 0 && AM.Scale == 0 &&
4454 "Addressing mode not supported for folding");
4455
4456 // The new instruction will be in the form `ld[u]r Rt, [Xn, #imm]`.
4457 unsigned Scale = 1;
4458 unsigned Opcode = MemI.getOpcode();
4459 if (isInt<9>(AM.Displacement))
4460 Opcode = unscaledOffsetOpcode(Opcode);
4461 else
4462 Opcode = scaledOffsetOpcode(Opcode, Scale);
4463
4464 auto B =
4465 BuildMI(MBB, MemI, DL, get(Opcode))
4466 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4467 .addReg(AM.BaseReg)
4468 .addImm(AM.Displacement / Scale)
4469 .setMemRefs(MemI.memoperands())
4470 .setMIFlags(MemI.getFlags());
4471 return B.getInstr();
4472 }
4473
4476 // The new instruction will be in the form `ldr Rt, [Xn, Wm, {s,u}xtw #N]`.
4477 assert(AM.ScaledReg && !AM.Displacement &&
4478 "Address offset can be a register or an immediate, but not both");
4479 unsigned Opcode = offsetExtendOpcode(MemI.getOpcode());
4480 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4481 // Make sure the offset register is in the correct register class.
4482 Register OffsetReg = AM.ScaledReg;
4483 const TargetRegisterClass *RC = MRI.getRegClass(OffsetReg);
4484 if (RC->hasSuperClassEq(&AArch64::GPR64RegClass)) {
4485 OffsetReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
4486 BuildMI(MBB, MemI, DL, get(TargetOpcode::COPY), OffsetReg)
4487 .addReg(AM.ScaledReg, {}, AArch64::sub_32);
4488 }
4489 auto B =
4490 BuildMI(MBB, MemI, DL, get(Opcode))
4491 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4492 .addReg(AM.BaseReg)
4493 .addReg(OffsetReg)
4495 .addImm(AM.Scale != 1)
4496 .setMemRefs(MemI.memoperands())
4497 .setMIFlags(MemI.getFlags());
4498
4499 return B.getInstr();
4500 }
4501
4503 "Function must not be called with an addressing mode it can't handle");
4504}
4505
4506/// Return true if the opcode is a post-index ld/st instruction, which really
4507/// loads from base+0.
4508static bool isPostIndexLdStOpcode(unsigned Opcode) {
4509 switch (Opcode) {
4510 default:
4511 return false;
4512 case AArch64::LD1Fourv16b_POST:
4513 case AArch64::LD1Fourv1d_POST:
4514 case AArch64::LD1Fourv2d_POST:
4515 case AArch64::LD1Fourv2s_POST:
4516 case AArch64::LD1Fourv4h_POST:
4517 case AArch64::LD1Fourv4s_POST:
4518 case AArch64::LD1Fourv8b_POST:
4519 case AArch64::LD1Fourv8h_POST:
4520 case AArch64::LD1Onev16b_POST:
4521 case AArch64::LD1Onev1d_POST:
4522 case AArch64::LD1Onev2d_POST:
4523 case AArch64::LD1Onev2s_POST:
4524 case AArch64::LD1Onev4h_POST:
4525 case AArch64::LD1Onev4s_POST:
4526 case AArch64::LD1Onev8b_POST:
4527 case AArch64::LD1Onev8h_POST:
4528 case AArch64::LD1Rv16b_POST:
4529 case AArch64::LD1Rv1d_POST:
4530 case AArch64::LD1Rv2d_POST:
4531 case AArch64::LD1Rv2s_POST:
4532 case AArch64::LD1Rv4h_POST:
4533 case AArch64::LD1Rv4s_POST:
4534 case AArch64::LD1Rv8b_POST:
4535 case AArch64::LD1Rv8h_POST:
4536 case AArch64::LD1Threev16b_POST:
4537 case AArch64::LD1Threev1d_POST:
4538 case AArch64::LD1Threev2d_POST:
4539 case AArch64::LD1Threev2s_POST:
4540 case AArch64::LD1Threev4h_POST:
4541 case AArch64::LD1Threev4s_POST:
4542 case AArch64::LD1Threev8b_POST:
4543 case AArch64::LD1Threev8h_POST:
4544 case AArch64::LD1Twov16b_POST:
4545 case AArch64::LD1Twov1d_POST:
4546 case AArch64::LD1Twov2d_POST:
4547 case AArch64::LD1Twov2s_POST:
4548 case AArch64::LD1Twov4h_POST:
4549 case AArch64::LD1Twov4s_POST:
4550 case AArch64::LD1Twov8b_POST:
4551 case AArch64::LD1Twov8h_POST:
4552 case AArch64::LD1i16_POST:
4553 case AArch64::LD1i32_POST:
4554 case AArch64::LD1i64_POST:
4555 case AArch64::LD1i8_POST:
4556 case AArch64::LD2Rv16b_POST:
4557 case AArch64::LD2Rv1d_POST:
4558 case AArch64::LD2Rv2d_POST:
4559 case AArch64::LD2Rv2s_POST:
4560 case AArch64::LD2Rv4h_POST:
4561 case AArch64::LD2Rv4s_POST:
4562 case AArch64::LD2Rv8b_POST:
4563 case AArch64::LD2Rv8h_POST:
4564 case AArch64::LD2Twov16b_POST:
4565 case AArch64::LD2Twov2d_POST:
4566 case AArch64::LD2Twov2s_POST:
4567 case AArch64::LD2Twov4h_POST:
4568 case AArch64::LD2Twov4s_POST:
4569 case AArch64::LD2Twov8b_POST:
4570 case AArch64::LD2Twov8h_POST:
4571 case AArch64::LD2i16_POST:
4572 case AArch64::LD2i32_POST:
4573 case AArch64::LD2i64_POST:
4574 case AArch64::LD2i8_POST:
4575 case AArch64::LD3Rv16b_POST:
4576 case AArch64::LD3Rv1d_POST:
4577 case AArch64::LD3Rv2d_POST:
4578 case AArch64::LD3Rv2s_POST:
4579 case AArch64::LD3Rv4h_POST:
4580 case AArch64::LD3Rv4s_POST:
4581 case AArch64::LD3Rv8b_POST:
4582 case AArch64::LD3Rv8h_POST:
4583 case AArch64::LD3Threev16b_POST:
4584 case AArch64::LD3Threev2d_POST:
4585 case AArch64::LD3Threev2s_POST:
4586 case AArch64::LD3Threev4h_POST:
4587 case AArch64::LD3Threev4s_POST:
4588 case AArch64::LD3Threev8b_POST:
4589 case AArch64::LD3Threev8h_POST:
4590 case AArch64::LD3i16_POST:
4591 case AArch64::LD3i32_POST:
4592 case AArch64::LD3i64_POST:
4593 case AArch64::LD3i8_POST:
4594 case AArch64::LD4Fourv16b_POST:
4595 case AArch64::LD4Fourv2d_POST:
4596 case AArch64::LD4Fourv2s_POST:
4597 case AArch64::LD4Fourv4h_POST:
4598 case AArch64::LD4Fourv4s_POST:
4599 case AArch64::LD4Fourv8b_POST:
4600 case AArch64::LD4Fourv8h_POST:
4601 case AArch64::LD4Rv16b_POST:
4602 case AArch64::LD4Rv1d_POST:
4603 case AArch64::LD4Rv2d_POST:
4604 case AArch64::LD4Rv2s_POST:
4605 case AArch64::LD4Rv4h_POST:
4606 case AArch64::LD4Rv4s_POST:
4607 case AArch64::LD4Rv8b_POST:
4608 case AArch64::LD4Rv8h_POST:
4609 case AArch64::LD4i16_POST:
4610 case AArch64::LD4i32_POST:
4611 case AArch64::LD4i64_POST:
4612 case AArch64::LD4i8_POST:
4613 case AArch64::LDAPRWpost:
4614 case AArch64::LDAPRXpost:
4615 case AArch64::LDIAPPWpost:
4616 case AArch64::LDIAPPXpost:
4617 case AArch64::LDPDpost:
4618 case AArch64::LDPQpost:
4619 case AArch64::LDPSWpost:
4620 case AArch64::LDPSpost:
4621 case AArch64::LDPWpost:
4622 case AArch64::LDPXpost:
4623 case AArch64::LDRBBpost:
4624 case AArch64::LDRBpost:
4625 case AArch64::LDRDpost:
4626 case AArch64::LDRHHpost:
4627 case AArch64::LDRHpost:
4628 case AArch64::LDRQpost:
4629 case AArch64::LDRSBWpost:
4630 case AArch64::LDRSBXpost:
4631 case AArch64::LDRSHWpost:
4632 case AArch64::LDRSHXpost:
4633 case AArch64::LDRSWpost:
4634 case AArch64::LDRSpost:
4635 case AArch64::LDRWpost:
4636 case AArch64::LDRXpost:
4637 case AArch64::ST1Fourv16b_POST:
4638 case AArch64::ST1Fourv1d_POST:
4639 case AArch64::ST1Fourv2d_POST:
4640 case AArch64::ST1Fourv2s_POST:
4641 case AArch64::ST1Fourv4h_POST:
4642 case AArch64::ST1Fourv4s_POST:
4643 case AArch64::ST1Fourv8b_POST:
4644 case AArch64::ST1Fourv8h_POST:
4645 case AArch64::ST1Onev16b_POST:
4646 case AArch64::ST1Onev1d_POST:
4647 case AArch64::ST1Onev2d_POST:
4648 case AArch64::ST1Onev2s_POST:
4649 case AArch64::ST1Onev4h_POST:
4650 case AArch64::ST1Onev4s_POST:
4651 case AArch64::ST1Onev8b_POST:
4652 case AArch64::ST1Onev8h_POST:
4653 case AArch64::ST1Threev16b_POST:
4654 case AArch64::ST1Threev1d_POST:
4655 case AArch64::ST1Threev2d_POST:
4656 case AArch64::ST1Threev2s_POST:
4657 case AArch64::ST1Threev4h_POST:
4658 case AArch64::ST1Threev4s_POST:
4659 case AArch64::ST1Threev8b_POST:
4660 case AArch64::ST1Threev8h_POST:
4661 case AArch64::ST1Twov16b_POST:
4662 case AArch64::ST1Twov1d_POST:
4663 case AArch64::ST1Twov2d_POST:
4664 case AArch64::ST1Twov2s_POST:
4665 case AArch64::ST1Twov4h_POST:
4666 case AArch64::ST1Twov4s_POST:
4667 case AArch64::ST1Twov8b_POST:
4668 case AArch64::ST1Twov8h_POST:
4669 case AArch64::ST1i16_POST:
4670 case AArch64::ST1i32_POST:
4671 case AArch64::ST1i64_POST:
4672 case AArch64::ST1i8_POST:
4673 case AArch64::ST2GPostIndex:
4674 case AArch64::ST2Twov16b_POST:
4675 case AArch64::ST2Twov2d_POST:
4676 case AArch64::ST2Twov2s_POST:
4677 case AArch64::ST2Twov4h_POST:
4678 case AArch64::ST2Twov4s_POST:
4679 case AArch64::ST2Twov8b_POST:
4680 case AArch64::ST2Twov8h_POST:
4681 case AArch64::ST2i16_POST:
4682 case AArch64::ST2i32_POST:
4683 case AArch64::ST2i64_POST:
4684 case AArch64::ST2i8_POST:
4685 case AArch64::ST3Threev16b_POST:
4686 case AArch64::ST3Threev2d_POST:
4687 case AArch64::ST3Threev2s_POST:
4688 case AArch64::ST3Threev4h_POST:
4689 case AArch64::ST3Threev4s_POST:
4690 case AArch64::ST3Threev8b_POST:
4691 case AArch64::ST3Threev8h_POST:
4692 case AArch64::ST3i16_POST:
4693 case AArch64::ST3i32_POST:
4694 case AArch64::ST3i64_POST:
4695 case AArch64::ST3i8_POST:
4696 case AArch64::ST4Fourv16b_POST:
4697 case AArch64::ST4Fourv2d_POST:
4698 case AArch64::ST4Fourv2s_POST:
4699 case AArch64::ST4Fourv4h_POST:
4700 case AArch64::ST4Fourv4s_POST:
4701 case AArch64::ST4Fourv8b_POST:
4702 case AArch64::ST4Fourv8h_POST:
4703 case AArch64::ST4i16_POST:
4704 case AArch64::ST4i32_POST:
4705 case AArch64::ST4i64_POST:
4706 case AArch64::ST4i8_POST:
4707 case AArch64::STGPostIndex:
4708 case AArch64::STGPpost:
4709 case AArch64::STPDpost:
4710 case AArch64::STPQpost:
4711 case AArch64::STPSpost:
4712 case AArch64::STPWpost:
4713 case AArch64::STPXpost:
4714 case AArch64::STRBBpost:
4715 case AArch64::STRBpost:
4716 case AArch64::STRDpost:
4717 case AArch64::STRHHpost:
4718 case AArch64::STRHpost:
4719 case AArch64::STRQpost:
4720 case AArch64::STRSpost:
4721 case AArch64::STRWpost:
4722 case AArch64::STRXpost:
4723 case AArch64::STZ2GPostIndex:
4724 case AArch64::STZGPostIndex:
4725 return true;
4726 }
4727}
4728
4730 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
4731 bool &OffsetIsScalable, TypeSize &Width) const {
4732 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4733 // Handle only loads/stores with base register followed by immediate offset.
4734 if (LdSt.getNumExplicitOperands() == 3) {
4735 // Non-paired instruction (e.g., ldr x1, [x0, #8]).
4736 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
4737 !LdSt.getOperand(2).isImm())
4738 return false;
4739 } else if (LdSt.getNumExplicitOperands() == 4) {
4740 // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
4741 if (!LdSt.getOperand(1).isReg() ||
4742 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
4743 !LdSt.getOperand(3).isImm())
4744 return false;
4745 } else
4746 return false;
4747
4748 // Get the scaling factor for the instruction and set the width for the
4749 // instruction.
4750 TypeSize Scale(0U, false);
4751 int64_t Dummy1, Dummy2;
4752
4753 // If this returns false, then it's an instruction we don't want to handle.
4754 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
4755 return false;
4756
4757 // Compute the offset. Offset is calculated as the immediate operand
4758 // multiplied by the scaling factor. Unscaled instructions have scaling factor
4759 // set to 1. Postindex are a special case which have an offset of 0.
4760 if (isPostIndexLdStOpcode(LdSt.getOpcode())) {
4761 BaseOp = &LdSt.getOperand(2);
4762 Offset = 0;
4763 } else if (LdSt.getNumExplicitOperands() == 3) {
4764 BaseOp = &LdSt.getOperand(1);
4765 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
4766 } else {
4767 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
4768 BaseOp = &LdSt.getOperand(2);
4769 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
4770 }
4771 OffsetIsScalable = Scale.isScalable();
4772
4773 return BaseOp->isReg() || BaseOp->isFI();
4774}
4775
4778 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4779 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
4780 assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
4781 return OfsOp;
4782}
4783
4784bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
4785 TypeSize &Width, int64_t &MinOffset,
4786 int64_t &MaxOffset) {
4787 switch (Opcode) {
4788 // Not a memory operation or something we want to handle.
4789 default:
4790 Scale = Width = TypeSize::getFixed(0);
4791 MinOffset = MaxOffset = 0;
4792 return false;
4793 // LDR / STR
4794 case AArch64::LDRQui:
4795 case AArch64::STRQui:
4796 Scale = Width = TypeSize::getFixed(16);
4797 MinOffset = 0;
4798 MaxOffset = 4095;
4799 break;
4800 case AArch64::LDRXui:
4801 case AArch64::LDRDui:
4802 case AArch64::STRXui:
4803 case AArch64::STRDui:
4804 case AArch64::PRFMui:
4805 case AArch64::ATOMIC_STORE_HINT_Xui:
4806 case AArch64::ATOMIC_STORE_HINT_Dui:
4807 Scale = Width = TypeSize::getFixed(8);
4808 MinOffset = 0;
4809 MaxOffset = 4095;
4810 break;
4811 case AArch64::LDRWui:
4812 case AArch64::LDRSui:
4813 case AArch64::LDRSWui:
4814 case AArch64::STRWui:
4815 case AArch64::STRSui:
4816 case AArch64::ATOMIC_STORE_HINT_Wui:
4817 case AArch64::ATOMIC_STORE_HINT_Sui:
4818 Scale = Width = TypeSize::getFixed(4);
4819 MinOffset = 0;
4820 MaxOffset = 4095;
4821 break;
4822 case AArch64::LDRHui:
4823 case AArch64::LDRHHui:
4824 case AArch64::LDRSHWui:
4825 case AArch64::LDRSHXui:
4826 case AArch64::STRHui:
4827 case AArch64::STRHHui:
4828 case AArch64::ATOMIC_STORE_HINT_Hui:
4829 Scale = Width = TypeSize::getFixed(2);
4830 MinOffset = 0;
4831 MaxOffset = 4095;
4832 break;
4833 case AArch64::LDRBui:
4834 case AArch64::LDRBBui:
4835 case AArch64::LDRSBWui:
4836 case AArch64::LDRSBXui:
4837 case AArch64::STRBui:
4838 case AArch64::STRBBui:
4839 case AArch64::ATOMIC_STORE_HINT_Bui:
4840 Scale = Width = TypeSize::getFixed(1);
4841 MinOffset = 0;
4842 MaxOffset = 4095;
4843 break;
4844 // post/pre inc
4845 case AArch64::STRQpre:
4846 case AArch64::LDRQpost:
4847 Scale = TypeSize::getFixed(1);
4848 Width = TypeSize::getFixed(16);
4849 MinOffset = -256;
4850 MaxOffset = 255;
4851 break;
4852 case AArch64::LDRDpost:
4853 case AArch64::LDRDpre:
4854 case AArch64::LDRXpost:
4855 case AArch64::LDRXpre:
4856 case AArch64::STRDpost:
4857 case AArch64::STRDpre:
4858 case AArch64::STRXpost:
4859 case AArch64::STRXpre:
4860 Scale = TypeSize::getFixed(1);
4861 Width = TypeSize::getFixed(8);
4862 MinOffset = -256;
4863 MaxOffset = 255;
4864 break;
4865 case AArch64::STRWpost:
4866 case AArch64::STRWpre:
4867 case AArch64::LDRWpost:
4868 case AArch64::LDRWpre:
4869 case AArch64::STRSpost:
4870 case AArch64::STRSpre:
4871 case AArch64::LDRSpost:
4872 case AArch64::LDRSpre:
4873 Scale = TypeSize::getFixed(1);
4874 Width = TypeSize::getFixed(4);
4875 MinOffset = -256;
4876 MaxOffset = 255;
4877 break;
4878 case AArch64::LDRHpost:
4879 case AArch64::LDRHpre:
4880 case AArch64::STRHpost:
4881 case AArch64::STRHpre:
4882 case AArch64::LDRHHpost:
4883 case AArch64::LDRHHpre:
4884 case AArch64::STRHHpost:
4885 case AArch64::STRHHpre:
4886 Scale = TypeSize::getFixed(1);
4887 Width = TypeSize::getFixed(2);
4888 MinOffset = -256;
4889 MaxOffset = 255;
4890 break;
4891 case AArch64::LDRBpost:
4892 case AArch64::LDRBpre:
4893 case AArch64::STRBpost:
4894 case AArch64::STRBpre:
4895 case AArch64::LDRBBpost:
4896 case AArch64::LDRBBpre:
4897 case AArch64::STRBBpost:
4898 case AArch64::STRBBpre:
4899 Scale = Width = TypeSize::getFixed(1);
4900 MinOffset = -256;
4901 MaxOffset = 255;
4902 break;
4903 // Unscaled
4904 case AArch64::LDURQi:
4905 case AArch64::STURQi:
4906 Scale = TypeSize::getFixed(1);
4907 Width = TypeSize::getFixed(16);
4908 MinOffset = -256;
4909 MaxOffset = 255;
4910 break;
4911 case AArch64::LDURXi:
4912 case AArch64::LDURDi:
4913 case AArch64::LDAPURXi:
4914 case AArch64::STURXi:
4915 case AArch64::STURDi:
4916 case AArch64::STLURXi:
4917 case AArch64::PRFUMi:
4918 case AArch64::ATOMIC_STORE_HINT_Xi:
4919 case AArch64::ATOMIC_STORE_HINT_Di:
4920 Scale = TypeSize::getFixed(1);
4921 Width = TypeSize::getFixed(8);
4922 MinOffset = -256;
4923 MaxOffset = 255;
4924 break;
4925 case AArch64::LDURWi:
4926 case AArch64::LDURSi:
4927 case AArch64::LDURSWi:
4928 case AArch64::LDAPURi:
4929 case AArch64::LDAPURSWi:
4930 case AArch64::STURWi:
4931 case AArch64::STURSi:
4932 case AArch64::STLURWi:
4933 case AArch64::ATOMIC_STORE_HINT_Wi:
4934 case AArch64::ATOMIC_STORE_HINT_Si:
4935 Scale = TypeSize::getFixed(1);
4936 Width = TypeSize::getFixed(4);
4937 MinOffset = -256;
4938 MaxOffset = 255;
4939 break;
4940 case AArch64::LDURHi:
4941 case AArch64::LDURHHi:
4942 case AArch64::LDURSHXi:
4943 case AArch64::LDURSHWi:
4944 case AArch64::LDAPURHi:
4945 case AArch64::LDAPURSHWi:
4946 case AArch64::LDAPURSHXi:
4947 case AArch64::STURHi:
4948 case AArch64::STURHHi:
4949 case AArch64::STLURHi:
4950 case AArch64::ATOMIC_STORE_HINT_Hi:
4951 Scale = TypeSize::getFixed(1);
4952 Width = TypeSize::getFixed(2);
4953 MinOffset = -256;
4954 MaxOffset = 255;
4955 break;
4956 case AArch64::LDURBi:
4957 case AArch64::LDURBBi:
4958 case AArch64::LDURSBXi:
4959 case AArch64::LDURSBWi:
4960 case AArch64::LDAPURBi:
4961 case AArch64::LDAPURSBWi:
4962 case AArch64::LDAPURSBXi:
4963 case AArch64::STURBi:
4964 case AArch64::STURBBi:
4965 case AArch64::STLURBi:
4966 case AArch64::ATOMIC_STORE_HINT_Bi:
4967 Scale = Width = TypeSize::getFixed(1);
4968 MinOffset = -256;
4969 MaxOffset = 255;
4970 break;
4971 // LDP / STP (including pre/post inc)
4972 case AArch64::LDPQi:
4973 case AArch64::LDNPQi:
4974 case AArch64::STPQi:
4975 case AArch64::STNPQi:
4976 case AArch64::LDPQpost:
4977 case AArch64::LDPQpre:
4978 case AArch64::STPQpost:
4979 case AArch64::STPQpre:
4980 Scale = TypeSize::getFixed(16);
4981 Width = TypeSize::getFixed(16 * 2);
4982 MinOffset = -64;
4983 MaxOffset = 63;
4984 break;
4985 case AArch64::LDPXi:
4986 case AArch64::LDPDi:
4987 case AArch64::LDNPXi:
4988 case AArch64::LDNPDi:
4989 case AArch64::STPXi:
4990 case AArch64::STPDi:
4991 case AArch64::STNPXi:
4992 case AArch64::STNPDi:
4993 case AArch64::LDPDpost:
4994 case AArch64::LDPDpre:
4995 case AArch64::LDPXpost:
4996 case AArch64::LDPXpre:
4997 case AArch64::STPDpost:
4998 case AArch64::STPDpre:
4999 case AArch64::STPXpost:
5000 case AArch64::STPXpre:
5001 Scale = TypeSize::getFixed(8);
5002 Width = TypeSize::getFixed(8 * 2);
5003 MinOffset = -64;
5004 MaxOffset = 63;
5005 break;
5006 case AArch64::LDPWi:
5007 case AArch64::LDPSi:
5008 case AArch64::LDNPWi:
5009 case AArch64::LDNPSi:
5010 case AArch64::STPWi:
5011 case AArch64::STPSi:
5012 case AArch64::STNPWi:
5013 case AArch64::STNPSi:
5014 case AArch64::LDPSpost:
5015 case AArch64::LDPSpre:
5016 case AArch64::LDPWpost:
5017 case AArch64::LDPWpre:
5018 case AArch64::STPSpost:
5019 case AArch64::STPSpre:
5020 case AArch64::STPWpost:
5021 case AArch64::STPWpre:
5022 Scale = TypeSize::getFixed(4);
5023 Width = TypeSize::getFixed(4 * 2);
5024 MinOffset = -64;
5025 MaxOffset = 63;
5026 break;
5027 case AArch64::StoreSwiftAsyncContext:
5028 // Store is an STRXui, but there might be an ADDXri in the expansion too.
5029 Scale = TypeSize::getFixed(1);
5030 Width = TypeSize::getFixed(8);
5031 MinOffset = 0;
5032 MaxOffset = 4095;
5033 break;
5034 case AArch64::ADDG:
5035 Scale = TypeSize::getFixed(16);
5036 Width = TypeSize::getFixed(0);
5037 MinOffset = 0;
5038 MaxOffset = 63;
5039 break;
5040 case AArch64::TAGPstack:
5041 Scale = TypeSize::getFixed(16);
5042 Width = TypeSize::getFixed(0);
5043 // TAGP with a negative offset turns into SUBP, which has a maximum offset
5044 // of 63 (not 64!).
5045 MinOffset = -63;
5046 MaxOffset = 63;
5047 break;
5048 case AArch64::LDG:
5049 case AArch64::STGi:
5050 case AArch64::STGPreIndex:
5051 case AArch64::STGPostIndex:
5052 case AArch64::STZGi:
5053 case AArch64::STZGPreIndex:
5054 case AArch64::STZGPostIndex:
5055 Scale = Width = TypeSize::getFixed(16);
5056 MinOffset = -256;
5057 MaxOffset = 255;
5058 break;
5059 // SVE
5060 case AArch64::STR_ZZZZXI:
5061 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
5062 case AArch64::LDR_ZZZZXI:
5063 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
5064 Scale = TypeSize::getScalable(16);
5065 Width = TypeSize::getScalable(16 * 4);
5066 MinOffset = -256;
5067 MaxOffset = 252;
5068 break;
5069 case AArch64::STR_ZZZXI:
5070 case AArch64::LDR_ZZZXI:
5071 Scale = TypeSize::getScalable(16);
5072 Width = TypeSize::getScalable(16 * 3);
5073 MinOffset = -256;
5074 MaxOffset = 253;
5075 break;
5076 case AArch64::STR_ZZXI:
5077 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
5078 case AArch64::LDR_ZZXI:
5079 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
5080 Scale = TypeSize::getScalable(16);
5081 Width = TypeSize::getScalable(16 * 2);
5082 MinOffset = -256;
5083 MaxOffset = 254;
5084 break;
5085 case AArch64::LDR_PXI:
5086 case AArch64::STR_PXI:
5087 Scale = Width = TypeSize::getScalable(2);
5088 MinOffset = -256;
5089 MaxOffset = 255;
5090 break;
5091 case AArch64::LDR_PPXI:
5092 case AArch64::STR_PPXI:
5093 Scale = TypeSize::getScalable(2);
5094 Width = TypeSize::getScalable(2 * 2);
5095 MinOffset = -256;
5096 MaxOffset = 254;
5097 break;
5098 case AArch64::LDR_ZXI:
5099 case AArch64::STR_ZXI:
5100 Scale = Width = TypeSize::getScalable(16);
5101 MinOffset = -256;
5102 MaxOffset = 255;
5103 break;
5104 case AArch64::LD1B_IMM:
5105 case AArch64::LD1H_IMM:
5106 case AArch64::LD1W_IMM:
5107 case AArch64::LD1D_IMM:
5108 case AArch64::LDNT1B_ZRI:
5109 case AArch64::LDNT1H_ZRI:
5110 case AArch64::LDNT1W_ZRI:
5111 case AArch64::LDNT1D_ZRI:
5112 case AArch64::ST1B_IMM:
5113 case AArch64::ST1H_IMM:
5114 case AArch64::ST1W_IMM:
5115 case AArch64::ST1D_IMM:
5116 case AArch64::STNT1B_ZRI:
5117 case AArch64::STNT1H_ZRI:
5118 case AArch64::STNT1W_ZRI:
5119 case AArch64::STNT1D_ZRI:
5120 case AArch64::LDNF1B_IMM:
5121 case AArch64::LDNF1H_IMM:
5122 case AArch64::LDNF1W_IMM:
5123 case AArch64::LDNF1D_IMM:
5124 // A full vectors worth of data
5125 // Width = mbytes * elements
5126 Scale = Width = TypeSize::getScalable(16);
5127 MinOffset = -8;
5128 MaxOffset = 7;
5129 break;
5130 case AArch64::LD2B_IMM:
5131 case AArch64::LD2H_IMM:
5132 case AArch64::LD2W_IMM:
5133 case AArch64::LD2D_IMM:
5134 case AArch64::ST2B_IMM:
5135 case AArch64::ST2H_IMM:
5136 case AArch64::ST2W_IMM:
5137 case AArch64::ST2D_IMM:
5138 case AArch64::LD1B_2Z_IMM:
5139 case AArch64::LD1B_2Z_STRIDED_IMM:
5140 case AArch64::LD1H_2Z_IMM:
5141 case AArch64::LD1H_2Z_STRIDED_IMM:
5142 case AArch64::LD1W_2Z_IMM:
5143 case AArch64::LD1W_2Z_STRIDED_IMM:
5144 case AArch64::LD1D_2Z_IMM:
5145 case AArch64::LD1D_2Z_STRIDED_IMM:
5146 case AArch64::LD1B_2Z_IMM_PSEUDO:
5147 case AArch64::LD1H_2Z_IMM_PSEUDO:
5148 case AArch64::LD1W_2Z_IMM_PSEUDO:
5149 case AArch64::LD1D_2Z_IMM_PSEUDO:
5150 case AArch64::ST1B_2Z_IMM:
5151 case AArch64::ST1B_2Z_STRIDED_IMM:
5152 case AArch64::ST1H_2Z_IMM:
5153 case AArch64::ST1H_2Z_STRIDED_IMM:
5154 case AArch64::ST1W_2Z_IMM:
5155 case AArch64::ST1W_2Z_STRIDED_IMM:
5156 case AArch64::ST1D_2Z_IMM:
5157 case AArch64::ST1D_2Z_STRIDED_IMM:
5158 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
5159 case AArch64::LDNT1B_2Z_IMM:
5160 case AArch64::LDNT1B_2Z_STRIDED_IMM:
5161 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
5162 case AArch64::LDNT1H_2Z_IMM:
5163 case AArch64::LDNT1H_2Z_STRIDED_IMM:
5164 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
5165 case AArch64::LDNT1W_2Z_IMM:
5166 case AArch64::LDNT1W_2Z_STRIDED_IMM:
5167 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
5168 case AArch64::LDNT1D_2Z_IMM:
5169 case AArch64::LDNT1D_2Z_STRIDED_IMM:
5170 case AArch64::STNT1B_2Z_IMM:
5171 case AArch64::STNT1B_2Z_STRIDED_IMM:
5172 case AArch64::STNT1H_2Z_IMM:
5173 case AArch64::STNT1H_2Z_STRIDED_IMM:
5174 case AArch64::STNT1W_2Z_IMM:
5175 case AArch64::STNT1W_2Z_STRIDED_IMM:
5176 case AArch64::STNT1D_2Z_IMM:
5177 case AArch64::STNT1D_2Z_STRIDED_IMM:
5178 case AArch64::ST1B_2Z_IMM_PSEUDO:
5179 case AArch64::ST1H_2Z_IMM_PSEUDO:
5180 case AArch64::ST1W_2Z_IMM_PSEUDO:
5181 case AArch64::ST1D_2Z_IMM_PSEUDO:
5182 case AArch64::STNT1B_2Z_IMM_PSEUDO:
5183 case AArch64::STNT1H_2Z_IMM_PSEUDO:
5184 case AArch64::STNT1W_2Z_IMM_PSEUDO:
5185 case AArch64::STNT1D_2Z_IMM_PSEUDO:
5186 Scale = Width = TypeSize::getScalable(16 * 2);
5187 MinOffset = -8;
5188 MaxOffset = 7;
5189 break;
5190 case AArch64::LD3B_IMM:
5191 case AArch64::LD3H_IMM:
5192 case AArch64::LD3W_IMM:
5193 case AArch64::LD3D_IMM:
5194 case AArch64::ST3B_IMM:
5195 case AArch64::ST3H_IMM:
5196 case AArch64::ST3W_IMM:
5197 case AArch64::ST3D_IMM:
5198 Scale = Width = TypeSize::getScalable(16 * 3);
5199 MinOffset = -8;
5200 MaxOffset = 7;
5201 break;
5202 case AArch64::LD4B_IMM:
5203 case AArch64::LD4H_IMM:
5204 case AArch64::LD4W_IMM:
5205 case AArch64::LD4D_IMM:
5206 case AArch64::ST4B_IMM:
5207 case AArch64::ST4H_IMM:
5208 case AArch64::ST4W_IMM:
5209 case AArch64::ST4D_IMM:
5210 case AArch64::LD1B_4Z_IMM:
5211 case AArch64::LD1B_4Z_STRIDED_IMM:
5212 case AArch64::LD1H_4Z_IMM:
5213 case AArch64::LD1H_4Z_STRIDED_IMM:
5214 case AArch64::LD1W_4Z_IMM:
5215 case AArch64::LD1W_4Z_STRIDED_IMM:
5216 case AArch64::LD1D_4Z_IMM:
5217 case AArch64::LD1D_4Z_STRIDED_IMM:
5218 case AArch64::LD1B_4Z_IMM_PSEUDO:
5219 case AArch64::LD1H_4Z_IMM_PSEUDO:
5220 case AArch64::LD1W_4Z_IMM_PSEUDO:
5221 case AArch64::LD1D_4Z_IMM_PSEUDO:
5222 case AArch64::ST1B_4Z_IMM:
5223 case AArch64::ST1B_4Z_STRIDED_IMM:
5224 case AArch64::ST1H_4Z_IMM:
5225 case AArch64::ST1H_4Z_STRIDED_IMM:
5226 case AArch64::ST1W_4Z_IMM:
5227 case AArch64::ST1W_4Z_STRIDED_IMM:
5228 case AArch64::ST1D_4Z_IMM:
5229 case AArch64::ST1D_4Z_STRIDED_IMM:
5230 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
5231 case AArch64::LDNT1B_4Z_IMM:
5232 case AArch64::LDNT1B_4Z_STRIDED_IMM:
5233 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
5234 case AArch64::LDNT1H_4Z_IMM:
5235 case AArch64::LDNT1H_4Z_STRIDED_IMM:
5236 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
5237 case AArch64::LDNT1W_4Z_IMM:
5238 case AArch64::LDNT1W_4Z_STRIDED_IMM:
5239 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
5240 case AArch64::LDNT1D_4Z_IMM:
5241 case AArch64::LDNT1D_4Z_STRIDED_IMM:
5242 case AArch64::STNT1B_4Z_IMM:
5243 case AArch64::STNT1B_4Z_STRIDED_IMM:
5244 case AArch64::STNT1H_4Z_IMM:
5245 case AArch64::STNT1H_4Z_STRIDED_IMM:
5246 case AArch64::STNT1W_4Z_IMM:
5247 case AArch64::STNT1W_4Z_STRIDED_IMM:
5248 case AArch64::STNT1D_4Z_IMM:
5249 case AArch64::STNT1D_4Z_STRIDED_IMM:
5250 case AArch64::ST1B_4Z_IMM_PSEUDO:
5251 case AArch64::ST1H_4Z_IMM_PSEUDO:
5252 case AArch64::ST1W_4Z_IMM_PSEUDO:
5253 case AArch64::ST1D_4Z_IMM_PSEUDO:
5254 case AArch64::STNT1B_4Z_IMM_PSEUDO:
5255 case AArch64::STNT1H_4Z_IMM_PSEUDO:
5256 case AArch64::STNT1W_4Z_IMM_PSEUDO:
5257 case AArch64::STNT1D_4Z_IMM_PSEUDO:
5258 Scale = Width = TypeSize::getScalable(16 * 4);
5259 MinOffset = -8;
5260 MaxOffset = 7;
5261 break;
5262 case AArch64::LD1B_H_IMM:
5263 case AArch64::LD1SB_H_IMM:
5264 case AArch64::LD1H_S_IMM:
5265 case AArch64::LD1SH_S_IMM:
5266 case AArch64::LD1W_D_IMM:
5267 case AArch64::LD1SW_D_IMM:
5268 case AArch64::ST1B_H_IMM:
5269 case AArch64::ST1H_S_IMM:
5270 case AArch64::ST1W_D_IMM:
5271 case AArch64::LDNF1B_H_IMM:
5272 case AArch64::LDNF1SB_H_IMM:
5273 case AArch64::LDNF1H_S_IMM:
5274 case AArch64::LDNF1SH_S_IMM:
5275 case AArch64::LDNF1W_D_IMM:
5276 case AArch64::LDNF1SW_D_IMM:
5277 // A half vector worth of data
5278 // Width = mbytes * elements
5279 Scale = Width = TypeSize::getScalable(8);
5280 MinOffset = -8;
5281 MaxOffset = 7;
5282 break;
5283 case AArch64::LD1B_S_IMM:
5284 case AArch64::LD1SB_S_IMM:
5285 case AArch64::LD1H_D_IMM:
5286 case AArch64::LD1SH_D_IMM:
5287 case AArch64::ST1B_S_IMM:
5288 case AArch64::ST1H_D_IMM:
5289 case AArch64::LDNF1B_S_IMM:
5290 case AArch64::LDNF1SB_S_IMM:
5291 case AArch64::LDNF1H_D_IMM:
5292 case AArch64::LDNF1SH_D_IMM:
5293 // A quarter vector worth of data
5294 // Width = mbytes * elements
5295 Scale = Width = TypeSize::getScalable(4);
5296 MinOffset = -8;
5297 MaxOffset = 7;
5298 break;
5299 case AArch64::LD1B_D_IMM:
5300 case AArch64::LD1SB_D_IMM:
5301 case AArch64::ST1B_D_IMM:
5302 case AArch64::LDNF1B_D_IMM:
5303 case AArch64::LDNF1SB_D_IMM:
5304 // A eighth vector worth of data
5305 // Width = mbytes * elements
5306 Scale = Width = TypeSize::getScalable(2);
5307 MinOffset = -8;
5308 MaxOffset = 7;
5309 break;
5310 case AArch64::ST2Gi:
5311 case AArch64::ST2GPreIndex:
5312 case AArch64::ST2GPostIndex:
5313 case AArch64::STZ2Gi:
5314 case AArch64::STZ2GPreIndex:
5315 case AArch64::STZ2GPostIndex:
5316 Scale = TypeSize::getFixed(16);
5317 Width = TypeSize::getFixed(32);
5318 MinOffset = -256;
5319 MaxOffset = 255;
5320 break;
5321 case AArch64::STGPi:
5322 case AArch64::STGPpost:
5323 case AArch64::STGPpre:
5324 Scale = Width = TypeSize::getFixed(16);
5325 MinOffset = -64;
5326 MaxOffset = 63;
5327 break;
5328 case AArch64::LD1RB_IMM:
5329 case AArch64::LD1RB_H_IMM:
5330 case AArch64::LD1RB_S_IMM:
5331 case AArch64::LD1RB_D_IMM:
5332 case AArch64::LD1RSB_H_IMM:
5333 case AArch64::LD1RSB_S_IMM:
5334 case AArch64::LD1RSB_D_IMM:
5335 Scale = Width = TypeSize::getFixed(1);
5336 MinOffset = 0;
5337 MaxOffset = 63;
5338 break;
5339 case AArch64::LD1RH_IMM:
5340 case AArch64::LD1RH_S_IMM:
5341 case AArch64::LD1RH_D_IMM:
5342 case AArch64::LD1RSH_S_IMM:
5343 case AArch64::LD1RSH_D_IMM:
5344 Scale = Width = TypeSize::getFixed(2);
5345 MinOffset = 0;
5346 MaxOffset = 63;
5347 break;
5348 case AArch64::LD1RW_IMM:
5349 case AArch64::LD1RW_D_IMM:
5350 case AArch64::LD1RSW_IMM:
5351 Scale = Width = TypeSize::getFixed(4);
5352 MinOffset = 0;
5353 MaxOffset = 63;
5354 break;
5355 case AArch64::LD1RD_IMM:
5356 Scale = Width = TypeSize::getFixed(8);
5357 MinOffset = 0;
5358 MaxOffset = 63;
5359 break;
5360 }
5361
5362 return true;
5363}
5364
5365// Scaling factor for unscaled load or store.
5367 switch (Opc) {
5368 default:
5369 llvm_unreachable("Opcode has unknown scale!");
5370 case AArch64::LDRBui:
5371 case AArch64::LDRBBui:
5372 case AArch64::LDURBBi:
5373 case AArch64::LDRSBWui:
5374 case AArch64::LDURSBWi:
5375 case AArch64::STRBui:
5376 case AArch64::STRBBui:
5377 case AArch64::STURBBi:
5378 return 1;
5379 case AArch64::LDRHui:
5380 case AArch64::LDRHHui:
5381 case AArch64::LDURHHi:
5382 case AArch64::LDRSHWui:
5383 case AArch64::LDURSHWi:
5384 case AArch64::STRHui:
5385 case AArch64::STRHHui:
5386 case AArch64::STURHHi:
5387 return 2;
5388 case AArch64::LDRSui:
5389 case AArch64::LDURSi:
5390 case AArch64::LDRSpre:
5391 case AArch64::LDRSWui:
5392 case AArch64::LDURSWi:
5393 case AArch64::LDRSWpre:
5394 case AArch64::LDRWpre:
5395 case AArch64::LDRWui:
5396 case AArch64::LDURWi:
5397 case AArch64::STRSui:
5398 case AArch64::STURSi:
5399 case AArch64::STRSpre:
5400 case AArch64::STRWui:
5401 case AArch64::STURWi:
5402 case AArch64::STRWpre:
5403 case AArch64::LDPSi:
5404 case AArch64::LDPSWi:
5405 case AArch64::LDPWi:
5406 case AArch64::STPSi:
5407 case AArch64::STPWi:
5408 return 4;
5409 case AArch64::LDRDui:
5410 case AArch64::LDURDi:
5411 case AArch64::LDRDpre:
5412 case AArch64::LDRXui:
5413 case AArch64::LDURXi:
5414 case AArch64::LDRXpre:
5415 case AArch64::STRDui:
5416 case AArch64::STURDi:
5417 case AArch64::STRDpre:
5418 case AArch64::STRXui:
5419 case AArch64::STURXi:
5420 case AArch64::STRXpre:
5421 case AArch64::LDPDi:
5422 case AArch64::LDPXi:
5423 case AArch64::STPDi:
5424 case AArch64::STPXi:
5425 return 8;
5426 case AArch64::LDRQui:
5427 case AArch64::LDURQi:
5428 case AArch64::STRQui:
5429 case AArch64::STURQi:
5430 case AArch64::STRQpre:
5431 case AArch64::LDPQi:
5432 case AArch64::LDRQpre:
5433 case AArch64::STPQi:
5434 case AArch64::STGi:
5435 case AArch64::STZGi:
5436 case AArch64::ST2Gi:
5437 case AArch64::STZ2Gi:
5438 case AArch64::STGPi:
5439 return 16;
5440 }
5441}
5442
5444 switch (MI.getOpcode()) {
5445 default:
5446 return false;
5447 case AArch64::LDRWpre:
5448 case AArch64::LDRXpre:
5449 case AArch64::LDRSWpre:
5450 case AArch64::LDRSpre:
5451 case AArch64::LDRDpre:
5452 case AArch64::LDRQpre:
5453 return true;
5454 }
5455}
5456
5458 switch (MI.getOpcode()) {
5459 default:
5460 return false;
5461 case AArch64::STRWpre:
5462 case AArch64::STRXpre:
5463 case AArch64::STRSpre:
5464 case AArch64::STRDpre:
5465 case AArch64::STRQpre:
5466 return true;
5467 }
5468}
5469
5471 return isPreLd(MI) || isPreSt(MI);
5472}
5473
5475 switch (MI.getOpcode()) {
5476 default:
5477 return false;
5478 case AArch64::LDURBBi:
5479 case AArch64::LDURHHi:
5480 case AArch64::LDURWi:
5481 case AArch64::LDRBBui:
5482 case AArch64::LDRHHui:
5483 case AArch64::LDRWui:
5484 case AArch64::LDRBBroX:
5485 case AArch64::LDRHHroX:
5486 case AArch64::LDRWroX:
5487 case AArch64::LDRBBroW:
5488 case AArch64::LDRHHroW:
5489 case AArch64::LDRWroW:
5490 return true;
5491 }
5492}
5493
5495 switch (MI.getOpcode()) {
5496 default:
5497 return false;
5498 case AArch64::LDURSBWi:
5499 case AArch64::LDURSHWi:
5500 case AArch64::LDURSBXi:
5501 case AArch64::LDURSHXi:
5502 case AArch64::LDURSWi:
5503 case AArch64::LDRSBWui:
5504 case AArch64::LDRSHWui:
5505 case AArch64::LDRSBXui:
5506 case AArch64::LDRSHXui:
5507 case AArch64::LDRSWui:
5508 case AArch64::LDRSBWroX:
5509 case AArch64::LDRSHWroX:
5510 case AArch64::LDRSBXroX:
5511 case AArch64::LDRSHXroX:
5512 case AArch64::LDRSWroX:
5513 case AArch64::LDRSBWroW:
5514 case AArch64::LDRSHWroW:
5515 case AArch64::LDRSBXroW:
5516 case AArch64::LDRSHXroW:
5517 case AArch64::LDRSWroW:
5518 return true;
5519 }
5520}
5521
5523 switch (MI.getOpcode()) {
5524 default:
5525 return false;
5526 case AArch64::LDPSi:
5527 case AArch64::LDPSWi:
5528 case AArch64::LDPDi:
5529 case AArch64::LDPQi:
5530 case AArch64::LDPWi:
5531 case AArch64::LDPXi:
5532 case AArch64::STPSi:
5533 case AArch64::STPDi:
5534 case AArch64::STPQi:
5535 case AArch64::STPWi:
5536 case AArch64::STPXi:
5537 case AArch64::STGPi:
5538 return true;
5539 }
5540}
5541
5543 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5544 unsigned Idx =
5546 : 1;
5547 return MI.getOperand(Idx);
5548}
5549
5550const MachineOperand &
5552 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5553 unsigned Idx =
5555 : 2;
5556 return MI.getOperand(Idx);
5557}
5558
5559const MachineOperand &
5561 switch (MI.getOpcode()) {
5562 default:
5563 llvm_unreachable("Unexpected opcode");
5564 case AArch64::LDRBroX:
5565 case AArch64::LDRBBroX:
5566 case AArch64::LDRSBXroX:
5567 case AArch64::LDRSBWroX:
5568 case AArch64::LDRHroX:
5569 case AArch64::LDRHHroX:
5570 case AArch64::LDRSHXroX:
5571 case AArch64::LDRSHWroX:
5572 case AArch64::LDRWroX:
5573 case AArch64::LDRSroX:
5574 case AArch64::LDRSWroX:
5575 case AArch64::LDRDroX:
5576 case AArch64::LDRXroX:
5577 case AArch64::LDRQroX:
5578 return MI.getOperand(4);
5579 }
5580}
5581
5583 Register Reg) {
5584 if (MI.getParent() == nullptr)
5585 return nullptr;
5586 const MachineFunction *MF = MI.getParent()->getParent();
5587 return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
5588}
5589
5591 auto IsHFPR = [&](const MachineOperand &Op) {
5592 if (!Op.isReg())
5593 return false;
5594 auto Reg = Op.getReg();
5595 if (Reg.isPhysical())
5596 return AArch64::FPR16RegClass.contains(Reg);
5597 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5598 return TRC == &AArch64::FPR16RegClass ||
5599 TRC == &AArch64::FPR16_loRegClass;
5600 };
5601 return llvm::any_of(MI.operands(), IsHFPR);
5602}
5603
5605 auto IsQFPR = [&](const MachineOperand &Op) {
5606 if (!Op.isReg())
5607 return false;
5608 auto Reg = Op.getReg();
5609 if (Reg.isPhysical())
5610 return AArch64::FPR128RegClass.contains(Reg);
5611 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5612 return TRC == &AArch64::FPR128RegClass ||
5613 TRC == &AArch64::FPR128_loRegClass;
5614 };
5615 return llvm::any_of(MI.operands(), IsQFPR);
5616}
5617
5619 switch (MI.getOpcode()) {
5620 case AArch64::BRK:
5621 case AArch64::HLT:
5622 case AArch64::PACIASP:
5623 case AArch64::PACIBSP:
5624 case AArch64::PACIASPPC:
5625 case AArch64::PACIBSPPC:
5626 // Implicit BTI behavior.
5627 return true;
5628 case AArch64::PAUTH_PROLOGUE:
5629 // PAUTH_PROLOGUE expands to PACI(A|B)SP.
5630 return true;
5631 case AArch64::HINT: {
5632 unsigned Imm = MI.getOperand(0).getImm();
5633 // Explicit BTI instruction.
5634 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
5635 return true;
5636 // PACI(A|B)SP instructions.
5637 if (Imm == 25 || Imm == 27)
5638 return true;
5639 return false;
5640 }
5641 default:
5642 return false;
5643 }
5644}
5645
5647 if (Reg == 0)
5648 return false;
5649 assert(Reg.isPhysical() && "Expected physical register in isFpOrNEON");
5650 return AArch64::FPR128RegClass.contains(Reg) ||
5651 AArch64::FPR64RegClass.contains(Reg) ||
5652 AArch64::FPR32RegClass.contains(Reg) ||
5653 AArch64::FPR16RegClass.contains(Reg) ||
5654 AArch64::FPR8RegClass.contains(Reg);
5655}
5656
5658 auto IsFPR = [&](const MachineOperand &Op) {
5659 if (!Op.isReg())
5660 return false;
5661 auto Reg = Op.getReg();
5662 if (Reg.isPhysical())
5663 return isFpOrNEON(Reg);
5664
5665 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5666 return TRC == &AArch64::FPR128RegClass ||
5667 TRC == &AArch64::FPR128_loRegClass ||
5668 TRC == &AArch64::FPR64RegClass ||
5669 TRC == &AArch64::FPR64_loRegClass ||
5670 TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
5671 TRC == &AArch64::FPR8RegClass;
5672 };
5673 return llvm::any_of(MI.operands(), IsFPR);
5674}
5675
5676// Scale the unscaled offsets. Returns false if the unscaled offset can't be
5677// scaled.
5678static bool scaleOffset(unsigned Opc, int64_t &Offset) {
5680
5681 // If the byte-offset isn't a multiple of the stride, we can't scale this
5682 // offset.
5683 if (Offset % Scale != 0)
5684 return false;
5685
5686 // Convert the byte-offset used by unscaled into an "element" offset used
5687 // by the scaled pair load/store instructions.
5688 Offset /= Scale;
5689 return true;
5690}
5691
5692static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
5693 if (FirstOpc == SecondOpc)
5694 return true;
5695 // We can also pair sign-ext and zero-ext instructions.
5696 switch (FirstOpc) {
5697 default:
5698 return false;
5699 case AArch64::STRSui:
5700 case AArch64::STURSi:
5701 return SecondOpc == AArch64::STRSui || SecondOpc == AArch64::STURSi;
5702 case AArch64::STRDui:
5703 case AArch64::STURDi:
5704 return SecondOpc == AArch64::STRDui || SecondOpc == AArch64::STURDi;
5705 case AArch64::STRQui:
5706 case AArch64::STURQi:
5707 return SecondOpc == AArch64::STRQui || SecondOpc == AArch64::STURQi;
5708 case AArch64::STRWui:
5709 case AArch64::STURWi:
5710 return SecondOpc == AArch64::STRWui || SecondOpc == AArch64::STURWi;
5711 case AArch64::STRXui:
5712 case AArch64::STURXi:
5713 return SecondOpc == AArch64::STRXui || SecondOpc == AArch64::STURXi;
5714 case AArch64::LDRSui:
5715 case AArch64::LDURSi:
5716 return SecondOpc == AArch64::LDRSui || SecondOpc == AArch64::LDURSi;
5717 case AArch64::LDRDui:
5718 case AArch64::LDURDi:
5719 return SecondOpc == AArch64::LDRDui || SecondOpc == AArch64::LDURDi;
5720 case AArch64::LDRQui:
5721 case AArch64::LDURQi:
5722 return SecondOpc == AArch64::LDRQui || SecondOpc == AArch64::LDURQi;
5723 case AArch64::LDRWui:
5724 case AArch64::LDURWi:
5725 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
5726 case AArch64::LDRSWui:
5727 case AArch64::LDURSWi:
5728 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
5729 case AArch64::LDRXui:
5730 case AArch64::LDURXi:
5731 return SecondOpc == AArch64::LDRXui || SecondOpc == AArch64::LDURXi;
5732 }
5733 // These instructions can't be paired based on their opcodes.
5734 return false;
5735}
5736
5737static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
5738 int64_t Offset1, unsigned Opcode1, int FI2,
5739 int64_t Offset2, unsigned Opcode2) {
5740 // Accesses through fixed stack object frame indices may access a different
5741 // fixed stack slot. Check that the object offsets + offsets match.
5742 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
5743 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
5744 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
5745 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
5746 // Convert to scaled object offsets.
5747 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
5748 if (ObjectOffset1 % Scale1 != 0)
5749 return false;
5750 ObjectOffset1 /= Scale1;
5751 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
5752 if (ObjectOffset2 % Scale2 != 0)
5753 return false;
5754 ObjectOffset2 /= Scale2;
5755 ObjectOffset1 += Offset1;
5756 ObjectOffset2 += Offset2;
5757 return ObjectOffset1 + 1 == ObjectOffset2;
5758 }
5759
5760 return FI1 == FI2;
5761}
5762
5763/// Detect opportunities for ldp/stp formation.
5764///
5765/// Only called for LdSt for which getMemOperandWithOffset returns true.
5767 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
5768 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
5769 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
5770 unsigned NumBytes) const {
5771 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
5772 const MachineOperand &BaseOp1 = *BaseOps1.front();
5773 const MachineOperand &BaseOp2 = *BaseOps2.front();
5774 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
5775 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
5776 if (BaseOp1.getType() != BaseOp2.getType())
5777 return false;
5778
5779 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
5780 "Only base registers and frame indices are supported.");
5781
5782 // Check for both base regs and base FI.
5783 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
5784 return false;
5785
5786 // Only cluster up to a single pair.
5787 if (ClusterSize > 2)
5788 return false;
5789
5790 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
5791 return false;
5792
5793 // Can we pair these instructions based on their opcodes?
5794 unsigned FirstOpc = FirstLdSt.getOpcode();
5795 unsigned SecondOpc = SecondLdSt.getOpcode();
5796 if (!canPairLdStOpc(FirstOpc, SecondOpc))
5797 return false;
5798
5799 // Can't merge volatiles or load/stores that have a hint to avoid pair
5800 // formation, for example.
5801 if (!isCandidateToMergeOrPair(FirstLdSt) ||
5802 !isCandidateToMergeOrPair(SecondLdSt))
5803 return false;
5804
5805 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
5806 int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
5807 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
5808 return false;
5809
5810 int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
5811 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
5812 return false;
5813
5814 // Pairwise instructions have a 7-bit signed offset field.
5815 if (Offset1 > 63 || Offset1 < -64)
5816 return false;
5817
5818 // The caller should already have ordered First/SecondLdSt by offset.
5819 // Note: except for non-equal frame index bases
5820 if (BaseOp1.isFI()) {
5821 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
5822 "Caller should have ordered offsets.");
5823
5824 const MachineFrameInfo &MFI =
5825 FirstLdSt.getParent()->getParent()->getFrameInfo();
5826 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
5827 BaseOp2.getIndex(), Offset2, SecondOpc);
5828 }
5829
5830 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
5831
5832 return Offset1 + 1 == Offset2;
5833}
5834
5836 MCRegister Reg, unsigned SubIdx,
5837 RegState State,
5838 const TargetRegisterInfo *TRI) {
5839 if (!SubIdx)
5840 return MIB.addReg(Reg, State);
5841
5842 if (Reg.isPhysical())
5843 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
5844 return MIB.addReg(Reg, State, SubIdx);
5845}
5846
5849 const DebugLoc &DL, MCRegister DestReg,
5850 MCRegister SrcReg, bool KillSrc,
5851 ArrayRef<unsigned> Indices) const {
5852 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
5854 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5855 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5856 unsigned NumRegs = Indices.size();
5857 MCRegister DestSubReg = TRI->getSubReg(DestReg, Indices[0]);
5858 assert(!AArch64::PNRRegClass.contains(DestSubReg) &&
5859 "Unexpected predicate tuple copy");
5860 unsigned MaxRegs = AArch64::PPRRegClass.contains(DestSubReg) ? 15 : 31;
5861
5862 int SubReg = 0, End = NumRegs, Incr = 1;
5863 // Copy in reverse if a forward copy will clobber the tuple
5864 if (((DestEncoding - SrcEncoding) & MaxRegs) < NumRegs) {
5865 SubReg = NumRegs - 1;
5866 End = -1;
5867 Incr = -1;
5868 }
5869
5870 for (; SubReg != End; SubReg += Incr) {
5871 DestSubReg = TRI->getSubReg(DestReg, Indices[SubReg]);
5872 MCRegister SrcSubReg = TRI->getSubReg(SrcReg, Indices[SubReg]);
5873 copyPhysRegImpl(MBB, I, DL, DestSubReg, SrcSubReg, KillSrc);
5874 }
5875}
5876
5879 const DebugLoc &DL, MCRegister DestReg,
5880 MCRegister SrcReg, bool KillSrc,
5881 unsigned Opcode, unsigned ZeroReg,
5882 llvm::ArrayRef<unsigned> Indices) const {
5884 unsigned NumRegs = Indices.size();
5885
5886#ifndef NDEBUG
5887 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5888 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5889 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
5890 "GPR reg sequences should not be able to overlap");
5891#endif
5892
5893 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
5894 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5895 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5896 MIB.addReg(ZeroReg);
5897 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5898 MIB.addImm(0);
5899 }
5900}
5901
5902/// Returns true if the instruction at I is in a streaming call site region,
5903/// within a single basic block.
5904/// A "call site streaming region" starts after smstart and ends at smstop
5905/// around a call to a streaming function. This walks backward from I.
5908 MachineFunction &MF = *MBB.getParent();
5910 if (!AFI->hasStreamingModeChanges())
5911 return false;
5912 // Walk backwards to find smstart/smstop
5913 for (MachineInstr &MI : reverse(make_range(MBB.begin(), I))) {
5914 unsigned Opc = MI.getOpcode();
5915 if (Opc == AArch64::MSRpstatesvcrImm1 || Opc == AArch64::MSRpstatePseudo) {
5916 // Check if this is SM change (not ZA)
5917 int64_t PState = MI.getOperand(0).getImm();
5918 if (PState == AArch64SVCR::SVCRSM || PState == AArch64SVCR::SVCRSMZA) {
5919 // Operand 1 is 1 for start, 0 for stop
5920 return MI.getOperand(1).getImm() == 1;
5921 }
5922 }
5923 }
5924 return false;
5925}
5926
5927/// Returns true if in a streaming call site region without SME-FA64.
5933
5936 const DebugLoc &DL, Register DestReg,
5937 Register SrcReg, bool KillSrc,
5938 bool RenamableDest,
5939 bool RenamableSrc) const {
5940 if (AArch64::GPR32spRegClass.contains(DestReg) &&
5941 AArch64::GPR32spRegClass.contains(SrcReg)) {
5942 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
5943 // If either operand is WSP, expand to ADD #0.
5944 if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5945 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5946 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
5947 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5948 &AArch64::GPR64spRegClass);
5949 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5950 &AArch64::GPR64spRegClass);
5951 // This instruction is reading and writing X registers. This may upset
5952 // the register scavenger and machine verifier, so we need to indicate
5953 // that we are reading an undefined value from SrcRegX, but a proper
5954 // value from SrcReg.
5955 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
5956 .addReg(SrcRegX, RegState::Undef)
5957 .addImm(0)
5959 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5960 ++NumZCRegMoveInstrsGPR;
5961 } else {
5962 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
5963 .addReg(SrcReg, getKillRegState(KillSrc))
5964 .addImm(0)
5966 if (Subtarget.hasZeroCycleRegMoveGPR32())
5967 ++NumZCRegMoveInstrsGPR;
5968 }
5969 } else if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5970 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5971 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
5972 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5973 &AArch64::GPR64spRegClass);
5974 assert(DestRegX.isValid() && "Destination super-reg not valid");
5975 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5976 &AArch64::GPR64spRegClass);
5977 assert(SrcRegX.isValid() && "Source super-reg not valid");
5978 // This instruction is reading and writing X registers. This may upset
5979 // the register scavenger and machine verifier, so we need to indicate
5980 // that we are reading an undefined value from SrcRegX, but a proper
5981 // value from SrcReg.
5982 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
5983 .addReg(AArch64::XZR)
5984 .addReg(SrcRegX, RegState::Undef)
5985 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5986 ++NumZCRegMoveInstrsGPR;
5987 } else {
5988 // Otherwise, expand to ORR WZR.
5989 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5990 .addReg(AArch64::WZR)
5991 .addReg(SrcReg, getKillRegState(KillSrc));
5992 if (Subtarget.hasZeroCycleRegMoveGPR32())
5993 ++NumZCRegMoveInstrsGPR;
5994 }
5995 return;
5996 }
5997
5998 // GPR32 zeroing
5999 if (AArch64::GPR32spRegClass.contains(DestReg) && SrcReg == AArch64::WZR) {
6000 if (Subtarget.hasZeroCycleZeroingGPR64() &&
6001 !Subtarget.hasZeroCycleZeroingGPR32()) {
6002 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
6003 &AArch64::GPR64spRegClass);
6004 assert(DestRegX.isValid() && "Destination super-reg not valid");
6005 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestRegX)
6006 .addImm(0)
6008 ++NumZCZeroingInstrsGPR;
6009 } else if (Subtarget.hasZeroCycleZeroingGPR32()) {
6010 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
6011 .addImm(0)
6013 ++NumZCZeroingInstrsGPR;
6014 } else {
6015 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
6016 .addReg(AArch64::WZR)
6017 .addReg(AArch64::WZR);
6018 }
6019 return;
6020 }
6021
6022 if (AArch64::GPR64spRegClass.contains(DestReg) &&
6023 AArch64::GPR64spRegClass.contains(SrcReg)) {
6024 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
6025 // If either operand is SP, expand to ADD #0.
6026 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
6027 .addReg(SrcReg, getKillRegState(KillSrc))
6028 .addImm(0)
6030 if (Subtarget.hasZeroCycleRegMoveGPR64())
6031 ++NumZCRegMoveInstrsGPR;
6032 } else {
6033 // Otherwise, expand to ORR XZR.
6034 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
6035 .addReg(AArch64::XZR)
6036 .addReg(SrcReg, getKillRegState(KillSrc));
6037 if (Subtarget.hasZeroCycleRegMoveGPR64())
6038 ++NumZCRegMoveInstrsGPR;
6039 }
6040 return;
6041 }
6042
6043 // GPR64 zeroing
6044 if (AArch64::GPR64spRegClass.contains(DestReg) && SrcReg == AArch64::XZR) {
6045 if (Subtarget.hasZeroCycleZeroingGPR64()) {
6046 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
6047 .addImm(0)
6049 ++NumZCZeroingInstrsGPR;
6050 } else {
6051 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
6052 .addReg(AArch64::XZR)
6053 .addReg(AArch64::XZR);
6054 }
6055 return;
6056 }
6057
6058 // Copy a Predicate register by ORRing with itself.
6059 if (AArch64::PPRRegClass.contains(DestReg) &&
6060 AArch64::PPRRegClass.contains(SrcReg)) {
6061 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6062 "Unexpected SVE register.");
6063 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
6064 .addReg(SrcReg) // Pg
6065 .addReg(SrcReg)
6066 .addReg(SrcReg, getKillRegState(KillSrc));
6067 return;
6068 }
6069
6070 // Copy a predicate-as-counter register by ORRing with itself as if it
6071 // were a regular predicate (mask) register.
6072 bool DestIsPNR = AArch64::PNRRegClass.contains(DestReg);
6073 bool SrcIsPNR = AArch64::PNRRegClass.contains(SrcReg);
6074 if (DestIsPNR || SrcIsPNR) {
6075 auto ToPPR = [](MCRegister R) -> MCRegister {
6076 return (R - AArch64::PN0) + AArch64::P0;
6077 };
6078 MCRegister PPRSrcReg = SrcIsPNR ? ToPPR(SrcReg) : SrcReg.asMCReg();
6079 MCRegister PPRDestReg = DestIsPNR ? ToPPR(DestReg) : DestReg.asMCReg();
6080
6081 if (PPRSrcReg != PPRDestReg) {
6082 auto NewMI = BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), PPRDestReg)
6083 .addReg(PPRSrcReg) // Pg
6084 .addReg(PPRSrcReg)
6085 .addReg(PPRSrcReg, getKillRegState(KillSrc));
6086 if (DestIsPNR)
6087 NewMI.addDef(DestReg, RegState::Implicit);
6088 }
6089 return;
6090 }
6091
6092 // Copy a predicate register pair by copying the individual sub-registers.
6093 if (AArch64::PPR2RegClass.contains(DestReg) &&
6094 AArch64::PPR2RegClass.contains(SrcReg)) {
6095 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6096 "Unexpected SVE predicate register.");
6097 static const unsigned Indices[] = {AArch64::psub0, AArch64::psub1};
6098 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6099 return;
6100 }
6101
6102 // Copy a Z register by ORRing with itself.
6103 if (AArch64::ZPRRegClass.contains(DestReg) &&
6104 AArch64::ZPRRegClass.contains(SrcReg)) {
6105 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6106 "Unexpected SVE register.");
6107 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
6108 .addReg(SrcReg)
6109 .addReg(SrcReg, getKillRegState(KillSrc));
6110 return;
6111 }
6112
6113 // Copy a Z register pair by copying the individual sub-registers.
6114 if ((AArch64::ZPR2RegClass.contains(DestReg) ||
6115 AArch64::ZPR2StridedOrContiguousRegClass.contains(DestReg)) &&
6116 (AArch64::ZPR2RegClass.contains(SrcReg) ||
6117 AArch64::ZPR2StridedOrContiguousRegClass.contains(SrcReg))) {
6118 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6119 "Unexpected SVE register.");
6120 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
6121 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6122 return;
6123 }
6124
6125 // Copy a Z register triple by copying the individual sub-registers.
6126 if (AArch64::ZPR3RegClass.contains(DestReg) &&
6127 AArch64::ZPR3RegClass.contains(SrcReg)) {
6128 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6129 "Unexpected SVE register.");
6130 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6131 AArch64::zsub2};
6132 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6133 return;
6134 }
6135
6136 // Copy a Z register quad by copying the individual sub-registers.
6137 if ((AArch64::ZPR4RegClass.contains(DestReg) ||
6138 AArch64::ZPR4StridedOrContiguousRegClass.contains(DestReg)) &&
6139 (AArch64::ZPR4RegClass.contains(SrcReg) ||
6140 AArch64::ZPR4StridedOrContiguousRegClass.contains(SrcReg))) {
6141 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6142 "Unexpected SVE register.");
6143 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6144 AArch64::zsub2, AArch64::zsub3};
6145 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6146 return;
6147 }
6148
6149 // Copy a DDDD register quad by copying the individual sub-registers.
6150 if (AArch64::DDDDRegClass.contains(DestReg) &&
6151 AArch64::DDDDRegClass.contains(SrcReg)) {
6152 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6153 AArch64::dsub2, AArch64::dsub3};
6154 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6155 return;
6156 }
6157
6158 // Copy a DDD register triple by copying the individual sub-registers.
6159 if (AArch64::DDDRegClass.contains(DestReg) &&
6160 AArch64::DDDRegClass.contains(SrcReg)) {
6161 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6162 AArch64::dsub2};
6163 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6164 return;
6165 }
6166
6167 // Copy a DD register pair by copying the individual sub-registers.
6168 if (AArch64::DDRegClass.contains(DestReg) &&
6169 AArch64::DDRegClass.contains(SrcReg)) {
6170 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
6171 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6172 return;
6173 }
6174
6175 // Copy a QQQQ register quad by copying the individual sub-registers.
6176 if (AArch64::QQQQRegClass.contains(DestReg) &&
6177 AArch64::QQQQRegClass.contains(SrcReg)) {
6178 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6179 AArch64::qsub2, AArch64::qsub3};
6180 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6181 return;
6182 }
6183
6184 // Copy a QQQ register triple by copying the individual sub-registers.
6185 if (AArch64::QQQRegClass.contains(DestReg) &&
6186 AArch64::QQQRegClass.contains(SrcReg)) {
6187 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6188 AArch64::qsub2};
6189 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6190 return;
6191 }
6192
6193 // Copy a QQ register pair by copying the individual sub-registers.
6194 if (AArch64::QQRegClass.contains(DestReg) &&
6195 AArch64::QQRegClass.contains(SrcReg)) {
6196 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
6197 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6198 return;
6199 }
6200
6201 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
6202 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
6203 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
6204 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
6205 AArch64::XZR, Indices);
6206 return;
6207 }
6208
6209 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
6210 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
6211 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
6212 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
6213 AArch64::WZR, Indices);
6214 return;
6215 }
6216
6217 if (AArch64::FPR128RegClass.contains(DestReg) &&
6218 AArch64::FPR128RegClass.contains(SrcReg)) {
6219 // In streaming regions, NEON is illegal but streaming-SVE is available.
6220 // Use SVE for copies if we're in a streaming region and SME is available.
6221 // With +sme-fa64, NEON is legal in streaming mode so we can use it.
6222 if ((Subtarget.isSVEorStreamingSVEAvailable() &&
6223 !Subtarget.isNeonAvailable()) ||
6224 mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6225 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
6226 .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
6227 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
6228 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
6229 } else if (Subtarget.isNeonAvailable()) {
6230 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
6231 .addReg(SrcReg)
6232 .addReg(SrcReg, getKillRegState(KillSrc));
6233 if (Subtarget.hasZeroCycleRegMoveFPR128())
6234 ++NumZCRegMoveInstrsFPR;
6235 } else {
6236 BuildMI(MBB, I, DL, get(AArch64::STRQpre))
6237 .addReg(AArch64::SP, RegState::Define)
6238 .addReg(SrcReg, getKillRegState(KillSrc))
6239 .addReg(AArch64::SP)
6240 .addImm(-16);
6241 BuildMI(MBB, I, DL, get(AArch64::LDRQpost))
6242 .addReg(AArch64::SP, RegState::Define)
6243 .addReg(DestReg, RegState::Define)
6244 .addReg(AArch64::SP)
6245 .addImm(16);
6246 }
6247 return;
6248 }
6249
6250 if (AArch64::FPR64RegClass.contains(DestReg) &&
6251 AArch64::FPR64RegClass.contains(SrcReg)) {
6252 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6253 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6254 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6255 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6256 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::dsub,
6257 &AArch64::FPR128RegClass);
6258 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::dsub,
6259 &AArch64::FPR128RegClass);
6260 // This instruction is reading and writing Q registers. This may upset
6261 // the register scavenger and machine verifier, so we need to indicate
6262 // that we are reading an undefined value from SrcRegQ, but a proper
6263 // value from SrcReg.
6264 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6265 .addReg(SrcRegQ, RegState::Undef)
6266 .addReg(SrcRegQ, RegState::Undef)
6267 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6268 ++NumZCRegMoveInstrsFPR;
6269 } else {
6270 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
6271 .addReg(SrcReg, getKillRegState(KillSrc));
6272 if (Subtarget.hasZeroCycleRegMoveFPR64())
6273 ++NumZCRegMoveInstrsFPR;
6274 }
6275 return;
6276 }
6277
6278 if (AArch64::FPR32RegClass.contains(DestReg) &&
6279 AArch64::FPR32RegClass.contains(SrcReg)) {
6280 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6281 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6282 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6283 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6284 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6285 &AArch64::FPR128RegClass);
6286 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6287 &AArch64::FPR128RegClass);
6288 // This instruction is reading and writing Q registers. This may upset
6289 // the register scavenger and machine verifier, so we need to indicate
6290 // that we are reading an undefined value from SrcRegQ, but a proper
6291 // value from SrcReg.
6292 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6293 .addReg(SrcRegQ, RegState::Undef)
6294 .addReg(SrcRegQ, RegState::Undef)
6295 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6296 ++NumZCRegMoveInstrsFPR;
6297 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6298 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6299 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6300 &AArch64::FPR64RegClass);
6301 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6302 &AArch64::FPR64RegClass);
6303 // This instruction is reading and writing D registers. This may upset
6304 // the register scavenger and machine verifier, so we need to indicate
6305 // that we are reading an undefined value from SrcRegD, but a proper
6306 // value from SrcReg.
6307 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6308 .addReg(SrcRegD, RegState::Undef)
6309 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6310 ++NumZCRegMoveInstrsFPR;
6311 } else {
6312 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6313 .addReg(SrcReg, getKillRegState(KillSrc));
6314 if (Subtarget.hasZeroCycleRegMoveFPR32())
6315 ++NumZCRegMoveInstrsFPR;
6316 }
6317 return;
6318 }
6319
6320 if (AArch64::FPR16RegClass.contains(DestReg) &&
6321 AArch64::FPR16RegClass.contains(SrcReg)) {
6322 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6323 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6324 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6325 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6326 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6327 &AArch64::FPR128RegClass);
6328 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6329 &AArch64::FPR128RegClass);
6330 // This instruction is reading and writing Q registers. This may upset
6331 // the register scavenger and machine verifier, so we need to indicate
6332 // that we are reading an undefined value from SrcRegQ, but a proper
6333 // value from SrcReg.
6334 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6335 .addReg(SrcRegQ, RegState::Undef)
6336 .addReg(SrcRegQ, RegState::Undef)
6337 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6338 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6339 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6340 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6341 &AArch64::FPR64RegClass);
6342 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6343 &AArch64::FPR64RegClass);
6344 // This instruction is reading and writing D registers. This may upset
6345 // the register scavenger and machine verifier, so we need to indicate
6346 // that we are reading an undefined value from SrcRegD, but a proper
6347 // value from SrcReg.
6348 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6349 .addReg(SrcRegD, RegState::Undef)
6350 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6351 } else {
6352 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6353 &AArch64::FPR32RegClass);
6354 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6355 &AArch64::FPR32RegClass);
6356 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6357 .addReg(SrcReg, getKillRegState(KillSrc));
6358 }
6359 return;
6360 }
6361
6362 if (AArch64::FPR8RegClass.contains(DestReg) &&
6363 AArch64::FPR8RegClass.contains(SrcReg)) {
6364 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6365 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6366 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6367 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6368 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6369 &AArch64::FPR128RegClass);
6370 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6371 &AArch64::FPR128RegClass);
6372 // This instruction is reading and writing Q registers. This may upset
6373 // the register scavenger and machine verifier, so we need to indicate
6374 // that we are reading an undefined value from SrcRegQ, but a proper
6375 // value from SrcReg.
6376 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6377 .addReg(SrcRegQ, RegState::Undef)
6378 .addReg(SrcRegQ, RegState::Undef)
6379 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6380 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6381 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6382 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6383 &AArch64::FPR64RegClass);
6384 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6385 &AArch64::FPR64RegClass);
6386 // This instruction is reading and writing D registers. This may upset
6387 // the register scavenger and machine verifier, so we need to indicate
6388 // that we are reading an undefined value from SrcRegD, but a proper
6389 // value from SrcReg.
6390 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6391 .addReg(SrcRegD, RegState::Undef)
6392 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6393 } else {
6394 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6395 &AArch64::FPR32RegClass);
6396 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6397 &AArch64::FPR32RegClass);
6398 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6399 .addReg(SrcReg, getKillRegState(KillSrc));
6400 }
6401 return;
6402 }
6403
6404 // Copies between GPR64 and FPR64.
6405 if (AArch64::FPR64RegClass.contains(DestReg) &&
6406 AArch64::GPR64RegClass.contains(SrcReg)) {
6407 if (AArch64::XZR == SrcReg) {
6408 BuildMI(MBB, I, DL, get(AArch64::FMOVD0), DestReg);
6409 } else {
6410 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
6411 .addReg(SrcReg, getKillRegState(KillSrc));
6412 }
6413 return;
6414 }
6415 if (AArch64::GPR64RegClass.contains(DestReg) &&
6416 AArch64::FPR64RegClass.contains(SrcReg)) {
6417 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
6418 .addReg(SrcReg, getKillRegState(KillSrc));
6419 return;
6420 }
6421 // Copies between GPR32 and FPR32.
6422 if (AArch64::FPR32RegClass.contains(DestReg) &&
6423 AArch64::GPR32RegClass.contains(SrcReg)) {
6424 if (AArch64::WZR == SrcReg) {
6425 BuildMI(MBB, I, DL, get(AArch64::FMOVS0), DestReg);
6426 } else {
6427 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
6428 .addReg(SrcReg, getKillRegState(KillSrc));
6429 }
6430 return;
6431 }
6432 if (AArch64::GPR32RegClass.contains(DestReg) &&
6433 AArch64::FPR32RegClass.contains(SrcReg)) {
6434 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
6435 .addReg(SrcReg, getKillRegState(KillSrc));
6436 return;
6437 }
6438
6439 if (DestReg == AArch64::NZCV) {
6440 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
6441 BuildMI(MBB, I, DL, get(AArch64::MSR))
6442 .addImm(AArch64SysReg::NZCV)
6443 .addReg(SrcReg, getKillRegState(KillSrc))
6444 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
6445 return;
6446 }
6447
6448 if (SrcReg == AArch64::NZCV) {
6449 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
6450 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
6451 .addImm(AArch64SysReg::NZCV)
6452 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
6453 return;
6454 }
6455
6456#ifndef NDEBUG
6457 errs() << RI.getRegAsmName(DestReg) << " = COPY " << RI.getRegAsmName(SrcReg)
6458 << "\n";
6459#endif
6460 llvm_unreachable("unimplemented reg-to-reg copy");
6461}
6462
6465 const DebugLoc &DL, Register DestReg,
6466 Register SrcReg, bool KillSrc,
6467 bool RenamableDest,
6468 bool RenamableSrc) const {
6469 ++NumCopyInstrs;
6470 copyPhysRegImpl(MBB, I, DL, DestReg, SrcReg, KillSrc, RenamableDest,
6471 RenamableSrc);
6472 return;
6473}
6474
6477 MachineBasicBlock::iterator InsertBefore,
6478 const MCInstrDesc &MCID,
6479 Register SrcReg, bool IsKill,
6480 unsigned SubIdx0, unsigned SubIdx1, int FI,
6481 MachineMemOperand *MMO) {
6482 Register SrcReg0 = SrcReg;
6483 Register SrcReg1 = SrcReg;
6484 if (SrcReg.isPhysical()) {
6485 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
6486 SubIdx0 = 0;
6487 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
6488 SubIdx1 = 0;
6489 }
6490 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6491 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
6492 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
6493 .addFrameIndex(FI)
6494 .addImm(0)
6495 .addMemOperand(MMO);
6496}
6497
6500 Register SrcReg, bool isKill, int FI,
6501 const TargetRegisterClass *RC,
6502 Register VReg,
6503 MachineInstr::MIFlag Flags) const {
6504 MachineFunction &MF = *MBB.getParent();
6505 MachineFrameInfo &MFI = MF.getFrameInfo();
6506
6508 MachineMemOperand *MMO =
6510 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6511 unsigned Opc = 0;
6512 bool Offset = true;
6514 unsigned StackID = TargetStackID::Default;
6515 switch (RI.getSpillSize(*RC)) {
6516 case 1:
6517 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6518 Opc = AArch64::STRBui;
6519 break;
6520 case 2: {
6521 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6522 Opc = AArch64::STRHui;
6523 else if (AArch64::PNRRegClass.hasSubClassEq(RC) ||
6524 AArch64::PPRRegClass.hasSubClassEq(RC)) {
6525 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6526 "Unexpected register store without SVE store instructions");
6527 Opc = AArch64::STR_PXI;
6529 }
6530 break;
6531 }
6532 case 4:
6533 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6534 Opc = AArch64::STRWui;
6535 if (SrcReg.isVirtual())
6536 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
6537 else
6538 assert(SrcReg != AArch64::WSP);
6539 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6540 Opc = AArch64::STRSui;
6541 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6542 Opc = AArch64::STR_PPXI;
6544 }
6545 break;
6546 case 8:
6547 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6548 Opc = AArch64::STRXui;
6549 if (SrcReg.isVirtual())
6550 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
6551 else
6552 assert(SrcReg != AArch64::SP);
6553 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6554 Opc = AArch64::STRDui;
6555 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6557 get(AArch64::STPWi), SrcReg, isKill,
6558 AArch64::sube32, AArch64::subo32, FI, MMO);
6559 return;
6560 }
6561 break;
6562 case 16:
6563 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6564 Opc = AArch64::STRQui;
6565 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6566 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6567 Opc = AArch64::ST1Twov1d;
6568 Offset = false;
6569 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6571 get(AArch64::STPXi), SrcReg, isKill,
6572 AArch64::sube64, AArch64::subo64, FI, MMO);
6573 return;
6574 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6575 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6576 "Unexpected register store without SVE store instructions");
6577 Opc = AArch64::STR_ZXI;
6579 }
6580 break;
6581 case 24:
6582 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6583 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6584 Opc = AArch64::ST1Threev1d;
6585 Offset = false;
6586 }
6587 break;
6588 case 32:
6589 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6590 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6591 Opc = AArch64::ST1Fourv1d;
6592 Offset = false;
6593 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6594 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6595 Opc = AArch64::ST1Twov2d;
6596 Offset = false;
6597 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6598 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6599 "Unexpected register store without SVE store instructions");
6600 Opc = AArch64::STR_ZZXI_STRIDED_CONTIGUOUS;
6602 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6603 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6604 "Unexpected register store without SVE store instructions");
6605 Opc = AArch64::STR_ZZXI;
6607 }
6608 break;
6609 case 48:
6610 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6611 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6612 Opc = AArch64::ST1Threev2d;
6613 Offset = false;
6614 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6615 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6616 "Unexpected register store without SVE store instructions");
6617 Opc = AArch64::STR_ZZZXI;
6619 }
6620 break;
6621 case 64:
6622 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6623 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6624 Opc = AArch64::ST1Fourv2d;
6625 Offset = false;
6626 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6627 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6628 "Unexpected register store without SVE store instructions");
6629 Opc = AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS;
6631 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6632 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6633 "Unexpected register store without SVE store instructions");
6634 Opc = AArch64::STR_ZZZZXI;
6636 }
6637 break;
6638 }
6639 assert(Opc && "Unknown register class");
6640 MFI.setStackID(FI, StackID);
6641
6643 .addReg(SrcReg, getKillRegState(isKill))
6644 .addFrameIndex(FI);
6645
6646 if (Offset)
6647 MI.addImm(0);
6648 if (PNRReg.isValid())
6649 MI.addDef(PNRReg, RegState::Implicit);
6650 MI.addMemOperand(MMO);
6651}
6652
6655 MachineBasicBlock::iterator InsertBefore,
6656 const MCInstrDesc &MCID,
6657 Register DestReg, unsigned SubIdx0,
6658 unsigned SubIdx1, int FI,
6659 MachineMemOperand *MMO) {
6660 Register DestReg0 = DestReg;
6661 Register DestReg1 = DestReg;
6662 bool IsUndef = true;
6663 if (DestReg.isPhysical()) {
6664 DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
6665 SubIdx0 = 0;
6666 DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
6667 SubIdx1 = 0;
6668 IsUndef = false;
6669 }
6670 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6671 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
6672 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
6673 .addFrameIndex(FI)
6674 .addImm(0)
6675 .addMemOperand(MMO);
6676}
6677
6680 Register DestReg, int FI,
6681 const TargetRegisterClass *RC,
6682 Register VReg, unsigned SubReg,
6683 MachineInstr::MIFlag Flags) const {
6684 MachineFunction &MF = *MBB.getParent();
6685 MachineFrameInfo &MFI = MF.getFrameInfo();
6687 MachineMemOperand *MMO =
6689 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6690
6691 unsigned Opc = 0;
6692 bool Offset = true;
6693 unsigned StackID = TargetStackID::Default;
6694 Register PNRReg;
6695 switch (TRI.getSpillSize(*RC)) {
6696 case 1:
6697 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6698 Opc = AArch64::LDRBui;
6699 break;
6700 case 2: {
6701 bool IsPNR = AArch64::PNRRegClass.hasSubClassEq(RC);
6702 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6703 Opc = AArch64::LDRHui;
6704 else if (IsPNR || AArch64::PPRRegClass.hasSubClassEq(RC)) {
6705 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6706 "Unexpected register load without SVE load instructions");
6707 if (IsPNR)
6708 PNRReg = DestReg;
6709 Opc = AArch64::LDR_PXI;
6711 }
6712 break;
6713 }
6714 case 4:
6715 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6716 Opc = AArch64::LDRWui;
6717 if (DestReg.isVirtual())
6718 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
6719 else
6720 assert(DestReg != AArch64::WSP);
6721 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6722 Opc = AArch64::LDRSui;
6723 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6724 Opc = AArch64::LDR_PPXI;
6726 }
6727 break;
6728 case 8:
6729 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6730 Opc = AArch64::LDRXui;
6731 if (DestReg.isVirtual())
6732 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
6733 else
6734 assert(DestReg != AArch64::SP);
6735 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6736 Opc = AArch64::LDRDui;
6737 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6739 get(AArch64::LDPWi), DestReg, AArch64::sube32,
6740 AArch64::subo32, FI, MMO);
6741 return;
6742 }
6743 break;
6744 case 16:
6745 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6746 Opc = AArch64::LDRQui;
6747 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6748 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6749 Opc = AArch64::LD1Twov1d;
6750 Offset = false;
6751 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6753 get(AArch64::LDPXi), DestReg, AArch64::sube64,
6754 AArch64::subo64, FI, MMO);
6755 return;
6756 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6757 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6758 "Unexpected register load without SVE load instructions");
6759 Opc = AArch64::LDR_ZXI;
6761 }
6762 break;
6763 case 24:
6764 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6765 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6766 Opc = AArch64::LD1Threev1d;
6767 Offset = false;
6768 }
6769 break;
6770 case 32:
6771 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6772 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6773 Opc = AArch64::LD1Fourv1d;
6774 Offset = false;
6775 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6776 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6777 Opc = AArch64::LD1Twov2d;
6778 Offset = false;
6779 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6780 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6781 "Unexpected register load without SVE load instructions");
6782 Opc = AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS;
6784 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6785 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6786 "Unexpected register load without SVE load instructions");
6787 Opc = AArch64::LDR_ZZXI;
6789 }
6790 break;
6791 case 48:
6792 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6793 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6794 Opc = AArch64::LD1Threev2d;
6795 Offset = false;
6796 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6797 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6798 "Unexpected register load without SVE load instructions");
6799 Opc = AArch64::LDR_ZZZXI;
6801 }
6802 break;
6803 case 64:
6804 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6805 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6806 Opc = AArch64::LD1Fourv2d;
6807 Offset = false;
6808 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6809 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6810 "Unexpected register load without SVE load instructions");
6811 Opc = AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS;
6813 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6814 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6815 "Unexpected register load without SVE load instructions");
6816 Opc = AArch64::LDR_ZZZZXI;
6818 }
6819 break;
6820 }
6821
6822 assert(Opc && "Unknown register class");
6823 MFI.setStackID(FI, StackID);
6824
6826 .addReg(DestReg, getDefRegState(true))
6827 .addFrameIndex(FI);
6828 if (Offset)
6829 MI.addImm(0);
6830 if (PNRReg.isValid() && !PNRReg.isVirtual())
6831 MI.addDef(PNRReg, RegState::Implicit);
6832 MI.addMemOperand(MMO);
6833}
6834
6836 const MachineInstr &UseMI,
6837 const TargetRegisterInfo *TRI) {
6838 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
6839 UseMI.getIterator()),
6840 [TRI](const MachineInstr &I) {
6841 return I.modifiesRegister(AArch64::NZCV, TRI) ||
6842 I.readsRegister(AArch64::NZCV, TRI);
6843 });
6844}
6845
6846void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6847 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
6848 // The smallest scalable element supported by scaled SVE addressing
6849 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6850 // byte offset must always be a multiple of 2.
6851 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6852
6853 // VGSized offsets are divided by '2', because the VG register is the
6854 // the number of 64bit granules as opposed to 128bit vector chunks,
6855 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
6856 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
6857 // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
6858 ByteSized = Offset.getFixed();
6859 VGSized = Offset.getScalable() / 2;
6860}
6861
6862/// Returns the offset in parts to which this frame offset can be
6863/// decomposed for the purpose of describing a frame offset.
6864/// For non-scalable offsets this is simply its byte size.
6865void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
6866 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
6867 int64_t &NumDataVectors) {
6868 // The smallest scalable element supported by scaled SVE addressing
6869 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6870 // byte offset must always be a multiple of 2.
6871 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6872
6873 NumBytes = Offset.getFixed();
6874 NumDataVectors = 0;
6875 NumPredicateVectors = Offset.getScalable() / 2;
6876 // This method is used to get the offsets to adjust the frame offset.
6877 // If the function requires ADDPL to be used and needs more than two ADDPL
6878 // instructions, part of the offset is folded into NumDataVectors so that it
6879 // uses ADDVL for part of it, reducing the number of ADDPL instructions.
6880 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
6881 NumPredicateVectors > 62) {
6882 NumDataVectors = NumPredicateVectors / 8;
6883 NumPredicateVectors -= NumDataVectors * 8;
6884 }
6885}
6886
6887// Convenience function to create a DWARF expression for: Constant `Operation`.
6888// This helper emits compact sequences for common cases. For example, for`-15
6889// DW_OP_plus`, this helper would create DW_OP_lit15 DW_OP_minus.
6892 if (Operation == dwarf::DW_OP_plus && Constant < 0 && -Constant <= 31) {
6893 // -Constant (1 to 31)
6894 Expr.push_back(dwarf::DW_OP_lit0 - Constant);
6895 Operation = dwarf::DW_OP_minus;
6896 } else if (Constant >= 0 && Constant <= 31) {
6897 // Literal value 0 to 31
6898 Expr.push_back(dwarf::DW_OP_lit0 + Constant);
6899 } else {
6900 // Signed constant
6901 Expr.push_back(dwarf::DW_OP_consts);
6903 }
6904 return Expr.push_back(Operation);
6905}
6906
6907// Convenience function to create a DWARF expression for a register.
6908static void appendReadRegExpr(SmallVectorImpl<char> &Expr, unsigned RegNum) {
6909 Expr.push_back((char)dwarf::DW_OP_bregx);
6911 Expr.push_back(0);
6912}
6913
6914// Convenience function to create a DWARF expression for loading a register from
6915// a CFA offset.
6917 int64_t OffsetFromDefCFA) {
6918 // This assumes the top of the DWARF stack contains the CFA.
6919 Expr.push_back(dwarf::DW_OP_dup);
6920 // Add the offset to the register.
6921 appendConstantExpr(Expr, OffsetFromDefCFA, dwarf::DW_OP_plus);
6922 // Dereference the address (loads a 64 bit value)..
6923 Expr.push_back(dwarf::DW_OP_deref);
6924}
6925
6926// Convenience function to create a comment for
6927// (+/-) NumBytes (* RegScale)?
6928static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment,
6929 StringRef RegScale = {}) {
6930 if (NumBytes) {
6931 Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
6932 if (!RegScale.empty())
6933 Comment << ' ' << RegScale;
6934 }
6935}
6936
6937// Creates an MCCFIInstruction:
6938// { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
6940 unsigned Reg,
6941 const StackOffset &Offset) {
6942 int64_t NumBytes, NumVGScaledBytes;
6943 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
6944 NumVGScaledBytes);
6945 std::string CommentBuffer;
6946 llvm::raw_string_ostream Comment(CommentBuffer);
6947
6948 if (Reg == AArch64::SP)
6949 Comment << "sp";
6950 else if (Reg == AArch64::FP)
6951 Comment << "fp";
6952 else
6953 Comment << printReg(Reg, &TRI);
6954
6955 // Build up the expression (Reg + NumBytes + VG * NumVGScaledBytes)
6956 SmallString<64> Expr;
6957 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6958 assert(DwarfReg <= 31 && "DwarfReg out of bounds (0..31)");
6959 // Reg + NumBytes
6960 Expr.push_back(dwarf::DW_OP_breg0 + DwarfReg);
6961 appendLEB128<LEB128Sign::Signed>(Expr, NumBytes);
6962 appendOffsetComment(NumBytes, Comment);
6963 if (NumVGScaledBytes) {
6964 // + VG * NumVGScaledBytes
6965 appendOffsetComment(NumVGScaledBytes, Comment, "* VG");
6966 appendReadRegExpr(Expr, TRI.getDwarfRegNum(AArch64::VG, true));
6967 appendConstantExpr(Expr, NumVGScaledBytes, dwarf::DW_OP_mul);
6968 Expr.push_back(dwarf::DW_OP_plus);
6969 }
6970
6971 // Wrap this into DW_CFA_def_cfa.
6972 SmallString<64> DefCfaExpr;
6973 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
6974 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
6975 DefCfaExpr.append(Expr.str());
6976 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
6977 Comment.str());
6978}
6979
6981 unsigned FrameReg, unsigned Reg,
6982 const StackOffset &Offset,
6983 bool LastAdjustmentWasScalable) {
6984 if (Offset.getScalable())
6985 return createDefCFAExpression(TRI, Reg, Offset);
6986
6987 if (FrameReg == Reg && !LastAdjustmentWasScalable)
6988 return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
6989
6990 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6991 return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
6992}
6993
6996 const StackOffset &OffsetFromDefCFA,
6997 std::optional<int64_t> IncomingVGOffsetFromDefCFA) {
6998 int64_t NumBytes, NumVGScaledBytes;
6999 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
7000 OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
7001
7002 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
7003
7004 // Non-scalable offsets can use DW_CFA_offset directly.
7005 if (!NumVGScaledBytes)
7006 return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
7007
7008 std::string CommentBuffer;
7009 llvm::raw_string_ostream Comment(CommentBuffer);
7010 Comment << printReg(Reg, &TRI) << " @ cfa";
7011
7012 // Build up expression (CFA + VG * NumVGScaledBytes + NumBytes)
7013 assert(NumVGScaledBytes && "Expected scalable offset");
7014 SmallString<64> OffsetExpr;
7015 // + VG * NumVGScaledBytes
7016 StringRef VGRegScale;
7017 if (IncomingVGOffsetFromDefCFA) {
7018 appendLoadRegExpr(OffsetExpr, *IncomingVGOffsetFromDefCFA);
7019 VGRegScale = "* IncomingVG";
7020 } else {
7021 appendReadRegExpr(OffsetExpr, TRI.getDwarfRegNum(AArch64::VG, true));
7022 VGRegScale = "* VG";
7023 }
7024 appendConstantExpr(OffsetExpr, NumVGScaledBytes, dwarf::DW_OP_mul);
7025 appendOffsetComment(NumVGScaledBytes, Comment, VGRegScale);
7026 OffsetExpr.push_back(dwarf::DW_OP_plus);
7027 if (NumBytes) {
7028 // + NumBytes
7029 appendOffsetComment(NumBytes, Comment);
7030 appendConstantExpr(OffsetExpr, NumBytes, dwarf::DW_OP_plus);
7031 }
7032
7033 // Wrap this into DW_CFA_expression
7034 SmallString<64> CfaExpr;
7035 CfaExpr.push_back(dwarf::DW_CFA_expression);
7036 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, DwarfReg);
7037 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, OffsetExpr.size());
7038 CfaExpr.append(OffsetExpr.str());
7039
7040 return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), SMLoc(),
7041 Comment.str());
7042}
7043
7044// Helper function to emit a frame offset adjustment from a given
7045// pointer (SrcReg), stored into DestReg. This function is explicit
7046// in that it requires the opcode.
7049 const DebugLoc &DL, unsigned DestReg,
7050 unsigned SrcReg, int64_t Offset, unsigned Opc,
7051 const TargetInstrInfo *TII,
7052 MachineInstr::MIFlag Flag, bool NeedsWinCFI,
7053 bool *HasWinCFI, bool EmitCFAOffset,
7054 StackOffset CFAOffset, unsigned FrameReg) {
7055 int Sign = 1;
7056 unsigned MaxEncoding, ShiftSize;
7057 switch (Opc) {
7058 case AArch64::ADDXri:
7059 case AArch64::ADDSXri:
7060 case AArch64::SUBXri:
7061 case AArch64::SUBSXri:
7062 MaxEncoding = 0xfff;
7063 ShiftSize = 12;
7064 break;
7065 case AArch64::ADDVL_XXI:
7066 case AArch64::ADDPL_XXI:
7067 case AArch64::ADDSVL_XXI:
7068 case AArch64::ADDSPL_XXI:
7069 MaxEncoding = 31;
7070 ShiftSize = 0;
7071 if (Offset < 0) {
7072 MaxEncoding = 32;
7073 Sign = -1;
7074 Offset = -Offset;
7075 }
7076 break;
7077 default:
7078 llvm_unreachable("Unsupported opcode");
7079 }
7080
7081 // `Offset` can be in bytes or in "scalable bytes".
7082 int VScale = 1;
7083 if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
7084 VScale = 16;
7085 else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
7086 VScale = 2;
7087
7088 // FIXME: If the offset won't fit in 24-bits, compute the offset into a
7089 // scratch register. If DestReg is a virtual register, use it as the
7090 // scratch register; otherwise, create a new virtual register (to be
7091 // replaced by the scavenger at the end of PEI). That case can be optimized
7092 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
7093 // register can be loaded with offset%8 and the add/sub can use an extending
7094 // instruction with LSL#3.
7095 // Currently the function handles any offsets but generates a poor sequence
7096 // of code.
7097 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
7098
7099 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
7100 Register TmpReg = DestReg;
7101 if (TmpReg == AArch64::XZR)
7102 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
7103 &AArch64::GPR64RegClass);
7104 do {
7105 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
7106 unsigned LocalShiftSize = 0;
7107 if (ThisVal > MaxEncoding) {
7108 ThisVal = ThisVal >> ShiftSize;
7109 LocalShiftSize = ShiftSize;
7110 }
7111 assert((ThisVal >> ShiftSize) <= MaxEncoding &&
7112 "Encoding cannot handle value that big");
7113
7114 Offset -= ThisVal << LocalShiftSize;
7115 if (Offset == 0)
7116 TmpReg = DestReg;
7117 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
7118 .addReg(SrcReg)
7119 .addImm(Sign * (int)ThisVal);
7120 if (ShiftSize)
7121 MBI = MBI.addImm(
7123 MBI = MBI.setMIFlag(Flag);
7124
7125 auto Change =
7126 VScale == 1
7127 ? StackOffset::getFixed(ThisVal << LocalShiftSize)
7128 : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
7129 if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
7130 CFAOffset += Change;
7131 else
7132 CFAOffset -= Change;
7133 if (EmitCFAOffset && DestReg == TmpReg) {
7134 MachineFunction &MF = *MBB.getParent();
7135 const TargetSubtargetInfo &STI = MF.getSubtarget();
7136 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
7137
7138 unsigned CFIIndex = MF.addFrameInst(
7139 createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
7140 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
7141 .addCFIIndex(CFIIndex)
7142 .setMIFlags(Flag);
7143 }
7144
7145 if (NeedsWinCFI) {
7146 int Imm = (int)(ThisVal << LocalShiftSize);
7147 if (VScale != 1 && DestReg == AArch64::SP) {
7148 if (HasWinCFI)
7149 *HasWinCFI = true;
7150 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AllocZ))
7151 .addImm(ThisVal)
7152 .setMIFlag(Flag);
7153 } else if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
7154 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
7155 assert(VScale == 1 && "Expected non-scalable operation");
7156 if (HasWinCFI)
7157 *HasWinCFI = true;
7158 if (Imm == 0)
7159 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
7160 else
7161 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
7162 .addImm(Imm)
7163 .setMIFlag(Flag);
7164 assert(Offset == 0 && "Expected remaining offset to be zero to "
7165 "emit a single SEH directive");
7166 } else if (DestReg == AArch64::SP) {
7167 assert(VScale == 1 && "Expected non-scalable operation");
7168 if (HasWinCFI)
7169 *HasWinCFI = true;
7170 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
7171 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
7172 .addImm(Imm)
7173 .setMIFlag(Flag);
7174 }
7175 }
7176
7177 SrcReg = TmpReg;
7178 } while (Offset);
7179}
7180
7183 unsigned DestReg, unsigned SrcReg,
7185 MachineInstr::MIFlag Flag, bool SetNZCV,
7186 bool NeedsWinCFI, bool *HasWinCFI,
7187 bool EmitCFAOffset, StackOffset CFAOffset,
7188 unsigned FrameReg) {
7189 // If a function is marked as arm_locally_streaming, then the runtime value of
7190 // vscale in the prologue/epilogue is different the runtime value of vscale
7191 // in the function's body. To avoid having to consider multiple vscales,
7192 // we can use `addsvl` to allocate any scalable stack-slots, which under
7193 // most circumstances will be only locals, not callee-save slots.
7194 const Function &F = MBB.getParent()->getFunction();
7195 bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
7196
7197 int64_t Bytes, NumPredicateVectors, NumDataVectors;
7198 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
7199 Offset, Bytes, NumPredicateVectors, NumDataVectors);
7200
7201 // Insert ADDSXri for scalable offset at the end.
7202 bool NeedsFinalDefNZCV = SetNZCV && (NumPredicateVectors || NumDataVectors);
7203 if (NeedsFinalDefNZCV)
7204 SetNZCV = false;
7205
7206 // First emit non-scalable frame offsets, or a simple 'mov'.
7207 if (Bytes || (!Offset && SrcReg != DestReg)) {
7208 assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
7209 "SP increment/decrement not 8-byte aligned");
7210 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
7211 if (Bytes < 0) {
7212 Bytes = -Bytes;
7213 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
7214 }
7215 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
7216 NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7217 FrameReg);
7218 CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
7219 ? StackOffset::getFixed(-Bytes)
7220 : StackOffset::getFixed(Bytes);
7221 SrcReg = DestReg;
7222 FrameReg = DestReg;
7223 }
7224
7225 assert(!(NeedsWinCFI && NumPredicateVectors) &&
7226 "WinCFI can't allocate fractions of an SVE data vector");
7227
7228 if (NumDataVectors) {
7229 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
7230 UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI, TII,
7231 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7232 FrameReg);
7233 CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
7234 SrcReg = DestReg;
7235 }
7236
7237 if (NumPredicateVectors) {
7238 assert(DestReg != AArch64::SP && "Unaligned access to SP");
7239 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
7240 UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI, TII,
7241 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7242 FrameReg);
7243 }
7244
7245 if (NeedsFinalDefNZCV)
7246 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDSXri), DestReg)
7247 .addReg(DestReg)
7248 .addImm(0)
7249 .addImm(0);
7250}
7251
7254 int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS,
7255 VirtRegMap *VRM) const {
7257 // This is a bit of a hack. Consider this instruction:
7258 //
7259 // %0 = COPY %sp; GPR64all:%0
7260 //
7261 // We explicitly chose GPR64all for the virtual register so such a copy might
7262 // be eliminated by RegisterCoalescer. However, that may not be possible, and
7263 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
7264 // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
7265 //
7266 // To prevent that, we are going to constrain the %0 register class here.
7267 if (MI.isFullCopy()) {
7268 Register DstReg = MI.getOperand(0).getReg();
7269 Register SrcReg = MI.getOperand(1).getReg();
7270 if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
7271 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
7272 return nullptr;
7273 }
7274 if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
7275 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
7276 return nullptr;
7277 }
7278 // Nothing can folded with copy from/to NZCV.
7279 if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
7280 return nullptr;
7281 }
7282
7283 // Handle the case where a copy is being spilled or filled but the source
7284 // and destination register class don't match. For example:
7285 //
7286 // %0 = COPY %xzr; GPR64common:%0
7287 //
7288 // In this case we can still safely fold away the COPY and generate the
7289 // following spill code:
7290 //
7291 // STRXui %xzr, %stack.0
7292 //
7293 // This also eliminates spilled cross register class COPYs (e.g. between x and
7294 // d regs) of the same size. For example:
7295 //
7296 // %0 = COPY %1; GPR64:%0, FPR64:%1
7297 //
7298 // will be filled as
7299 //
7300 // LDRDui %0, fi<#0>
7301 //
7302 // instead of
7303 //
7304 // LDRXui %Temp, fi<#0>
7305 // %0 = FMOV %Temp
7306 //
7307 if (MI.isCopy() && Ops.size() == 1 &&
7308 // Make sure we're only folding the explicit COPY defs/uses.
7309 (Ops[0] == 0 || Ops[0] == 1)) {
7310 bool IsSpill = Ops[0] == 0;
7311 bool IsFill = !IsSpill;
7313 const MachineRegisterInfo &MRI = MF.getRegInfo();
7314 MachineBasicBlock &MBB = *MI.getParent();
7315 const MachineOperand &DstMO = MI.getOperand(0);
7316 const MachineOperand &SrcMO = MI.getOperand(1);
7317 Register DstReg = DstMO.getReg();
7318 Register SrcReg = SrcMO.getReg();
7319 // This is slightly expensive to compute for physical regs since
7320 // getMinimalPhysRegClass is slow.
7321 auto getRegClass = [&](unsigned Reg) {
7322 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
7323 : TRI.getMinimalPhysRegClass(Reg);
7324 };
7325
7326 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
7327 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
7328 TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
7329 "Mismatched register size in non subreg COPY");
7330 if (IsSpill)
7331 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
7332 getRegClass(SrcReg), Register());
7333 else
7334 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
7335 getRegClass(DstReg), Register());
7336 return &*--InsertPt;
7337 }
7338
7339 // Handle cases like spilling def of:
7340 //
7341 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
7342 //
7343 // where the physical register source can be widened and stored to the full
7344 // virtual reg destination stack slot, in this case producing:
7345 //
7346 // STRXui %xzr, %stack.0
7347 //
7348 if (IsSpill && DstMO.isUndef() && SrcReg == AArch64::WZR &&
7349 TRI.getRegSizeInBits(*getRegClass(DstReg)) == 64) {
7350 assert(SrcMO.getSubReg() == 0 &&
7351 "Unexpected subreg on physical register");
7352 storeRegToStackSlot(MBB, InsertPt, AArch64::XZR, SrcMO.isKill(),
7353 FrameIndex, &AArch64::GPR64RegClass, Register());
7354 return &*--InsertPt;
7355 }
7356
7357 // Handle cases like filling use of:
7358 //
7359 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
7360 //
7361 // where we can load the full virtual reg source stack slot, into the subreg
7362 // destination, in this case producing:
7363 //
7364 // LDRWui %0:sub_32<def,read-undef>, %stack.0
7365 //
7366 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
7367 const TargetRegisterClass *FillRC = nullptr;
7368 switch (DstMO.getSubReg()) {
7369 default:
7370 break;
7371 case AArch64::sub_32:
7372 if (AArch64::GPR64RegClass.hasSubClassEq(getRegClass(DstReg)))
7373 FillRC = &AArch64::GPR32RegClass;
7374 break;
7375 case AArch64::ssub:
7376 FillRC = &AArch64::FPR32RegClass;
7377 break;
7378 case AArch64::dsub:
7379 FillRC = &AArch64::FPR64RegClass;
7380 break;
7381 }
7382
7383 if (FillRC) {
7384 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
7385 TRI.getRegSizeInBits(*FillRC) &&
7386 "Mismatched regclass size on folded subreg COPY");
7387 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC,
7388 Register());
7389 MachineInstr &LoadMI = *--InsertPt;
7390 MachineOperand &LoadDst = LoadMI.getOperand(0);
7391 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
7392 LoadDst.setSubReg(DstMO.getSubReg());
7393 LoadDst.setIsUndef();
7394 return &LoadMI;
7395 }
7396 }
7397 }
7398
7399 // Cannot fold.
7400 return nullptr;
7401}
7402
7404 StackOffset &SOffset,
7405 bool *OutUseUnscaledOp,
7406 unsigned *OutUnscaledOp,
7407 int64_t *EmittableOffset) {
7408 // Set output values in case of early exit.
7409 if (EmittableOffset)
7410 *EmittableOffset = 0;
7411 if (OutUseUnscaledOp)
7412 *OutUseUnscaledOp = false;
7413 if (OutUnscaledOp)
7414 *OutUnscaledOp = 0;
7415
7416 // Exit early for structured vector spills/fills as they can't take an
7417 // immediate offset.
7418 switch (MI.getOpcode()) {
7419 default:
7420 break;
7421 case AArch64::LD1Rv1d:
7422 case AArch64::LD1Rv2s:
7423 case AArch64::LD1Rv2d:
7424 case AArch64::LD1Rv4h:
7425 case AArch64::LD1Rv4s:
7426 case AArch64::LD1Rv8b:
7427 case AArch64::LD1Rv8h:
7428 case AArch64::LD1Rv16b:
7429 case AArch64::LD1Twov2d:
7430 case AArch64::LD1Threev2d:
7431 case AArch64::LD1Fourv2d:
7432 case AArch64::LD1Twov1d:
7433 case AArch64::LD1Threev1d:
7434 case AArch64::LD1Fourv1d:
7435 case AArch64::ST1Twov2d:
7436 case AArch64::ST1Threev2d:
7437 case AArch64::ST1Fourv2d:
7438 case AArch64::ST1Twov1d:
7439 case AArch64::ST1Threev1d:
7440 case AArch64::ST1Fourv1d:
7441 case AArch64::ST1i8:
7442 case AArch64::ST1i16:
7443 case AArch64::ST1i32:
7444 case AArch64::ST1i64:
7445 case AArch64::IRG:
7446 case AArch64::IRGstack:
7447 case AArch64::STGloop:
7448 case AArch64::STZGloop:
7450 }
7451
7452 // Get the min/max offset and the scale.
7453 TypeSize ScaleValue(0U, false), Width(0U, false);
7454 int64_t MinOff, MaxOff;
7455 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
7456 MaxOff))
7457 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7458
7459 // Construct the complete offset.
7460 bool IsMulVL = ScaleValue.isScalable();
7461 unsigned Scale = ScaleValue.getKnownMinValue();
7462 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
7463
7464 const MachineOperand &ImmOpnd =
7465 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
7466 Offset += ImmOpnd.getImm() * Scale;
7467
7468 // If the offset doesn't match the scale, we rewrite the instruction to
7469 // use the unscaled instruction instead. Likewise, if we have a negative
7470 // offset and there is an unscaled op to use.
7471 std::optional<unsigned> UnscaledOp =
7473 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
7474 if (useUnscaledOp &&
7475 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
7476 MaxOff))
7477 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7478
7479 Scale = ScaleValue.getKnownMinValue();
7480 assert(IsMulVL == ScaleValue.isScalable() &&
7481 "Unscaled opcode has different value for scalable");
7482
7483 int64_t Remainder = Offset % Scale;
7484 assert(!(Remainder && useUnscaledOp) &&
7485 "Cannot have remainder when using unscaled op");
7486
7487 assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
7488 int64_t NewOffset = Offset / Scale;
7489 if (MinOff <= NewOffset && NewOffset <= MaxOff)
7490 Offset = Remainder;
7491 else {
7492 // Try to minimise the number of instructions required to materialise the
7493 // offset calculation. Specifically, for fixed offsets, if masking out the
7494 // low 12 bits leaves a legal add immediate, we can realise the offset
7495 // calculation with a single add instruction. Whenever this is possible,
7496 // prefer this split.
7497 int64_t HighPart = Offset & ~0xFFF;
7498 int64_t LowPart = Offset & 0xFFF;
7499 int64_t LowScaled = LowPart / Scale;
7500 if (!IsMulVL && NewOffset >= 0 && LowPart % Scale == 0 &&
7501 MinOff <= LowScaled && LowScaled <= MaxOff &&
7503 NewOffset = LowScaled;
7504 Offset = HighPart;
7505 } else {
7506 // Default to a greedy split: take the memop immediate to be maximum /
7507 // minimum expressible offset and materialise the remainder.
7508 NewOffset = NewOffset < 0 ? MinOff : MaxOff;
7509 Offset = Offset - (NewOffset * Scale);
7510 }
7511 }
7512
7513 if (EmittableOffset)
7514 *EmittableOffset = NewOffset;
7515 if (OutUseUnscaledOp)
7516 *OutUseUnscaledOp = useUnscaledOp;
7517 if (OutUnscaledOp && UnscaledOp)
7518 *OutUnscaledOp = *UnscaledOp;
7519
7520 if (IsMulVL)
7521 SOffset = StackOffset::get(SOffset.getFixed(), Offset);
7522 else
7523 SOffset = StackOffset::get(Offset, SOffset.getScalable());
7525 (SOffset ? 0 : AArch64FrameOffsetIsLegal);
7526}
7527
7529 unsigned FrameReg, StackOffset &Offset,
7530 const AArch64InstrInfo *TII) {
7531 unsigned Opcode = MI.getOpcode();
7532 unsigned ImmIdx = FrameRegIdx + 1;
7533
7534 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
7535 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
7536 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
7537 MI.getOperand(0).getReg(), FrameReg, Offset, TII,
7538 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
7539 MI.eraseFromParent();
7540 Offset = StackOffset();
7541 return true;
7542 }
7543
7544 int64_t NewOffset;
7545 unsigned UnscaledOp;
7546 bool UseUnscaledOp;
7547 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
7548 &UnscaledOp, &NewOffset);
7551 // Replace the FrameIndex with FrameReg.
7552 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
7553 if (UseUnscaledOp)
7554 MI.setDesc(TII->get(UnscaledOp));
7555
7556 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
7557 return !Offset;
7558 }
7559
7560 return false;
7561}
7562
7568
7569MCInst AArch64InstrInfo::getNop() const { return MCInstBuilder(AArch64::NOP); }
7570
7571// AArch64 supports MachineCombiner.
7572bool AArch64InstrInfo::useMachineCombiner() const { return true; }
7573
7574// True when Opc sets flag
7575static bool isCombineInstrSettingFlag(unsigned Opc) {
7576 switch (Opc) {
7577 case AArch64::ADDSWrr:
7578 case AArch64::ADDSWri:
7579 case AArch64::ADDSXrr:
7580 case AArch64::ADDSXri:
7581 case AArch64::SUBSWrr:
7582 case AArch64::SUBSXrr:
7583 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7584 case AArch64::SUBSWri:
7585 case AArch64::SUBSXri:
7586 return true;
7587 default:
7588 break;
7589 }
7590 return false;
7591}
7592
7593// 32b Opcodes that can be combined with a MUL
7594static bool isCombineInstrCandidate32(unsigned Opc) {
7595 switch (Opc) {
7596 case AArch64::ADDWrr:
7597 case AArch64::ADDWri:
7598 case AArch64::ADDWrs:
7599 case AArch64::SUBWrr:
7600 case AArch64::ADDSWrr:
7601 case AArch64::ADDSWri:
7602 case AArch64::SUBSWrr:
7603 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7604 case AArch64::SUBWri:
7605 case AArch64::SUBSWri:
7606 return true;
7607 default:
7608 break;
7609 }
7610 return false;
7611}
7612
7613// 64b Opcodes that can be combined with a MUL
7614static bool isCombineInstrCandidate64(unsigned Opc) {
7615 switch (Opc) {
7616 case AArch64::ADDXrr:
7617 case AArch64::ADDXri:
7618 case AArch64::ADDXrs:
7619 case AArch64::SUBXrr:
7620 case AArch64::ADDSXrr:
7621 case AArch64::ADDSXri:
7622 case AArch64::SUBSXrr:
7623 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7624 case AArch64::SUBXri:
7625 case AArch64::SUBSXri:
7626 case AArch64::ADDv8i8:
7627 case AArch64::ADDv16i8:
7628 case AArch64::ADDv4i16:
7629 case AArch64::ADDv8i16:
7630 case AArch64::ADDv2i32:
7631 case AArch64::ADDv4i32:
7632 case AArch64::SUBv8i8:
7633 case AArch64::SUBv16i8:
7634 case AArch64::SUBv4i16:
7635 case AArch64::SUBv8i16:
7636 case AArch64::SUBv2i32:
7637 case AArch64::SUBv4i32:
7638 return true;
7639 default:
7640 break;
7641 }
7642 return false;
7643}
7644
7645// FP Opcodes that can be combined with a FMUL.
7646static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
7647 switch (Inst.getOpcode()) {
7648 default:
7649 break;
7650 case AArch64::FADDHrr:
7651 case AArch64::FADDSrr:
7652 case AArch64::FADDDrr:
7653 case AArch64::FADDv4f16:
7654 case AArch64::FADDv8f16:
7655 case AArch64::FADDv2f32:
7656 case AArch64::FADDv2f64:
7657 case AArch64::FADDv4f32:
7658 case AArch64::FSUBHrr:
7659 case AArch64::FSUBSrr:
7660 case AArch64::FSUBDrr:
7661 case AArch64::FSUBv4f16:
7662 case AArch64::FSUBv8f16:
7663 case AArch64::FSUBv2f32:
7664 case AArch64::FSUBv2f64:
7665 case AArch64::FSUBv4f32:
7666 // We can fuse FADD/FSUB with FMUL, if FADD/FSUB has the contract fast-math
7667 // flag.
7668 return Inst.getFlag(MachineInstr::FmContract);
7669 }
7670 return false;
7671}
7672
7673// Opcodes that can be combined with a MUL
7677
7678//
7679// Utility routine that checks if \param MO is defined by an
7680// \param CombineOpc instruction in the basic block \param MBB
7682 unsigned CombineOpc, unsigned ZeroReg = 0,
7683 bool CheckZeroReg = false) {
7684 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7685 MachineInstr *MI = nullptr;
7686
7687 if (MO.isReg() && MO.getReg().isVirtual())
7688 MI = MRI.getUniqueVRegDef(MO.getReg());
7689 // And it needs to be in the trace (otherwise, it won't have a depth).
7690 if (!MI || MI->getParent() != &MBB || MI->getOpcode() != CombineOpc)
7691 return false;
7692 // Must only used by the user we combine with.
7693 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
7694 return false;
7695
7696 if (CheckZeroReg) {
7697 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
7698 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
7699 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
7700 // The third input reg must be zero.
7701 if (MI->getOperand(3).getReg() != ZeroReg)
7702 return false;
7703 }
7704
7705 if (isCombineInstrSettingFlag(CombineOpc) &&
7706 MI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) == -1)
7707 return false;
7708
7709 return true;
7710}
7711
7712//
7713// Is \param MO defined by an integer multiply and can be combined?
7715 unsigned MulOpc, unsigned ZeroReg) {
7716 return canCombine(MBB, MO, MulOpc, ZeroReg, true);
7717}
7718
7719//
7720// Is \param MO defined by a floating-point multiply and can be combined?
7722 unsigned MulOpc) {
7723 return canCombine(MBB, MO, MulOpc);
7724}
7725
7726// TODO: There are many more machine instruction opcodes to match:
7727// 1. Other data types (integer, vectors)
7728// 2. Other math / logic operations (xor, or)
7729// 3. Other forms of the same operation (intrinsics and other variants)
7730bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
7731 bool Invert) const {
7732 if (Invert)
7733 return false;
7734 switch (Inst.getOpcode()) {
7735 // == Floating-point types ==
7736 // -- Floating-point instructions --
7737 case AArch64::FADDHrr:
7738 case AArch64::FADDSrr:
7739 case AArch64::FADDDrr:
7740 case AArch64::FMULHrr:
7741 case AArch64::FMULSrr:
7742 case AArch64::FMULDrr:
7743 case AArch64::FMULX16:
7744 case AArch64::FMULX32:
7745 case AArch64::FMULX64:
7746 // -- Advanced SIMD instructions --
7747 case AArch64::FADDv4f16:
7748 case AArch64::FADDv8f16:
7749 case AArch64::FADDv2f32:
7750 case AArch64::FADDv4f32:
7751 case AArch64::FADDv2f64:
7752 case AArch64::FMULv4f16:
7753 case AArch64::FMULv8f16:
7754 case AArch64::FMULv2f32:
7755 case AArch64::FMULv4f32:
7756 case AArch64::FMULv2f64:
7757 case AArch64::FMULXv4f16:
7758 case AArch64::FMULXv8f16:
7759 case AArch64::FMULXv2f32:
7760 case AArch64::FMULXv4f32:
7761 case AArch64::FMULXv2f64:
7762 // -- SVE instructions --
7763 // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
7764 // in the SVE instruction set (though there are predicated ones).
7765 case AArch64::FADD_ZZZ_H:
7766 case AArch64::FADD_ZZZ_S:
7767 case AArch64::FADD_ZZZ_D:
7768 case AArch64::FMUL_ZZZ_H:
7769 case AArch64::FMUL_ZZZ_S:
7770 case AArch64::FMUL_ZZZ_D:
7773
7774 // == Integer types ==
7775 // -- Base instructions --
7776 // Opcodes MULWrr and MULXrr don't exist because
7777 // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
7778 // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
7779 // The machine-combiner does not support three-source-operands machine
7780 // instruction. So we cannot reassociate MULs.
7781 case AArch64::ADDWrr:
7782 case AArch64::ADDXrr:
7783 case AArch64::ANDWrr:
7784 case AArch64::ANDXrr:
7785 case AArch64::ORRWrr:
7786 case AArch64::ORRXrr:
7787 case AArch64::EORWrr:
7788 case AArch64::EORXrr:
7789 case AArch64::EONWrr:
7790 case AArch64::EONXrr:
7791 // -- Advanced SIMD instructions --
7792 // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
7793 // in the Advanced SIMD instruction set.
7794 case AArch64::ADDv8i8:
7795 case AArch64::ADDv16i8:
7796 case AArch64::ADDv4i16:
7797 case AArch64::ADDv8i16:
7798 case AArch64::ADDv2i32:
7799 case AArch64::ADDv4i32:
7800 case AArch64::ADDv1i64:
7801 case AArch64::ADDv2i64:
7802 case AArch64::MULv8i8:
7803 case AArch64::MULv16i8:
7804 case AArch64::MULv4i16:
7805 case AArch64::MULv8i16:
7806 case AArch64::MULv2i32:
7807 case AArch64::MULv4i32:
7808 case AArch64::ANDv8i8:
7809 case AArch64::ANDv16i8:
7810 case AArch64::ORRv8i8:
7811 case AArch64::ORRv16i8:
7812 case AArch64::EORv8i8:
7813 case AArch64::EORv16i8:
7814 // -- SVE instructions --
7815 case AArch64::ADD_ZZZ_B:
7816 case AArch64::ADD_ZZZ_H:
7817 case AArch64::ADD_ZZZ_S:
7818 case AArch64::ADD_ZZZ_D:
7819 case AArch64::MUL_ZZZ_B:
7820 case AArch64::MUL_ZZZ_H:
7821 case AArch64::MUL_ZZZ_S:
7822 case AArch64::MUL_ZZZ_D:
7823 case AArch64::AND_ZZZ:
7824 case AArch64::ORR_ZZZ:
7825 case AArch64::EOR_ZZZ:
7826 return true;
7827
7828 default:
7829 return false;
7830 }
7831}
7832
7833/// Find instructions that can be turned into madd.
7835 SmallVectorImpl<unsigned> &Patterns) {
7836 unsigned Opc = Root.getOpcode();
7837 MachineBasicBlock &MBB = *Root.getParent();
7838 bool Found = false;
7839
7841 return false;
7843 int Cmp_NZCV =
7844 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
7845 // When NZCV is live bail out.
7846 if (Cmp_NZCV == -1)
7847 return false;
7848 unsigned NewOpc = convertToNonFlagSettingOpc(Root);
7849 // When opcode can't change bail out.
7850 // CHECKME: do we miss any cases for opcode conversion?
7851 if (NewOpc == Opc)
7852 return false;
7853 Opc = NewOpc;
7854 }
7855
7856 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
7857 unsigned Pattern) {
7858 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
7859 Patterns.push_back(Pattern);
7860 Found = true;
7861 }
7862 };
7863
7864 const AArch64Subtarget &STI =
7865 MBB.getParent()->getSubtarget<AArch64Subtarget>();
7866 auto setShfFound = [&](int Opcode, unsigned ZeroReg, unsigned Pattern) {
7867 // TODO: Currently its not possible to reject the combine for Apple targets
7868 // based on the scheduling model, because we have gaps in modeling and
7869 // analysis. Once we fill the gaps, remove the subtarget feature and the
7870 // associated check here.
7871 if (STI.hasShiftMaddSlow())
7872 return;
7873
7874 unsigned ShiftImm = Root.getOperand(3).getImm();
7876
7877 if ((ShiftTy != AArch64_AM::LSL && ShiftTy != AArch64_AM::LSR &&
7878 ShiftTy != AArch64_AM::ASR) ||
7879 AArch64_AM::getShiftValue(ShiftImm) == 0)
7880 return;
7881
7882 if (!canCombineWithMUL(MBB, Root.getOperand(1), Opcode, ZeroReg))
7883 return;
7884
7885 Patterns.push_back(Pattern);
7886 Found = true;
7887 };
7888
7889 auto setVFound = [&](int Opcode, int Operand, unsigned Pattern) {
7890 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
7891 Patterns.push_back(Pattern);
7892 Found = true;
7893 }
7894 };
7895
7897
7898 switch (Opc) {
7899 default:
7900 break;
7901 case AArch64::ADDWrr:
7902 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7903 "ADDWrr does not have register operands");
7904 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
7905 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
7906 break;
7907 case AArch64::ADDXrr:
7908 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
7909 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
7910 break;
7911 case AArch64::SUBWrr:
7912 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
7913 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
7914 break;
7915 case AArch64::SUBXrr:
7916 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
7917 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
7918 break;
7919 case AArch64::ADDWri:
7920 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
7921 break;
7922 case AArch64::ADDXri:
7923 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
7924 break;
7925 case AArch64::SUBWri:
7926 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
7927 break;
7928 case AArch64::SUBXri:
7929 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
7930 break;
7931 case AArch64::ADDWrs:
7932 setShfFound(AArch64::MADDWrrr, AArch64::WZR, MCP::MULADDWS_OP1);
7933 break;
7934 case AArch64::ADDXrs:
7935 setShfFound(AArch64::MADDXrrr, AArch64::XZR, MCP::MULADDXS_OP1);
7936 break;
7937 case AArch64::ADDv8i8:
7938 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
7939 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
7940 break;
7941 case AArch64::ADDv16i8:
7942 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
7943 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
7944 break;
7945 case AArch64::ADDv4i16:
7946 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
7947 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
7948 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
7949 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
7950 break;
7951 case AArch64::ADDv8i16:
7952 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
7953 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
7954 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
7955 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
7956 break;
7957 case AArch64::ADDv2i32:
7958 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
7959 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
7960 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
7961 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
7962 break;
7963 case AArch64::ADDv4i32:
7964 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
7965 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
7966 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
7967 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
7968 break;
7969 case AArch64::SUBv8i8:
7970 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
7971 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
7972 break;
7973 case AArch64::SUBv16i8:
7974 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
7975 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
7976 break;
7977 case AArch64::SUBv4i16:
7978 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
7979 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
7980 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
7981 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
7982 break;
7983 case AArch64::SUBv8i16:
7984 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
7985 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
7986 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
7987 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
7988 break;
7989 case AArch64::SUBv2i32:
7990 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
7991 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
7992 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
7993 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
7994 break;
7995 case AArch64::SUBv4i32:
7996 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
7997 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
7998 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
7999 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
8000 break;
8001 }
8002 return Found;
8003}
8004
8005std::optional<TargetInstrInfo::FMAChainLinkInfo>
8006AArch64InstrInfo::getFMAChainLinkInfo(const MachineInstr &MI) const {
8007 switch (MI.getOpcode()) {
8008 default:
8009 return std::nullopt;
8010 // Rd = Rn * Rm + Ra.
8011 case AArch64::FMADDSrrr:
8012 return FMAChainLinkInfo{AArch64::FADDSrr, AArch64::FMULSrr, 3};
8013 case AArch64::FMADDDrrr:
8014 return FMAChainLinkInfo{AArch64::FADDDrr, AArch64::FMULDrr, 3};
8015 // Vd += Vn * Vm.
8016 case AArch64::FMLAv1i32_indexed:
8017 return FMAChainLinkInfo{AArch64::FADDSrr, AArch64::FMULv1i32_indexed, 1};
8018 case AArch64::FMLAv1i64_indexed:
8019 return FMAChainLinkInfo{AArch64::FADDDrr, AArch64::FMULv1i64_indexed, 1};
8020 case AArch64::FMLAv2f32:
8021 return FMAChainLinkInfo{AArch64::FADDv2f32, AArch64::FMULv2f32, 1};
8022 case AArch64::FMLAv4f32:
8023 return FMAChainLinkInfo{AArch64::FADDv4f32, AArch64::FMULv4f32, 1};
8024 case AArch64::FMLAv2f64:
8025 return FMAChainLinkInfo{AArch64::FADDv2f64, AArch64::FMULv2f64, 1};
8026 case AArch64::FMLAv2i32_indexed:
8027 return FMAChainLinkInfo{AArch64::FADDv2f32, AArch64::FMULv2i32_indexed, 1};
8028 case AArch64::FMLAv4i32_indexed:
8029 return FMAChainLinkInfo{AArch64::FADDv4f32, AArch64::FMULv4i32_indexed, 1};
8030 case AArch64::FMLAv2i64_indexed:
8031 return FMAChainLinkInfo{AArch64::FADDv2f64, AArch64::FMULv2i64_indexed, 1};
8032 case AArch64::FADDSrr:
8033 case AArch64::FADDDrr:
8034 case AArch64::FADDv2f32:
8035 case AArch64::FADDv4f32:
8036 case AArch64::FADDv2f64:
8037 return FMAChainLinkInfo{MI.getOpcode(), 0, -1};
8038 }
8039}
8040
8041bool AArch64InstrInfo::isAccumulationOpcode(unsigned Opcode) const {
8042 switch (Opcode) {
8043 default:
8044 break;
8045 case AArch64::UABALB_ZZZ_D:
8046 case AArch64::UABALB_ZZZ_H:
8047 case AArch64::UABALB_ZZZ_S:
8048 case AArch64::UABALT_ZZZ_D:
8049 case AArch64::UABALT_ZZZ_H:
8050 case AArch64::UABALT_ZZZ_S:
8051 case AArch64::SABALB_ZZZ_D:
8052 case AArch64::SABALB_ZZZ_S:
8053 case AArch64::SABALB_ZZZ_H:
8054 case AArch64::SABALT_ZZZ_D:
8055 case AArch64::SABALT_ZZZ_S:
8056 case AArch64::SABALT_ZZZ_H:
8057 case AArch64::UABALv16i8_v8i16:
8058 case AArch64::UABALv2i32_v2i64:
8059 case AArch64::UABALv4i16_v4i32:
8060 case AArch64::UABALv4i32_v2i64:
8061 case AArch64::UABALv8i16_v4i32:
8062 case AArch64::UABALv8i8_v8i16:
8063 case AArch64::UABAv16i8:
8064 case AArch64::UABAv2i32:
8065 case AArch64::UABAv4i16:
8066 case AArch64::UABAv4i32:
8067 case AArch64::UABAv8i16:
8068 case AArch64::UABAv8i8:
8069 case AArch64::SABALv16i8_v8i16:
8070 case AArch64::SABALv2i32_v2i64:
8071 case AArch64::SABALv4i16_v4i32:
8072 case AArch64::SABALv4i32_v2i64:
8073 case AArch64::SABALv8i16_v4i32:
8074 case AArch64::SABALv8i8_v8i16:
8075 case AArch64::SABAv16i8:
8076 case AArch64::SABAv2i32:
8077 case AArch64::SABAv4i16:
8078 case AArch64::SABAv4i32:
8079 case AArch64::SABAv8i16:
8080 case AArch64::SABAv8i8:
8081 return true;
8082 }
8083
8084 return false;
8085}
8086
8087unsigned AArch64InstrInfo::getAccumulationStartOpcode(
8088 unsigned AccumulationOpcode) const {
8089 switch (AccumulationOpcode) {
8090 default:
8091 llvm_unreachable("Unsupported accumulation Opcode!");
8092 case AArch64::UABALB_ZZZ_D:
8093 return AArch64::UABDLB_ZZZ_D;
8094 case AArch64::UABALB_ZZZ_H:
8095 return AArch64::UABDLB_ZZZ_H;
8096 case AArch64::UABALB_ZZZ_S:
8097 return AArch64::UABDLB_ZZZ_S;
8098 case AArch64::UABALT_ZZZ_D:
8099 return AArch64::UABDLT_ZZZ_D;
8100 case AArch64::UABALT_ZZZ_H:
8101 return AArch64::UABDLT_ZZZ_H;
8102 case AArch64::UABALT_ZZZ_S:
8103 return AArch64::UABDLT_ZZZ_S;
8104 case AArch64::UABALv16i8_v8i16:
8105 return AArch64::UABDLv16i8_v8i16;
8106 case AArch64::UABALv2i32_v2i64:
8107 return AArch64::UABDLv2i32_v2i64;
8108 case AArch64::UABALv4i16_v4i32:
8109 return AArch64::UABDLv4i16_v4i32;
8110 case AArch64::UABALv4i32_v2i64:
8111 return AArch64::UABDLv4i32_v2i64;
8112 case AArch64::UABALv8i16_v4i32:
8113 return AArch64::UABDLv8i16_v4i32;
8114 case AArch64::UABALv8i8_v8i16:
8115 return AArch64::UABDLv8i8_v8i16;
8116 case AArch64::UABAv16i8:
8117 return AArch64::UABDv16i8;
8118 case AArch64::UABAv2i32:
8119 return AArch64::UABDv2i32;
8120 case AArch64::UABAv4i16:
8121 return AArch64::UABDv4i16;
8122 case AArch64::UABAv4i32:
8123 return AArch64::UABDv4i32;
8124 case AArch64::UABAv8i16:
8125 return AArch64::UABDv8i16;
8126 case AArch64::UABAv8i8:
8127 return AArch64::UABDv8i8;
8128 case AArch64::SABALB_ZZZ_D:
8129 return AArch64::SABDLB_ZZZ_D;
8130 case AArch64::SABALB_ZZZ_S:
8131 return AArch64::SABDLB_ZZZ_S;
8132 case AArch64::SABALB_ZZZ_H:
8133 return AArch64::SABDLB_ZZZ_H;
8134 case AArch64::SABALT_ZZZ_D:
8135 return AArch64::SABDLT_ZZZ_D;
8136 case AArch64::SABALT_ZZZ_S:
8137 return AArch64::SABDLT_ZZZ_S;
8138 case AArch64::SABALT_ZZZ_H:
8139 return AArch64::SABDLT_ZZZ_H;
8140 case AArch64::SABALv16i8_v8i16:
8141 return AArch64::SABDLv16i8_v8i16;
8142 case AArch64::SABALv2i32_v2i64:
8143 return AArch64::SABDLv2i32_v2i64;
8144 case AArch64::SABALv4i16_v4i32:
8145 return AArch64::SABDLv4i16_v4i32;
8146 case AArch64::SABALv4i32_v2i64:
8147 return AArch64::SABDLv4i32_v2i64;
8148 case AArch64::SABALv8i16_v4i32:
8149 return AArch64::SABDLv8i16_v4i32;
8150 case AArch64::SABALv8i8_v8i16:
8151 return AArch64::SABDLv8i8_v8i16;
8152 case AArch64::SABAv16i8:
8153 return AArch64::SABDv16i8;
8154 case AArch64::SABAv2i32:
8155 return AArch64::SABDv2i32;
8156 case AArch64::SABAv4i16:
8157 return AArch64::SABDv4i16;
8158 case AArch64::SABAv4i32:
8159 return AArch64::SABDv4i32;
8160 case AArch64::SABAv8i16:
8161 return AArch64::SABDv8i16;
8162 case AArch64::SABAv8i8:
8163 return AArch64::SABDv8i8;
8164 }
8165}
8166
8167/// Floating-Point Support
8168
8169/// Find instructions that can be turned into madd.
8171 SmallVectorImpl<unsigned> &Patterns) {
8172
8173 if (!isCombineInstrCandidateFP(Root))
8174 return false;
8175
8176 MachineBasicBlock &MBB = *Root.getParent();
8177 bool Found = false;
8178
8179 auto Match = [&](int Opcode, int Operand, unsigned Pattern) -> bool {
8180 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
8181 Patterns.push_back(Pattern);
8182 return true;
8183 }
8184 return false;
8185 };
8186
8188
8189 switch (Root.getOpcode()) {
8190 default:
8191 assert(false && "Unsupported FP instruction in combiner\n");
8192 break;
8193 case AArch64::FADDHrr:
8194 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8195 "FADDHrr does not have register operands");
8196
8197 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
8198 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
8199 break;
8200 case AArch64::FADDSrr:
8201 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8202 "FADDSrr does not have register operands");
8203
8204 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
8205 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
8206
8207 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
8208 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
8209 break;
8210 case AArch64::FADDDrr:
8211 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
8212 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
8213
8214 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
8215 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
8216 break;
8217 case AArch64::FADDv4f16:
8218 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
8219 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
8220
8221 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
8222 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
8223 break;
8224 case AArch64::FADDv8f16:
8225 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
8226 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
8227
8228 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
8229 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
8230 break;
8231 case AArch64::FADDv2f32:
8232 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
8233 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
8234
8235 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
8236 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
8237 break;
8238 case AArch64::FADDv2f64:
8239 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
8240 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
8241
8242 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
8243 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
8244 break;
8245 case AArch64::FADDv4f32:
8246 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
8247 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
8248
8249 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
8250 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
8251 break;
8252 case AArch64::FSUBHrr:
8253 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
8254 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
8255 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
8256 break;
8257 case AArch64::FSUBSrr:
8258 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
8259
8260 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
8261 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
8262
8263 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
8264 break;
8265 case AArch64::FSUBDrr:
8266 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
8267
8268 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
8269 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
8270
8271 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
8272 break;
8273 case AArch64::FSUBv4f16:
8274 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
8275 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
8276
8277 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
8278 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
8279 break;
8280 case AArch64::FSUBv8f16:
8281 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
8282 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
8283
8284 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
8285 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
8286 break;
8287 case AArch64::FSUBv2f32:
8288 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
8289 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
8290
8291 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
8292 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
8293 break;
8294 case AArch64::FSUBv2f64:
8295 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
8296 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
8297
8298 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
8299 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
8300 break;
8301 case AArch64::FSUBv4f32:
8302 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
8303 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
8304
8305 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
8306 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
8307 break;
8308 }
8309 return Found;
8310}
8311
8313 SmallVectorImpl<unsigned> &Patterns) {
8314 MachineBasicBlock &MBB = *Root.getParent();
8315 bool Found = false;
8316
8317 auto Match = [&](unsigned Opcode, int Operand, unsigned Pattern) -> bool {
8318 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8319 MachineOperand &MO = Root.getOperand(Operand);
8320 MachineInstr *MI = nullptr;
8321 if (MO.isReg() && MO.getReg().isVirtual())
8322 MI = MRI.getUniqueVRegDef(MO.getReg());
8323 // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
8324 if (MI && MI->getOpcode() == TargetOpcode::COPY &&
8325 MI->getOperand(1).getReg().isVirtual())
8326 MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
8327 if (MI && MI->getOpcode() == Opcode) {
8328 Patterns.push_back(Pattern);
8329 return true;
8330 }
8331 return false;
8332 };
8333
8335
8336 switch (Root.getOpcode()) {
8337 default:
8338 return false;
8339 case AArch64::FMULv2f32:
8340 Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
8341 Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
8342 break;
8343 case AArch64::FMULv2f64:
8344 Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
8345 Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
8346 break;
8347 case AArch64::FMULv4f16:
8348 Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
8349 Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
8350 break;
8351 case AArch64::FMULv4f32:
8352 Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
8353 Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
8354 break;
8355 case AArch64::FMULv8f16:
8356 Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
8357 Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
8358 break;
8359 }
8360
8361 return Found;
8362}
8363
8365 SmallVectorImpl<unsigned> &Patterns) {
8366 unsigned Opc = Root.getOpcode();
8367 MachineBasicBlock &MBB = *Root.getParent();
8368 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8369
8370 auto Match = [&](unsigned Opcode, unsigned Pattern) -> bool {
8371 MachineOperand &MO = Root.getOperand(1);
8372 MachineInstr *MI = MRI.getUniqueVRegDef(MO.getReg());
8373 if (MI != nullptr && (MI->getOpcode() == Opcode) &&
8374 MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()) &&
8378 MI->getFlag(MachineInstr::MIFlag::FmNsz)) {
8379 Patterns.push_back(Pattern);
8380 return true;
8381 }
8382 return false;
8383 };
8384
8385 switch (Opc) {
8386 default:
8387 break;
8388 case AArch64::FNEGDr:
8389 return Match(AArch64::FMADDDrrr, AArch64MachineCombinerPattern::FNMADD);
8390 case AArch64::FNEGSr:
8391 return Match(AArch64::FMADDSrrr, AArch64MachineCombinerPattern::FNMADD);
8392 }
8393
8394 return false;
8395}
8396
8397/// Return true when a code sequence can improve throughput. It
8398/// should be called only for instructions in loops.
8399/// \param Pattern - combiner pattern
8401 switch (Pattern) {
8402 default:
8403 break;
8509 return true;
8510 } // end switch (Pattern)
8511 return false;
8512}
8513
8514/// Find other MI combine patterns.
8516 SmallVectorImpl<unsigned> &Patterns) {
8517 // A - (B + C) ==> (A - B) - C or (A - C) - B
8518 unsigned Opc = Root.getOpcode();
8519 MachineBasicBlock &MBB = *Root.getParent();
8520
8521 switch (Opc) {
8522 case AArch64::SUBWrr:
8523 case AArch64::SUBSWrr:
8524 case AArch64::SUBXrr:
8525 case AArch64::SUBSXrr:
8526 // Found candidate root.
8527 break;
8528 default:
8529 return false;
8530 }
8531
8533 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) ==
8534 -1)
8535 return false;
8536
8537 if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
8538 canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
8539 canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
8540 canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
8543 return true;
8544 }
8545
8546 return false;
8547}
8548
8549/// Check if the given instruction forms a gather load pattern that can be
8550/// optimized for better Memory-Level Parallelism (MLP). This function
8551/// identifies chains of NEON lane load instructions that load data from
8552/// different memory addresses into individual lanes of a 128-bit vector
8553/// register, then attempts to split the pattern into parallel loads to break
8554/// the serial dependency between instructions.
8555///
8556/// Pattern Matched:
8557/// Initial scalar load -> SUBREG_TO_REG (lane 0) -> LD1i* (lane 1) ->
8558/// LD1i* (lane 2) -> ... -> LD1i* (lane N-1, Root)
8559///
8560/// Transformed Into:
8561/// Two parallel vector loads using fewer lanes each, followed by ZIP1v2i64
8562/// to combine the results, enabling better memory-level parallelism.
8563///
8564/// Supported Element Types:
8565/// - 32-bit elements (LD1i32, 4 lanes total)
8566/// - 16-bit elements (LD1i16, 8 lanes total)
8567/// - 8-bit elements (LD1i8, 16 lanes total)
8569 SmallVectorImpl<unsigned> &Patterns,
8570 unsigned LoadLaneOpCode, unsigned NumLanes) {
8571 const MachineFunction *MF = Root.getMF();
8572
8573 // Early exit if optimizing for size.
8574 if (MF->getFunction().hasMinSize())
8575 return false;
8576
8577 const MachineRegisterInfo &MRI = MF->getRegInfo();
8579
8580 // The root of the pattern must load into the last lane of the vector.
8581 if (Root.getOperand(2).getImm() != NumLanes - 1)
8582 return false;
8583
8584 // Check that we have load into all lanes except lane 0.
8585 // For each load we also want to check that:
8586 // 1. It has a single non-debug use (since we will be replacing the virtual
8587 // register)
8588 // 2. That the addressing mode only uses a single pointer operand
8589 auto *CurrInstr = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8590 auto Range = llvm::seq<unsigned>(1, NumLanes - 1);
8591 SmallSet<unsigned, 16> RemainingLanes(Range.begin(), Range.end());
8593 while (!RemainingLanes.empty() && CurrInstr &&
8594 CurrInstr->getOpcode() == LoadLaneOpCode &&
8595 MRI.hasOneNonDBGUse(CurrInstr->getOperand(0).getReg()) &&
8596 CurrInstr->getNumOperands() == 4) {
8597 RemainingLanes.erase(CurrInstr->getOperand(2).getImm());
8598 LoadInstrs.push_back(CurrInstr);
8599 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8600 }
8601
8602 // Check that we have found a match for lanes N-1.. 1.
8603 if (!RemainingLanes.empty())
8604 return false;
8605
8606 // Match the SUBREG_TO_REG sequence.
8607 if (CurrInstr->getOpcode() != TargetOpcode::SUBREG_TO_REG)
8608 return false;
8609
8610 // Verify that the subreg to reg loads an integer into the first lane.
8611 auto Lane0LoadReg = CurrInstr->getOperand(1).getReg();
8612 unsigned SingleLaneSizeInBits = 128 / NumLanes;
8613 if (TRI->getRegSizeInBits(Lane0LoadReg, MRI) != SingleLaneSizeInBits)
8614 return false;
8615
8616 // Verify that it also has a single non debug use.
8617 if (!MRI.hasOneNonDBGUse(Lane0LoadReg))
8618 return false;
8619
8620 LoadInstrs.push_back(MRI.getUniqueVRegDef(Lane0LoadReg));
8621
8622 // If there is any chance of aliasing, do not apply the pattern.
8623 // Walk backward through the MBB starting from Root.
8624 // Exit early if we've encountered all load instructions or hit the search
8625 // limit.
8626 auto MBBItr = Root.getIterator();
8627 unsigned RemainingSteps =
8628 MF->getSubtarget<AArch64Subtarget>().getCLOpts().search_limit;
8629 SmallPtrSet<const MachineInstr *, 16> RemainingLoadInstrs;
8630 RemainingLoadInstrs.insert(LoadInstrs.begin(), LoadInstrs.end());
8631 const MachineBasicBlock *MBB = Root.getParent();
8632
8633 for (; MBBItr != MBB->begin() && RemainingSteps > 0 &&
8634 !RemainingLoadInstrs.empty();
8635 --MBBItr, --RemainingSteps) {
8636 const MachineInstr &CurrInstr = *MBBItr;
8637
8638 // Remove this instruction from remaining loads if it's one we're tracking.
8639 RemainingLoadInstrs.erase(&CurrInstr);
8640
8641 // Check for potential aliasing with any of the load instructions to
8642 // optimize.
8643 if (CurrInstr.isLoadFoldBarrier())
8644 return false;
8645 }
8646
8647 // If we hit the search limit without finding all load instructions,
8648 // don't match the pattern.
8649 if (RemainingSteps == 0 && !RemainingLoadInstrs.empty())
8650 return false;
8651
8652 switch (NumLanes) {
8653 case 4:
8655 break;
8656 case 8:
8658 break;
8659 case 16:
8661 break;
8662 default:
8663 llvm_unreachable("Got bad number of lanes for gather pattern.");
8664 }
8665
8666 return true;
8667}
8668
8669/// Search for patterns of LD instructions we can optimize.
8671 SmallVectorImpl<unsigned> &Patterns) {
8672
8673 // The pattern searches for loads into single lanes.
8674 switch (Root.getOpcode()) {
8675 case AArch64::LD1i32:
8676 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 4);
8677 case AArch64::LD1i16:
8678 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 8);
8679 case AArch64::LD1i8:
8680 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 16);
8681 default:
8682 return false;
8683 }
8684}
8685
8686/// Generate optimized instruction sequence for gather load patterns to improve
8687/// Memory-Level Parallelism (MLP). This function transforms a chain of
8688/// sequential NEON lane loads into parallel vector loads that can execute
8689/// concurrently.
8690static void
8694 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8695 unsigned Pattern, unsigned NumLanes) {
8696 MachineFunction &MF = *Root.getParent()->getParent();
8699
8700 // Gather the initial load instructions to build the pattern.
8701 SmallVector<MachineInstr *, 16> LoadToLaneInstrs;
8702 MachineInstr *CurrInstr = &Root;
8703 for (unsigned i = 0; i < NumLanes - 1; ++i) {
8704 LoadToLaneInstrs.push_back(CurrInstr);
8705 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8706 }
8707
8708 // Sort the load instructions according to the lane.
8709 llvm::sort(LoadToLaneInstrs,
8710 [](const MachineInstr *A, const MachineInstr *B) {
8711 return A->getOperand(2).getImm() > B->getOperand(2).getImm();
8712 });
8713
8714 MachineInstr *SubregToReg = CurrInstr;
8715 LoadToLaneInstrs.push_back(
8716 MRI.getUniqueVRegDef(SubregToReg->getOperand(1).getReg()));
8717 auto LoadToLaneInstrsAscending = llvm::reverse(LoadToLaneInstrs);
8718
8719 const TargetRegisterClass *FPR128RegClass =
8720 MRI.getRegClass(Root.getOperand(0).getReg());
8721
8722 // Helper lambda to create a LD1 instruction.
8723 auto CreateLD1Instruction = [&](MachineInstr *OriginalInstr,
8724 Register SrcRegister, unsigned Lane,
8725 Register OffsetRegister) {
8726 auto NewRegister = MRI.createVirtualRegister(FPR128RegClass);
8727 MachineInstrBuilder LoadIndexIntoRegister =
8728 BuildMI(MF, MIMetadata(*OriginalInstr), TII->get(Root.getOpcode()),
8729 NewRegister)
8730 .addReg(SrcRegister)
8731 .addImm(Lane)
8732 .addReg(OffsetRegister)
8733 .setMemRefs(OriginalInstr->memoperands());
8734 InstrIdxForVirtReg.insert(std::make_pair(NewRegister, InsInstrs.size()));
8735 InsInstrs.push_back(LoadIndexIntoRegister);
8736 return NewRegister;
8737 };
8738
8739 // Helper to create load instruction based on the NumLanes in the NEON
8740 // register we are rewriting.
8741 auto CreateLDRInstruction =
8742 [&](unsigned NumLanes, Register DestReg, Register OffsetReg,
8744 unsigned Opcode;
8745 switch (NumLanes) {
8746 case 4:
8747 Opcode = AArch64::LDRSui;
8748 break;
8749 case 8:
8750 Opcode = AArch64::LDRHui;
8751 break;
8752 case 16:
8753 Opcode = AArch64::LDRBui;
8754 break;
8755 default:
8757 "Got unsupported number of lanes in machine-combiner gather pattern");
8758 }
8759 // Immediate offset load
8760 return BuildMI(MF, MIMetadata(Root), TII->get(Opcode), DestReg)
8761 .addReg(OffsetReg)
8762 .addImm(0)
8763 .setMemRefs(MMOs);
8764 };
8765
8766 // Load the remaining lanes into register 0.
8767 auto LanesToLoadToReg0 =
8768 llvm::make_range(LoadToLaneInstrsAscending.begin() + 1,
8769 LoadToLaneInstrsAscending.begin() + NumLanes / 2);
8770 Register PrevReg = SubregToReg->getOperand(0).getReg();
8771 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg0)) {
8772 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8773 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8774 OffsetRegOperand.getReg());
8775 DelInstrs.push_back(LoadInstr);
8776 }
8777 Register LastLoadReg0 = PrevReg;
8778
8779 // First load into register 1. Perform an integer load to zero out the upper
8780 // lanes in a single instruction.
8781 MachineInstr *Lane0Load = *LoadToLaneInstrsAscending.begin();
8782 MachineInstr *OriginalSplitLoad =
8783 *std::next(LoadToLaneInstrsAscending.begin(), NumLanes / 2);
8784 Register DestRegForMiddleIndex = MRI.createVirtualRegister(
8785 MRI.getRegClass(Lane0Load->getOperand(0).getReg()));
8786
8787 const MachineOperand &OriginalSplitToLoadOffsetOperand =
8788 OriginalSplitLoad->getOperand(3);
8789 MachineInstrBuilder MiddleIndexLoadInstr =
8790 CreateLDRInstruction(NumLanes, DestRegForMiddleIndex,
8791 OriginalSplitToLoadOffsetOperand.getReg(),
8792 OriginalSplitLoad->memoperands());
8793
8794 InstrIdxForVirtReg.insert(
8795 std::make_pair(DestRegForMiddleIndex, InsInstrs.size()));
8796 InsInstrs.push_back(MiddleIndexLoadInstr);
8797 DelInstrs.push_back(OriginalSplitLoad);
8798
8799 // Subreg To Reg instruction for register 1.
8800 Register DestRegForSubregToReg = MRI.createVirtualRegister(FPR128RegClass);
8801 unsigned SubregType;
8802 switch (NumLanes) {
8803 case 4:
8804 SubregType = AArch64::ssub;
8805 break;
8806 case 8:
8807 SubregType = AArch64::hsub;
8808 break;
8809 case 16:
8810 SubregType = AArch64::bsub;
8811 break;
8812 default:
8814 "Got invalid NumLanes for machine-combiner gather pattern");
8815 }
8816
8817 auto SubRegToRegInstr =
8818 BuildMI(MF, MIMetadata(Root), TII->get(SubregToReg->getOpcode()),
8819 DestRegForSubregToReg)
8820 .addReg(DestRegForMiddleIndex)
8821 .addImm(SubregType);
8822 InstrIdxForVirtReg.insert(
8823 std::make_pair(DestRegForSubregToReg, InsInstrs.size()));
8824 InsInstrs.push_back(SubRegToRegInstr);
8825
8826 // Load remaining lanes into register 1.
8827 auto LanesToLoadToReg1 =
8828 llvm::make_range(LoadToLaneInstrsAscending.begin() + NumLanes / 2 + 1,
8829 LoadToLaneInstrsAscending.end());
8830 PrevReg = SubRegToRegInstr->getOperand(0).getReg();
8831 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg1)) {
8832 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8833 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8834 OffsetRegOperand.getReg());
8835
8836 // Do not add the last reg to DelInstrs - it will be removed later.
8837 if (Index == NumLanes / 2 - 2) {
8838 break;
8839 }
8840 DelInstrs.push_back(LoadInstr);
8841 }
8842 Register LastLoadReg1 = PrevReg;
8843
8844 // Create the final zip instruction to combine the results.
8845 MachineInstrBuilder ZipInstr =
8846 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::ZIP1v2i64),
8847 Root.getOperand(0).getReg())
8848 .addReg(LastLoadReg0)
8849 .addReg(LastLoadReg1);
8850 InsInstrs.push_back(ZipInstr);
8851}
8852
8866
8867/// Return true when there is potentially a faster code sequence for an
8868/// instruction chain ending in \p Root. All potential patterns are listed in
8869/// the \p Pattern vector. Pattern should be sorted in priority order since the
8870/// pattern evaluator stops checking as soon as it finds a faster sequence.
8871
8872bool AArch64InstrInfo::getMachineCombinerPatterns(
8873 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
8874 bool DoRegPressureReduce) const {
8875 // Integer patterns
8876 if (getMaddPatterns(Root, Patterns))
8877 return true;
8878 // Floating point patterns
8879 if (getFMULPatterns(Root, Patterns))
8880 return true;
8881 if (getFMAPatterns(Root, Patterns))
8882 return true;
8883 if (getFNEGPatterns(Root, Patterns))
8884 return true;
8885
8886 // Other patterns
8887 if (getMiscPatterns(Root, Patterns))
8888 return true;
8889
8890 // Load patterns
8891 if (getLoadPatterns(Root, Patterns))
8892 return true;
8893
8894 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
8895 DoRegPressureReduce);
8896}
8897
8899/// genFusedMultiply - Generate fused multiply instructions.
8900/// This function supports both integer and floating point instructions.
8901/// A typical example:
8902/// F|MUL I=A,B,0
8903/// F|ADD R,I,C
8904/// ==> F|MADD R,A,B,C
8905/// \param MF Containing MachineFunction
8906/// \param MRI Register information
8907/// \param TII Target information
8908/// \param Root is the F|ADD instruction
8909/// \param [out] InsInstrs is a vector of machine instructions and will
8910/// contain the generated madd instruction
8911/// \param IdxMulOpd is index of operand in Root that is the result of
8912/// the F|MUL. In the example above IdxMulOpd is 1.
8913/// \param MaddOpc the opcode fo the f|madd instruction
8914/// \param RC Register class of operands
8915/// \param kind of fma instruction (addressing mode) to be generated
8916/// \param ReplacedAddend is the result register from the instruction
8917/// replacing the non-combined operand, if any.
8918static MachineInstr *
8920 const TargetInstrInfo *TII, MachineInstr &Root,
8921 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
8922 unsigned MaddOpc, const TargetRegisterClass *RC,
8924 const Register *ReplacedAddend = nullptr) {
8925 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8926
8927 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
8928 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8929 Register ResultReg = Root.getOperand(0).getReg();
8930 Register SrcReg0 = MUL->getOperand(1).getReg();
8931 Register SrcReg1 = MUL->getOperand(2).getReg();
8932
8933 Register SrcReg2 =
8934 ReplacedAddend ? *ReplacedAddend : Root.getOperand(IdxOtherOpd).getReg();
8935
8936 if (ResultReg.isVirtual())
8937 MRI.constrainRegClass(ResultReg, RC);
8938 if (SrcReg0.isVirtual())
8939 MRI.constrainRegClass(SrcReg0, RC);
8940 if (SrcReg1.isVirtual())
8941 MRI.constrainRegClass(SrcReg1, RC);
8942 if (SrcReg2.isVirtual())
8943 MRI.constrainRegClass(SrcReg2, RC);
8944
8946 if (kind == FMAInstKind::Default)
8947 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8948 .addReg(SrcReg0)
8949 .addReg(SrcReg1)
8950 .addReg(SrcReg2);
8951 else if (kind == FMAInstKind::Indexed)
8952 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8953 .addReg(SrcReg2)
8954 .addReg(SrcReg0)
8955 .addReg(SrcReg1)
8956 .addImm(MUL->getOperand(3).getImm());
8957 else if (kind == FMAInstKind::Accumulator)
8958 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8959 .addReg(SrcReg2)
8960 .addReg(SrcReg0)
8961 .addReg(SrcReg1);
8962 else
8963 assert(false && "Invalid FMA instruction kind \n");
8964 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
8965 InsInstrs.push_back(MIB);
8966 return MUL;
8967}
8968
8969/// MUL I=A,B,0
8970/// ADDrs R,I,C,shift
8971/// ==>
8972/// SBFM/UBFM J=C,shift
8973/// MADD R,A,B,J
8975 const TargetInstrInfo *TII, MachineInstr &Root,
8978 unsigned MaddOpc, bool Is64Bit,
8979 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
8980 const TargetRegisterClass *RC =
8981 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
8982 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8983 Register ResultReg = Root.getOperand(0).getReg();
8984 Register SrcReg0 = MUL->getOperand(1).getReg();
8985 Register SrcReg1 = MUL->getOperand(2).getReg();
8986 Register ShiftedReg = Root.getOperand(2).getReg();
8987
8988 if (ResultReg.isVirtual())
8989 MRI.constrainRegClass(ResultReg, RC);
8990 if (SrcReg0.isVirtual())
8991 MRI.constrainRegClass(SrcReg0, RC);
8992 if (SrcReg1.isVirtual())
8993 MRI.constrainRegClass(SrcReg1, RC);
8994 if (ShiftedReg.isVirtual())
8995 MRI.constrainRegClass(ShiftedReg, RC);
8996
8997 unsigned ShiftImm = Root.getOperand(3).getImm();
8998 unsigned ShiftVal = AArch64_AM::getShiftValue(ShiftImm);
8999 unsigned RegSize = Is64Bit ? 64 : 32;
9000 unsigned BFMOpc;
9001 unsigned ImmR, ImmS;
9002 switch (AArch64_AM::getShiftType(ShiftImm)) {
9003 case AArch64_AM::ASR:
9004 BFMOpc = Is64Bit ? AArch64::SBFMXri : AArch64::SBFMWri;
9005 ImmR = ShiftVal;
9006 ImmS = RegSize - 1;
9007 break;
9008 case AArch64_AM::LSR:
9009 BFMOpc = Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri;
9010 ImmR = ShiftVal;
9011 ImmS = RegSize - 1;
9012 break;
9013 case AArch64_AM::LSL:
9014 BFMOpc = Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri;
9015 ImmR = (RegSize - ShiftVal) % RegSize;
9016 ImmS = RegSize - 1 - ShiftVal;
9017 break;
9018 default:
9019 llvm_unreachable("Unexpected shift type");
9020 }
9021
9022 Register ShiftReg = MRI.createVirtualRegister(RC);
9023 MachineInstrBuilder MIB1 =
9024 BuildMI(MF, MIMetadata(Root), TII->get(BFMOpc), ShiftReg)
9025 .addReg(ShiftedReg)
9026 .addImm(ImmR)
9027 .addImm(ImmS);
9028 InstrIdxForVirtReg.insert(std::make_pair(ShiftReg, InsInstrs.size()));
9029 InsInstrs.push_back(MIB1);
9030
9031 uint32_t Flags = Root.getFlags() & MUL->getFlags() &
9033
9034 MachineInstrBuilder MIB2 =
9035 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
9036 .addReg(SrcReg0)
9037 .addReg(SrcReg1)
9038 .addReg(ShiftReg)
9039 .setMIFlags(Flags);
9040
9041 InsInstrs.push_back(MIB2);
9042 DelInstrs.push_back(MUL);
9043 DelInstrs.push_back(&Root);
9044}
9045
9046static MachineInstr *
9048 const TargetInstrInfo *TII, MachineInstr &Root,
9050 MachineInstr *MAD = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
9051
9052 unsigned Opc = 0;
9053 const TargetRegisterClass *RC = MRI.getRegClass(MAD->getOperand(0).getReg());
9054 if (AArch64::FPR32RegClass.hasSubClassEq(RC))
9055 Opc = AArch64::FNMADDSrrr;
9056 else if (AArch64::FPR64RegClass.hasSubClassEq(RC))
9057 Opc = AArch64::FNMADDDrrr;
9058 else
9059 return nullptr;
9060
9061 Register ResultReg = Root.getOperand(0).getReg();
9062 Register SrcReg0 = MAD->getOperand(1).getReg();
9063 Register SrcReg1 = MAD->getOperand(2).getReg();
9064 Register SrcReg2 = MAD->getOperand(3).getReg();
9065 if (ResultReg.isVirtual())
9066 MRI.constrainRegClass(ResultReg, RC);
9067 if (SrcReg0.isVirtual())
9068 MRI.constrainRegClass(SrcReg0, RC);
9069 if (SrcReg1.isVirtual())
9070 MRI.constrainRegClass(SrcReg1, RC);
9071 if (SrcReg2.isVirtual())
9072 MRI.constrainRegClass(SrcReg2, RC);
9073
9075 BuildMI(MF, MIMetadata(Root), TII->get(Opc), ResultReg)
9076 .addReg(SrcReg0)
9077 .addReg(SrcReg1)
9078 .addReg(SrcReg2);
9079 InsInstrs.push_back(MIB);
9080
9081 return MAD;
9082}
9083
9084/// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
9085static MachineInstr *
9088 unsigned IdxDupOp, unsigned MulOpc,
9090 assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
9091 "Invalid index of FMUL operand");
9092
9093 MachineFunction &MF = *Root.getMF();
9095
9096 MachineInstr *Dup =
9097 MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
9098
9099 if (Dup->getOpcode() == TargetOpcode::COPY)
9100 Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
9101
9102 Register DupSrcReg = Dup->getOperand(1).getReg();
9103 MRI.constrainRegClass(DupSrcReg, RC);
9104
9105 unsigned DupSrcLane = Dup->getOperand(2).getImm();
9106
9107 unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
9108 MachineOperand &MulOp = Root.getOperand(IdxMulOp);
9109
9110 Register ResultReg = Root.getOperand(0).getReg();
9111
9113 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
9114 .add(MulOp)
9115 .addReg(DupSrcReg)
9116 .addImm(DupSrcLane);
9117
9118 InsInstrs.push_back(MIB);
9119 return &Root;
9120}
9121
9122/// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
9123/// instructions.
9124///
9125/// \see genFusedMultiply
9129 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
9130 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9132}
9133
9134/// genNeg - Helper to generate an intermediate negation of the second operand
9135/// of Root
9137 const TargetInstrInfo *TII, MachineInstr &Root,
9139 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
9140 unsigned MnegOpc, const TargetRegisterClass *RC) {
9141 Register NewVR = MRI.createVirtualRegister(RC);
9143 BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
9144 .add(Root.getOperand(2));
9145 InsInstrs.push_back(MIB);
9146
9147 assert(InstrIdxForVirtReg.empty());
9148 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9149
9150 return NewVR;
9151}
9152
9153/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
9154/// instructions with an additional negation of the accumulator
9158 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
9159 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
9160 assert(IdxMulOpd == 1);
9161
9162 Register NewVR =
9163 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
9164 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9165 FMAInstKind::Accumulator, &NewVR);
9166}
9167
9168/// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
9169/// instructions.
9170///
9171/// \see genFusedMultiply
9175 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
9176 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9178}
9179
9180/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
9181/// instructions with an additional negation of the accumulator
9185 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
9186 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
9187 assert(IdxMulOpd == 1);
9188
9189 Register NewVR =
9190 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
9191
9192 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9193 FMAInstKind::Indexed, &NewVR);
9194}
9195
9196/// genMaddR - Generate madd instruction and combine mul and add using
9197/// an extra virtual register
9198/// Example - an ADD intermediate needs to be stored in a register:
9199/// MUL I=A,B,0
9200/// ADD R,I,Imm
9201/// ==> ORR V, ZR, Imm
9202/// ==> MADD R,A,B,V
9203/// \param MF Containing MachineFunction
9204/// \param MRI Register information
9205/// \param TII Target information
9206/// \param Root is the ADD instruction
9207/// \param [out] InsInstrs is a vector of machine instructions and will
9208/// contain the generated madd instruction
9209/// \param IdxMulOpd is index of operand in Root that is the result of
9210/// the MUL. In the example above IdxMulOpd is 1.
9211/// \param MaddOpc the opcode fo the madd instruction
9212/// \param VR is a virtual register that holds the value of an ADD operand
9213/// (V in the example above).
9214/// \param RC Register class of operands
9216 const TargetInstrInfo *TII, MachineInstr &Root,
9218 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
9219 const TargetRegisterClass *RC) {
9220 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
9221
9222 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
9223 Register ResultReg = Root.getOperand(0).getReg();
9224 Register SrcReg0 = MUL->getOperand(1).getReg();
9225 Register SrcReg1 = MUL->getOperand(2).getReg();
9226
9227 if (ResultReg.isVirtual())
9228 MRI.constrainRegClass(ResultReg, RC);
9229 if (SrcReg0.isVirtual())
9230 MRI.constrainRegClass(SrcReg0, RC);
9231 if (SrcReg1.isVirtual())
9232 MRI.constrainRegClass(SrcReg1, RC);
9234 MRI.constrainRegClass(VR, RC);
9235
9237 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
9238 .addReg(SrcReg0)
9239 .addReg(SrcReg1)
9240 .addReg(VR);
9241 // Insert the MADD
9242 InsInstrs.push_back(MIB);
9243 return MUL;
9244}
9245
9246/// Do the following transformation
9247/// A - (B + C) ==> (A - B) - C
9248/// A - (B + C) ==> (A - C) - B
9250 const TargetInstrInfo *TII, MachineInstr &Root,
9253 unsigned IdxOpd1,
9254 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
9255 assert(IdxOpd1 == 1 || IdxOpd1 == 2);
9256 unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
9257 MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
9258
9259 Register ResultReg = Root.getOperand(0).getReg();
9260 Register RegA = Root.getOperand(1).getReg();
9261 Register RegB = AddMI->getOperand(IdxOpd1).getReg();
9262 Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
9263 Register NewVR =
9264 MRI.createVirtualRegister(MRI.getRegClass(Root.getOperand(2).getReg()));
9265
9266 unsigned Opcode = Root.getOpcode();
9267 if (Opcode == AArch64::SUBSWrr)
9268 Opcode = AArch64::SUBWrr;
9269 else if (Opcode == AArch64::SUBSXrr)
9270 Opcode = AArch64::SUBXrr;
9271 else
9272 assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
9273 "Unexpected instruction opcode.");
9274
9275 uint32_t Flags = Root.mergeFlagsWith(*AddMI);
9276 Flags &= ~MachineInstr::NoSWrap;
9277 Flags &= ~MachineInstr::NoUWrap;
9278
9279 MachineInstrBuilder MIB1 =
9280 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
9281 .addReg(RegA)
9282 .addReg(RegB)
9283 .setMIFlags(Flags);
9284 MachineInstrBuilder MIB2 =
9285 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
9286 .addReg(NewVR)
9287 .addReg(RegC)
9288 .setMIFlags(Flags);
9289
9290 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9291 InsInstrs.push_back(MIB1);
9292 InsInstrs.push_back(MIB2);
9293 DelInstrs.push_back(AddMI);
9294 DelInstrs.push_back(&Root);
9295}
9296
9297unsigned AArch64InstrInfo::getReduceOpcodeForAccumulator(
9298 unsigned int AccumulatorOpCode) const {
9299 switch (AccumulatorOpCode) {
9300 case AArch64::UABALB_ZZZ_D:
9301 case AArch64::SABALB_ZZZ_D:
9302 case AArch64::UABALT_ZZZ_D:
9303 case AArch64::SABALT_ZZZ_D:
9304 return AArch64::ADD_ZZZ_D;
9305 case AArch64::UABALB_ZZZ_H:
9306 case AArch64::SABALB_ZZZ_H:
9307 case AArch64::UABALT_ZZZ_H:
9308 case AArch64::SABALT_ZZZ_H:
9309 return AArch64::ADD_ZZZ_H;
9310 case AArch64::UABALB_ZZZ_S:
9311 case AArch64::SABALB_ZZZ_S:
9312 case AArch64::UABALT_ZZZ_S:
9313 case AArch64::SABALT_ZZZ_S:
9314 return AArch64::ADD_ZZZ_S;
9315 case AArch64::UABALv16i8_v8i16:
9316 case AArch64::SABALv8i8_v8i16:
9317 case AArch64::SABAv8i16:
9318 case AArch64::UABAv8i16:
9319 return AArch64::ADDv8i16;
9320 case AArch64::SABALv2i32_v2i64:
9321 case AArch64::UABALv2i32_v2i64:
9322 case AArch64::SABALv4i32_v2i64:
9323 return AArch64::ADDv2i64;
9324 case AArch64::UABALv4i16_v4i32:
9325 case AArch64::SABALv4i16_v4i32:
9326 case AArch64::SABALv8i16_v4i32:
9327 case AArch64::SABAv4i32:
9328 case AArch64::UABAv4i32:
9329 return AArch64::ADDv4i32;
9330 case AArch64::UABALv4i32_v2i64:
9331 return AArch64::ADDv2i64;
9332 case AArch64::UABALv8i16_v4i32:
9333 return AArch64::ADDv4i32;
9334 case AArch64::UABALv8i8_v8i16:
9335 case AArch64::SABALv16i8_v8i16:
9336 return AArch64::ADDv8i16;
9337 case AArch64::UABAv16i8:
9338 case AArch64::SABAv16i8:
9339 return AArch64::ADDv16i8;
9340 case AArch64::UABAv4i16:
9341 case AArch64::SABAv4i16:
9342 return AArch64::ADDv4i16;
9343 case AArch64::UABAv2i32:
9344 case AArch64::SABAv2i32:
9345 return AArch64::ADDv2i32;
9346 case AArch64::UABAv8i8:
9347 case AArch64::SABAv8i8:
9348 return AArch64::ADDv8i8;
9349 default:
9350 llvm_unreachable("Unknown accumulator opcode");
9351 }
9352}
9353
9354/// When getMachineCombinerPatterns() finds potential patterns,
9355/// this function generates the instructions that could replace the
9356/// original code sequence
9357void AArch64InstrInfo::genAlternativeCodeSequence(
9358 MachineInstr &Root, unsigned Pattern,
9361 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
9362 MachineBasicBlock &MBB = *Root.getParent();
9363 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9364 MachineFunction &MF = *MBB.getParent();
9365 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9366
9367 MachineInstr *MUL = nullptr;
9368 const TargetRegisterClass *RC;
9369 unsigned Opc;
9370 switch (Pattern) {
9371 default:
9372 // Reassociate instructions.
9373 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9374 DelInstrs, InstrIdxForVirtReg);
9375 return;
9377 // A - (B + C)
9378 // ==> (A - B) - C
9379 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
9380 InstrIdxForVirtReg);
9381 return;
9383 // A - (B + C)
9384 // ==> (A - C) - B
9385 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
9386 InstrIdxForVirtReg);
9387 return;
9390 // MUL I=A,B,0
9391 // ADD R,I,C
9392 // ==> MADD R,A,B,C
9393 // --- Create(MADD);
9395 Opc = AArch64::MADDWrrr;
9396 RC = &AArch64::GPR32RegClass;
9397 } else {
9398 Opc = AArch64::MADDXrrr;
9399 RC = &AArch64::GPR64RegClass;
9400 }
9401 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9402 break;
9405 // MUL I=A,B,0
9406 // ADD R,C,I
9407 // ==> MADD R,A,B,C
9408 // --- Create(MADD);
9410 Opc = AArch64::MADDWrrr;
9411 RC = &AArch64::GPR32RegClass;
9412 } else {
9413 Opc = AArch64::MADDXrrr;
9414 RC = &AArch64::GPR64RegClass;
9415 }
9416 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9417 break;
9422 // MUL I=A,B,0
9423 // ADD/SUB R,I,Imm
9424 // ==> MOV V, Imm/-Imm
9425 // ==> MADD R,A,B,V
9426 // --- Create(MADD);
9427 const TargetRegisterClass *RC;
9428 unsigned BitSize, MovImm;
9431 MovImm = AArch64::MOVi32imm;
9432 RC = &AArch64::GPR32spRegClass;
9433 BitSize = 32;
9434 Opc = AArch64::MADDWrrr;
9435 RC = &AArch64::GPR32RegClass;
9436 } else {
9437 MovImm = AArch64::MOVi64imm;
9438 RC = &AArch64::GPR64spRegClass;
9439 BitSize = 64;
9440 Opc = AArch64::MADDXrrr;
9441 RC = &AArch64::GPR64RegClass;
9442 }
9444 uint64_t Imm = Root.getOperand(2).getImm();
9445
9446 if (Root.getOperand(3).isImm()) {
9447 unsigned Val = Root.getOperand(3).getImm();
9448 Imm = Imm << Val;
9449 }
9450 bool IsSub = Pattern == AArch64MachineCombinerPattern::MULSUBWI_OP1 ||
9452 uint64_t UImm = SignExtend64(IsSub ? -Imm : Imm, BitSize);
9453 // Check that the immediate can be composed via a single instruction.
9455 AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
9456 if (Insn.size() != 1)
9457 return;
9458 MachineInstrBuilder MIB1 =
9459 BuildMI(MF, MIMetadata(Root), TII->get(MovImm), NewVR)
9460 .addImm(IsSub ? -Imm : Imm);
9461 InsInstrs.push_back(MIB1);
9462 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9463 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9464 break;
9465 }
9468 // MUL I=A,B,0
9469 // SUB R,I, C
9470 // ==> SUB V, 0, C
9471 // ==> MADD R,A,B,V // = -C + A*B
9472 // --- Create(MADD);
9473 const TargetRegisterClass *SubRC;
9474 unsigned SubOpc, ZeroReg;
9476 SubOpc = AArch64::SUBWrr;
9477 SubRC = &AArch64::GPR32spRegClass;
9478 ZeroReg = AArch64::WZR;
9479 Opc = AArch64::MADDWrrr;
9480 RC = &AArch64::GPR32RegClass;
9481 } else {
9482 SubOpc = AArch64::SUBXrr;
9483 SubRC = &AArch64::GPR64spRegClass;
9484 ZeroReg = AArch64::XZR;
9485 Opc = AArch64::MADDXrrr;
9486 RC = &AArch64::GPR64RegClass;
9487 }
9488 Register NewVR = MRI.createVirtualRegister(SubRC);
9489 // SUB NewVR, 0, C
9490 MachineInstrBuilder MIB1 =
9491 BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
9492 .addReg(ZeroReg)
9493 .add(Root.getOperand(2));
9494 InsInstrs.push_back(MIB1);
9495 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9496 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9497 break;
9498 }
9501 // MUL I=A,B,0
9502 // SUB R,C,I
9503 // ==> MSUB R,A,B,C (computes C - A*B)
9504 // --- Create(MSUB);
9506 Opc = AArch64::MSUBWrrr;
9507 RC = &AArch64::GPR32RegClass;
9508 } else {
9509 Opc = AArch64::MSUBXrrr;
9510 RC = &AArch64::GPR64RegClass;
9511 }
9512 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9513 break;
9515 genMaddShf(MF, MRI, TII, Root, InsInstrs, DelInstrs, AArch64::MADDWrrr,
9516 false, InstrIdxForVirtReg);
9517 return;
9519 genMaddShf(MF, MRI, TII, Root, InsInstrs, DelInstrs, AArch64::MADDXrrr,
9520 true, InstrIdxForVirtReg);
9521 return;
9523 Opc = AArch64::MLAv8i8;
9524 RC = &AArch64::FPR64RegClass;
9525 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9526 break;
9528 Opc = AArch64::MLAv8i8;
9529 RC = &AArch64::FPR64RegClass;
9530 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9531 break;
9533 Opc = AArch64::MLAv16i8;
9534 RC = &AArch64::FPR128RegClass;
9535 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9536 break;
9538 Opc = AArch64::MLAv16i8;
9539 RC = &AArch64::FPR128RegClass;
9540 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9541 break;
9543 Opc = AArch64::MLAv4i16;
9544 RC = &AArch64::FPR64RegClass;
9545 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9546 break;
9548 Opc = AArch64::MLAv4i16;
9549 RC = &AArch64::FPR64RegClass;
9550 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9551 break;
9553 Opc = AArch64::MLAv8i16;
9554 RC = &AArch64::FPR128RegClass;
9555 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9556 break;
9558 Opc = AArch64::MLAv8i16;
9559 RC = &AArch64::FPR128RegClass;
9560 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9561 break;
9563 Opc = AArch64::MLAv2i32;
9564 RC = &AArch64::FPR64RegClass;
9565 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9566 break;
9568 Opc = AArch64::MLAv2i32;
9569 RC = &AArch64::FPR64RegClass;
9570 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9571 break;
9573 Opc = AArch64::MLAv4i32;
9574 RC = &AArch64::FPR128RegClass;
9575 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9576 break;
9578 Opc = AArch64::MLAv4i32;
9579 RC = &AArch64::FPR128RegClass;
9580 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9581 break;
9582
9584 Opc = AArch64::MLAv8i8;
9585 RC = &AArch64::FPR64RegClass;
9586 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9587 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
9588 RC);
9589 break;
9591 Opc = AArch64::MLSv8i8;
9592 RC = &AArch64::FPR64RegClass;
9593 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9594 break;
9596 Opc = AArch64::MLAv16i8;
9597 RC = &AArch64::FPR128RegClass;
9598 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9599 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
9600 RC);
9601 break;
9603 Opc = AArch64::MLSv16i8;
9604 RC = &AArch64::FPR128RegClass;
9605 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9606 break;
9608 Opc = AArch64::MLAv4i16;
9609 RC = &AArch64::FPR64RegClass;
9610 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9611 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9612 RC);
9613 break;
9615 Opc = AArch64::MLSv4i16;
9616 RC = &AArch64::FPR64RegClass;
9617 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9618 break;
9620 Opc = AArch64::MLAv8i16;
9621 RC = &AArch64::FPR128RegClass;
9622 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9623 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9624 RC);
9625 break;
9627 Opc = AArch64::MLSv8i16;
9628 RC = &AArch64::FPR128RegClass;
9629 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9630 break;
9632 Opc = AArch64::MLAv2i32;
9633 RC = &AArch64::FPR64RegClass;
9634 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9635 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9636 RC);
9637 break;
9639 Opc = AArch64::MLSv2i32;
9640 RC = &AArch64::FPR64RegClass;
9641 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9642 break;
9644 Opc = AArch64::MLAv4i32;
9645 RC = &AArch64::FPR128RegClass;
9646 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9647 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9648 RC);
9649 break;
9651 Opc = AArch64::MLSv4i32;
9652 RC = &AArch64::FPR128RegClass;
9653 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9654 break;
9655
9657 Opc = AArch64::MLAv4i16_indexed;
9658 RC = &AArch64::FPR64RegClass;
9659 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9660 break;
9662 Opc = AArch64::MLAv4i16_indexed;
9663 RC = &AArch64::FPR64RegClass;
9664 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9665 break;
9667 Opc = AArch64::MLAv8i16_indexed;
9668 RC = &AArch64::FPR128RegClass;
9669 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9670 break;
9672 Opc = AArch64::MLAv8i16_indexed;
9673 RC = &AArch64::FPR128RegClass;
9674 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9675 break;
9677 Opc = AArch64::MLAv2i32_indexed;
9678 RC = &AArch64::FPR64RegClass;
9679 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9680 break;
9682 Opc = AArch64::MLAv2i32_indexed;
9683 RC = &AArch64::FPR64RegClass;
9684 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9685 break;
9687 Opc = AArch64::MLAv4i32_indexed;
9688 RC = &AArch64::FPR128RegClass;
9689 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9690 break;
9692 Opc = AArch64::MLAv4i32_indexed;
9693 RC = &AArch64::FPR128RegClass;
9694 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9695 break;
9696
9698 Opc = AArch64::MLAv4i16_indexed;
9699 RC = &AArch64::FPR64RegClass;
9700 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9701 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9702 RC);
9703 break;
9705 Opc = AArch64::MLSv4i16_indexed;
9706 RC = &AArch64::FPR64RegClass;
9707 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9708 break;
9710 Opc = AArch64::MLAv8i16_indexed;
9711 RC = &AArch64::FPR128RegClass;
9712 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9713 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9714 RC);
9715 break;
9717 Opc = AArch64::MLSv8i16_indexed;
9718 RC = &AArch64::FPR128RegClass;
9719 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9720 break;
9722 Opc = AArch64::MLAv2i32_indexed;
9723 RC = &AArch64::FPR64RegClass;
9724 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9725 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9726 RC);
9727 break;
9729 Opc = AArch64::MLSv2i32_indexed;
9730 RC = &AArch64::FPR64RegClass;
9731 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9732 break;
9734 Opc = AArch64::MLAv4i32_indexed;
9735 RC = &AArch64::FPR128RegClass;
9736 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9737 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9738 RC);
9739 break;
9741 Opc = AArch64::MLSv4i32_indexed;
9742 RC = &AArch64::FPR128RegClass;
9743 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9744 break;
9745
9746 // Floating Point Support
9748 Opc = AArch64::FMADDHrrr;
9749 RC = &AArch64::FPR16RegClass;
9750 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9751 break;
9753 Opc = AArch64::FMADDSrrr;
9754 RC = &AArch64::FPR32RegClass;
9755 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9756 break;
9758 Opc = AArch64::FMADDDrrr;
9759 RC = &AArch64::FPR64RegClass;
9760 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9761 break;
9762
9764 Opc = AArch64::FMADDHrrr;
9765 RC = &AArch64::FPR16RegClass;
9766 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9767 break;
9769 Opc = AArch64::FMADDSrrr;
9770 RC = &AArch64::FPR32RegClass;
9771 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9772 break;
9774 Opc = AArch64::FMADDDrrr;
9775 RC = &AArch64::FPR64RegClass;
9776 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9777 break;
9778
9780 Opc = AArch64::FMLAv1i32_indexed;
9781 RC = &AArch64::FPR32RegClass;
9782 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9784 break;
9786 Opc = AArch64::FMLAv1i32_indexed;
9787 RC = &AArch64::FPR32RegClass;
9788 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9790 break;
9791
9793 Opc = AArch64::FMLAv1i64_indexed;
9794 RC = &AArch64::FPR64RegClass;
9795 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9797 break;
9799 Opc = AArch64::FMLAv1i64_indexed;
9800 RC = &AArch64::FPR64RegClass;
9801 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9803 break;
9804
9806 RC = &AArch64::FPR64RegClass;
9807 Opc = AArch64::FMLAv4i16_indexed;
9808 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9810 break;
9812 RC = &AArch64::FPR64RegClass;
9813 Opc = AArch64::FMLAv4f16;
9814 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9816 break;
9818 RC = &AArch64::FPR64RegClass;
9819 Opc = AArch64::FMLAv4i16_indexed;
9820 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9822 break;
9824 RC = &AArch64::FPR64RegClass;
9825 Opc = AArch64::FMLAv4f16;
9826 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9828 break;
9829
9832 RC = &AArch64::FPR64RegClass;
9834 Opc = AArch64::FMLAv2i32_indexed;
9835 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9837 } else {
9838 Opc = AArch64::FMLAv2f32;
9839 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9841 }
9842 break;
9845 RC = &AArch64::FPR64RegClass;
9847 Opc = AArch64::FMLAv2i32_indexed;
9848 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9850 } else {
9851 Opc = AArch64::FMLAv2f32;
9852 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9854 }
9855 break;
9856
9858 RC = &AArch64::FPR128RegClass;
9859 Opc = AArch64::FMLAv8i16_indexed;
9860 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9862 break;
9864 RC = &AArch64::FPR128RegClass;
9865 Opc = AArch64::FMLAv8f16;
9866 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9868 break;
9870 RC = &AArch64::FPR128RegClass;
9871 Opc = AArch64::FMLAv8i16_indexed;
9872 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9874 break;
9876 RC = &AArch64::FPR128RegClass;
9877 Opc = AArch64::FMLAv8f16;
9878 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9880 break;
9881
9884 RC = &AArch64::FPR128RegClass;
9886 Opc = AArch64::FMLAv2i64_indexed;
9887 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9889 } else {
9890 Opc = AArch64::FMLAv2f64;
9891 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9893 }
9894 break;
9897 RC = &AArch64::FPR128RegClass;
9899 Opc = AArch64::FMLAv2i64_indexed;
9900 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9902 } else {
9903 Opc = AArch64::FMLAv2f64;
9904 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9906 }
9907 break;
9908
9911 RC = &AArch64::FPR128RegClass;
9913 Opc = AArch64::FMLAv4i32_indexed;
9914 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9916 } else {
9917 Opc = AArch64::FMLAv4f32;
9918 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9920 }
9921 break;
9922
9925 RC = &AArch64::FPR128RegClass;
9927 Opc = AArch64::FMLAv4i32_indexed;
9928 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9930 } else {
9931 Opc = AArch64::FMLAv4f32;
9932 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9934 }
9935 break;
9936
9938 Opc = AArch64::FNMSUBHrrr;
9939 RC = &AArch64::FPR16RegClass;
9940 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9941 break;
9943 Opc = AArch64::FNMSUBSrrr;
9944 RC = &AArch64::FPR32RegClass;
9945 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9946 break;
9948 Opc = AArch64::FNMSUBDrrr;
9949 RC = &AArch64::FPR64RegClass;
9950 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9951 break;
9952
9954 Opc = AArch64::FNMADDHrrr;
9955 RC = &AArch64::FPR16RegClass;
9956 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9957 break;
9959 Opc = AArch64::FNMADDSrrr;
9960 RC = &AArch64::FPR32RegClass;
9961 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9962 break;
9964 Opc = AArch64::FNMADDDrrr;
9965 RC = &AArch64::FPR64RegClass;
9966 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9967 break;
9968
9970 Opc = AArch64::FMSUBHrrr;
9971 RC = &AArch64::FPR16RegClass;
9972 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9973 break;
9975 Opc = AArch64::FMSUBSrrr;
9976 RC = &AArch64::FPR32RegClass;
9977 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9978 break;
9980 Opc = AArch64::FMSUBDrrr;
9981 RC = &AArch64::FPR64RegClass;
9982 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9983 break;
9984
9986 Opc = AArch64::FMLSv1i32_indexed;
9987 RC = &AArch64::FPR32RegClass;
9988 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9990 break;
9991
9993 Opc = AArch64::FMLSv1i64_indexed;
9994 RC = &AArch64::FPR64RegClass;
9995 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9997 break;
9998
10001 RC = &AArch64::FPR64RegClass;
10003 MachineInstrBuilder MIB1 =
10004 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
10005 .add(Root.getOperand(2));
10006 InsInstrs.push_back(MIB1);
10007 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10009 Opc = AArch64::FMLAv4f16;
10010 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10011 FMAInstKind::Accumulator, &NewVR);
10012 } else {
10013 Opc = AArch64::FMLAv4i16_indexed;
10014 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10015 FMAInstKind::Indexed, &NewVR);
10016 }
10017 break;
10018 }
10020 RC = &AArch64::FPR64RegClass;
10021 Opc = AArch64::FMLSv4f16;
10022 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10024 break;
10026 RC = &AArch64::FPR64RegClass;
10027 Opc = AArch64::FMLSv4i16_indexed;
10028 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10030 break;
10031
10034 RC = &AArch64::FPR64RegClass;
10036 Opc = AArch64::FMLSv2i32_indexed;
10037 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10039 } else {
10040 Opc = AArch64::FMLSv2f32;
10041 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10043 }
10044 break;
10045
10048 RC = &AArch64::FPR128RegClass;
10050 MachineInstrBuilder MIB1 =
10051 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
10052 .add(Root.getOperand(2));
10053 InsInstrs.push_back(MIB1);
10054 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10056 Opc = AArch64::FMLAv8f16;
10057 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10058 FMAInstKind::Accumulator, &NewVR);
10059 } else {
10060 Opc = AArch64::FMLAv8i16_indexed;
10061 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10062 FMAInstKind::Indexed, &NewVR);
10063 }
10064 break;
10065 }
10067 RC = &AArch64::FPR128RegClass;
10068 Opc = AArch64::FMLSv8f16;
10069 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10071 break;
10073 RC = &AArch64::FPR128RegClass;
10074 Opc = AArch64::FMLSv8i16_indexed;
10075 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10077 break;
10078
10081 RC = &AArch64::FPR128RegClass;
10083 Opc = AArch64::FMLSv2i64_indexed;
10084 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10086 } else {
10087 Opc = AArch64::FMLSv2f64;
10088 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10090 }
10091 break;
10092
10095 RC = &AArch64::FPR128RegClass;
10097 Opc = AArch64::FMLSv4i32_indexed;
10098 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10100 } else {
10101 Opc = AArch64::FMLSv4f32;
10102 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
10104 }
10105 break;
10108 RC = &AArch64::FPR64RegClass;
10110 MachineInstrBuilder MIB1 =
10111 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
10112 .add(Root.getOperand(2));
10113 InsInstrs.push_back(MIB1);
10114 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10116 Opc = AArch64::FMLAv2i32_indexed;
10117 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10118 FMAInstKind::Indexed, &NewVR);
10119 } else {
10120 Opc = AArch64::FMLAv2f32;
10121 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10122 FMAInstKind::Accumulator, &NewVR);
10123 }
10124 break;
10125 }
10128 RC = &AArch64::FPR128RegClass;
10130 MachineInstrBuilder MIB1 =
10131 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
10132 .add(Root.getOperand(2));
10133 InsInstrs.push_back(MIB1);
10134 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10136 Opc = AArch64::FMLAv4i32_indexed;
10137 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10138 FMAInstKind::Indexed, &NewVR);
10139 } else {
10140 Opc = AArch64::FMLAv4f32;
10141 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10142 FMAInstKind::Accumulator, &NewVR);
10143 }
10144 break;
10145 }
10148 RC = &AArch64::FPR128RegClass;
10150 MachineInstrBuilder MIB1 =
10151 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
10152 .add(Root.getOperand(2));
10153 InsInstrs.push_back(MIB1);
10154 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10156 Opc = AArch64::FMLAv2i64_indexed;
10157 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10158 FMAInstKind::Indexed, &NewVR);
10159 } else {
10160 Opc = AArch64::FMLAv2f64;
10161 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10162 FMAInstKind::Accumulator, &NewVR);
10163 }
10164 break;
10165 }
10168 unsigned IdxDupOp =
10170 : 2;
10171 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
10172 &AArch64::FPR128RegClass, MRI);
10173 break;
10174 }
10177 unsigned IdxDupOp =
10179 : 2;
10180 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
10181 &AArch64::FPR128RegClass, MRI);
10182 break;
10183 }
10186 unsigned IdxDupOp =
10188 : 2;
10189 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
10190 &AArch64::FPR128_loRegClass, MRI);
10191 break;
10192 }
10195 unsigned IdxDupOp =
10197 : 2;
10198 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
10199 &AArch64::FPR128RegClass, MRI);
10200 break;
10201 }
10204 unsigned IdxDupOp =
10206 : 2;
10207 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
10208 &AArch64::FPR128_loRegClass, MRI);
10209 break;
10210 }
10212 MUL = genFNegatedMAD(MF, MRI, TII, Root, InsInstrs);
10213 break;
10214 }
10216 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10217 Pattern, 4);
10218 break;
10219 }
10221 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10222 Pattern, 8);
10223 break;
10224 }
10226 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10227 Pattern, 16);
10228 break;
10229 }
10230
10231 } // end switch (Pattern)
10232 // Record MUL and ADD/SUB for deletion
10233 if (MUL)
10234 DelInstrs.push_back(MUL);
10235 DelInstrs.push_back(&Root);
10236
10237 // Set the flags on the inserted instructions to be the merged flags of the
10238 // instructions that we have combined.
10239 uint32_t Flags = Root.getFlags();
10240 if (MUL)
10241 Flags = Root.mergeFlagsWith(*MUL);
10242 for (auto *MI : InsInstrs)
10243 MI->setFlags(Flags);
10244}
10245
10246/// Replace csincr-branch sequence by simple conditional branch
10247///
10248/// Examples:
10249/// 1. \code
10250/// csinc w9, wzr, wzr, <condition code>
10251/// tbnz w9, #0, 0x44
10252/// \endcode
10253/// to
10254/// \code
10255/// b.<inverted condition code>
10256/// \endcode
10257///
10258/// 2. \code
10259/// csinc w9, wzr, wzr, <condition code>
10260/// tbz w9, #0, 0x44
10261/// \endcode
10262/// to
10263/// \code
10264/// b.<condition code>
10265/// \endcode
10266///
10267/// Replace compare and branch sequence by TBZ/TBNZ instruction when the
10268/// compare's constant operand is power of 2.
10269///
10270/// Examples:
10271/// \code
10272/// and w8, w8, #0x400
10273/// cbnz w8, L1
10274/// \endcode
10275/// to
10276/// \code
10277/// tbnz w8, #10, L1
10278/// \endcode
10279///
10280/// \param MI Conditional Branch
10281/// \return True when the simple conditional branch is generated
10282///
10284 bool IsNegativeBranch = false;
10285 bool IsTestAndBranch = false;
10286 unsigned TargetBBInMI = 0;
10287 switch (MI.getOpcode()) {
10288 default:
10289 llvm_unreachable("Unknown branch instruction?");
10290 case AArch64::Bcc:
10291 case AArch64::CBWPri:
10292 case AArch64::CBXPri:
10293 case AArch64::CBBAssertExt:
10294 case AArch64::CBHAssertExt:
10295 case AArch64::CBWPrr:
10296 case AArch64::CBXPrr:
10297 return false;
10298 case AArch64::CBZW:
10299 case AArch64::CBZX:
10300 TargetBBInMI = 1;
10301 break;
10302 case AArch64::CBNZW:
10303 case AArch64::CBNZX:
10304 TargetBBInMI = 1;
10305 IsNegativeBranch = true;
10306 break;
10307 case AArch64::TBZW:
10308 case AArch64::TBZX:
10309 TargetBBInMI = 2;
10310 IsTestAndBranch = true;
10311 break;
10312 case AArch64::TBNZW:
10313 case AArch64::TBNZX:
10314 TargetBBInMI = 2;
10315 IsNegativeBranch = true;
10316 IsTestAndBranch = true;
10317 break;
10318 }
10319 // So we increment a zero register and test for bits other
10320 // than bit 0? Conservatively bail out in case the verifier
10321 // missed this case.
10322 if (IsTestAndBranch && MI.getOperand(1).getImm())
10323 return false;
10324
10325 // Find Definition.
10326 assert(MI.getParent() && "Incomplete machine instruction\n");
10327 MachineBasicBlock *MBB = MI.getParent();
10328 MachineFunction *MF = MBB->getParent();
10330 Register VReg = MI.getOperand(0).getReg();
10331 if (!VReg.isVirtual())
10332 return false;
10333
10334 MachineInstr *DefMI = MRI->getVRegDef(VReg);
10335 if (!DefMI)
10336 return false;
10337
10338 // Look through COPY instructions to find definition.
10339 while (DefMI->isCopy()) {
10340 Register CopyVReg = DefMI->getOperand(1).getReg();
10341 if (!CopyVReg.isVirtual())
10342 return false;
10343 if (!MRI->hasOneNonDBGUse(CopyVReg))
10344 return false;
10345 DefMI = MRI->getVRegDef(CopyVReg);
10346 if (!DefMI)
10347 return false;
10348 }
10349
10350 switch (DefMI->getOpcode()) {
10351 default:
10352 return false;
10353 // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
10354 case AArch64::ANDWri:
10355 case AArch64::ANDXri: {
10356 if (IsTestAndBranch)
10357 return false;
10358 if (DefMI->getParent() != MBB)
10359 return false;
10360 if (!MRI->hasOneNonDBGUse(VReg))
10361 return false;
10362
10363 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
10364 uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
10365 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
10366 if (!isPowerOf2_64(Mask))
10367 return false;
10368
10369 MachineOperand &MO = DefMI->getOperand(1);
10370 Register NewReg = MO.getReg();
10371 if (!NewReg.isVirtual())
10372 return false;
10373
10374 if (!MRI->getVRegDef(NewReg))
10375 return false;
10376
10377 MachineBasicBlock &RefToMBB = *MBB;
10378 MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
10379 DebugLoc DL = MI.getDebugLoc();
10380 unsigned Imm = Log2_64(Mask);
10381 unsigned Opc = (Imm < 32)
10382 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
10383 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
10384 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
10385 .addReg(NewReg)
10386 .addImm(Imm)
10387 .addMBB(TBB);
10388 // Register lives on to the CBZ now.
10389 MO.setIsKill(false);
10390
10391 // For immediate smaller than 32, we need to use the 32-bit
10392 // variant (W) in all cases. Indeed the 64-bit variant does not
10393 // allow to encode them.
10394 // Therefore, if the input register is 64-bit, we need to take the
10395 // 32-bit sub-part.
10396 if (!Is32Bit && Imm < 32)
10397 NewMI->getOperand(0).setSubReg(AArch64::sub_32);
10398 MI.eraseFromParent();
10399 return true;
10400 }
10401 // Look for CSINC
10402 case AArch64::CSINCWr:
10403 case AArch64::CSINCXr: {
10404 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
10405 DefMI->getOperand(2).getReg() == AArch64::WZR) &&
10406 !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
10407 DefMI->getOperand(2).getReg() == AArch64::XZR))
10408 return false;
10409
10410 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
10411 true) != -1)
10412 return false;
10413
10414 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
10415 // Convert only when the condition code is not modified between
10416 // the CSINC and the branch. The CC may be used by other
10417 // instructions in between.
10419 return false;
10420 MachineBasicBlock &RefToMBB = *MBB;
10421 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
10422 DebugLoc DL = MI.getDebugLoc();
10423 if (IsNegativeBranch)
10425 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
10426 MI.eraseFromParent();
10427 return true;
10428 }
10429 }
10430}
10431
10432std::pair<unsigned, unsigned>
10433AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
10434 const unsigned Mask = AArch64II::MO_FRAGMENT;
10435 return std::make_pair(TF & Mask, TF & ~Mask);
10436}
10437
10439AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
10440 using namespace AArch64II;
10441
10442 static const std::pair<unsigned, const char *> TargetFlags[] = {
10443 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
10444 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
10445 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
10446 {MO_HI12, "aarch64-hi12"}};
10447 return ArrayRef(TargetFlags);
10448}
10449
10451AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
10452 using namespace AArch64II;
10453
10454 static const std::pair<unsigned, const char *> TargetFlags[] = {
10455 {MO_COFFSTUB, "aarch64-coffstub"},
10456 {MO_GOT, "aarch64-got"},
10457 {MO_NC, "aarch64-nc"},
10458 {MO_S, "aarch64-s"},
10459 {MO_TLS, "aarch64-tls"},
10460 {MO_DLLIMPORT, "aarch64-dllimport"},
10461 {MO_PREL, "aarch64-prel"},
10462 {MO_TAGGED, "aarch64-tagged"},
10463 {MO_ARM64EC_CALLMANGLE, "aarch64-arm64ec-callmangle"},
10464 };
10465 return ArrayRef(TargetFlags);
10466}
10467
10469AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
10470 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10471 {{MOSuppressPair, "aarch64-suppress-pair"},
10472 {MOStridedAccess, "aarch64-strided-access"}};
10473 return ArrayRef(TargetFlags);
10474}
10475
10476/// Constants defining how certain sequences should be outlined.
10477/// This encompasses how an outlined function should be called, and what kind of
10478/// frame should be emitted for that outlined function.
10479///
10480/// \p MachineOutlinerDefault implies that the function should be called with
10481/// a save and restore of LR to the stack.
10482///
10483/// That is,
10484///
10485/// I1 Save LR OUTLINED_FUNCTION:
10486/// I2 --> BL OUTLINED_FUNCTION I1
10487/// I3 Restore LR I2
10488/// I3
10489/// RET
10490///
10491/// * Call construction overhead: 3 (save + BL + restore)
10492/// * Frame construction overhead: 1 (ret)
10493/// * Requires stack fixups? Yes
10494///
10495/// \p MachineOutlinerTailCall implies that the function is being created from
10496/// a sequence of instructions ending in a return.
10497///
10498/// That is,
10499///
10500/// I1 OUTLINED_FUNCTION:
10501/// I2 --> B OUTLINED_FUNCTION I1
10502/// RET I2
10503/// RET
10504///
10505/// * Call construction overhead: 1 (B)
10506/// * Frame construction overhead: 0 (Return included in sequence)
10507/// * Requires stack fixups? No
10508///
10509/// \p MachineOutlinerNoLRSave implies that the function should be called using
10510/// a BL instruction, but doesn't require LR to be saved and restored. This
10511/// happens when LR is known to be dead.
10512///
10513/// That is,
10514///
10515/// I1 OUTLINED_FUNCTION:
10516/// I2 --> BL OUTLINED_FUNCTION I1
10517/// I3 I2
10518/// I3
10519/// RET
10520///
10521/// * Call construction overhead: 1 (BL)
10522/// * Frame construction overhead: 1 (RET)
10523/// * Requires stack fixups? No
10524///
10525/// \p MachineOutlinerThunk implies that the function is being created from
10526/// a sequence of instructions ending in a call. The outlined function is
10527/// called with a BL instruction, and the outlined function tail-calls the
10528/// original call destination.
10529///
10530/// That is,
10531///
10532/// I1 OUTLINED_FUNCTION:
10533/// I2 --> BL OUTLINED_FUNCTION I1
10534/// BL f I2
10535/// B f
10536/// * Call construction overhead: 1 (BL)
10537/// * Frame construction overhead: 0
10538/// * Requires stack fixups? No
10539///
10540/// \p MachineOutlinerRegSave implies that the function should be called with a
10541/// save and restore of LR to an available register. This allows us to avoid
10542/// stack fixups. Note that this outlining variant is compatible with the
10543/// NoLRSave case.
10544///
10545/// That is,
10546///
10547/// I1 Save LR OUTLINED_FUNCTION:
10548/// I2 --> BL OUTLINED_FUNCTION I1
10549/// I3 Restore LR I2
10550/// I3
10551/// RET
10552///
10553/// * Call construction overhead: 3 (save + BL + restore)
10554/// * Frame construction overhead: 1 (ret)
10555/// * Requires stack fixups? No
10556///
10557/// When Pointer Authentication (PAC) is enabled:
10558/// - MachineOutlinerDefault, MachineOutlinerRegSave, MachineOutlinerThunk,
10559/// and MachineOutlinerNoLRSave: Return address is signed in the prologue and
10560/// authenticated in the epilogue if required by the signing scope.
10561/// - MachineOutlinerTailCall: Rejected if return address signing is required
10562/// to avoid corrupting the caller's LR.
10563
10565 MachineOutlinerDefault, /// Emit a save, restore, call, and return.
10566 MachineOutlinerTailCall, /// Only emit a branch.
10567 MachineOutlinerNoLRSave, /// Emit a call and return.
10568 MachineOutlinerThunk, /// Emit a call and tail-call.
10569 MachineOutlinerRegSave /// Same as default, but save to a register.
10570};
10571
10577
10578/// Return true if the frame-record form of the outlined prologue is enabled for
10579/// the target of \p MF.
10580///
10581/// A non-leaf outlined function must save LR. On MachO, saving LR alone
10582/// (str x30) has no compact unwind encoding, so we get a large DWARF FDE
10583/// instead. Saving FP and LR as a frame record (stp x29, x30 ; mov x29, sp)
10584/// gets the small FRAME encoding, and costs one extra instruction.
10586 return MF.getSubtarget<AArch64Subtarget>()
10587 .getCLOpts()
10588 .outliner_compact_unwind_frame &&
10590}
10591
10592/// Return true if the outlined function in \p MBB should save FP and LR as a
10593/// frame record instead of saving LR alone.
10595 const MachineBasicBlock &MBB) {
10596 const MachineFunction &MF = *MBB.getParent();
10597
10598 // Only worth it if the function has unwind info to shrink.
10601 return false;
10602
10603 // Only safe if the outlined code never touches FP, since we overwrite it.
10605 for (const MachineInstr &MI : MBB.instrs())
10606 LRU.accumulate(MI);
10607 return LRU.available(AArch64::FP);
10608}
10609
10610/// Predict what the above will answer, for use while costing candidates. The
10611/// outlined function does not exist yet, so answer from \p RepeatedSequenceLocs
10612/// instead. This is only an estimate; buildOutlinedFrame() makes the call.
10614 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10615 const TargetRegisterInfo &TRI) {
10616 if (!isCompactUnwindFrameRecordEnabled(*RepeatedSequenceLocs.front().getMF()))
10617 return false;
10618
10619 // The outlined function is nounwind only if every candidate is, so it has
10620 // unwind info if any candidate does.
10621 if (llvm::none_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10622 const MachineFunction &MF = *C.getMF();
10623 return MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF);
10624 }))
10625 return false;
10626
10627 // FP is free in the outlined function only if it is free in every candidate.
10628 return llvm::all_of(RepeatedSequenceLocs, [&TRI](outliner::Candidate &C) {
10629 return C.isAvailableInsideSeq(AArch64::FP, TRI);
10630 });
10631}
10632
10634AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
10635 MachineFunction *MF = C.getMF();
10636 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
10637 const AArch64RegisterInfo *ARI =
10638 static_cast<const AArch64RegisterInfo *>(&TRI);
10639 // Check if there is an available register across the sequence that we can
10640 // use.
10641 for (unsigned Reg : AArch64::GPR64RegClass) {
10642 if (!ARI->isReservedReg(*MF, Reg) &&
10643 Reg != AArch64::LR && // LR is not reserved, but don't use it.
10644 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
10645 Reg != AArch64::X17 && // Ditto for X17.
10646 C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
10647 C.isAvailableInsideSeq(Reg, TRI))
10648 return Reg;
10649 }
10650 return Register();
10651}
10652
10653static bool
10655 const outliner::Candidate &b) {
10656 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10657 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10658
10659 return MFIa->getSignReturnAddressCondition() ==
10661}
10662
10663static bool
10665 const outliner::Candidate &b) {
10666 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10667 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10668
10669 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
10670}
10671
10673 const outliner::Candidate &b) {
10674 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10675 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10676
10677 const AArch64Subtarget &SubtargetA =
10679 const AArch64Subtarget &SubtargetB =
10680 b.getMF()->getSubtarget<AArch64Subtarget>();
10681
10682 // Return true only if branch-protection-pauth-lr attributes match
10683 // and +pauth-lr feature is enabled for both.
10684 if (MFIa->branchProtectionPAuthLR() != MFIb->branchProtectionPAuthLR())
10685 return false;
10686
10687 return !MFIa->branchProtectionPAuthLR() ||
10688 SubtargetA.hasPAuthLR() == SubtargetB.hasPAuthLR();
10689}
10690
10692 const outliner::Candidate &b) {
10693 const AArch64Subtarget &SubtargetA =
10695 const AArch64Subtarget &SubtargetB =
10696 b.getMF()->getSubtarget<AArch64Subtarget>();
10697 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
10698}
10699
10700namespace {
10701struct SPAddSubImmEncoding {
10702 unsigned Opcode;
10703 int64_t Imm;
10704 int64_t Shift;
10705};
10706} // namespace
10707
10708/// Returns true if \p MI is an ADD/SUBXri with an immediate offset that reads
10709/// SP but does not write SP (e.g. "add x0, sp, #48").
10710static bool isSPAddSubImm(const MachineInstr &MI) {
10711 if (MI.getOpcode() != AArch64::ADDXri && MI.getOpcode() != AArch64::SUBXri)
10712 return false;
10713
10714 assert(MI.getNumExplicitOperands() == 4 && "Wrong number of operands");
10715 assert(MI.getOperand(0).isReg() && MI.getOperand(1).isReg() &&
10716 MI.getOperand(3).isImm() && "Unexpected add/sub immediate operands");
10717
10718 if (MI.getOperand(0).getReg() == AArch64::SP)
10719 return false;
10720 if (MI.getOperand(1).getReg() != AArch64::SP)
10721 return false;
10722
10723 return MI.getOperand(2).isImm();
10724}
10725
10726/// Adjust the signed byte offset of \p MI, which must satisfy isSPAddSubImm,
10727/// by \p Delta and re-encode the result. Returns std::nullopt if the adjusted
10728/// offset is not encodable.
10729static std::optional<SPAddSubImmEncoding>
10730adjustSPAddSubImm(const MachineInstr &MI, int64_t Delta) {
10731 assert(isSPAddSubImm(MI) && "Expected an SP-based add/sub immediate");
10732 bool IsSub = MI.getOpcode() == AArch64::SUBXri;
10733
10734 // ADD/SUBXri encode a 12-bit unsigned immediate with an optional left shift
10735 // which can only be 12.
10736 int64_t ShiftImm = MI.getOperand(3).getImm();
10738 "Unexpected add/sub immediate shift type");
10739 unsigned Shift = AArch64_AM::getShiftValue(ShiftImm);
10740 assert((Shift == 0 || Shift == 12) && "Unexpected add/sub immediate shift");
10741
10742 int64_t Offset = MI.getOperand(2).getImm() << Shift;
10743 if (IsSub)
10744 Offset = -Offset;
10745
10746 // Apply the adjustment and try to re-encode.
10747 int64_t NewOffset = Offset + Delta;
10748 int64_t AbsOffset = std::abs(NewOffset);
10749
10750 SPAddSubImmEncoding Enc;
10751 Enc.Opcode = NewOffset < 0 ? AArch64::SUBXri : AArch64::ADDXri;
10752
10753 // Try to encode as a 12-bit immediate with shift=0 first.
10754 if (AbsOffset <= 0xfff) {
10755 Enc.Imm = AbsOffset;
10757 } else if ((AbsOffset & 0xfff) == 0 && (AbsOffset >> 12) <= 0xfff) {
10758 Enc.Imm = AbsOffset >> 12;
10760 } else {
10761 return std::nullopt;
10762 }
10763
10764 return Enc;
10765}
10766
10767std::optional<std::unique_ptr<outliner::OutlinedFunction>>
10768AArch64InstrInfo::getOutliningCandidateInfo(
10769 const MachineModuleInfo &MMI,
10770 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10771 unsigned MinRepeats) const {
10772 unsigned SequenceSize = 0;
10773 for (auto &MI : RepeatedSequenceLocs[0])
10774 SequenceSize += getInstSizeInBytes(MI);
10775
10776 unsigned NumBytesToCreateFrame = 0;
10777
10778 // Avoid splitting ADRP ADD/LDR pair into outlined functions.
10779 // These instructions are fused together by the scheduler.
10780 // Any candidate where ADRP is the last instruction should be rejected
10781 // as that will lead to splitting ADRP pair.
10782 MachineInstr &LastMI = RepeatedSequenceLocs[0].back();
10783 MachineInstr &FirstMI = RepeatedSequenceLocs[0].front();
10784 if (LastMI.getOpcode() == AArch64::ADRP &&
10785 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_PAGE) != 0 &&
10786 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10787 return std::nullopt;
10788 }
10789
10790 // Similarly any candidate where the first instruction is ADD/LDR with a
10791 // page offset should be rejected to avoid ADRP splitting.
10792 if ((FirstMI.getOpcode() == AArch64::ADDXri ||
10793 FirstMI.getOpcode() == AArch64::LDRXui) &&
10794 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_PAGEOFF) != 0 &&
10795 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10796 return std::nullopt;
10797 }
10798
10799 // We only allow outlining for functions having exactly matching return
10800 // address signing attributes, i.e., all share the same value for the
10801 // attribute "sign-return-address", all share the same type of key they
10802 // are signed with & all share the same pauth-lr attributes.
10803 // Additionally we require all functions to simultaneously either support
10804 // v8.3a features or not. Otherwise an outlined function could get signed
10805 // using dedicated v8.3 instructions and a call from a function that doesn't
10806 // support v8.3 instructions would therefore be invalid.
10807 if (std::adjacent_find(
10808 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
10809 [](const outliner::Candidate &a, const outliner::Candidate &b) {
10810 // Return true if a and b are non-equal w.r.t. return address
10811 // signing, support of v8.3a features or support of pauth-lr
10812 if (outliningCandidatesSigningScopeConsensus(a, b) &&
10813 outliningCandidatesSigningKeyConsensus(a, b) &&
10814 outliningCandidatesV8_3OpsConsensus(a, b) &&
10815 outliningCandidatesPAuthLRConsensus(a, b)) {
10816 return false;
10817 }
10818 return true;
10819 }) != RepeatedSequenceLocs.end()) {
10820 return std::nullopt;
10821 }
10822
10823 // Since at this point all candidates agree on their return address signing
10824 // picking just one is fine. If the candidate functions potentially sign their
10825 // return addresses, the outlined function should do the same. Note that in
10826 // the case of "sign-return-address"="non-leaf" this is an assumption: It is
10827 // not certainly true that the outlined function will have to sign its return
10828 // address but this decision is made later, when the decision to outline
10829 // has already been made.
10830 // The same holds for the number of additional instructions we need: On
10831 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
10832 // necessary. However, at this point we don't know if the outlined function
10833 // will have a RET instruction so we assume the worst.
10834 const TargetRegisterInfo &TRI = getRegisterInfo();
10835 // Performing a tail call may require extra checks when PAuth is enabled.
10836 // If PAuth is disabled, set it to zero for uniformity.
10837 unsigned NumBytesToCheckLRInTCEpilogue = 0;
10838 const auto RASignCondition = RepeatedSequenceLocs[0]
10839 .getMF()
10840 ->getInfo<AArch64FunctionInfo>()
10841 ->getSignReturnAddressCondition();
10842 if (RASignCondition != SignReturnAddress::None) {
10843 // Candidates that have Return Address Authentication Hardening enabled are
10844 // discarded.
10845 //
10846 // In its current form, the machine outliner does not preserve X16/X17
10847 // across outlined function calls, even though it should as they are
10848 // caller-saved registers. And since the hardening based on load from the
10849 // return address may clobber one of these registers, if they are alive
10850 // across a call their value would be lost due to the hardening mechanism.
10851 llvm::erase_if(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10852 return C.getMF()
10853 ->getInfo<AArch64FunctionInfo>()
10854 ->shouldHardenSignReturnAddress();
10855 });
10856 // If the sequence doesn't have enough candidates left, then we're done.
10857 if (RepeatedSequenceLocs.size() < MinRepeats)
10858 return std::nullopt;
10859
10860 // PAuth is enabled - set extra tail call cost, if any.
10861 auto LRCheckMethod = Subtarget.getAuthenticatedLRCheckMethod(
10862 *RepeatedSequenceLocs[0].getMF());
10863 NumBytesToCheckLRInTCEpilogue =
10865 // Checking the authenticated LR value may significantly impact
10866 // SequenceSize, so account for it for more precise results.
10867 if (isTailCallReturnInst(RepeatedSequenceLocs[0].back()))
10868 SequenceSize += NumBytesToCheckLRInTCEpilogue;
10869 }
10870
10871 // Properties about candidate MBBs that hold for all of them.
10872 unsigned FlagsSetInAll = 0xF;
10873
10874 // Compute liveness information for each candidate, and set FlagsSetInAll.
10875 for (outliner::Candidate &C : RepeatedSequenceLocs)
10876 FlagsSetInAll &= C.Flags;
10877
10878 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back().getOpcode();
10879
10880 // Helper lambda which sets call information for every candidate.
10881 auto SetCandidateCallInfo =
10882 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
10883 for (outliner::Candidate &C : RepeatedSequenceLocs)
10884 C.setCallInfo(CallID, NumBytesForCall);
10885 };
10886
10887 unsigned FrameID = MachineOutlinerDefault;
10888 NumBytesToCreateFrame += 4;
10889
10890 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10891 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
10892 });
10893
10894 // We check to see if CFI Instructions are present, and if they are
10895 // we find the number of CFI Instructions in the candidates.
10896 unsigned CFICount = 0;
10897 for (auto &I : RepeatedSequenceLocs[0]) {
10898 if (I.isCFIInstruction())
10899 CFICount++;
10900 }
10901
10902 // We compare the number of found CFI Instructions to the number of CFI
10903 // instructions in the parent function for each candidate. We must check this
10904 // since if we outline one of the CFI instructions in a function, we have to
10905 // outline them all for correctness. If we do not, the address offsets will be
10906 // incorrect between the two sections of the program.
10907 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10908 std::vector<MCCFIInstruction> CFIInstructions =
10909 C.getMF()->getFrameInstructions();
10910
10911 if (CFICount > 0 && CFICount != CFIInstructions.size())
10912 return std::nullopt;
10913 }
10914
10915 // Returns true if an instructions is safe to fix up, false otherwise.
10916 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
10917 if (MI.isCall())
10918 return true;
10919
10920 if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
10921 !MI.readsRegister(AArch64::SP, &TRI))
10922 return true;
10923
10924 // Any modification of SP will break our code to save/restore LR.
10925 // FIXME: We could handle some instructions which add a constant
10926 // offset to SP, with a bit more work.
10927 if (MI.modifiesRegister(AArch64::SP, &TRI))
10928 return false;
10929
10930 // At this point, we have a stack instruction that we might need to
10931 // fix up. We'll handle it if it's a load or store.
10932 if (MI.mayLoadOrStore()) {
10933 const MachineOperand *Base; // Filled with the base operand of MI.
10934 int64_t Offset; // Filled with the offset of MI.
10935 bool OffsetIsScalable;
10936
10937 // Does it allow us to offset the base operand and is the base the
10938 // register SP?
10939 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable) ||
10940 !Base->isReg() || Base->getReg() != AArch64::SP)
10941 return false;
10942
10943 // Fixe-up code below assumes bytes.
10944 if (OffsetIsScalable)
10945 return false;
10946
10947 // Find the minimum/maximum offset for this instruction and check
10948 // if fixing it up would be in range.
10949 int64_t MinOffset,
10950 MaxOffset; // Unscaled offsets for the instruction.
10951 // The scale to multiply the offsets by.
10952 TypeSize Scale(0U, false), DummyWidth(0U, false);
10953 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
10954
10955 Offset += 16; // Update the offset to what it would be if we outlined.
10956 if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
10957 Offset > MaxOffset * (int64_t)Scale.getFixedValue())
10958 return false;
10959
10960 // It's in range, so we can outline it.
10961 return true;
10962 }
10963
10964 if (isSPAddSubImm(MI))
10965 return adjustSPAddSubImm(MI, 16).has_value();
10966
10967 // FIXME: Add handling for other SP-based address calculations that can be
10968 // adjusted after outlining.
10969 return false;
10970 };
10971
10972 // True if it's possible to fix up each stack instruction in this sequence.
10973 // Important for frames/call variants that modify the stack.
10974 bool AllStackInstrsSafe =
10975 llvm::all_of(RepeatedSequenceLocs[0], IsSafeToFixup);
10976
10977 // If the last instruction in any candidate is a terminator, then we should
10978 // tail call all of the candidates.
10979 if (RepeatedSequenceLocs[0].back().isTerminator()) {
10980 // Reject tail calls if they would require return address signing, as we
10981 // cannot safely sign them without corrupting the caller's inherited LR.
10983 RASignCondition,
10984 any_of(RepeatedSequenceLocs[0], [](const MachineInstr &MI) {
10985 return MI.isCall() && !MI.isReturn();
10986 })))
10987 return std::nullopt;
10988
10989 FrameID = MachineOutlinerTailCall;
10990 NumBytesToCreateFrame = 0;
10991 unsigned NumBytesForCall = 4 + NumBytesToCheckLRInTCEpilogue;
10992 SetCandidateCallInfo(MachineOutlinerTailCall, NumBytesForCall);
10993 }
10994
10995 else if (LastInstrOpcode == AArch64::BL ||
10996 ((LastInstrOpcode == AArch64::BLR ||
10997 LastInstrOpcode == AArch64::BLRNoIP) &&
10998 !HasBTI)) {
10999 // FIXME: Do we need to check if the code after this uses the value of LR?
11000 FrameID = MachineOutlinerThunk;
11001 NumBytesToCreateFrame = NumBytesToCheckLRInTCEpilogue;
11002 SetCandidateCallInfo(MachineOutlinerThunk, 4);
11003 }
11004
11005 else {
11006 // We need to decide how to emit calls + frames. We can always emit the same
11007 // frame if we don't need to save to the stack. If we have to save to the
11008 // stack, then we need a different frame.
11009 unsigned NumBytesNoStackCalls = 0;
11010 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
11011
11012 // Check if we have to save LR.
11013 for (outliner::Candidate &C : RepeatedSequenceLocs) {
11014 bool LRAvailable =
11016 ? C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI)
11017 : true;
11018 // If we have a noreturn caller, then we're going to be conservative and
11019 // say that we have to save LR. If we don't have a ret at the end of the
11020 // block, then we can't reason about liveness accurately.
11021 //
11022 // FIXME: We can probably do better than always disabling this in
11023 // noreturn functions by fixing up the liveness info.
11024 bool IsNoReturn =
11025 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
11026
11027 // Is LR available? If so, we don't need a save.
11028 if (LRAvailable && !IsNoReturn) {
11029 NumBytesNoStackCalls += 4;
11030 C.setCallInfo(MachineOutlinerNoLRSave, 4);
11031 CandidatesWithoutStackFixups.push_back(C);
11032 }
11033
11034 // Is an unused register available? If so, we won't modify the stack, so
11035 // we can outline with the same frame type as those that don't save LR.
11036 else if (findRegisterToSaveLRTo(C)) {
11037 NumBytesNoStackCalls += 12;
11038 C.setCallInfo(MachineOutlinerRegSave, 12);
11039 CandidatesWithoutStackFixups.push_back(C);
11040 }
11041
11042 // Is SP used in the sequence at all? If not, we don't have to modify
11043 // the stack, so we are guaranteed to get the same frame.
11044 else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
11045 NumBytesNoStackCalls += 12;
11046 C.setCallInfo(MachineOutlinerDefault, 12);
11047 CandidatesWithoutStackFixups.push_back(C);
11048 }
11049
11050 // If we outline this, we need to modify the stack. Pretend we don't
11051 // outline this by saving all of its bytes.
11052 else {
11053 NumBytesNoStackCalls += SequenceSize;
11054 }
11055 }
11056
11057 // If there are no places where we have to save LR, then note that we
11058 // don't have to update the stack. Otherwise, give every candidate the
11059 // default call type, as long as it's safe to do so.
11060 if (!AllStackInstrsSafe ||
11061 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
11062 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
11063 FrameID = MachineOutlinerNoLRSave;
11064 if (RepeatedSequenceLocs.size() < MinRepeats)
11065 return std::nullopt;
11066 } else {
11067 SetCandidateCallInfo(MachineOutlinerDefault, 12);
11068
11069 // Bugzilla ID: 46767
11070 // TODO: Check if fixing up the stack more than once is safe so we can
11071 // outline these.
11072 //
11073 // An outline resulting in a caller that requires stack fixups at the
11074 // callsite to a callee that also requires stack fixups can happen when
11075 // there are no available registers at the candidate callsite for a
11076 // candidate that itself also has calls.
11077 //
11078 // In other words if function_containing_sequence in the following pseudo
11079 // assembly requires that we save LR at the point of the call, but there
11080 // are no available registers: in this case we save using SP and as a
11081 // result the SP offsets requires stack fixups by multiples of 16.
11082 //
11083 // function_containing_sequence:
11084 // ...
11085 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
11086 // call OUTLINED_FUNCTION_N
11087 // restore LR from SP
11088 // ...
11089 //
11090 // OUTLINED_FUNCTION_N:
11091 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
11092 // ...
11093 // bl foo
11094 // restore LR from SP
11095 // ret
11096 //
11097 // Because the code to handle more than one stack fixup does not
11098 // currently have the proper checks for legality, these cases will assert
11099 // in the AArch64 MachineOutliner. This is because the code to do this
11100 // needs more hardening, testing, better checks that generated code is
11101 // legal, etc and because it is only verified to handle a single pass of
11102 // stack fixup.
11103 //
11104 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
11105 // these cases until they are known to be handled. Bugzilla 46767 is
11106 // referenced in comments at the assert site.
11107 //
11108 // To avoid asserting (or generating non-legal code on noassert builds)
11109 // we remove all candidates which would need more than one stack fixup by
11110 // pruning the cases where the candidate has calls while also having no
11111 // available LR and having no available general purpose registers to copy
11112 // LR to (ie one extra stack save/restore).
11113 //
11114 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
11115 erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
11116 auto IsCall = [](const MachineInstr &MI) { return MI.isCall(); };
11117 return (llvm::any_of(C, IsCall)) &&
11118 (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
11119 !findRegisterToSaveLRTo(C));
11120 });
11121 }
11122 }
11123
11124 // If we dropped all of the candidates, bail out here.
11125 if (RepeatedSequenceLocs.size() < MinRepeats)
11126 return std::nullopt;
11127 }
11128
11129 // Does every candidate's MBB contain a call? If so, then we might have a call
11130 // in the range.
11131 bool ModStackToSaveLR = false;
11132 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
11133 // Check if the range contains a call. These require a save + restore of the
11134 // link register.
11135 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
11136 if (any_of(drop_end(FirstCand),
11137 [](const MachineInstr &MI) { return MI.isCall(); }))
11138 ModStackToSaveLR = true;
11139
11140 // Handle the last instruction separately. If this is a tail call, then the
11141 // last instruction is a call. We don't want to save + restore in this case.
11142 // However, it could be possible that the last instruction is a call without
11143 // it being valid to tail call this sequence. We should consider this as
11144 // well.
11145 else if (FrameID != MachineOutlinerThunk &&
11146 FrameID != MachineOutlinerTailCall && FirstCand.back().isCall())
11147 ModStackToSaveLR = true;
11148
11149 if (ModStackToSaveLR) {
11150 // We can't fix up the stack. Bail out.
11151 if (!AllStackInstrsSafe)
11152 return std::nullopt;
11153
11154 // Save + restore LR.
11155 NumBytesToCreateFrame += 8;
11156
11157 // Add the extra mov if we will save a frame record instead of just LR.
11159 RepeatedSequenceLocs, TRI))
11160 NumBytesToCreateFrame += 4;
11161 }
11162 }
11163
11164 // If we have CFI instructions, we can only outline if the outlined section
11165 // can be a tail call
11166 if (FrameID != MachineOutlinerTailCall && CFICount > 0)
11167 return std::nullopt;
11168
11169 if (FrameID != MachineOutlinerTailCall &&
11171 ModStackToSaveLR))
11172 NumBytesToCreateFrame += 8;
11173 if (RASignCondition == SignReturnAddress::All) {
11174 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
11175 int SPValue = 0;
11176 for (const MachineInstr &MI : C) {
11177 if (!MI.isCall() && MI.modifiesRegister(AArch64::SP, &TRI)) {
11178 switch (MI.getOpcode()) {
11179 case AArch64::ADDXri:
11180 case AArch64::ADDWri:
11181 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
11182 assert(MI.getOperand(2).isImm() && "Expected immediate");
11183 assert(MI.getOperand(1).isReg() && "Expected register");
11184 if (MI.getOperand(1).getReg() == AArch64::SP)
11185 SPValue += MI.getOperand(2).getImm();
11186 else
11187 return true;
11188 break;
11189 case AArch64::SUBXri:
11190 case AArch64::SUBWri:
11191 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
11192 assert(MI.getOperand(2).isImm() && "Expected immediate");
11193 assert(MI.getOperand(1).isReg() && "Expected register");
11194 if (MI.getOperand(1).getReg() == AArch64::SP)
11195 SPValue -= MI.getOperand(2).getImm();
11196 else
11197 return true;
11198 break;
11199 default:
11200 return true;
11201 }
11202 }
11203 }
11204 return SPValue != 0;
11205 };
11206
11207 if (hasIllegalSPModification(RepeatedSequenceLocs[0]))
11208 return std::nullopt;
11209 }
11210
11211 return std::make_unique<outliner::OutlinedFunction>(
11212 RepeatedSequenceLocs, SequenceSize, NumBytesToCreateFrame, FrameID);
11213}
11214
11215void AArch64InstrInfo::mergeOutliningCandidateAttributes(
11216 Function &F, std::vector<outliner::Candidate> &Candidates) const {
11217 // If a bunch of candidates reach this point they must agree on their return
11218 // address signing. It is therefore enough to just consider the signing
11219 // behaviour of one of them
11220 const auto &CFn = Candidates.front().getMF()->getFunction();
11221
11222 if (CFn.hasFnAttribute("ptrauth-returns"))
11223 F.addFnAttr(CFn.getFnAttribute("ptrauth-returns"));
11224 if (CFn.hasFnAttribute("ptrauth-auth-traps"))
11225 F.addFnAttr(CFn.getFnAttribute("ptrauth-auth-traps"));
11226 if (CFn.hasFnAttribute("branch-protection-pauth-lr"))
11227 F.addFnAttr(CFn.getFnAttribute("branch-protection-pauth-lr"));
11228 // Since all candidates belong to the same module, just copy the
11229 // function-level attributes of an arbitrary function.
11230 if (CFn.hasFnAttribute("sign-return-address"))
11231 F.addFnAttr(CFn.getFnAttribute("sign-return-address"));
11232 if (CFn.hasFnAttribute("sign-return-address-key"))
11233 F.addFnAttr(CFn.getFnAttribute("sign-return-address-key"));
11234 // The "sign-return-address-harden" attribute is not included because no
11235 // candidate is supposed to have hardening enabled.
11236 assert(llvm::none_of(Candidates, [](const outliner::Candidate &C) {
11237 return C.getMF()
11238 ->getInfo<AArch64FunctionInfo>()
11239 ->shouldHardenSignReturnAddress();
11240 }));
11241
11242 AArch64GenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
11243}
11244
11245bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
11246 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
11248 OutlineFromLinkOnceODRs))
11249 return false;
11250
11251 // Outlining from functions with redzones is unsafe since the outliner may
11252 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
11253 // outline from it.
11254 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
11255 if (!AFI || AFI->hasRedZone().value_or(true))
11256 return false;
11257
11258 // FIXME: Determine whether it is safe to outline from functions which contain
11259 // streaming-mode changes. We may need to ensure any smstart/smstop pairs are
11260 // outlined together and ensure it is safe to outline with async unwind info,
11261 // required for saving & restoring VG around calls.
11262 if (AFI->hasStreamingModeChanges())
11263 return false;
11264
11265 // FIXME: Teach the outliner to generate/handle Windows unwind info.
11266 if (MF.usesWindowsUnwindInfo())
11267 return false;
11268
11269 // It's safe to outline from MF.
11270 return true;
11271}
11272
11274AArch64InstrInfo::getOutlinableRanges(MachineBasicBlock &MBB,
11275 unsigned &Flags) const {
11277 "Must track liveness!");
11279 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
11280 Ranges;
11281 // According to the AArch64 Procedure Call Standard, the following are
11282 // undefined on entry/exit from a function call:
11283 //
11284 // * Registers x16, x17, (and thus w16, w17)
11285 // * Condition codes (and thus the NZCV register)
11286 //
11287 // If any of these registers are used inside or live across an outlined
11288 // function, then they may be modified later, either by the compiler or
11289 // some other tool (like the linker).
11290 //
11291 // To avoid outlining in these situations, partition each block into ranges
11292 // where these registers are dead. We will only outline from those ranges.
11293 LiveRegUnits LRU(getRegisterInfo());
11294 auto AreAllUnsafeRegsDead = [&LRU]() {
11295 return LRU.available(AArch64::W16) && LRU.available(AArch64::W17) &&
11296 LRU.available(AArch64::NZCV);
11297 };
11298
11299 // We need to know if LR is live across an outlining boundary later on in
11300 // order to decide how we'll create the outlined call, frame, etc.
11301 //
11302 // It's pretty expensive to check this for *every candidate* within a block.
11303 // That's some potentially n^2 behaviour, since in the worst case, we'd need
11304 // to compute liveness from the end of the block for O(n) candidates within
11305 // the block.
11306 //
11307 // So, to improve the average case, let's keep track of liveness from the end
11308 // of the block to the beginning of *every outlinable range*. If we know that
11309 // LR is available in every range we could outline from, then we know that
11310 // we don't need to check liveness for any candidate within that range.
11311 bool LRAvailableEverywhere = true;
11312 // Compute liveness bottom-up.
11313 LRU.addLiveOuts(MBB);
11314 // Update flags that require info about the entire MBB.
11315 auto UpdateWholeMBBFlags = [&Flags](const MachineInstr &MI) {
11316 if (MI.isCall() && !MI.isTerminator())
11318 };
11319 // Range: [RangeBegin, RangeEnd)
11320 MachineBasicBlock::instr_iterator RangeBegin, RangeEnd;
11321 unsigned RangeLen;
11322 auto CreateNewRangeStartingAt =
11323 [&RangeBegin, &RangeEnd,
11324 &RangeLen](MachineBasicBlock::instr_iterator NewBegin) {
11325 RangeBegin = NewBegin;
11326 RangeEnd = std::next(RangeBegin);
11327 RangeLen = 0;
11328 };
11329 auto SaveRangeIfNonEmpty = [&RangeLen, &Ranges, &RangeBegin, &RangeEnd]() {
11330 // At least one unsafe register is not dead. We do not want to outline at
11331 // this point. If it is long enough to outline from and does not cross a
11332 // bundle boundary, save the range [RangeBegin, RangeEnd).
11333 if (RangeLen <= 1)
11334 return;
11335 if (!RangeBegin.isEnd() && RangeBegin->isBundledWithPred())
11336 return;
11337 if (!RangeEnd.isEnd() && RangeEnd->isBundledWithPred())
11338 return;
11339 Ranges.emplace_back(RangeBegin, RangeEnd);
11340 };
11341 // Find the first point where all unsafe registers are dead.
11342 // FIND: <safe instr> <-- end of first potential range
11343 // SKIP: <unsafe def>
11344 // SKIP: ... everything between ...
11345 // SKIP: <unsafe use>
11346 auto FirstPossibleEndPt = MBB.instr_rbegin();
11347 for (; FirstPossibleEndPt != MBB.instr_rend(); ++FirstPossibleEndPt) {
11348 if (!FirstPossibleEndPt->isDebugInstr())
11349 LRU.stepBackward(*FirstPossibleEndPt);
11350 // Update flags that impact how we outline across the entire block,
11351 // regardless of safety.
11352 UpdateWholeMBBFlags(*FirstPossibleEndPt);
11353 if (AreAllUnsafeRegsDead())
11354 break;
11355 }
11356 // If we exhausted the entire block, we have no safe ranges to outline.
11357 if (FirstPossibleEndPt == MBB.instr_rend())
11358 return Ranges;
11359 // Current range.
11360 CreateNewRangeStartingAt(FirstPossibleEndPt->getIterator());
11361 // StartPt points to the first place where all unsafe registers
11362 // are dead (if there is any such point). Begin partitioning the MBB into
11363 // ranges.
11364 // Pseudo probes are ordinary instructions to the mapper, so only skip debug
11365 // instructions here.
11366 for (auto &MI : instructionsWithoutDebug(FirstPossibleEndPt, MBB.instr_rend(),
11367 /*SkipPseudoOp=*/false)) {
11368 LRU.stepBackward(MI);
11369 UpdateWholeMBBFlags(MI);
11370 if (!AreAllUnsafeRegsDead()) {
11371 SaveRangeIfNonEmpty();
11372 CreateNewRangeStartingAt(MI.getIterator());
11373 continue;
11374 }
11375 LRAvailableEverywhere &= LRU.available(AArch64::LR);
11376 // Pseudo probes count because the mapper treats them as ordinary
11377 // instructions.
11378 RangeBegin = MI.getIterator();
11379 ++RangeLen;
11380 }
11381 // Above loop misses the last (or only) range. If we are still safe, then
11382 // let's save the range.
11383 if (AreAllUnsafeRegsDead())
11384 SaveRangeIfNonEmpty();
11385 if (Ranges.empty())
11386 return Ranges;
11387 // We found the ranges bottom-up. Mapping expects the top-down. Reverse
11388 // the order.
11389 std::reverse(Ranges.begin(), Ranges.end());
11390 // If there is at least one outlinable range where LR is unavailable
11391 // somewhere, remember that.
11392 if (!LRAvailableEverywhere)
11394 return Ranges;
11395}
11396
11398AArch64InstrInfo::getOutliningTypeImpl(const MachineModuleInfo &MMI,
11400 unsigned Flags) const {
11401 MachineInstr &MI = *MIT;
11402
11403 // Don't outline anything used for return address signing. The outlined
11404 // function will get signed later if needed
11405 switch (MI.getOpcode()) {
11406 case AArch64::PACM:
11407 case AArch64::PACIASP:
11408 case AArch64::PACIBSP:
11409 case AArch64::PACIASPPC:
11410 case AArch64::PACIBSPPC:
11411 case AArch64::PACNBIASPPC:
11412 case AArch64::PACNBIBSPPC:
11413 case AArch64::AUTIASP:
11414 case AArch64::AUTIBSP:
11415 case AArch64::AUTIASPPCi:
11416 case AArch64::AUTIASPPCr:
11417 case AArch64::AUTIBSPPCi:
11418 case AArch64::AUTIBSPPCr:
11419 case AArch64::RETAA:
11420 case AArch64::RETAB:
11421 case AArch64::RETAASPPCi:
11422 case AArch64::RETAASPPCr:
11423 case AArch64::RETABSPPCi:
11424 case AArch64::RETABSPPCr:
11425 case AArch64::EMITBKEY:
11426 case AArch64::PAUTH_PROLOGUE:
11427 case AArch64::PAUTH_EPILOGUE:
11428 case AArch64::PAUTH_EPILOGUE_ENTRY_SP:
11430 }
11431
11432 // We can only outline these if we will tail call the outlined function, or
11433 // fix up the CFI offsets. Currently, CFI instructions are outlined only if
11434 // in a tail call.
11435 //
11436 // FIXME: If the proper fixups for the offset are implemented, this should be
11437 // possible.
11438 if (MI.isCFIInstruction())
11440
11441 // Is this a terminator for a basic block?
11442 if (MI.isTerminator())
11443 // TargetInstrInfo::getOutliningType has already filtered out anything
11444 // that would break this, so we can allow it here.
11446
11447 // Make sure none of the operands are un-outlinable.
11448 for (const MachineOperand &MOP : MI.operands()) {
11449 // A check preventing CFI indices was here before, but only CFI
11450 // instructions should have those.
11451 assert(!MOP.isCFIIndex());
11452
11453 // If it uses LR or W30 explicitly, then don't touch it.
11454 if (MOP.isReg() && !MOP.isImplicit() &&
11455 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
11457 }
11458
11459 // Special cases for instructions that can always be outlined, but will fail
11460 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
11461 // be outlined because they don't require a *specific* value to be in LR.
11462 if (MI.getOpcode() == AArch64::ADRP)
11464
11465 // If MI is a call we might be able to outline it. We don't want to outline
11466 // any calls that rely on the position of items on the stack. When we outline
11467 // something containing a call, we have to emit a save and restore of LR in
11468 // the outlined function. Currently, this always happens by saving LR to the
11469 // stack. Thus, if we outline, say, half the parameters for a function call
11470 // plus the call, then we'll break the callee's expectations for the layout
11471 // of the stack.
11472 //
11473 // FIXME: Allow calls to functions which construct a stack frame, as long
11474 // as they don't access arguments on the stack.
11475 // FIXME: Figure out some way to analyze functions defined in other modules.
11476 // We should be able to compute the memory usage based on the IR calling
11477 // convention, even if we can't see the definition.
11478 if (MI.isCall()) {
11479 // Get the function associated with the call. Look at each operand and find
11480 // the one that represents the callee and get its name.
11481 const Function *Callee = nullptr;
11482 for (const MachineOperand &MOP : MI.operands()) {
11483 if (MOP.isGlobal()) {
11484 Callee = dyn_cast<Function>(MOP.getGlobal());
11485 break;
11486 }
11487 }
11488
11489 // Never outline calls to mcount. There isn't any rule that would require
11490 // this, but the Linux kernel's "ftrace" feature depends on it.
11491 if (Callee && Callee->getName() == "\01_mcount")
11493
11494 // If we don't know anything about the callee, assume it depends on the
11495 // stack layout of the caller. In that case, it's only legal to outline
11496 // as a tail-call. Explicitly list the call instructions we know about so we
11497 // don't get unexpected results with call pseudo-instructions.
11498 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
11499 if (MI.getOpcode() == AArch64::BLR ||
11500 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
11501 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
11502
11503 if (!Callee)
11504 return UnknownCallOutlineType;
11505
11506 // We have a function we have information about. Check it if it's something
11507 // can safely outline.
11508 MachineFunction *CalleeMF = MMI.getMachineFunction(*Callee);
11509
11510 // We don't know what's going on with the callee at all. Don't touch it.
11511 if (!CalleeMF)
11512 return UnknownCallOutlineType;
11513
11514 // Check if we know anything about the callee saves on the function. If we
11515 // don't, then don't touch it, since that implies that we haven't
11516 // computed anything about its stack frame yet.
11517 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
11518 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
11519 MFI.getNumObjects() > 0)
11520 return UnknownCallOutlineType;
11521
11522 // At this point, we can say that CalleeMF ought to not pass anything on the
11523 // stack. Therefore, we can outline it.
11525 }
11526
11527 // Don't touch the link register or W30.
11528 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
11529 MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
11531
11532 // Don't outline BTI instructions, because that will prevent the outlining
11533 // site from being indirectly callable.
11534 if (hasBTISemantics(MI))
11536
11538}
11539
11540void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
11541 for (MachineInstr &MI : MBB) {
11542 const MachineOperand *Base;
11543 TypeSize Width(0, false);
11544 int64_t Offset;
11545 bool OffsetIsScalable;
11546
11547 // Is this a load or store with an immediate offset with SP as the base?
11548 if (MI.mayLoadOrStore() &&
11549 getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable,
11550 Width) &&
11551 Base->isReg() && Base->getReg() == AArch64::SP) {
11552 TypeSize Scale(0U, false);
11553 int64_t Dummy1, Dummy2;
11554
11555 MachineOperand &StackOffsetOperand =
11557 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
11558 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
11559 assert(Scale != 0 && "Unexpected opcode!");
11560 assert(!OffsetIsScalable && "Expected offset to be a byte offset");
11561
11562 // We've pushed the return address to the stack, so add 16 to the offset.
11563 // This is safe, since we already checked if it would overflow when we
11564 // checked if this instruction was legal to outline.
11565 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
11566 StackOffsetOperand.setImm(NewImm);
11567 continue;
11568 }
11569
11570 if (isSPAddSubImm(MI)) {
11571 auto Enc = adjustSPAddSubImm(MI, 16);
11572 assert(Enc && "Unencodable SP add/sub should not have been outlined");
11573 MI.setDesc(get(Enc->Opcode));
11574 MI.getOperand(2).setImm(Enc->Imm);
11575 MI.getOperand(3).setImm(Enc->Shift);
11576 }
11577 }
11578}
11579
11581 const AArch64InstrInfo *TII,
11582 bool ShouldSignReturnAddr) {
11583 if (!ShouldSignReturnAddr)
11584 return;
11585
11586 // Thunks do not naturally have LR in their live-ins, but PAC signing
11587 // requires it. Add it to prevent machine verifier crashes.
11588 if (!MBB.isLiveIn(AArch64::LR))
11589 MBB.addLiveIn(AArch64::LR);
11590
11591 BuildMI(MBB, MBB.begin(), DebugLoc(), TII->get(AArch64::PAUTH_PROLOGUE))
11593 TII->createPauthEpilogueInstr(MBB, DebugLoc());
11594}
11595
11596void AArch64InstrInfo::buildOutlinedFrame(
11598 const outliner::OutlinedFunction &OF) const {
11599
11600 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
11601
11602 if (OF.FrameConstructionID == MachineOutlinerTailCall)
11603 FI->setOutliningStyle("Tail Call");
11604 else if (OF.FrameConstructionID == MachineOutlinerThunk) {
11605 // For thunk outlining, rewrite the last instruction from a call to a
11606 // tail-call.
11607 MachineInstr *Call = &*--MBB.instr_end();
11608 unsigned TailOpcode;
11609 if (Call->getOpcode() == AArch64::BL) {
11610 TailOpcode = AArch64::TCRETURNdi;
11611 } else {
11612 assert(Call->getOpcode() == AArch64::BLR ||
11613 Call->getOpcode() == AArch64::BLRNoIP);
11614 TailOpcode = AArch64::TCRETURNriALL;
11615 }
11616 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
11617 .add(Call->getOperand(0))
11618 .addImm(0);
11619 MBB.insert(MBB.end(), TC);
11621
11622 FI->setOutliningStyle("Thunk");
11623 }
11624
11625 bool IsLeafFunction = true;
11626
11627 // Is there a call in the outlined range?
11628 auto IsNonTailCall = [](const MachineInstr &MI) {
11629 return MI.isCall() && !MI.isReturn();
11630 };
11631
11632 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
11633 // Fix up the instructions in the range, since we're going to modify the
11634 // stack.
11635
11636 // Bugzilla ID: 46767
11637 // TODO: Check if fixing up twice is safe so we can outline these.
11638 assert(OF.FrameConstructionID != MachineOutlinerDefault &&
11639 "Can only fix up stack references once");
11640 fixupPostOutline(MBB);
11641
11642 IsLeafFunction = false;
11643
11644 // LR has to be a live in so that we can save it.
11645 if (!MBB.isLiveIn(AArch64::LR))
11646 MBB.addLiveIn(AArch64::LR);
11647
11650
11651 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11652 OF.FrameConstructionID == MachineOutlinerThunk)
11653 Et = std::prev(MBB.end());
11654
11655 // There is a call in the range, so we must save LR. Save it as part of a
11656 // frame record when that gives us a smaller compact unwind encoding.
11658 // FP is saved here, so it must be live-in.
11659 if (!MBB.isLiveIn(AArch64::FP))
11660 MBB.addLiveIn(AArch64::FP);
11661
11662 // stp x29, x30, [sp, #-16]! (the pre-index imm is scaled by 8: -2 * 8)
11663 MachineInstr *STPXpre = BuildMI(MF, DebugLoc(), get(AArch64::STPXpre))
11664 .addReg(AArch64::SP, RegState::Define)
11665 .addReg(AArch64::FP)
11666 .addReg(AArch64::LR)
11667 .addReg(AArch64::SP)
11668 .addImm(-2);
11669 It = MBB.insert(It, STPXpre);
11670
11671 // mov x29, sp (add x29, sp, #0), so x29 points at the frame record.
11672 MachineInstr *SetFP = BuildMI(MF, DebugLoc(), get(AArch64::ADDXri))
11673 .addReg(AArch64::FP, RegState::Define)
11674 .addReg(AArch64::SP)
11675 .addImm(0)
11676 .addImm(0);
11677 MBB.insertAfter(It, SetFP);
11678
11679 // Describe the frame record with FP as the CFA. The encoder needs all
11680 // three to pick FRAME. No need to check for unwind info here: we only
11681 // get here if the function has it.
11682 CFIInstBuilder CFIBuilder(MBB, std::next(SetFP->getIterator()),
11684 CFIBuilder.buildDefCFA(AArch64::FP, 16);
11685 CFIBuilder.buildOffset(AArch64::LR, -8);
11686 CFIBuilder.buildOffset(AArch64::FP, -16);
11687
11688 // ldp x29, x30, [sp], #16
11689 MachineInstr *LDPXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDPXpost))
11690 .addReg(AArch64::SP, RegState::Define)
11691 .addReg(AArch64::FP, RegState::Define)
11692 .addReg(AArch64::LR, RegState::Define)
11693 .addReg(AArch64::SP)
11694 .addImm(2);
11695 Et = MBB.insert(Et, LDPXpost);
11696 } else {
11697 // Insert a save before the outlined region
11698 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11699 .addReg(AArch64::SP, RegState::Define)
11700 .addReg(AArch64::LR)
11701 .addReg(AArch64::SP)
11702 .addImm(-16);
11703 It = MBB.insert(It, STRXpre);
11704
11705 if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
11706 CFIInstBuilder CFIBuilder(MBB, It, MachineInstr::FrameSetup);
11707
11708 // Add a CFI saying the stack was moved 16 B down.
11709 CFIBuilder.buildDefCFAOffset(16);
11710
11711 // Add a CFI saying that the LR that we want to find is now 16 B higher
11712 // than before.
11713 CFIBuilder.buildOffset(AArch64::LR, -16);
11714 }
11715
11716 // Insert a restore before the terminator for the function.
11717 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11718 .addReg(AArch64::SP, RegState::Define)
11719 .addReg(AArch64::LR, RegState::Define)
11720 .addReg(AArch64::SP)
11721 .addImm(16);
11722 Et = MBB.insert(Et, LDRXpost);
11723 }
11724 }
11725
11726 auto RASignCondition = FI->getSignReturnAddressCondition();
11727 bool ShouldSignReturnAddr = AArch64FunctionInfo::shouldSignReturnAddress(
11728 RASignCondition, !IsLeafFunction);
11729
11730 // If this is a tail call outlined function, then there's already a return.
11731 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11732 OF.FrameConstructionID == MachineOutlinerThunk) {
11733 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11734 return;
11735 }
11736
11737 // It's not a tail call, so we have to insert the return ourselves.
11738
11739 // LR has to be a live in so that we can return to it.
11740 if (!MBB.isLiveIn(AArch64::LR))
11741 MBB.addLiveIn(AArch64::LR);
11742
11743 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
11744 .addReg(AArch64::LR);
11745 MBB.insert(MBB.end(), ret);
11746
11747 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11748
11749 FI->setOutliningStyle("Function");
11750
11751 // Did we have to modify the stack by saving the link register?
11752 if (OF.FrameConstructionID != MachineOutlinerDefault)
11753 return;
11754
11755 // We modified the stack.
11756 // Walk over the basic block and fix up all the stack accesses.
11757 fixupPostOutline(MBB);
11758}
11759
11760MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
11763
11764 // Are we tail calling?
11765 if (C.CallConstructionID == MachineOutlinerTailCall) {
11766 // If yes, then we can just branch to the label.
11767 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
11768 .addGlobalAddress(M.getNamedValue(MF.getName()))
11769 .addImm(0));
11770 return It;
11771 }
11772
11773 // Are we saving the link register?
11774 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
11775 C.CallConstructionID == MachineOutlinerThunk) {
11776 // No, so just insert the call.
11777 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11778 .addGlobalAddress(M.getNamedValue(MF.getName())));
11779 return It;
11780 }
11781
11782 // We want to return the spot where we inserted the call.
11784
11785 // Instructions for saving and restoring LR around the call instruction we're
11786 // going to insert.
11787 MachineInstr *Save;
11788 MachineInstr *Restore;
11789 // Can we save to a register?
11790 if (C.CallConstructionID == MachineOutlinerRegSave) {
11791 // FIXME: This logic should be sunk into a target-specific interface so that
11792 // we don't have to recompute the register.
11793 Register Reg = findRegisterToSaveLRTo(C);
11794 assert(Reg && "No callee-saved register available?");
11795
11796 // LR has to be a live in so that we can save it.
11797 if (!MBB.isLiveIn(AArch64::LR))
11798 MBB.addLiveIn(AArch64::LR);
11799
11800 // Save and restore LR from Reg.
11801 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
11802 .addReg(AArch64::XZR)
11803 .addReg(AArch64::LR)
11804 .addImm(0);
11805 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
11806 .addReg(AArch64::XZR)
11807 .addReg(Reg)
11808 .addImm(0);
11809 } else {
11810 // We have the default case. Save and restore from SP.
11811 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11812 .addReg(AArch64::SP, RegState::Define)
11813 .addReg(AArch64::LR)
11814 .addReg(AArch64::SP)
11815 .addImm(-16);
11816 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11817 .addReg(AArch64::SP, RegState::Define)
11818 .addReg(AArch64::LR, RegState::Define)
11819 .addReg(AArch64::SP)
11820 .addImm(16);
11821 }
11822
11823 It = MBB.insert(It, Save);
11824 It++;
11825
11826 // Insert the call.
11827 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11828 .addGlobalAddress(M.getNamedValue(MF.getName())));
11829 CallPt = It;
11830 It++;
11831
11832 It = MBB.insert(It, Restore);
11833 return CallPt;
11834}
11835
11836bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
11837 MachineFunction &MF) const {
11838 return MF.getFunction().hasMinSize();
11839}
11840
11841void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock &MBB,
11843 DebugLoc &DL,
11844 bool AllowSideEffects) const {
11845 const MachineFunction &MF = *MBB.getParent();
11846 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
11847 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
11848
11849 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
11850 BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg).addImm(0).addImm(0);
11851 } else if (STI.isSVEorStreamingSVEAvailable()) {
11852 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
11853 .addImm(0)
11854 .addImm(0);
11855 } else if (STI.isNeonAvailable()) {
11856 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
11857 .addImm(0);
11858 } else {
11859 // No Advanced SIMD (streaming-compatible without SVE, or +nosimd), so use
11860 // `fmov d...` instead of `movi v...`; writing `d` also clears the upper
11861 // 64 bits.
11862 assert(STI.hasFPARMv8() && "Expected FP to be available.");
11863 Register Reg64 = TRI.getSubReg(Reg, AArch64::dsub);
11864 BuildMI(MBB, Iter, DL, get(AArch64::FMOVD0), Reg64);
11865 }
11866}
11867
11868std::optional<DestSourcePair>
11870
11871 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
11872 // and zero immediate operands used as an alias for mov instruction.
11873 if ((MI.getOpcode() == AArch64::ORRWrs &&
11874 MI.getOperand(1).getReg() == AArch64::WZR &&
11875 MI.getOperand(3).getImm() == 0x0) ||
11876 (MI.getOpcode() == AArch64::ORRWrr &&
11877 MI.getOperand(1).getReg() == AArch64::WZR)) {
11878 // Check that the w->w move is not a zero-extending w->x mov.
11879 if ((MI.getOperand(0).getReg().isPhysical() &&
11880 MI.findRegisterDefOperandIdx(
11881 getXRegFromWReg(MI.getOperand(0).getReg()),
11882 /*TRI=*/nullptr) == -1) ||
11883 (MI.getOperand(0).getReg().isVirtual() &&
11884 !MI.getOperand(0).getSubReg()))
11885 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11886 }
11887
11888 if (MI.getOpcode() == AArch64::ORRXrs &&
11889 MI.getOperand(1).getReg() == AArch64::XZR &&
11890 MI.getOperand(3).getImm() == 0x0)
11891 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11892
11893 return std::nullopt;
11894}
11895
11896std::optional<DestSourcePair>
11898 if ((MI.getOpcode() == AArch64::ORRWrs &&
11899 MI.getOperand(1).getReg() == AArch64::WZR &&
11900 MI.getOperand(3).getImm() == 0x0) ||
11901 (MI.getOpcode() == AArch64::ORRWrr &&
11902 MI.getOperand(1).getReg() == AArch64::WZR))
11903 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11904 return std::nullopt;
11905}
11906
11907std::optional<RegImmPair>
11908AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
11909 int Sign = 1;
11910 int64_t Offset = 0;
11911
11912 // TODO: Handle cases where Reg is a super- or sub-register of the
11913 // destination register.
11914 const MachineOperand &Op0 = MI.getOperand(0);
11915 if (!Op0.isReg() || Reg != Op0.getReg())
11916 return std::nullopt;
11917
11918 switch (MI.getOpcode()) {
11919 default:
11920 return std::nullopt;
11921 case AArch64::SUBWri:
11922 case AArch64::SUBXri:
11923 case AArch64::SUBSWri:
11924 case AArch64::SUBSXri:
11925 Sign *= -1;
11926 [[fallthrough]];
11927 case AArch64::ADDSWri:
11928 case AArch64::ADDSXri:
11929 case AArch64::ADDWri:
11930 case AArch64::ADDXri: {
11931 // TODO: Third operand can be global address (usually some string).
11932 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
11933 !MI.getOperand(2).isImm())
11934 return std::nullopt;
11935 int Shift = MI.getOperand(3).getImm();
11936 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
11937 Offset = Sign * (MI.getOperand(2).getImm() << Shift);
11938 }
11939 }
11940 return RegImmPair{MI.getOperand(1).getReg(), Offset};
11941}
11942
11943/// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
11944/// the destination register then, if possible, describe the value in terms of
11945/// the source register.
11946static std::optional<ParamLoadedValue>
11948 const TargetInstrInfo *TII,
11949 const TargetRegisterInfo *TRI) {
11950 auto DestSrc = TII->isCopyLikeInstr(MI);
11951 if (!DestSrc)
11952 return std::nullopt;
11953
11954 Register DestReg = DestSrc->Destination->getReg();
11955 Register SrcReg = DestSrc->Source->getReg();
11956
11957 if (!DestReg.isValid() || !SrcReg.isValid())
11958 return std::nullopt;
11959
11960 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
11961
11962 // If the described register is the destination, just return the source.
11963 if (DestReg == DescribedReg)
11964 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11965
11966 // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
11967 if (MI.getOpcode() == AArch64::ORRWrs &&
11968 TRI->isSuperRegister(DestReg, DescribedReg))
11969 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11970
11971 // We may need to describe the lower part of a ORRXrs move.
11972 if (MI.getOpcode() == AArch64::ORRXrs &&
11973 TRI->isSubRegister(DestReg, DescribedReg)) {
11974 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
11975 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
11976 }
11977
11978 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
11979 "Unhandled ORR[XW]rs copy case");
11980
11981 return std::nullopt;
11982}
11983
11984bool AArch64InstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
11985 // Functions cannot be split to different sections on AArch64 if they have
11986 // a red zone. This is because relaxing a cross-section branch may require
11987 // incrementing the stack pointer to spill a register, which would overwrite
11988 // the red zone.
11989 if (MF.getInfo<AArch64FunctionInfo>()->hasRedZone().value_or(true))
11990 return false;
11991
11993}
11994
11995bool AArch64InstrInfo::isMBBSafeToSplitToCold(
11996 const MachineBasicBlock &MBB) const {
11997 // Asm Goto blocks can contain conditional branches to goto labels, which can
11998 // get moved out of range of the branch instruction.
11999 auto isAsmGoto = [](const MachineInstr &MI) {
12000 return MI.getOpcode() == AArch64::INLINEASM_BR;
12001 };
12002 if (llvm::any_of(MBB, isAsmGoto) || MBB.isInlineAsmBrIndirectTarget())
12003 return false;
12004
12005 // Because jump tables are label-relative instead of table-relative, they all
12006 // must be in the same section or relocation fixup handling will fail.
12007
12008 // Check if MBB is a jump table target
12009 const MachineJumpTableInfo *MJTI = MBB.getParent()->getJumpTableInfo();
12010 auto containsMBB = [&MBB](const MachineJumpTableEntry &JTE) {
12011 return llvm::is_contained(JTE.MBBs, &MBB);
12012 };
12013 if (MJTI != nullptr && llvm::any_of(MJTI->getJumpTables(), containsMBB))
12014 return false;
12015
12016 // Check if MBB contains a jump table lookup
12017 for (const MachineInstr &MI : MBB) {
12018 switch (MI.getOpcode()) {
12019 case TargetOpcode::G_BRJT:
12020 case AArch64::JumpTableDest32:
12021 case AArch64::JumpTableDest16:
12022 case AArch64::JumpTableDest8:
12023 return false;
12024 default:
12025 continue;
12026 }
12027 }
12028
12029 // MBB isn't a special case, so it's safe to be split to the cold section.
12030 return true;
12031}
12032
12033std::optional<ParamLoadedValue>
12034AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
12035 Register Reg) const {
12036 const MachineFunction *MF = MI.getMF();
12037 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
12038 switch (MI.getOpcode()) {
12039 case AArch64::MOVZWi:
12040 case AArch64::MOVZXi: {
12041 // MOVZWi may be used for producing zero-extended 32-bit immediates in
12042 // 64-bit parameters, so we need to consider super-registers.
12043 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
12044 return std::nullopt;
12045
12046 if (!MI.getOperand(1).isImm())
12047 return std::nullopt;
12048 int64_t Immediate = MI.getOperand(1).getImm();
12049 int Shift = MI.getOperand(2).getImm();
12050 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
12051 nullptr);
12052 }
12053 case AArch64::ORRWrs:
12054 case AArch64::ORRXrs:
12055 return describeORRLoadedValue(MI, Reg, this, TRI);
12056 }
12057
12059}
12060
12061bool AArch64InstrInfo::isExtendLikelyToBeFolded(
12062 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
12063 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
12064 ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
12065 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
12066
12067 // Anyexts are nops.
12068 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
12069 return true;
12070
12071 Register DefReg = ExtMI.getOperand(0).getReg();
12072 if (!MRI.hasOneNonDBGUse(DefReg))
12073 return false;
12074
12075 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
12076 // addressing mode.
12077 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
12078 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
12079}
12080
12081uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
12082 return get(Opc).TSFlags & AArch64::ElementSizeMask;
12083}
12084
12085bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
12086 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
12087}
12088
12089bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
12090 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
12091}
12092
12093unsigned int
12094AArch64InstrInfo::getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
12095 return OptLevel >= CodeGenOptLevel::Aggressive ? 6 : 2;
12096}
12097
12098bool AArch64InstrInfo::isLegalAddressingMode(unsigned NumBytes, int64_t Offset,
12099 unsigned Scale) const {
12100 if (Offset && Scale)
12101 return false;
12102
12103 // Check Reg + Imm
12104 if (!Scale) {
12105 // 9-bit signed offset
12106 if (isInt<9>(Offset))
12107 return true;
12108
12109 // 12-bit unsigned offset
12110 unsigned Shift = Log2_64(NumBytes);
12111 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
12112 // Must be a multiple of NumBytes (NumBytes is a power of 2)
12113 (Offset >> Shift) << Shift == Offset)
12114 return true;
12115 return false;
12116 }
12117
12118 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
12119 return Scale == 1 || (Scale > 0 && Scale == NumBytes);
12120}
12121
12123 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
12124 return AArch64::BLRNoIP;
12125 else
12126 return AArch64::BLR;
12127}
12128
12130 DebugLoc DL) const {
12131 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
12132 auto Builder = BuildMI(MBB, InsertPt, DL, get(AArch64::PAUTH_EPILOGUE))
12134
12135 MachineFunction &MF = *MBB.getParent();
12136 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
12137 auto &AFL = *static_cast<const AArch64FrameLowering *>(
12138 MF.getSubtarget().getFrameLowering());
12139 if (AFL.getArgumentStackToRestore(MF, MBB)) {
12140 Builder.addReg(AArch64::X17, RegState::ImplicitDefine);
12141 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
12142 if (AFI->branchProtectionPAuthLR())
12143 Builder.addReg(AArch64::X15, RegState::ImplicitDefine);
12144 return;
12145 }
12146
12147 if (AFI->branchProtectionPAuthLR() && !Subtarget.hasPAuthLR())
12148 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
12149}
12150
12152AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,
12153 Register TargetReg, bool FrameSetup) const {
12154 assert(TargetReg != AArch64::SP && "New top of stack cannot already be in SP");
12155
12156 MachineBasicBlock &MBB = *MBBI->getParent();
12157 MachineFunction &MF = *MBB.getParent();
12158 const AArch64InstrInfo *TII =
12159 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
12160 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
12161 DebugLoc DL = MBB.findDebugLoc(MBBI);
12162
12163 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
12164 MachineBasicBlock *LoopTestMBB =
12165 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12166 MF.insert(MBBInsertPoint, LoopTestMBB);
12167 MachineBasicBlock *LoopBodyMBB =
12168 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12169 MF.insert(MBBInsertPoint, LoopBodyMBB);
12170 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12171 MF.insert(MBBInsertPoint, ExitMBB);
12172 MachineInstr::MIFlag Flags =
12174
12175 // LoopTest:
12176 // SUB SP, SP, #ProbeSize
12177 emitFrameOffset(*LoopTestMBB, LoopTestMBB->end(), DL, AArch64::SP,
12178 AArch64::SP, StackOffset::getFixed(-ProbeSize), TII, Flags);
12179
12180 // CMP SP, TargetReg
12181 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
12182 AArch64::XZR)
12183 .addReg(AArch64::SP)
12184 .addReg(TargetReg)
12186 .setMIFlags(Flags);
12187
12188 // B.<Cond> LoopExit
12189 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::Bcc))
12191 .addMBB(ExitMBB)
12192 .setMIFlags(Flags);
12193
12194 // LDR XZR, [SP]
12195 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::LDRXui))
12196 .addDef(AArch64::XZR)
12197 .addReg(AArch64::SP)
12198 .addImm(0)
12202 Align(8)))
12203 .setMIFlags(Flags);
12204
12205 // B loop
12206 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::B))
12207 .addMBB(LoopTestMBB)
12208 .setMIFlags(Flags);
12209
12210 // LoopExit:
12211 // MOV SP, TargetReg
12212 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::ADDXri), AArch64::SP)
12213 .addReg(TargetReg)
12214 .addImm(0)
12216 .setMIFlags(Flags);
12217
12218 // LDR XZR, [SP]
12219 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::LDRXui))
12220 .addReg(AArch64::XZR, RegState::Define)
12221 .addReg(AArch64::SP)
12222 .addImm(0)
12223 .setMIFlags(Flags);
12224
12225 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
12227
12228 LoopTestMBB->addSuccessor(ExitMBB);
12229 LoopTestMBB->addSuccessor(LoopBodyMBB);
12230 LoopBodyMBB->addSuccessor(LoopTestMBB);
12231 MBB.addSuccessor(LoopTestMBB);
12232
12233 // Update liveins.
12234 if (MF.getRegInfo().reservedRegsFrozen())
12235 fullyRecomputeLiveIns({ExitMBB, LoopBodyMBB, LoopTestMBB});
12236
12237 return ExitMBB->begin();
12238}
12239
12240namespace {
12241class AArch64PipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
12242 MachineFunction *MF;
12243 const TargetInstrInfo *TII;
12244 MachineRegisterInfo &MRI;
12245
12246 /// The block of the loop
12247 MachineBasicBlock *LoopBB;
12248 /// The conditional branch of the loop
12249 MachineInstr *CondBranch;
12250 /// The compare instruction for loop control
12251 MachineInstr *Comp;
12252 /// The number of the operand of the loop counter value in Comp
12253 unsigned CompCounterOprNum;
12254 /// The instruction that updates the loop counter value
12255 MachineInstr *Update;
12256 /// The number of the operand of the loop counter value in Update
12257 unsigned UpdateCounterOprNum;
12258 /// The initial value of the loop counter
12259 Register Init;
12260 /// True iff Update is a predecessor of Comp
12261 bool IsUpdatePriorComp;
12262
12263 /// The normalized condition used by createTripCountGreaterCondition()
12264 SmallVector<MachineOperand, 4> Cond;
12265
12266public:
12267 AArch64PipelinerLoopInfo(MachineBasicBlock *LoopBB, MachineInstr *CondBranch,
12268 MachineInstr *Comp, unsigned CompCounterOprNum,
12269 MachineInstr *Update, unsigned UpdateCounterOprNum,
12270 Register Init, bool IsUpdatePriorComp,
12271 const SmallVectorImpl<MachineOperand> &Cond)
12272 : MF(Comp->getParent()->getParent()),
12273 TII(MF->getSubtarget().getInstrInfo()), MRI(MF->getRegInfo()),
12274 LoopBB(LoopBB), CondBranch(CondBranch), Comp(Comp),
12275 CompCounterOprNum(CompCounterOprNum), Update(Update),
12276 UpdateCounterOprNum(UpdateCounterOprNum), Init(Init),
12277 IsUpdatePriorComp(IsUpdatePriorComp), Cond(Cond.begin(), Cond.end()) {}
12278
12279 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
12280 // Make the instructions for loop control be placed in stage 0.
12281 // The predecessors of Comp are considered by the caller.
12282 return MI == Comp;
12283 }
12284
12285 std::optional<bool> createTripCountGreaterCondition(
12286 int TC, MachineBasicBlock &MBB,
12287 SmallVectorImpl<MachineOperand> &CondParam) override {
12288 // A branch instruction will be inserted as "if (Cond) goto epilogue".
12289 // Cond is normalized for such use.
12290 // The predecessors of the branch are assumed to have already been inserted.
12291 CondParam = Cond;
12292 return {};
12293 }
12294
12295 void createRemainingIterationsGreaterCondition(
12296 int TC, MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &Cond,
12297 DenseMap<MachineInstr *, MachineInstr *> &LastStage0Insts) override;
12298
12299 void setPreheader(MachineBasicBlock *NewPreheader) override {}
12300
12301 void adjustTripCount(int TripCountAdjust) override {}
12302
12303 bool isMVEExpanderSupported() override { return true; }
12304};
12305} // namespace
12306
12307/// Clone an instruction from MI. The register of ReplaceOprNum-th operand
12308/// is replaced by ReplaceReg. The output register is newly created.
12309/// The other operands are unchanged from MI.
12310static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum,
12311 Register ReplaceReg, MachineBasicBlock &MBB,
12312 MachineBasicBlock::iterator InsertTo) {
12313 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
12314 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
12315 MachineInstr *NewMI = MBB.getParent()->CloneMachineInstr(MI);
12316 Register Result = 0;
12317 for (unsigned I = 0; I < NewMI->getNumOperands(); ++I) {
12318 if (I == 0 && NewMI->getOperand(0).getReg().isVirtual()) {
12319 Result = MRI.createVirtualRegister(
12320 MRI.getRegClass(NewMI->getOperand(0).getReg()));
12321 NewMI->getOperand(I).setReg(Result);
12322 } else if (I == ReplaceOprNum) {
12323 MRI.constrainRegClass(ReplaceReg, TII->getRegClass(NewMI->getDesc(), I));
12324 NewMI->getOperand(I).setReg(ReplaceReg);
12325 }
12326 }
12327 MBB.insert(InsertTo, NewMI);
12328 return Result;
12329}
12330
12331void AArch64PipelinerLoopInfo::createRemainingIterationsGreaterCondition(
12334 // Create and accumulate conditions for next TC iterations.
12335 // Example:
12336 // SUBSXrr N, counter, implicit-def $nzcv # compare instruction for the last
12337 // # iteration of the kernel
12338 //
12339 // # insert the following instructions
12340 // cond = CSINCXr 0, 0, C, implicit $nzcv
12341 // counter = ADDXri counter, 1 # clone from this->Update
12342 // SUBSXrr n, counter, implicit-def $nzcv # clone from this->Comp
12343 // cond = CSINCXr cond, cond, C, implicit $nzcv
12344 // ... (repeat TC times)
12345 // SUBSXri cond, 0, implicit-def $nzcv
12346
12347 assert(CondBranch->getOpcode() == AArch64::Bcc);
12348 // CondCode to exit the loop
12350 (AArch64CC::CondCode)CondBranch->getOperand(0).getImm();
12351 if (CondBranch->getOperand(1).getMBB() == LoopBB)
12353
12354 // Accumulate conditions to exit the loop
12355 Register AccCond = AArch64::XZR;
12356
12357 // If CC holds, CurCond+1 is returned; otherwise CurCond is returned.
12358 auto AccumulateCond = [&](Register CurCond,
12360 Register NewCond = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
12361 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::CSINCXr))
12362 .addReg(NewCond, RegState::Define)
12363 .addReg(CurCond)
12364 .addReg(CurCond)
12366 return NewCond;
12367 };
12368
12369 if (!LastStage0Insts.empty() && LastStage0Insts[Comp]->getParent() == &MBB) {
12370 // Update and Comp for I==0 are already exists in MBB
12371 // (MBB is an unrolled kernel)
12372 Register Counter;
12373 for (int I = 0; I <= TC; ++I) {
12374 Register NextCounter;
12375 if (I != 0)
12376 NextCounter =
12377 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12378
12379 AccCond = AccumulateCond(AccCond, CC);
12380
12381 if (I != TC) {
12382 if (I == 0) {
12383 if (Update != Comp && IsUpdatePriorComp) {
12384 Counter =
12385 LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12386 NextCounter = cloneInstr(Update, UpdateCounterOprNum, Counter, MBB,
12387 MBB.end());
12388 } else {
12389 // can use already calculated value
12390 NextCounter = LastStage0Insts[Update]->getOperand(0).getReg();
12391 }
12392 } else if (Update != Comp) {
12393 NextCounter =
12394 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12395 }
12396 }
12397 Counter = NextCounter;
12398 }
12399 } else {
12400 Register Counter;
12401 if (LastStage0Insts.empty()) {
12402 // use initial counter value (testing if the trip count is sufficient to
12403 // be executed by pipelined code)
12404 Counter = Init;
12405 if (IsUpdatePriorComp)
12406 Counter =
12407 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12408 } else {
12409 // MBB is an epilogue block. LastStage0Insts[Comp] is in the kernel block.
12410 Counter = LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12411 }
12412
12413 for (int I = 0; I <= TC; ++I) {
12414 Register NextCounter;
12415 NextCounter =
12416 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12417 AccCond = AccumulateCond(AccCond, CC);
12418 if (I != TC && Update != Comp)
12419 NextCounter =
12420 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12421 Counter = NextCounter;
12422 }
12423 }
12424
12425 // If AccCond == 0, the remainder is greater than TC.
12426 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::SUBSXri))
12427 .addReg(AArch64::XZR, RegState::Define | RegState::Dead)
12428 .addReg(AccCond)
12429 .addImm(0)
12430 .addImm(0);
12431 Cond.clear();
12433}
12434
12435static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB,
12436 Register &RegMBB, Register &RegOther) {
12437 assert(Phi.getNumOperands() == 5);
12438 if (Phi.getOperand(2).getMBB() == MBB) {
12439 RegMBB = Phi.getOperand(1).getReg();
12440 RegOther = Phi.getOperand(3).getReg();
12441 } else {
12442 assert(Phi.getOperand(4).getMBB() == MBB);
12443 RegMBB = Phi.getOperand(3).getReg();
12444 RegOther = Phi.getOperand(1).getReg();
12445 }
12446}
12447
12449 if (!Reg.isVirtual())
12450 return false;
12451 const MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
12452 return MRI.getDefBlock(Reg) != BB;
12453}
12454
12455/// If Reg is an induction variable, return true and set some parameters
12456static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB,
12457 MachineInstr *&UpdateInst,
12458 unsigned &UpdateCounterOprNum, Register &InitReg,
12459 bool &IsUpdatePriorComp) {
12460 // Example:
12461 //
12462 // Preheader:
12463 // InitReg = ...
12464 // LoopBB:
12465 // Reg0 = PHI (InitReg, Preheader), (Reg1, LoopBB)
12466 // Reg = COPY Reg0 ; COPY is ignored.
12467 // Reg1 = ADD Reg, #1; UpdateInst. Incremented by a loop invariant value.
12468 // ; Reg is the value calculated in the previous
12469 // ; iteration, so IsUpdatePriorComp == false.
12470
12471 if (LoopBB->pred_size() != 2)
12472 return false;
12473 if (!Reg.isVirtual())
12474 return false;
12475 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
12476 UpdateInst = nullptr;
12477 UpdateCounterOprNum = 0;
12478 InitReg = 0;
12479 IsUpdatePriorComp = true;
12480 Register CurReg = Reg;
12481 while (true) {
12482 MachineInstr *Def = MRI.getVRegDef(CurReg);
12483 if (Def->getParent() != LoopBB)
12484 return false;
12485 if (Def->isCopy()) {
12486 // Ignore copy instructions unless they contain subregisters
12487 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
12488 return false;
12489 CurReg = Def->getOperand(1).getReg();
12490 } else if (Def->isPHI()) {
12491 if (InitReg != 0)
12492 return false;
12493 if (!UpdateInst)
12494 IsUpdatePriorComp = false;
12495 extractPhiReg(*Def, LoopBB, CurReg, InitReg);
12496 } else {
12497 if (UpdateInst)
12498 return false;
12499 switch (Def->getOpcode()) {
12500 case AArch64::ADDSXri:
12501 case AArch64::ADDSWri:
12502 case AArch64::SUBSXri:
12503 case AArch64::SUBSWri:
12504 case AArch64::ADDXri:
12505 case AArch64::ADDWri:
12506 case AArch64::SUBXri:
12507 case AArch64::SUBWri:
12508 UpdateInst = Def;
12509 UpdateCounterOprNum = 1;
12510 break;
12511 case AArch64::ADDSXrr:
12512 case AArch64::ADDSWrr:
12513 case AArch64::SUBSXrr:
12514 case AArch64::SUBSWrr:
12515 case AArch64::ADDXrr:
12516 case AArch64::ADDWrr:
12517 case AArch64::SUBXrr:
12518 case AArch64::SUBWrr:
12519 UpdateInst = Def;
12520 if (isDefinedOutside(Def->getOperand(2).getReg(), LoopBB))
12521 UpdateCounterOprNum = 1;
12522 else if (isDefinedOutside(Def->getOperand(1).getReg(), LoopBB))
12523 UpdateCounterOprNum = 2;
12524 else
12525 return false;
12526 break;
12527 default:
12528 return false;
12529 }
12530 CurReg = Def->getOperand(UpdateCounterOprNum).getReg();
12531 }
12532
12533 if (!CurReg.isVirtual())
12534 return false;
12535 if (Reg == CurReg)
12536 break;
12537 }
12538
12539 if (!UpdateInst)
12540 return false;
12541
12542 return true;
12543}
12544
12545std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
12547 // Accept loops that meet the following conditions
12548 // * The conditional branch is BCC
12549 // * The compare instruction is ADDS/SUBS/WHILEXX
12550 // * One operand of the compare is an induction variable and the other is a
12551 // loop invariant value
12552 // * The induction variable is incremented/decremented by a single instruction
12553 // * Does not contain CALL or instructions which have unmodeled side effects
12554
12555 for (MachineInstr &MI : *LoopBB)
12556 if (MI.isCall() || MI.hasUnmodeledSideEffects())
12557 // This instruction may use NZCV, which interferes with the instruction to
12558 // be inserted for loop control.
12559 return nullptr;
12560
12561 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
12563 if (analyzeBranch(*LoopBB, TBB, FBB, Cond))
12564 return nullptr;
12565
12566 // Infinite loops are not supported
12567 if (TBB == LoopBB && FBB == LoopBB)
12568 return nullptr;
12569
12570 // Must be conditional branch
12571 if (TBB != LoopBB && FBB == nullptr)
12572 return nullptr;
12573
12574 assert((TBB == LoopBB || FBB == LoopBB) &&
12575 "The Loop must be a single-basic-block loop");
12576
12577 MachineInstr *CondBranch = &*LoopBB->getFirstTerminator();
12579
12580 if (CondBranch->getOpcode() != AArch64::Bcc)
12581 return nullptr;
12582
12583 // Normalization for createTripCountGreaterCondition()
12584 if (TBB == LoopBB)
12586
12587 MachineInstr *Comp = nullptr;
12588 unsigned CompCounterOprNum = 0;
12589 for (MachineInstr &MI : reverse(*LoopBB)) {
12590 if (MI.modifiesRegister(AArch64::NZCV, &TRI)) {
12591 // Guarantee that the compare is SUBS/ADDS/WHILEXX and that one of the
12592 // operands is a loop invariant value
12593
12594 switch (MI.getOpcode()) {
12595 case AArch64::SUBSXri:
12596 case AArch64::SUBSWri:
12597 case AArch64::ADDSXri:
12598 case AArch64::ADDSWri:
12599 Comp = &MI;
12600 CompCounterOprNum = 1;
12601 break;
12602 case AArch64::ADDSWrr:
12603 case AArch64::ADDSXrr:
12604 case AArch64::SUBSWrr:
12605 case AArch64::SUBSXrr:
12606 Comp = &MI;
12607 break;
12608 default:
12609 if (isWhileOpcode(MI.getOpcode())) {
12610 Comp = &MI;
12611 break;
12612 }
12613 return nullptr;
12614 }
12615
12616 if (CompCounterOprNum == 0) {
12617 if (isDefinedOutside(Comp->getOperand(1).getReg(), LoopBB))
12618 CompCounterOprNum = 2;
12619 else if (isDefinedOutside(Comp->getOperand(2).getReg(), LoopBB))
12620 CompCounterOprNum = 1;
12621 else
12622 return nullptr;
12623 }
12624 break;
12625 }
12626 }
12627 if (!Comp)
12628 return nullptr;
12629
12630 MachineInstr *Update = nullptr;
12631 Register Init;
12632 bool IsUpdatePriorComp;
12633 unsigned UpdateCounterOprNum;
12634 if (!getIndVarInfo(Comp->getOperand(CompCounterOprNum).getReg(), LoopBB,
12635 Update, UpdateCounterOprNum, Init, IsUpdatePriorComp))
12636 return nullptr;
12637
12638 return std::make_unique<AArch64PipelinerLoopInfo>(
12639 LoopBB, CondBranch, Comp, CompCounterOprNum, Update, UpdateCounterOprNum,
12640 Init, IsUpdatePriorComp, Cond);
12641}
12642
12643/// verifyInstruction - Perform target specific instruction verification.
12644bool AArch64InstrInfo::verifyInstruction(const MachineInstr &MI,
12645 StringRef &ErrInfo) const {
12646 // Verify that immediate offsets on load/store instructions are within range.
12647 // Stack objects with an FI operand are excluded as they can be fixed up
12648 // during PEI.
12649 TypeSize Scale(0U, false), Width(0U, false);
12650 int64_t MinOffset, MaxOffset;
12651 if (getMemOpInfo(MI.getOpcode(), Scale, Width, MinOffset, MaxOffset)) {
12652 unsigned ImmIdx = getLoadStoreImmIdx(MI.getOpcode());
12653 if (MI.getOperand(ImmIdx).isImm() && !MI.getOperand(ImmIdx - 1).isFI()) {
12654 int64_t Imm = MI.getOperand(ImmIdx).getImm();
12655 if (Imm < MinOffset || Imm > MaxOffset) {
12656 ErrInfo = "Unexpected immediate on load/store instruction";
12657 return false;
12658 }
12659 }
12660 }
12661
12662 const MCInstrDesc &MCID = MI.getDesc();
12663 for (unsigned Op = 0; Op < MCID.getNumOperands(); Op++) {
12664 const MachineOperand &MO = MI.getOperand(Op);
12665 switch (MCID.operands()[Op].OperandType) {
12667 if (!MO.isImm() || MO.getImm() != 0) {
12668 ErrInfo = "OPERAND_IMPLICIT_IMM_0 should be 0";
12669 return false;
12670 }
12671 break;
12673 if (!MO.isImm() ||
12675 (AArch64_AM::getShiftValue(MO.getImm()) != 8 &&
12676 AArch64_AM::getShiftValue(MO.getImm()) != 16)) {
12677 ErrInfo = "OPERAND_SHIFT_MSL should be msl shift of 8 or 16";
12678 return false;
12679 }
12680 break;
12682 if (!MO.isImm() || (MO.getImm() != 0 && MO.getImm() != 1)) {
12683 ErrInfo = "OPERAND_IMM_UINT1 should be 0 or 1";
12684 return false;
12685 }
12686 break;
12688 if (!MO.isImm() || MO.getImm() <= 0 || MO.getImm() > 16) {
12689 ErrInfo = "OPERAND_IMM_UINT4plus1 should be in the range 1 to 16";
12690 return false;
12691 }
12692 break;
12694 if (!MO.isImm() || !isUInt<5>(MO.getImm())) {
12695 ErrInfo = "OPERAND_IMM_UINT5 should be in the range 0 to 31";
12696 return false;
12697 }
12698 break;
12700 if (!MO.isImm() || !isUInt<8>(MO.getImm())) {
12701 ErrInfo = "OPERAND_IMM_UINT8 should be in the range 0 to 255";
12702 return false;
12703 }
12704 break;
12705 default:
12706 break;
12707 }
12708 }
12709 return true;
12710}
12711
12712#define GET_INSTRINFO_HELPERS
12713#define GET_INSTRMAP_INFO
12714#include "AArch64GenInstrInfo.inc"
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const AArch64Subtarget & Subtarget
SDValue Pred
static Register genNeg(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned MnegOpc, const TargetRegisterClass *RC)
genNeg - Helper to generate an intermediate negation of the second operand of Root
static bool isFrameStoreOpcode(int Opcode)
static bool getMaddPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Find instructions that can be turned into madd.
static AArch64CC::CondCode findCondCodeUsedByInstr(const MachineInstr &Instr)
Find a condition code used by the instruction.
static void updateOperandRegClass(MachineInstr &Instr)
static MachineInstr * genFusedMultiplyAcc(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC)
genFusedMultiplyAcc - Helper to generate fused multiply accumulate instructions.
static MachineInstr * genFusedMultiplyAccNeg(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned IdxMulOpd, unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC)
genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate instructions with an additional...
static bool isCombineInstrCandidate64(unsigned Opc)
static bool isFrameLoadOpcode(int Opcode)
static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg)
static bool areCFlagsAccessedBetweenInstrs(MachineBasicBlock::iterator From, MachineBasicBlock::iterator To, const TargetRegisterInfo *TRI, const AccessKind AccessToCheck=AK_All)
True when condition flags are accessed (either by writing or reading) on the instruction trace starti...
static std::optional< SPAddSubImmEncoding > adjustSPAddSubImm(const MachineInstr &MI, int64_t Delta)
Adjust the signed byte offset of MI, which must satisfy isSPAddSubImm, by Delta and re-encode the res...
static bool getFMAPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Floating-Point Support.
static bool isADDSRegImm(unsigned Opcode)
static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI)
static bool isANDOpcode(MachineInstr &MI)
static bool predictCompactUnwindFrameRecordForOutlinedFunction(std::vector< outliner::Candidate > &RepeatedSequenceLocs, const TargetRegisterInfo &TRI)
Predict what the above will answer, for use while costing candidates.
static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment, StringRef RegScale={})
static unsigned sForm(MachineInstr &Instr)
Get opcode of S version of Instr.
static unsigned getBranchDisplacementBits(const AArch64Options &CLOpts, unsigned Opc)
static bool isCombineInstrSettingFlag(unsigned Opc)
static bool getFNEGPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB, MachineInstr *&UpdateInst, unsigned &UpdateCounterOprNum, Register &InitReg, bool &IsUpdatePriorComp)
If Reg is an induction variable, return true and set some parameters.
static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc)
static bool mustAvoidNeonAtMBBI(const AArch64Subtarget &Subtarget, MachineBasicBlock &MBB, MachineBasicBlock::iterator I)
Returns true if in a streaming call site region without SME-FA64.
static bool isPostIndexLdStOpcode(unsigned Opcode)
Return true if the opcode is a post-index ld/st instruction, which really loads from base+0.
static std::optional< unsigned > getLFIInstSizeInBytes(const MachineInstr &MI)
Return the maximum number of bytes of code the specified instruction may be after LFI rewriting.
static std::optional< ParamLoadedValue > describeORRLoadedValue(const MachineInstr &MI, Register DescribedReg, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
If the given ORR instruction is a copy, and DescribedReg overlaps with the destination register then,...
static bool getFMULPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
static void genMaddShf(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, unsigned MaddOpc, bool Is64Bit, DenseMap< Register, unsigned > &InstrIdxForVirtReg)
MUL I=A,B,0 ADDrs R,I,C,shift ==> SBFM/UBFM J=C,shift MADD R,A,B,J.
static void appendReadRegExpr(SmallVectorImpl< char > &Expr, unsigned RegNum)
static MachineInstr * genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR, const TargetRegisterClass *RC)
genMaddR - Generate madd instruction and combine mul and add using an extra virtual register Example ...
static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum, Register ReplaceReg, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertTo)
Clone an instruction from MI.
static bool scaleOffset(unsigned Opc, int64_t &Offset)
static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO, unsigned MulOpc)
unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale)
static MachineInstr * genFusedMultiplyIdx(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC)
genFusedMultiplyIdx - Helper to generate fused multiply accumulate instructions.
static MachineInstr * genIndexedMultiply(MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxDupOp, unsigned MulOpc, const TargetRegisterClass *RC, MachineRegisterInfo &MRI)
Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
static bool shouldUseCompactUnwindFrameRecordForOutlinedFunction(const MachineBasicBlock &MBB)
Return true if the outlined function in MBB should save FP and LR as a frame record instead of saving...
static bool isSUBSRegImm(unsigned Opcode)
static const TargetRegisterClass * getRegClass(const MachineInstr &MI, Register Reg)
static bool isInStreamingCallSiteRegion(MachineBasicBlock &MBB, MachineBasicBlock::iterator I)
Returns true if the instruction at I is in a streaming call site region, within a single basic block.
static bool canCmpInstrBeRemoved(MachineInstr &MI, MachineInstr &CmpInstr, int CmpValue, const TargetRegisterInfo &TRI, SmallVectorImpl< MachineInstr * > &CCUseInstrs, bool &IsInvertCC)
unsigned unscaledOffsetOpcode(unsigned Opcode)
static bool getLoadPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Search for patterns of LD instructions we can optimize.
static bool canInstrSubstituteCmpInstr(MachineInstr &MI, MachineInstr &CmpInstr, const TargetRegisterInfo &TRI)
Check if CmpInstr can be substituted by MI.
static UsedNZCV getUsedNZCV(AArch64CC::CondCode CC)
static bool isCombineInstrCandidateFP(const MachineInstr &Inst)
static bool isCompactUnwindFrameRecordEnabled(const MachineFunction &MF)
Return true if the frame-record form of the outlined prologue is enabled for the target of MF.
static void appendLoadRegExpr(SmallVectorImpl< char > &Expr, int64_t OffsetFromDefCFA)
static void appendConstantExpr(SmallVectorImpl< char > &Expr, int64_t Constant, dwarf::LocationAtom Operation)
static unsigned convertToNonFlagSettingOpc(const MachineInstr &MI)
Return the opcode that does not set flags when possible - otherwise return the original opcode.
static bool outliningCandidatesV8_3OpsConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static bool isCombineInstrCandidate32(unsigned Opc)
static void parseCondBranch(MachineInstr *LastInst, MachineBasicBlock *&Target, SmallVectorImpl< MachineOperand > &Cond)
static unsigned offsetExtendOpcode(unsigned Opcode)
MachineOutlinerMBBFlags
@ LRUnavailableSomewhere
@ UnsafeRegsDead
static void loadRegPairFromStackSlot(const TargetRegisterInfo &TRI, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MCInstrDesc &MCID, Register DestReg, unsigned SubIdx0, unsigned SubIdx1, int FI, MachineMemOperand *MMO)
static void generateGatherLanePattern(MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned Pattern, unsigned NumLanes)
Generate optimized instruction sequence for gather load patterns to improve Memory-Level Parallelism ...
static bool getMiscPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns)
Find other MI combine patterns.
static bool outliningCandidatesSigningKeyConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static const MachineInstrBuilder & AddSubReg(const MachineInstrBuilder &MIB, MCRegister Reg, unsigned SubIdx, RegState State, const TargetRegisterInfo *TRI)
static bool outliningCandidatesSigningScopeConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1, int64_t Offset1, unsigned Opcode1, int FI2, int64_t Offset2, unsigned Opcode2)
static bool outliningCandidatesPAuthLRConsensus(const outliner::Candidate &a, const outliner::Candidate &b)
static bool isValidCBExtend(int64_t Opc, AArch64_AM::ShiftExtendType Ext)
static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB, Register &RegMBB, Register &RegOther)
static MCCFIInstruction createDefCFAExpression(const TargetRegisterInfo &TRI, unsigned Reg, const StackOffset &Offset)
static bool isSPAddSubImm(const MachineInstr &MI)
Returns true if MI is an ADD/SUBXri with an immediate offset that reads SP but does not write SP (e....
static bool isDefinedOutside(Register Reg, const MachineBasicBlock *BB)
static MachineInstr * genFusedMultiply(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC, FMAInstKind kind=FMAInstKind::Default, const Register *ReplacedAddend=nullptr)
genFusedMultiply - Generate fused multiply instructions.
static bool getGatherLanePattern(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, unsigned LoadLaneOpCode, unsigned NumLanes)
Check if the given instruction forms a gather load pattern that can be optimized for better Memory-Le...
static MachineInstr * genFusedMultiplyIdxNeg(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg, unsigned IdxMulOpd, unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC)
genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate instructions with an additional...
static bool isCombineInstrCandidate(unsigned Opc)
static unsigned regOffsetOpcode(unsigned Opcode)
MachineOutlinerClass
Constants defining how certain sequences should be outlined.
@ MachineOutlinerTailCall
Emit a save, restore, call, and return.
@ MachineOutlinerRegSave
Emit a call and tail-call.
@ MachineOutlinerNoLRSave
Only emit a branch.
@ MachineOutlinerThunk
Emit a call and return.
@ MachineOutlinerDefault
static bool areCFlagsAliveInSuccessors(const MachineBasicBlock *MBB)
Check if AArch64::NZCV should be alive in successors of MBB.
static void emitFrameOffsetAdj(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, int64_t Offset, unsigned Opc, const TargetInstrInfo *TII, MachineInstr::MIFlag Flag, bool NeedsWinCFI, bool *HasWinCFI, bool EmitCFAOffset, StackOffset CFAOffset, unsigned FrameReg)
static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize)
static void genSubAdd2SubSub(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, unsigned IdxOpd1, DenseMap< Register, unsigned > &InstrIdxForVirtReg)
Do the following transformation A - (B + C) ==> (A - B) - C A - (B + C) ==> (A - C) - B.
static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg, unsigned *NewReg=nullptr)
static void signOutlinedFunction(MachineFunction &MF, MachineBasicBlock &MBB, const AArch64InstrInfo *TII, bool ShouldSignReturnAddr)
static MachineInstr * genFNegatedMAD(MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs)
static bool canCombineWithMUL(MachineBasicBlock &MBB, MachineOperand &MO, unsigned MulOpc, unsigned ZeroReg)
static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI, MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MCInstrDesc &MCID, Register SrcReg, bool IsKill, unsigned SubIdx0, unsigned SubIdx1, int FI, MachineMemOperand *MMO)
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Forward Handle Accesses
@ Default
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
A set of register units.
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file declares the machine register scavenger class.
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
SignReturnAddress getSignReturnAddressCondition() const
void setOutliningStyle(const std::string &Style)
bool needsDwarfUnwindInfo(const MachineFunction &MF) const
std::optional< bool > hasRedZone() const
static bool shouldSignReturnAddress(SignReturnAddress Condition, bool IsLRSpilled)
static bool isHForm(const MachineInstr &MI)
Returns whether the instruction is in H form (16 bit operands)
void insertSelect(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DstReg, ArrayRef< MachineOperand > Cond, Register TrueReg, Register FalseReg) const override
static bool hasBTISemantics(const MachineInstr &MI)
Returns whether the instruction can be compatible with non-zero BTYPE.
static bool isQForm(const MachineInstr &MI)
Returns whether the instruction is in Q form (128 bit operands)
static bool getMemOpInfo(unsigned Opcode, TypeSize &Scale, TypeSize &Width, int64_t &MinOffset, int64_t &MaxOffset)
Returns true if opcode Opc is a memory operation.
static bool isTailCallReturnInst(const MachineInstr &MI)
Returns true if MI is one of the TCRETURN* instructions.
static bool isFPRCopy(const MachineInstr &MI)
Does this instruction rename an FPR without modifying bits?
MachineInstr * emitLdStWithAddr(MachineInstr &MemI, const ExtAddrMode &AM) const override
std::optional< DestSourcePair > isCopyInstrImpl(const MachineInstr &MI) const override
If the specific machine instruction is an instruction that moves/copies value from one register to an...
MachineBasicBlock * getBranchDestBlock(const MachineInstr &MI) const override
unsigned getInstSizeInBytes(const MachineInstr &MI) const override
GetInstSize - Return the number of bytes of code the specified instruction may be.
static bool isZExtLoad(const MachineInstr &MI)
Returns whether the instruction is a zero-extending load.
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
void copyPhysRegImpl(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const override
static bool isGPRCopy(const MachineInstr &MI)
Does this instruction rename a GPR without modifying bits?
static unsigned convertToFlagSettingOpc(unsigned Opc)
Return the opcode that set flags when possible.
void createPauthEpilogueInstr(MachineBasicBlock &MBB, DebugLoc DL) const
Return true when there is potentially a faster code sequence for an instruction chain ending in Root.
bool isBranchOffsetInRange(unsigned BranchOpc, int64_t BrOffset) const override
Register isLoadFromStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const override
Check for post-frame ptr elimination stack locations as well.
static const MachineOperand & getLdStOffsetOp(const MachineInstr &MI)
Returns the immediate offset operator of a load/store.
bool isCoalescableExtInstr(const MachineInstr &MI, Register &SrcReg, Register &DstReg, unsigned &SubIdx) const override
static std::optional< unsigned > getUnscaledLdSt(unsigned Opc)
Returns the unscaled load/store for the scaled load/store opcode, if there is a corresponding unscale...
static bool hasUnscaledLdStOffset(unsigned Opc)
Return true if it has an unscaled load/store offset.
static const MachineOperand & getLdStAmountOp(const MachineInstr &MI)
Returns the shift amount operator of a load/store.
static bool isPreLdSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load/store.
bool analyzeBranchPredicate(MachineBasicBlock &MBB, MachineBranchPredicate &MBP, bool AllowModify) const override
void insertIndirectBranch(MachineBasicBlock &MBB, MachineBasicBlock &NewDestBB, MachineBasicBlock &RestoreBB, const DebugLoc &DL, int64_t BrOffset, RegScavenger *RS) const override
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
static bool isPairableLdStInst(const MachineInstr &MI)
Return true if pairing the given load or store may be paired with another.
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
static bool isSExtLoad(const MachineInstr &MI)
Returns whether the instruction is a sign-extending load.
const AArch64RegisterInfo & getRegisterInfo() const
getRegisterInfo - TargetInstrInfo is a superset of MRegister info.
static bool isPreSt(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed store.
void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
AArch64InstrInfo(const AArch64Subtarget &STI)
static bool isPairedLdSt(const MachineInstr &MI)
Returns whether the instruction is a paired load/store.
MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const override
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
bool getMemOperandsWithOffsetWidth(const MachineInstr &MI, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const override
static bool isStridedAccess(const MachineInstr &MI)
Return true if the given load or store is a strided memory access.
bool shouldClusterMemOps(ArrayRef< const MachineOperand * > BaseOps1, int64_t Offset1, bool OffsetIsScalable1, ArrayRef< const MachineOperand * > BaseOps2, int64_t Offset2, bool OffsetIsScalable2, unsigned ClusterSize, unsigned NumBytes) const override
Detect opportunities for ldp/stp formation.
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
bool isThroughputPattern(unsigned Pattern) const override
Return true when a code sequence can improve throughput.
bool canInsertSelect(const MachineBasicBlock &, ArrayRef< MachineOperand > Cond, Register, Register, Register, SelectExpansion &) const override
MachineOperand & getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const
Return the immediate offset of the base register in a load/store LdSt.
std::optional< ExtAddrMode > getAddrModeFromMemoryOp(const MachineInstr &MemI) const override
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
bool canFoldIntoAddrMode(const MachineInstr &MemI, Register Reg, const MachineInstr &AddrI, ExtAddrMode &AM) const override
static bool isLdStPairSuppressed(const MachineInstr &MI)
Return true if pairing the given load or store is hinted to be unprofitable.
Register isStoreToStackSlotPostFE(const MachineInstr &MI, int &FrameIndex) const override
Check for post-frame ptr elimination stack locations as well.
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const override
void copyPhysRegTuple(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, llvm::ArrayRef< unsigned > Indices) const
bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
AArch64CC::CondCode insertCmpForCondBr(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, ArrayRef< MachineOperand > Cond) const
Inserts the compare instruction needed to un-fuse a fused conditional branch instruction and returns ...
bool optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask, int64_t CmpValue, const MachineRegisterInfo *MRI) const override
optimizeCompareInstr - Convert the instruction supplying the argument to the comparison into one that...
static unsigned getLoadStoreImmIdx(unsigned Opc)
Returns the index for the immediate for a given instruction.
static bool isGPRZero(const MachineInstr &MI)
Does this instruction set its full destination register to zero?
void copyGPRRegTuple(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, MCRegister DestReg, MCRegister SrcReg, bool KillSrc, unsigned Opcode, unsigned ZeroReg, llvm::ArrayRef< unsigned > Indices) const
bool getMemOperandWithOffsetWidth(const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset, bool &OffsetIsScalable, TypeSize &Width) const
If OffsetIsScalable is set to 'true', the offset is scaled by vscale.
bool analyzeCompare(const MachineInstr &MI, Register &SrcReg, Register &SrcReg2, int64_t &CmpMask, int64_t &CmpValue) const override
analyzeCompare - For a comparison instruction, return the source registers in SrcReg and SrcReg2,...
CombinerObjective getCombinerObjective(unsigned Pattern) const override
static bool isFpOrNEON(Register Reg)
Returns whether the physical register is FP or NEON.
bool isAsCheapAsAMove(const MachineInstr &MI) const override
std::optional< DestSourcePair > isCopyLikeInstrImpl(const MachineInstr &MI) const override
static void suppressLdStPair(MachineInstr &MI)
Hint that pairing the given load or store is unprofitable.
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
static bool isPreLd(const MachineInstr &MI)
Returns whether the instruction is a pre-indexed load.
bool optimizeCondBranch(MachineInstr &MI) const override
Replace csincr-branch sequence by simple conditional branch.
static int getMemScale(unsigned Opc)
Scaling factor for (scaled or unscaled) load or store.
bool isCandidateToMergeOrPair(const MachineInstr &MI) const
Return true if this is a load/store that can be potentially paired/merged.
MCInst getNop() const override
static const MachineOperand & getLdStBaseOp(const MachineInstr &MI)
Returns the base register operator of a load/store.
bool isReservedReg(const MachineFunction &MF, MCRegister Reg) const
const AArch64RegisterInfo * getRegisterInfo() const override
bool isNeonAvailable() const
Returns true if the target has NEON and the function at runtime is known to have NEON enabled (e....
bool isSVEorStreamingSVEAvailable() const
Returns true if the target has access to either the full range of SVE instructions,...
AArch64PAuth::AuthCheckMethod getAuthenticatedLRCheckMethod(const MachineFunction &MF) const
Choose a method of checking LR before performing a tail call.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
This is an important base class in LLVM.
Definition Constant.h:44
A debug info location.
Definition DebugLoc.h:126
bool empty() const
Definition DenseMap.h:716
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
LLVM_ABI void accumulate(const MachineInstr &MI)
Adds all register units used, defined or clobbered in MI.
static LocationSize precise(uint64_t Value)
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:69
static MCCFIInstruction cfiDefCfa(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa defines a rule for computing CFA as: take address from Register and add Offset to it.
Definition MCDwarf.h:630
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:672
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:645
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:758
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
static constexpr unsigned NoRegister
Definition MCRegister.h:62
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Set of metadata that should be preserved when using BuildMI().
bool isInlineAsmBrIndirectTarget() const
Returns true if this is the indirect dest of an INLINEASM_BR.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
reverse_instr_iterator instr_rbegin()
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
reverse_instr_iterator instr_rend()
Instructions::iterator instr_iterator
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
LLVM_ABI bool isLiveIn(MCRegister Reg, LaneBitmask LaneMask=LaneBitmask::getAll()) const
Return true if the specified register is in the live in set.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
void setStackID(int ObjectIdx, uint8_t ID)
bool isCalleeSavedInfoValid() const
Has the callee saved info been calculated yet?
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
unsigned getNumObjects() const
Return the number of objects.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool usesWindowsUnwindInfo() const
True if this function describes its unwind information with Windows SEH unwind opcodes (....
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
reverse_iterator getReverse() const
Get a reverse iterator to the same node.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
bool mayLoadOrStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read or modify memory.
const MachineBasicBlock * getParent() const
bool isCall(QueryType Type=AnyInBundle) const
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
LLVM_ABI uint32_t mergeFlagsWith(const MachineInstr &Other) const
Return the MIFlags which represent both MachineInstrs.
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
bool definesRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr fully defines the specified register.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
LLVM_ABI bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
LLVM_ABI bool isLoadFoldBarrier() const
Returns true if it is illegal to fold a load across this instruction.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI int findRegisterDefOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false) const
Returns the operand index that is a def of the specified register or -1 if it is not found.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const std::vector< MachineJumpTableEntry > & getJumpTables() const
A description of a memory reference used in the backend.
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
This class contains meta information specific to a module.
LLVM_ABI MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
void setIsDead(bool Val=true)
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
unsigned getTargetFlags() const
static MachineOperand CreateImm(int64_t Val)
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI bool hasOneNonDBGUse(Register RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug use of the specified register.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool reservedRegsFrozen() const
reservedRegsFrozen - Returns true after freezeReservedRegs() was called to ensure the set of reserved...
use_instr_nodbg_iterator use_instr_nodbg_begin(Register RegNo) const
const TargetRegisterClass * getRegClassOrNull(Register Reg) const
Return the register class of Reg, or null if Reg has not been assigned a register class yet.
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
Represents a location in source code.
Definition SMLoc.h:22
bool erase(PtrType Ptr)
Remove pointer from the set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool empty() const
Definition SmallSet.h:169
bool erase(const T &V)
Definition SmallSet.h:200
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:70
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:42
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Object returned by analyzeLoopForPipelining.
TargetInstrInfo - Interface to description of machine instruction set.
virtual void genAlternativeCodeSequence(MachineInstr &Root, unsigned Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstIdxForVirtReg) const
When getMachineCombinerPatterns() finds patterns, this function generates the instructions that could...
virtual std::optional< ParamLoadedValue > describeLoadedValue(const MachineInstr &MI, Register Reg) const
Produce the expression describing the MI loading a value into the physical register Reg.
virtual bool getMachineCombinerPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce) const
Return true when there is potentially a faster code sequence for an instruction chain ending in Root.
virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF, bool OutlineFromLinkOnceODRs) const
Return true if the function can safely be outlined from.
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
virtual CombinerObjective getCombinerObjective(unsigned Pattern) const
Return the objective of a combiner pattern.
virtual bool isFunctionSafeToSplit(const MachineFunction &MF) const
Return true if the function is a viable candidate for machine function splitting.
const MCAsmInfo & getMCAsmInfo() const
Return target specific asm information.
CodeModel::Model getCodeModel() const
Returns the code model.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Target - Wrapper for Target specific information.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition Triple.h:879
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:355
Value * getOperand(unsigned i) const
Definition User.h:207
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static CondCode getInvertedCondCode(CondCode Code)
@ MO_DLLIMPORT
MO_DLLIMPORT - On a symbol operand, this represents that the reference to the symbol is for an import...
@ MO_NC
MO_NC - Indicates whether the linker is expected to check the symbol reference for overflow.
@ MO_G1
MO_G1 - A symbol operand with this flag (granule 1) represents the bits 16-31 of a 64-bit address,...
@ MO_S
MO_S - Indicates that the bits of the symbol operand represented by MO_G0 etc are signed.
@ MO_PAGEOFF
MO_PAGEOFF - A symbol operand with this flag represents the offset of that symbol within a 4K page.
@ MO_GOT
MO_GOT - This flag indicates that a symbol operand represents the address of the GOT entry for the sy...
@ MO_PREL
MO_PREL - Indicates that the bits of the symbol operand represented by MO_G0 etc are PC relative.
@ MO_G0
MO_G0 - A symbol operand with this flag (granule 0) represents the bits 0-15 of a 64-bit address,...
@ MO_ARM64EC_CALLMANGLE
MO_ARM64EC_CALLMANGLE - Operand refers to the Arm64EC-mangled version of a symbol,...
@ MO_PAGE
MO_PAGE - A symbol operand with this flag represents the pc-relative offset of the 4K page containing...
@ MO_HI12
MO_HI12 - This flag indicates that a symbol operand represents the bits 13-24 of a 64-bit address,...
@ MO_TLS
MO_TLS - Indicates that the operand being accessed is some kind of thread-local symbol.
@ MO_G2
MO_G2 - A symbol operand with this flag (granule 2) represents the bits 32-47 of a 64-bit address,...
@ MO_TAGGED
MO_TAGGED - With MO_PAGE, indicates that the page includes a memory tag in bits 56-63.
@ MO_G3
MO_G3 - A symbol operand with this flag (granule 3) represents the high 16-bits of a 64-bit address,...
@ MO_COFFSTUB
MO_COFFSTUB - On a symbol operand "FOO", this indicates that the reference is actually to the "....
unsigned getCheckerSizeInBytes(AuthCheckMethod Method)
Returns the number of bytes added by checkAuthenticatedRegister.
static uint64_t decodeLogicalImmediate(uint64_t val, unsigned regSize)
decodeLogicalImmediate - Decode a logical immediate value in the form "N:immr:imms" (where the immr a...
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
static unsigned getArithExtendImm(AArch64_AM::ShiftExtendType ET, unsigned Imm)
getArithExtendImm - Encode the extend type and shift amount for an arithmetic instruction: imm: 3-bit...
constexpr bool isLegalArithImmed(const uint64_t C)
isLegalArithImmed -
static unsigned getArithShiftValue(unsigned Imm)
getArithShiftValue - get the arithmetic shift value.
static uint64_t encodeLogicalImmediate(uint64_t imm, unsigned regSize)
encodeLogicalImmediate - Return the encoded immediate value for a logical immediate instruction of th...
static AArch64_AM::ShiftExtendType getExtendType(unsigned Imm)
getExtendType - Extract the extend type for operands of arithmetic ops.
static AArch64_AM::ShiftExtendType getArithExtendType(unsigned Imm)
static AArch64_AM::ShiftExtendType getShiftType(unsigned Imm)
getShiftType - Extract the shift type.
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
void expandMOVAddr(unsigned Opcode, unsigned TargetFlags, bool IsTargetMachO, SmallVectorImpl< AddrInsnModel > &Insn)
void expandMOVImm(uint64_t Imm, unsigned BitSize, SmallVectorImpl< ImmInsnModel > &Insn)
Expand a MOVi32imm or MOVi64imm pseudo instruction to one or more real move-immediate instructions to...
static const uint64_t InstrFlagIsWhile
static const uint64_t InstrFlagIsPTestLike
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Init
Initialization function, sets up the coroutine frame.
Definition CodeView.h:644
constexpr double e
InstrType
Represents how an instruction should be mapped by the outliner.
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It, then continue incrementing it while it points to a debug instruction.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
static bool isCondBranchOpcode(int Opc)
MCCFIInstruction createDefCFA(const TargetRegisterInfo &TRI, unsigned FrameReg, unsigned Reg, const StackOffset &Offset, bool LastAdjustmentWasScalable=true)
static bool isPTrueOpcode(unsigned Opc)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
int isAArch64FrameOffsetLegal(const MachineInstr &MI, StackOffset &Offset, bool *OutUseUnscaledOp=nullptr, unsigned *OutUnscaledOp=nullptr, int64_t *EmittableOffset=nullptr)
Check if the Offset is a valid frame offset for MI.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
RegState
Flags to represent properties of register accesses.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
@ Define
Register definition.
@ Renamable
Register that may be renamed.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
constexpr RegState getKillRegState(bool B)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
static bool isIndirectBranchOpcode(int Opc)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
unsigned getBLRCallOpcode(const MachineFunction &MF)
Return opcode to be used for indirect calls.
@ AArch64FrameOffsetIsLegal
Offset is legal.
@ AArch64FrameOffsetCanUpdate
Offset can apply, at least partly.
@ AArch64FrameOffsetCannotUpdate
Offset cannot apply.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
Op::Description Desc
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
static bool isSEHInstruction(const MachineInstr &MI)
bool isLFIPrePostMemAccess(unsigned Opcode)
Returns true if Opcode is a pre- or post-indexed memory access that the LFI rewriter expands with a b...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
AArch64MachineCombinerPattern
@ MULSUBv8i16_OP2
@ FMULv4i16_indexed_OP1
@ FMLSv1i32_indexed_OP2
@ MULSUBv2i32_indexed_OP1
@ FMLAv2i32_indexed_OP2
@ MULADDv4i16_indexed_OP2
@ FMLAv1i64_indexed_OP1
@ MULSUBv16i8_OP1
@ FMLAv8i16_indexed_OP2
@ FMULv2i32_indexed_OP1
@ MULSUBv8i16_indexed_OP2
@ FMLAv1i64_indexed_OP2
@ MULSUBv4i16_indexed_OP2
@ FMLAv1i32_indexed_OP1
@ FMLAv2i64_indexed_OP2
@ FMLSv8i16_indexed_OP1
@ MULSUBv2i32_OP1
@ FMULv4i16_indexed_OP2
@ MULSUBv4i32_indexed_OP2
@ FMULv2i64_indexed_OP2
@ FMLAv4i32_indexed_OP1
@ MULADDv4i16_OP2
@ FMULv8i16_indexed_OP2
@ MULSUBv4i16_OP1
@ MULADDv4i32_OP2
@ MULADDv2i32_OP2
@ MULADDv16i8_OP2
@ FMLSv4i16_indexed_OP1
@ MULADDv16i8_OP1
@ FMLAv2i64_indexed_OP1
@ FMLAv1i32_indexed_OP2
@ FMLSv2i64_indexed_OP2
@ MULADDv2i32_OP1
@ MULADDv4i32_OP1
@ MULADDv2i32_indexed_OP1
@ MULSUBv16i8_OP2
@ MULADDv4i32_indexed_OP1
@ MULADDv2i32_indexed_OP2
@ FMLAv4i16_indexed_OP2
@ MULSUBv8i16_OP1
@ FMULv2i32_indexed_OP2
@ FMLSv2i32_indexed_OP2
@ FMLSv4i32_indexed_OP1
@ FMULv2i64_indexed_OP1
@ MULSUBv4i16_OP2
@ FMLSv4i16_indexed_OP2
@ FMLAv2i32_indexed_OP1
@ FMLSv2i32_indexed_OP1
@ FMLAv8i16_indexed_OP1
@ MULSUBv4i16_indexed_OP1
@ FMLSv4i32_indexed_OP2
@ MULADDv4i32_indexed_OP2
@ MULSUBv4i32_OP2
@ MULSUBv8i16_indexed_OP1
@ MULADDv8i16_OP2
@ MULSUBv2i32_indexed_OP2
@ FMULv4i32_indexed_OP2
@ FMLSv2i64_indexed_OP1
@ MULADDv4i16_OP1
@ FMLAv4i32_indexed_OP2
@ MULADDv8i16_indexed_OP1
@ FMULv4i32_indexed_OP1
@ FMLAv4i16_indexed_OP1
@ FMULv8i16_indexed_OP1
@ MULADDv8i16_OP1
@ MULSUBv4i32_indexed_OP1
@ MULSUBv4i32_OP1
@ FMLSv8i16_indexed_OP2
@ MULADDv8i16_indexed_OP2
@ MULSUBv2i32_OP2
@ FMLSv1i64_indexed_OP2
@ MULADDv4i16_indexed_OP1
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void emitFrameOffset(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, unsigned DestReg, unsigned SrcReg, StackOffset Offset, const TargetInstrInfo *TII, MachineInstr::MIFlag=MachineInstr::NoFlags, bool SetNZCV=false, bool NeedsWinCFI=false, bool *HasWinCFI=nullptr, bool EmitCFAOffset=false, StackOffset InitialOffset={}, unsigned FrameReg=AArch64::SP)
emitFrameOffset - Emit instructions as needed to set DestReg to SrcReg plus Offset.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr RegState getDefRegState(bool B)
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
std::optional< UsedNZCV > examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr, const TargetRegisterInfo &TRI, SmallVectorImpl< MachineInstr * > *CCUseInstrs=nullptr)
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
static MCRegister getXRegFromWReg(MCRegister Reg)
MCCFIInstruction createCFAOffset(const TargetRegisterInfo &MRI, unsigned Reg, const StackOffset &OffsetFromDefCFA, std::optional< int64_t > IncomingVGOffsetFromDefCFA)
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
static bool isUncondBranchOpcode(int Opc)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
bool rewriteAArch64FrameIndex(MachineInstr &MI, unsigned FrameRegIdx, unsigned FrameReg, StackOffset &Offset, const AArch64InstrInfo *TII)
rewriteAArch64FrameIndex - Rewrite MI to access 'Offset' bytes from the FP.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
static const MachineMemOperand::Flags MOSuppressPair
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
void appendLEB128(SmallVectorImpl< U > &Buffer, T Value)
Definition LEB128.h:280
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool optimizeTerminators(MachineBasicBlock *MBB, const TargetInstrInfo &TII)
std::pair< MachineOperand, DIExpression * > ParamLoadedValue
bool isNZCVTouchedInInstructionRange(const MachineInstr &DefMI, const MachineInstr &UseMI, const TargetRegisterInfo *TRI)
Return true if there is an instruction /after/ DefMI and before UseMI which either reads or clobbers ...
static const MachineMemOperand::Flags MOStridedAccess
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr RegState getUndefRegState(bool B)
void fullyRecomputeLiveIns(ArrayRef< MachineBasicBlock * > MBBs)
Convenience function for recomputing live-in's for a set of MBBs until the computation converges.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Used to describe addressing mode similar to ExtAddrMode in CodeGenPrepare.
LLVM_ABI static const MBBSectionID ColdSectionID
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getUnknownStack(MachineFunction &MF)
Stack memory without other information.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
An individual sequence of instructions to be replaced with a call to an outlined function.
MachineFunction * getMF() const
The information necessary to create an outlined function for some class of candidate.