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 // RET through LR may also expand to 2 instructions if a deferred LR guard
104 // is flushed before the return.
105 return 8;
106 case AArch64::RETAA:
107 case AArch64::RETAB:
108 // Authenticated returns expand to 3 instructions (authenticate + guard +
109 // ret).
110 return 12;
111 case AArch64::BRAA:
112 case AArch64::BRAAZ:
113 case AArch64::BRAB:
114 case AArch64::BRABZ:
115 case AArch64::BLRAA:
116 case AArch64::BLRAAZ:
117 case AArch64::BLRAB:
118 case AArch64::BLRABZ:
119 // Authenticated branches/calls expand to 3 instructions (authenticate +
120 // guard + branch).
121 return 12;
122 case AArch64::AUTIASP:
123 case AArch64::AUTIBSP:
124 case AArch64::AUTIAZ:
125 case AArch64::AUTIBZ:
126 case AArch64::XPACLRI:
127 // Authenticating LR expands to the instruction plus a deferred LR guard.
128 return 8;
129 case AArch64::SYSxt:
130 // VA-based DC/IC ops (op1=3, Cn=7, op2=1) expand to 2 instructions.
131 if (MI.getOperand(0).getImm() == 3 && MI.getOperand(1).getImm() == 7 &&
132 MI.getOperand(3).getImm() == 1)
133 return 8;
134 return std::nullopt;
135 default:
136 break;
137 }
138
139 // Detect instructions that explicitly define SP or LR.
140 bool ModifiesLR = false;
141 bool ModifiesSP = false;
142 for (const MachineOperand &MO : MI.defs()) {
143 if (!MO.isReg())
144 continue;
145 if (MO.getReg() == AArch64::LR)
146 ModifiesLR = true;
147 else if (MO.getReg() == AArch64::SP)
148 ModifiesSP = true;
149 }
150
151 // Memory accesses expand to a base-register guard plus the rewritten access
152 // (8 bytes), with an extra base-register update for pre/post-index forms (12
153 // bytes total). If the access also defines LR, an LR mask is appended (+4
154 // bytes). Depending on additional optimizations that the rewriter performs,
155 // this may be an overestimate.
156 if (MI.mayLoadOrStore()) {
157 unsigned Size = isLFIPrePostMemAccess(MI.getOpcode()) ? 12 : 8;
158 if (ModifiesLR)
159 Size += 4;
160 return Size;
161 }
162
163 // Non memory operations that modify LR or SP expand to 2 instructions.
164 if (ModifiesSP || ModifiesLR)
165 return 8;
166
167 // Default case: instructions that don't cause expansion.
168 // - TP accesses in LFI are a single load/store, so no expansion.
169 // - All remaining instructions are not rewritten.
170 return std::nullopt;
171}
172
173/// GetInstSize - Return the number of bytes of code the specified
174/// instruction may be. This returns the maximum number of bytes.
176 const MCInstrDesc &Desc = MI.getDesc();
177 if (!Desc.isPseudo() && !Subtarget.isLFI()) {
178 assert(Desc.getSize() == 4 && "Unexpected instruction size");
179 return 4;
180 }
181
182 const MachineBasicBlock &MBB = *MI.getParent();
183 const MachineFunction *MF = MBB.getParent();
184 const Function &F = MF->getFunction();
185 const MCAsmInfo &MAI = MF->getTarget().getMCAsmInfo();
186
187 {
188 auto Op = MI.getOpcode();
189 if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
190 return getInlineAsmLength(MI.getOperand(0).getSymbolName(), MAI);
191 }
192
193 // Meta-instructions emit no code.
194 if (MI.isMetaInstruction())
195 return 0;
196
197 // FIXME: We currently only handle pseudoinstructions that don't get expanded
198 // before the assembly printer.
199 unsigned NumBytes = 0;
200
201 // LFI rewriter expansions that supersede normal sizing.
202 const auto &STI = MF->getSubtarget<AArch64Subtarget>();
203 if (STI.isLFI())
204 if (auto Size = getLFIInstSizeInBytes(MI))
205 return *Size;
206
207 if (!MI.isBundle() && isTailCallReturnInst(MI)) {
208 NumBytes = Desc.getSize() ? Desc.getSize() : 4;
209
210 const auto *MFI = MF->getInfo<AArch64FunctionInfo>();
211 if (!MFI->shouldSignReturnAddress(*MF))
212 return NumBytes;
213
214 auto Method = STI.getAuthenticatedLRCheckMethod(*MF);
215 NumBytes += AArch64PAuth::getCheckerSizeInBytes(Method);
216 return NumBytes;
217 }
218
219 // Size should be preferably set in
220 // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
221 // Specific cases handle instructions of variable sizes
222 switch (Desc.getOpcode()) {
223 default:
224 if (Desc.getSize())
225 return Desc.getSize();
226
227 // Anything not explicitly designated otherwise (i.e. pseudo-instructions
228 // with fixed constant size but not specified in .td file) is a normal
229 // 4-byte insn.
230 NumBytes = 4;
231 break;
232 case TargetOpcode::STACKMAP:
233 // The upper bound for a stackmap intrinsic is the full length of its shadow
234 NumBytes = StackMapOpers(&MI).getNumPatchBytes();
235 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
236 break;
237 case TargetOpcode::PATCHPOINT:
238 // The size of the patchpoint intrinsic is the number of bytes requested
239 NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
240 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
241 break;
242 case TargetOpcode::STATEPOINT:
243 NumBytes = StatepointOpers(&MI).getNumPatchBytes();
244 assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
245 // No patch bytes means a normal call inst is emitted
246 if (NumBytes == 0)
247 NumBytes = 4;
248 break;
249 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
250 // If `patchable-function-entry` is set, PATCHABLE_FUNCTION_ENTER
251 // instructions are expanded to the specified number of NOPs. Otherwise,
252 // they are expanded to 36-byte XRay sleds.
253 NumBytes =
254 F.getFnAttributeAsParsedInteger("patchable-function-entry", 9) * 4;
255 break;
256 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
257 case TargetOpcode::PATCHABLE_TAIL_CALL:
258 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
259 // An XRay sled can be 4 bytes of alignment plus a 32-byte block.
260 NumBytes = 36;
261 break;
262 case TargetOpcode::PATCHABLE_EVENT_CALL:
263 // EVENT_CALL XRay sleds are exactly 6 instructions long (no alignment).
264 NumBytes = 24;
265 break;
266
267 case AArch64::SPACE:
268 NumBytes = MI.getOperand(1).getImm();
269 break;
270 case AArch64::MOVaddr:
271 case AArch64::MOVaddrJT:
272 case AArch64::MOVaddrCP:
273 case AArch64::MOVaddrBA:
274 case AArch64::MOVaddrTLS:
275 case AArch64::MOVaddrEXT: {
276 // Use the same logic as the pseudo expansion to count instructions.
279 MI.getOperand(1).getTargetFlags(),
280 Subtarget.isTargetMachO(), Insn);
281 NumBytes = Insn.size() * 4;
282 break;
283 }
284
285 case AArch64::MOVi32imm:
286 case AArch64::MOVi64imm: {
287 // Use the same logic as the pseudo expansion to count instructions.
288 unsigned BitSize = Desc.getOpcode() == AArch64::MOVi32imm ? 32 : 64;
290 AArch64_IMM::expandMOVImm(MI.getOperand(1).getImm(), BitSize, Insn);
291 NumBytes = Insn.size() * 4;
292 break;
293 }
294
295 case TargetOpcode::BUNDLE:
296 NumBytes = getInstBundleSize(MI);
297 break;
298 }
299
300 return NumBytes;
301}
302
305 // Block ends with fall-through condbranch.
306 switch (LastInst->getOpcode()) {
307 default:
308 llvm_unreachable("Unknown branch instruction?");
309 case AArch64::Bcc:
310 Target = LastInst->getOperand(1).getMBB();
311 Cond.push_back(LastInst->getOperand(0));
312 break;
313 case AArch64::CBZW:
314 case AArch64::CBZX:
315 case AArch64::CBNZW:
316 case AArch64::CBNZX:
317 Target = LastInst->getOperand(1).getMBB();
318 Cond.push_back(MachineOperand::CreateImm(-1));
319 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
320 Cond.push_back(LastInst->getOperand(0));
321 break;
322 case AArch64::TBZW:
323 case AArch64::TBZX:
324 case AArch64::TBNZW:
325 case AArch64::TBNZX:
326 Target = LastInst->getOperand(2).getMBB();
327 Cond.push_back(MachineOperand::CreateImm(-1));
328 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
329 Cond.push_back(LastInst->getOperand(0));
330 Cond.push_back(LastInst->getOperand(1));
331 break;
332 case AArch64::CBWPri:
333 case AArch64::CBXPri:
334 case AArch64::CBWPrr:
335 case AArch64::CBXPrr:
336 Target = LastInst->getOperand(3).getMBB();
337 Cond.push_back(MachineOperand::CreateImm(-1));
338 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
339 Cond.push_back(LastInst->getOperand(0));
340 Cond.push_back(LastInst->getOperand(1));
341 Cond.push_back(LastInst->getOperand(2));
342 break;
343 case AArch64::CBBAssertExt:
344 case AArch64::CBHAssertExt:
345 Target = LastInst->getOperand(3).getMBB();
346 Cond.push_back(MachineOperand::CreateImm(-1)); // -1
347 Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode())); // Opc
348 Cond.push_back(LastInst->getOperand(0)); // Cond
349 Cond.push_back(LastInst->getOperand(1)); // Op0
350 Cond.push_back(LastInst->getOperand(2)); // Op1
351 Cond.push_back(LastInst->getOperand(4)); // Ext0
352 Cond.push_back(LastInst->getOperand(5)); // Ext1
353 break;
354 }
355}
356
357static unsigned getBranchDisplacementBits(const AArch64Options &CLOpts,
358 unsigned Opc) {
359 switch (Opc) {
360 default:
361 llvm_unreachable("unexpected opcode!");
362 case AArch64::B:
363 return CLOpts.b_offset_bits;
364 case AArch64::TBNZW:
365 case AArch64::TBZW:
366 case AArch64::TBNZX:
367 case AArch64::TBZX:
368 return CLOpts.tbz_offset_bits;
369 case AArch64::CBNZW:
370 case AArch64::CBZW:
371 case AArch64::CBNZX:
372 case AArch64::CBZX:
373 return CLOpts.cbz_offset_bits;
374 case AArch64::Bcc:
375 return CLOpts.bcc_offset_bits;
376 case AArch64::CBWPri:
377 case AArch64::CBXPri:
378 case AArch64::CBBAssertExt:
379 case AArch64::CBHAssertExt:
380 case AArch64::CBWPrr:
381 case AArch64::CBXPrr:
382 return CLOpts.cb_offset_bits;
383 }
384}
385
387 int64_t BrOffset) const {
388 unsigned Bits = getBranchDisplacementBits(Subtarget.getCLOpts(), BranchOp);
389 assert(Bits >= 3 && "max branch displacement must be enough to jump"
390 "over conditional branch expansion");
391 return isIntN(Bits, BrOffset / 4);
392}
393
396 switch (MI.getOpcode()) {
397 default:
398 llvm_unreachable("unexpected opcode!");
399 case AArch64::B:
400 return MI.getOperand(0).getMBB();
401 case AArch64::TBZW:
402 case AArch64::TBNZW:
403 case AArch64::TBZX:
404 case AArch64::TBNZX:
405 return MI.getOperand(2).getMBB();
406 case AArch64::CBZW:
407 case AArch64::CBNZW:
408 case AArch64::CBZX:
409 case AArch64::CBNZX:
410 case AArch64::Bcc:
411 return MI.getOperand(1).getMBB();
412 case AArch64::CBWPri:
413 case AArch64::CBXPri:
414 case AArch64::CBBAssertExt:
415 case AArch64::CBHAssertExt:
416 case AArch64::CBWPrr:
417 case AArch64::CBXPrr:
418 return MI.getOperand(3).getMBB();
419 }
420}
421
423 MachineBasicBlock &NewDestBB,
424 MachineBasicBlock &RestoreBB,
425 const DebugLoc &DL,
426 int64_t BrOffset,
427 RegScavenger *RS) const {
428 assert(RS && "RegScavenger required for long branching");
429 assert(MBB.empty() &&
430 "new block should be inserted for expanding unconditional branch");
431 assert(MBB.pred_size() == 1);
432 assert(RestoreBB.empty() &&
433 "restore block should be inserted for restoring clobbered registers");
434
435 auto buildIndirectBranch = [&](Register Reg, MachineBasicBlock &DestBB) {
436 // Offsets outside of the signed 33-bit range are not supported for ADRP +
437 // ADD.
438 if (!isInt<33>(BrOffset))
440 "Branch offsets outside of the signed 33-bit range not supported");
441
442 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADRP), Reg)
443 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGE);
444 BuildMI(MBB, MBB.end(), DL, get(AArch64::ADDXri), Reg)
445 .addReg(Reg)
446 .addSym(DestBB.getSymbol(), AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
447 .addImm(0);
448 BuildMI(MBB, MBB.end(), DL, get(AArch64::BR)).addReg(Reg);
449 };
450
451 RS->enterBasicBlockEnd(MBB);
452 // If X16 is unused, we can rely on the linker to insert a range extension
453 // thunk if NewDestBB is out of range of a single B instruction.
454 constexpr Register Reg = AArch64::X16;
455 if (!RS->isRegUsed(Reg)) {
456 insertUnconditionalBranch(MBB, &NewDestBB, DL);
457 RS->setRegUsed(Reg);
458 return;
459 }
460
461 // In a cold block without BTI, insert the indirect branch if a register is
462 // free. Skip this if BTI is enabled to avoid inserting a BTI at the target,
463 // prioritizing a dynamic cost in cold code over a static cost in hot code.
464 AArch64FunctionInfo *AFI = MBB.getParent()->getInfo<AArch64FunctionInfo>();
465 bool HasBTI = AFI && AFI->branchTargetEnforcement();
466 if (MBB.getSectionID() == MBBSectionID::ColdSectionID && !HasBTI) {
467 Register Scavenged = RS->FindUnusedReg(&AArch64::GPR64RegClass);
468 if (Scavenged.isValid()) {
469 buildIndirectBranch(Scavenged, NewDestBB);
470 RS->setRegUsed(Scavenged);
471 return;
472 }
473 }
474
475 // Note: Spilling X16 briefly moves the stack pointer, making it incompatible
476 // with red zones.
477 if (!AFI || AFI->hasRedZone().value_or(true))
479 "Unable to insert indirect branch inside function that has red zone");
480
481 // Otherwise, spill X16 and defer range extension to the linker.
482 BuildMI(MBB, MBB.end(), DL, get(AArch64::STRXpre))
483 .addReg(AArch64::SP, RegState::Define)
484 .addReg(Reg)
485 .addReg(AArch64::SP)
486 .addImm(-16);
487
488 BuildMI(MBB, MBB.end(), DL, get(AArch64::B)).addMBB(&RestoreBB);
489
490 BuildMI(RestoreBB, RestoreBB.end(), DL, get(AArch64::LDRXpost))
491 .addReg(AArch64::SP, RegState::Define)
493 .addReg(AArch64::SP)
494 .addImm(16);
495}
496
497// Branch analysis.
500 MachineBasicBlock *&FBB,
502 bool AllowModify) const {
503 // If the block has no terminators, it just falls into the block after it.
504 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
505 if (I == MBB.end())
506 return false;
507
508 // Skip over SpeculationBarrierEndBB terminators
509 if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
510 I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
511 --I;
512 }
513
514 if (!isUnpredicatedTerminator(*I))
515 return false;
516
517 // Get the last instruction in the block.
518 MachineInstr *LastInst = &*I;
519
520 // If there is only one terminator instruction, process it.
521 unsigned LastOpc = LastInst->getOpcode();
522 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
523 if (isUncondBranchOpcode(LastOpc)) {
524 TBB = LastInst->getOperand(0).getMBB();
525 return false;
526 }
527 if (isCondBranchOpcode(LastOpc)) {
528 // Block ends with fall-through condbranch.
529 parseCondBranch(LastInst, TBB, Cond);
530 return false;
531 }
532 return true; // Can't handle indirect branch.
533 }
534
535 // Get the instruction before it if it is a terminator.
536 MachineInstr *SecondLastInst = &*I;
537 unsigned SecondLastOpc = SecondLastInst->getOpcode();
538
539 // If AllowModify is true and the block ends with two or more unconditional
540 // branches, delete all but the first unconditional branch.
541 if (AllowModify && isUncondBranchOpcode(LastOpc)) {
542 while (isUncondBranchOpcode(SecondLastOpc)) {
543 LastInst->eraseFromParent();
544 LastInst = SecondLastInst;
545 LastOpc = LastInst->getOpcode();
546 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
547 // Return now the only terminator is an unconditional branch.
548 TBB = LastInst->getOperand(0).getMBB();
549 return false;
550 }
551 SecondLastInst = &*I;
552 SecondLastOpc = SecondLastInst->getOpcode();
553 }
554 }
555
556 // If we're allowed to modify and the block ends in a unconditional branch
557 // which could simply fallthrough, remove the branch. (Note: This case only
558 // matters when we can't understand the whole sequence, otherwise it's also
559 // handled by BranchFolding.cpp.)
560 if (AllowModify && isUncondBranchOpcode(LastOpc) &&
561 MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
562 LastInst->eraseFromParent();
563 LastInst = SecondLastInst;
564 LastOpc = LastInst->getOpcode();
565 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
566 assert(!isUncondBranchOpcode(LastOpc) &&
567 "unreachable unconditional branches removed above");
568
569 if (isCondBranchOpcode(LastOpc)) {
570 // Block ends with fall-through condbranch.
571 parseCondBranch(LastInst, TBB, Cond);
572 return false;
573 }
574 return true; // Can't handle indirect branch.
575 }
576 SecondLastInst = &*I;
577 SecondLastOpc = SecondLastInst->getOpcode();
578 }
579
580 // If there are three terminators, we don't know what sort of block this is.
581 if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
582 return true;
583
584 // If the block ends with a B and a Bcc, handle it.
585 if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
586 parseCondBranch(SecondLastInst, TBB, Cond);
587 FBB = LastInst->getOperand(0).getMBB();
588 return false;
589 }
590
591 // If the block ends with two unconditional branches, handle it. The second
592 // one is not executed, so remove it.
593 if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
594 TBB = SecondLastInst->getOperand(0).getMBB();
595 I = LastInst;
596 if (AllowModify)
597 I->eraseFromParent();
598 return false;
599 }
600
601 // ...likewise if it ends with an indirect branch followed by an unconditional
602 // branch.
603 if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
604 I = LastInst;
605 if (AllowModify)
606 I->eraseFromParent();
607 return true;
608 }
609
610 // Otherwise, can't handle this.
611 return true;
612}
613
615 MachineBranchPredicate &MBP,
616 bool AllowModify) const {
617 // Use analyzeBranch to validate the branch pattern.
618 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
620 if (analyzeBranch(MBB, TBB, FBB, Cond, AllowModify))
621 return true;
622
623 // analyzeBranch returns success with empty Cond for unconditional branches.
624 if (Cond.empty())
625 return true;
626
627 MBP.TrueDest = TBB;
628 assert(MBP.TrueDest && "expected!");
629 MBP.FalseDest = FBB ? FBB : MBB.getNextNode();
630
631 MBP.ConditionDef = nullptr;
632 MBP.SingleUseCondition = false;
633
634 // Find the conditional branch. After analyzeBranch succeeds with non-empty
635 // Cond, there's exactly one conditional branch - either last (fallthrough)
636 // or second-to-last (followed by unconditional B).
637 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
638 if (I == MBB.end())
639 return true;
640
641 if (isUncondBranchOpcode(I->getOpcode())) {
642 if (I == MBB.begin())
643 return true;
644 --I;
645 }
646
647 MachineInstr *CondBranch = &*I;
648 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
649
650 switch (CondBranch->getOpcode()) {
651 default:
652 return true;
653
654 case AArch64::Bcc:
655 // Bcc takes the NZCV flag as the operand to branch on, walk up the
656 // instruction stream to find the last instruction to define NZCV.
658 if (MI.modifiesRegister(AArch64::NZCV, /*TRI=*/nullptr)) {
659 MBP.ConditionDef = &MI;
660 break;
661 }
662 }
663 return false;
664
665 case AArch64::CBZW:
666 case AArch64::CBZX:
667 case AArch64::CBNZW:
668 case AArch64::CBNZX: {
669 MBP.LHS = CondBranch->getOperand(0);
670 MBP.RHS = MachineOperand::CreateImm(0);
671 unsigned Opc = CondBranch->getOpcode();
672 MBP.Predicate = (Opc == AArch64::CBNZX || Opc == AArch64::CBNZW)
673 ? MachineBranchPredicate::PRED_NE
674 : MachineBranchPredicate::PRED_EQ;
675 Register CondReg = MBP.LHS.getReg();
676 if (CondReg.isVirtual())
677 MBP.ConditionDef = MRI.getVRegDef(CondReg);
678 return false;
679 }
680
681 case AArch64::TBZW:
682 case AArch64::TBZX:
683 case AArch64::TBNZW:
684 case AArch64::TBNZX: {
685 Register CondReg = CondBranch->getOperand(0).getReg();
686 if (CondReg.isVirtual())
687 MBP.ConditionDef = MRI.getVRegDef(CondReg);
688 return false;
689 }
690 }
691}
692
695 if (Cond[0].getImm() != -1) {
696 // Regular Bcc
699 } else {
700 // Folded compare-and-branch
701 switch (Cond[1].getImm()) {
702 default:
703 llvm_unreachable("Unknown conditional branch!");
704 case AArch64::CBZW:
705 Cond[1].setImm(AArch64::CBNZW);
706 break;
707 case AArch64::CBNZW:
708 Cond[1].setImm(AArch64::CBZW);
709 break;
710 case AArch64::CBZX:
711 Cond[1].setImm(AArch64::CBNZX);
712 break;
713 case AArch64::CBNZX:
714 Cond[1].setImm(AArch64::CBZX);
715 break;
716 case AArch64::TBZW:
717 Cond[1].setImm(AArch64::TBNZW);
718 break;
719 case AArch64::TBNZW:
720 Cond[1].setImm(AArch64::TBZW);
721 break;
722 case AArch64::TBZX:
723 Cond[1].setImm(AArch64::TBNZX);
724 break;
725 case AArch64::TBNZX:
726 Cond[1].setImm(AArch64::TBZX);
727 break;
728
729 // Cond is { -1, Opcode, CC, Op0, Op1, ... }
730 case AArch64::CBWPri:
731 case AArch64::CBXPri:
732 case AArch64::CBBAssertExt:
733 case AArch64::CBHAssertExt:
734 case AArch64::CBWPrr:
735 case AArch64::CBXPrr: {
736 // Pseudos using standard 4bit Arm condition codes
738 static_cast<AArch64CC::CondCode>(Cond[2].getImm());
740 }
741 }
742 }
743
744 return false;
745}
746
748 int *BytesRemoved) const {
749 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
750 if (I == MBB.end())
751 return 0;
752
753 if (!isUncondBranchOpcode(I->getOpcode()) &&
754 !isCondBranchOpcode(I->getOpcode()))
755 return 0;
756
757 // Remove the branch.
758 I->eraseFromParent();
759
760 I = MBB.end();
761
762 if (I == MBB.begin()) {
763 if (BytesRemoved)
764 *BytesRemoved = 4;
765 return 1;
766 }
767 --I;
768 if (!isCondBranchOpcode(I->getOpcode())) {
769 if (BytesRemoved)
770 *BytesRemoved = 4;
771 return 1;
772 }
773
774 // Remove the branch.
775 I->eraseFromParent();
776 if (BytesRemoved)
777 *BytesRemoved = 8;
778
779 return 2;
780}
781
782void AArch64InstrInfo::instantiateCondBranch(
785 if (Cond[0].getImm() != -1) {
786 // Regular Bcc
787 BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
788 } else {
789 // Folded compare-and-branch
790 // Note that we use addOperand instead of addReg to keep the flags.
791
792 // cbz, cbnz
793 const MachineInstrBuilder MIB =
794 BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
795
796 // tbz/tbnz
797 if (Cond.size() > 3)
798 MIB.add(Cond[3]);
799
800 // cb
801 if (Cond.size() > 4)
802 MIB.add(Cond[4]);
803
804 MIB.addMBB(TBB);
805
806 // cb[b,h]
807 if (Cond.size() > 5) {
808 MIB.addImm(Cond[5].getImm());
809 MIB.addImm(Cond[6].getImm());
810 }
811 }
812}
813
816 ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
817 // Shouldn't be a fall through.
818 assert(TBB && "insertBranch must not be told to insert a fallthrough");
819
820 if (!FBB) {
821 if (Cond.empty()) // Unconditional branch?
822 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
823 else
824 instantiateCondBranch(MBB, DL, TBB, Cond);
825
826 if (BytesAdded)
827 *BytesAdded = 4;
828
829 return 1;
830 }
831
832 // Two-way conditional branch.
833 instantiateCondBranch(MBB, DL, TBB, Cond);
834 BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
835
836 if (BytesAdded)
837 *BytesAdded = 8;
838
839 return 2;
840}
841
842#ifndef NDEBUG
844 switch (Ext) {
845 default:
846 return false;
847 case AArch64_AM::UXTB:
848 case AArch64_AM::SXTB:
849 return Opc == AArch64::CBBAssertExt;
850 case AArch64_AM::UXTH:
851 case AArch64_AM::SXTH:
852 return Opc == AArch64::CBHAssertExt;
853 }
854}
855#endif
856
860 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
861
862 // Parse the condition code, see parseCondBranch() above.
864 switch (Cond.size()) {
865 default:
866 llvm_unreachable("Unknown condition opcode in Cond");
867 case 1: // b.cc
869 break;
870 case 3: { // cbz/cbnz
871 // We must insert a compare against 0.
872 bool Is64Bit;
873 switch (Cond[1].getImm()) {
874 default:
875 llvm_unreachable("Unknown branch opcode in Cond");
876 case AArch64::CBZW:
877 Is64Bit = false;
879 break;
880 case AArch64::CBZX:
881 Is64Bit = true;
883 break;
884 case AArch64::CBNZW:
885 Is64Bit = false;
887 break;
888 case AArch64::CBNZX:
889 Is64Bit = true;
891 break;
892 }
893 Register SrcReg = Cond[2].getReg();
894 if (Is64Bit) {
895 // cmp reg, #0 is actually subs xzr, reg, #0.
896 MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
897 BuildMI(MBB, MI, DL, get(AArch64::SUBSXri), AArch64::XZR)
898 .addReg(SrcReg)
899 .addImm(0)
900 .addImm(0);
901 } else {
902 MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
903 BuildMI(MBB, MI, DL, get(AArch64::SUBSWri), AArch64::WZR)
904 .addReg(SrcReg)
905 .addImm(0)
906 .addImm(0);
907 }
908 } break;
909 case 4: { // tbz/tbnz
910 // We must insert a tst instruction.
911 switch (Cond[1].getImm()) {
912 default:
913 llvm_unreachable("Unknown branch opcode in Cond");
914 case AArch64::TBZW:
915 case AArch64::TBZX:
917 break;
918 case AArch64::TBNZW:
919 case AArch64::TBNZX:
921 break;
922 }
923 // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
924 if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
925 BuildMI(MBB, MI, DL, get(AArch64::ANDSWri), AArch64::WZR)
926 .addReg(Cond[2].getReg())
927 .addImm(
929 else
930 BuildMI(MBB, MI, DL, get(AArch64::ANDSXri), AArch64::XZR)
931 .addReg(Cond[2].getReg())
932 .addImm(
934 } break;
935 case 5: { // cb
936 // We must insert a cmp, that is a subs
937 // 0 1 2 3 4
938 // Cond is { -1, Opcode, CC, Op0, Op1 }
939 unsigned SubsOpc, SubsDestReg;
940 bool IsImm = false;
941 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
942 switch (Cond[1].getImm()) {
943 default:
944 llvm_unreachable("Unknown branch opcode in Cond");
945 case AArch64::CBWPri:
946 SubsOpc = AArch64::SUBSWri;
947 SubsDestReg = AArch64::WZR;
948 IsImm = true;
949 break;
950 case AArch64::CBXPri:
951 SubsOpc = AArch64::SUBSXri;
952 SubsDestReg = AArch64::XZR;
953 IsImm = true;
954 break;
955 case AArch64::CBWPrr:
956 SubsOpc = AArch64::SUBSWrr;
957 SubsDestReg = AArch64::WZR;
958 IsImm = false;
959 break;
960 case AArch64::CBXPrr:
961 SubsOpc = AArch64::SUBSXrr;
962 SubsDestReg = AArch64::XZR;
963 IsImm = false;
964 break;
965 }
966
967 if (IsImm) {
968 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
969 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
970 .addReg(Cond[3].getReg())
971 .addImm(Cond[4].getImm())
972 .addImm(0);
973 } else {
974 MRI.constrainRegClass(Cond[3].getReg(), getRegClass(get(SubsOpc), 1));
975 MRI.constrainRegClass(Cond[4].getReg(), getRegClass(get(SubsOpc), 2));
976 BuildMI(MBB, MI, DL, get(SubsOpc), SubsDestReg)
977 .addReg(Cond[3].getReg())
978 .addReg(Cond[4].getReg());
979 }
980 } break;
981 case 7: { // cb[b,h]
982 // We must insert a cmp, that is a subs, but also zero- or sign-extensions
983 // that have been folded. For the first operand we codegen an explicit
984 // extension, for the second operand we fold the extension into cmp.
985 // 0 1 2 3 4 5 6
986 // Cond is { -1, Opcode, CC, Op0, Op1, Ext0, Ext1 }
987
988 // We need a new register for the now explicitly extended register
989 Register Reg = Cond[3].getReg();
991 unsigned ExtOpc;
992 unsigned ExtBits;
993 AArch64_AM::ShiftExtendType ExtendType =
995 assert(isValidCBExtend(Cond[1].getImm(), ExtendType) &&
996 "Unexpected compare-and-branch instruction for extend type");
997 switch (ExtendType) {
998 default:
999 llvm_unreachable("Unknown shift-extend for CB instruction");
1000 case AArch64_AM::SXTB:
1001 ExtOpc = AArch64::SBFMWri;
1002 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1003 break;
1004 case AArch64_AM::SXTH:
1005 ExtOpc = AArch64::SBFMWri;
1006 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1007 break;
1008 case AArch64_AM::UXTB:
1009 ExtOpc = AArch64::ANDWri;
1010 ExtBits = AArch64_AM::encodeLogicalImmediate(0xff, 32);
1011 break;
1012 case AArch64_AM::UXTH:
1013 ExtOpc = AArch64::ANDWri;
1014 ExtBits = AArch64_AM::encodeLogicalImmediate(0xffff, 32);
1015 break;
1016 }
1017
1018 // Build the explicit extension of the first operand
1019 Reg = MRI.createVirtualRegister(&AArch64::GPR32commonRegClass);
1021 BuildMI(MBB, MI, DL, get(ExtOpc), Reg).addReg(Cond[3].getReg());
1022 if (ExtOpc != AArch64::ANDWri)
1023 MBBI.addImm(0);
1024 MBBI.addImm(ExtBits);
1025 }
1026
1027 // Now, subs with an extended second operand
1029 MRI.constrainRegClass(Reg, &AArch64::GPR32commonRegClass);
1030 AArch64_AM::ShiftExtendType ExtendType =
1032 assert(isValidCBExtend(Cond[1].getImm(), ExtendType) &&
1033 "Unexpected compare-and-branch instruction for extend type");
1034 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrx), AArch64::WZR)
1035 .addReg(Reg)
1036 .addReg(Cond[4].getReg())
1037 .addImm(AArch64_AM::getArithExtendImm(ExtendType, 0));
1038 } // If no extension is needed, just a regular subs
1039 else {
1040 BuildMI(MBB, MI, DL, get(AArch64::SUBSWrr), AArch64::WZR)
1041 .addReg(Reg)
1042 .addReg(Cond[4].getReg());
1043 }
1044
1045 CC = static_cast<AArch64CC::CondCode>(Cond[2].getImm());
1046 } break;
1047 }
1048 return CC;
1049}
1050
1052 const TargetInstrInfo &TII) {
1053 for (MachineInstr &MI : MBB->terminators()) {
1054 unsigned Opc = MI.getOpcode();
1055 switch (Opc) {
1056 case AArch64::CBZW:
1057 case AArch64::CBZX:
1058 case AArch64::TBZW:
1059 case AArch64::TBZX:
1060 // CBZ/TBZ with WZR/XZR -> unconditional B
1061 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1062 MI.getOperand(0).getReg() == AArch64::XZR) {
1063 DEBUG_WITH_TYPE("optimizeTerminators",
1064 dbgs() << "Removing always taken branch: " << MI);
1065 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1066 SmallVector<MachineBasicBlock *> Succs(MBB->successors());
1067 for (auto *S : Succs)
1068 if (S != Target)
1069 MBB->removeSuccessor(S);
1070 DebugLoc DL = MI.getDebugLoc();
1071 while (MBB->rbegin() != &MI)
1072 MBB->rbegin()->eraseFromParent();
1073 MI.eraseFromParent();
1074 BuildMI(MBB, DL, TII.get(AArch64::B)).addMBB(Target);
1075 return true;
1076 }
1077 break;
1078 case AArch64::CBNZW:
1079 case AArch64::CBNZX:
1080 case AArch64::TBNZW:
1081 case AArch64::TBNZX:
1082 // CBNZ/TBNZ with WZR/XZR -> never taken, remove branch and successor
1083 if (MI.getOperand(0).getReg() == AArch64::WZR ||
1084 MI.getOperand(0).getReg() == AArch64::XZR) {
1085 DEBUG_WITH_TYPE("optimizeTerminators",
1086 dbgs() << "Removing never taken branch: " << MI);
1087 MachineBasicBlock *Target = TII.getBranchDestBlock(MI);
1088 MI.getParent()->removeSuccessor(Target);
1089 MI.eraseFromParent();
1090 return true;
1091 }
1092 break;
1093 }
1094 }
1095 return false;
1096}
1097
1098// Find the original register that VReg is copied from.
1099static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
1100 while (Register::isVirtualRegister(VReg)) {
1101 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1102 if (!DefMI || !DefMI->isFullCopy())
1103 return VReg;
1104 VReg = DefMI->getOperand(1).getReg();
1105 }
1106 return VReg;
1107}
1108
1109// Determine if VReg is defined by an instruction that can be folded into a
1110// csel instruction. If so, return the folded opcode, and the replacement
1111// register.
1112static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
1113 unsigned *NewReg = nullptr) {
1114 VReg = removeCopies(MRI, VReg);
1115 if (!Register::isVirtualRegister(VReg))
1116 return 0;
1117
1118 bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
1119 const MachineInstr *DefMI = MRI.getVRegDef(VReg);
1120 if (!DefMI)
1121 return 0;
1122 unsigned Opc = 0;
1123 unsigned SrcReg = 0;
1124 switch (DefMI->getOpcode()) {
1125 case AArch64::SUBREG_TO_REG:
1126 // Check for the following way to define an 64-bit immediate:
1127 // %0:gpr32 = MOVi32imm 1
1128 // %1:gpr64 = SUBREG_TO_REG %0:gpr32, %subreg.sub_32
1129 if (!DefMI->getOperand(1).isReg())
1130 return 0;
1131 if (!DefMI->getOperand(2).isImm() ||
1132 DefMI->getOperand(2).getImm() != AArch64::sub_32)
1133 return 0;
1134 DefMI = MRI.getVRegDef(DefMI->getOperand(1).getReg());
1135 if (DefMI->getOpcode() != AArch64::MOVi32imm)
1136 return 0;
1137 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1138 return 0;
1139 assert(Is64Bit);
1140 SrcReg = AArch64::XZR;
1141 Opc = AArch64::CSINCXr;
1142 break;
1143
1144 case AArch64::MOVi32imm:
1145 case AArch64::MOVi64imm:
1146 if (!DefMI->getOperand(1).isImm() || DefMI->getOperand(1).getImm() != 1)
1147 return 0;
1148 SrcReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1149 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1150 break;
1151
1152 case AArch64::ADDSXri:
1153 case AArch64::ADDSWri:
1154 // if NZCV is used, do not fold.
1155 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1156 true) == -1)
1157 return 0;
1158 // fall-through to ADDXri and ADDWri.
1159 [[fallthrough]];
1160 case AArch64::ADDXri:
1161 case AArch64::ADDWri:
1162 // add x, 1 -> csinc.
1163 if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
1164 DefMI->getOperand(3).getImm() != 0)
1165 return 0;
1166 SrcReg = DefMI->getOperand(1).getReg();
1167 Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
1168 break;
1169
1170 case AArch64::ORNXrr:
1171 case AArch64::ORNWrr: {
1172 // not x -> csinv, represented as orn dst, xzr, src.
1173 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1174 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1175 return 0;
1176 SrcReg = DefMI->getOperand(2).getReg();
1177 Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
1178 break;
1179 }
1180
1181 case AArch64::SUBSXrr:
1182 case AArch64::SUBSWrr:
1183 // if NZCV is used, do not fold.
1184 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
1185 true) == -1)
1186 return 0;
1187 // fall-through to SUBXrr and SUBWrr.
1188 [[fallthrough]];
1189 case AArch64::SUBXrr:
1190 case AArch64::SUBWrr: {
1191 // neg x -> csneg, represented as sub dst, xzr, src.
1192 unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
1193 if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
1194 return 0;
1195 SrcReg = DefMI->getOperand(2).getReg();
1196 Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
1197 break;
1198 }
1199 default:
1200 return 0;
1201 }
1202 assert(Opc && SrcReg && "Missing parameters");
1203
1204 if (NewReg)
1205 *NewReg = SrcReg;
1206 return Opc;
1207}
1208
1211 Register DstReg, Register TrueReg,
1212 Register FalseReg,
1213 SelectExpansion &Exp) const {
1214 // Check register classes.
1215 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1216 const TargetRegisterClass *RC =
1217 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1218 if (!RC)
1219 return false;
1220
1221 // Also need to check the dest regclass, in case we're trying to optimize
1222 // something like:
1223 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
1224 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
1225 return false;
1226
1227 // Expanding cbz/tbz requires a flag setting instruction in addition to the
1228 // select, adding an extra cycle of latency on the condition.
1229 unsigned ExtraCondLat = Cond.size() != 1;
1230 Exp.NumInsts = 1 + ExtraCondLat;
1231 if (ExtraCondLat)
1232 Exp.ClobberedPhysRegs.push_back(AArch64::NZCV);
1233
1234 // GPRs are handled by csel.
1235 // FIXME: Fold in x+1, -x, and ~x when applicable.
1236 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
1237 AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
1238 // Single-cycle csel, csinc, csinv, and csneg.
1239 Exp.CondCycles = 1 + ExtraCondLat;
1240 Exp.TrueCycles = Exp.FalseCycles = 1;
1241 if (canFoldIntoCSel(MRI, TrueReg))
1242 Exp.TrueCycles = 0;
1243 else if (canFoldIntoCSel(MRI, FalseReg))
1244 Exp.FalseCycles = 0;
1245 return true;
1246 }
1247
1248 // Scalar floating point is handled by fcsel.
1249 // FIXME: Form fabs, fmin, and fmax when applicable.
1250 if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
1251 AArch64::FPR32RegClass.hasSubClassEq(RC)) {
1252 Exp.CondCycles = 5 + ExtraCondLat;
1253 Exp.TrueCycles = Exp.FalseCycles = 2;
1254 return true;
1255 }
1256
1257 // No single conditional move for a 128-bit vector, but we can emit a sequence
1258 // of csetm (~1), dup (~5, cross domain), bsl (~2).
1259 if (AArch64::FPR128RegClass.hasSubClassEq(RC) &&
1260 Subtarget.isNeonAvailable() &&
1261 !MBB.getParent()->getFunction().hasMinSize()) {
1262 Exp.CondCycles = 8 + ExtraCondLat;
1263 Exp.TrueCycles = Exp.FalseCycles = 2;
1264 Exp.NumInsts = 3 + ExtraCondLat;
1265 return true;
1266 }
1267
1268 return false;
1269}
1270
1273 const DebugLoc &DL, Register DstReg,
1275 Register TrueReg, Register FalseReg) const {
1276
1277 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1279
1280 // A 128-bit vector has no conditional move so blend the operands with a mask
1281 // built from the flags.
1282 if (MRI.constrainRegClass(DstReg, &AArch64::FPR128RegClass)) {
1283 assert(Subtarget.isNeonAvailable() && "Expected NEON for a vector select");
1284 MRI.constrainRegClass(TrueReg, &AArch64::FPR128RegClass);
1285 MRI.constrainRegClass(FalseReg, &AArch64::FPR128RegClass);
1286 Register CondSet = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1287 BuildMI(MBB, I, DL, get(AArch64::CSINVXr), CondSet)
1288 .addReg(AArch64::XZR)
1289 .addReg(AArch64::XZR)
1291 Register Mask = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
1292 BuildMI(MBB, I, DL, get(AArch64::DUPv2i64gpr), Mask).addReg(CondSet);
1293 BuildMI(MBB, I, DL, get(AArch64::BSPv16i8), DstReg)
1294 .addReg(Mask)
1295 .addReg(TrueReg)
1296 .addReg(FalseReg);
1297 return;
1298 }
1299
1300 unsigned Opc = 0;
1301 const TargetRegisterClass *RC = nullptr;
1302 bool TryFold = false;
1303 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
1304 RC = &AArch64::GPR64RegClass;
1305 Opc = AArch64::CSELXr;
1306 TryFold = true;
1307 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
1308 RC = &AArch64::GPR32RegClass;
1309 Opc = AArch64::CSELWr;
1310 TryFold = true;
1311 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
1312 RC = &AArch64::FPR64RegClass;
1313 Opc = AArch64::FCSELDrrr;
1314 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
1315 RC = &AArch64::FPR32RegClass;
1316 Opc = AArch64::FCSELSrrr;
1317 }
1318 assert(RC && "Unsupported regclass");
1319
1320 // Try folding simple instructions into the csel.
1321 if (TryFold) {
1322 unsigned NewReg = 0;
1323 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewReg);
1324 if (FoldedOpc) {
1325 // The folded opcodes csinc, csinc and csneg apply the operation to
1326 // FalseReg, so we need to invert the condition.
1328 TrueReg = FalseReg;
1329 } else
1330 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewReg);
1331
1332 // Fold the operation. Leave any dead instructions for DCE to clean up.
1333 if (FoldedOpc) {
1334 FalseReg = NewReg;
1335 Opc = FoldedOpc;
1336 // Extend the live range of NewReg.
1337 MRI.clearKillFlags(NewReg);
1338 }
1339 }
1340
1341 // Pull all virtual register into the appropriate class.
1342 MRI.constrainRegClass(TrueReg, RC);
1343 // FalseReg might be WZR or XZR if the folded operand is a literal 1.
1344 assert(
1345 (FalseReg.isVirtual() || FalseReg == AArch64::WZR ||
1346 FalseReg == AArch64::XZR) &&
1347 "FalseReg was folded into a non-virtual register other than WZR or XZR");
1348 if (FalseReg.isVirtual())
1349 MRI.constrainRegClass(FalseReg, RC);
1350
1351 // Insert the csel.
1352 BuildMI(MBB, I, DL, get(Opc), DstReg)
1353 .addReg(TrueReg)
1354 .addReg(FalseReg)
1355 .addImm(CC);
1356}
1357
1358// Return true if Imm can be loaded into a register by a "cheap" sequence of
1359// instructions. For now, "cheap" means at most two instructions.
1360static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize) {
1361 if (BitSize == 32)
1362 return true;
1363
1364 assert(BitSize == 64 && "Only bit sizes of 32 or 64 allowed");
1365 uint64_t Imm = static_cast<uint64_t>(MI.getOperand(1).getImm());
1367 AArch64_IMM::expandMOVImm(Imm, BitSize, Is);
1368
1369 return Is.size() <= 2;
1370}
1371
1372// Check if a COPY instruction is cheap.
1373static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI) {
1374 assert(MI.isCopy() && "Expected COPY instruction");
1375 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1376
1377 // Cross-bank copies (e.g., between GPR and FPR) are expensive on AArch64,
1378 // typically requiring an FMOV instruction with a 2-6 cycle latency.
1379 auto GetRegClass = [&](Register Reg) -> const TargetRegisterClass * {
1380 if (Reg.isVirtual())
1381 return MRI.getRegClass(Reg);
1382 if (Reg.isPhysical())
1383 return RI.getMinimalPhysRegClass(Reg);
1384 return nullptr;
1385 };
1386 const TargetRegisterClass *DstRC = GetRegClass(MI.getOperand(0).getReg());
1387 const TargetRegisterClass *SrcRC = GetRegClass(MI.getOperand(1).getReg());
1388 if (DstRC && SrcRC && !RI.getCommonSubClass(DstRC, SrcRC))
1389 return false;
1390
1391 return MI.isAsCheapAsAMove();
1392}
1393
1394// FIXME: this implementation should be micro-architecture dependent, so a
1395// micro-architecture target hook should be introduced here in future.
1397 if (Subtarget.hasExynosCheapAsMoveHandling()) {
1398 if (isExynosCheapAsMove(MI))
1399 return true;
1400 return MI.isAsCheapAsAMove();
1401 }
1402
1403 switch (MI.getOpcode()) {
1404 default:
1405 return MI.isAsCheapAsAMove();
1406
1407 case TargetOpcode::COPY:
1408 return isCheapCopy(MI, RI);
1409
1410 case AArch64::ADDWrs:
1411 case AArch64::ADDXrs:
1412 case AArch64::SUBWrs:
1413 case AArch64::SUBXrs:
1414 return Subtarget.hasALULSLFast() && MI.getOperand(3).getImm() <= 4;
1415
1416 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
1417 // ORRXri, it is as cheap as MOV.
1418 // Likewise if it can be expanded to MOVZ/MOVN/MOVK.
1419 case AArch64::MOVi32imm:
1420 return isCheapImmediate(MI, 32);
1421 case AArch64::MOVi64imm:
1422 return isCheapImmediate(MI, 64);
1423 }
1424}
1425
1426bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
1427 switch (MI.getOpcode()) {
1428 default:
1429 return false;
1430
1431 case AArch64::ADDWrs:
1432 case AArch64::ADDXrs:
1433 case AArch64::ADDSWrs:
1434 case AArch64::ADDSXrs: {
1435 unsigned Imm = MI.getOperand(3).getImm();
1436 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1437 if (ShiftVal == 0)
1438 return true;
1439 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
1440 }
1441
1442 case AArch64::ADDWrx:
1443 case AArch64::ADDXrx:
1444 case AArch64::ADDXrx64:
1445 case AArch64::ADDSWrx:
1446 case AArch64::ADDSXrx:
1447 case AArch64::ADDSXrx64: {
1448 unsigned Imm = MI.getOperand(3).getImm();
1450 default:
1451 return false;
1452 case AArch64_AM::UXTB:
1453 case AArch64_AM::UXTH:
1454 case AArch64_AM::UXTW:
1455 case AArch64_AM::UXTX:
1457 }
1458 }
1459
1460 case AArch64::SUBWrs:
1461 case AArch64::SUBSWrs: {
1462 unsigned Imm = MI.getOperand(3).getImm();
1463 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1464 return ShiftVal == 0 ||
1465 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
1466 }
1467
1468 case AArch64::SUBXrs:
1469 case AArch64::SUBSXrs: {
1470 unsigned Imm = MI.getOperand(3).getImm();
1471 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1472 return ShiftVal == 0 ||
1473 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
1474 }
1475
1476 case AArch64::SUBWrx:
1477 case AArch64::SUBXrx:
1478 case AArch64::SUBXrx64:
1479 case AArch64::SUBSWrx:
1480 case AArch64::SUBSXrx:
1481 case AArch64::SUBSXrx64: {
1482 unsigned Imm = MI.getOperand(3).getImm();
1484 default:
1485 return false;
1486 case AArch64_AM::UXTB:
1487 case AArch64_AM::UXTH:
1488 case AArch64_AM::UXTW:
1489 case AArch64_AM::UXTX:
1491 }
1492 }
1493
1494 case AArch64::LDRBBroW:
1495 case AArch64::LDRBBroX:
1496 case AArch64::LDRBroW:
1497 case AArch64::LDRBroX:
1498 case AArch64::LDRDroW:
1499 case AArch64::LDRDroX:
1500 case AArch64::LDRHHroW:
1501 case AArch64::LDRHHroX:
1502 case AArch64::LDRHroW:
1503 case AArch64::LDRHroX:
1504 case AArch64::LDRQroW:
1505 case AArch64::LDRQroX:
1506 case AArch64::LDRSBWroW:
1507 case AArch64::LDRSBWroX:
1508 case AArch64::LDRSBXroW:
1509 case AArch64::LDRSBXroX:
1510 case AArch64::LDRSHWroW:
1511 case AArch64::LDRSHWroX:
1512 case AArch64::LDRSHXroW:
1513 case AArch64::LDRSHXroX:
1514 case AArch64::LDRSWroW:
1515 case AArch64::LDRSWroX:
1516 case AArch64::LDRSroW:
1517 case AArch64::LDRSroX:
1518 case AArch64::LDRWroW:
1519 case AArch64::LDRWroX:
1520 case AArch64::LDRXroW:
1521 case AArch64::LDRXroX:
1522 case AArch64::PRFMroW:
1523 case AArch64::PRFMroX:
1524 case AArch64::STRBBroW:
1525 case AArch64::STRBBroX:
1526 case AArch64::STRBroW:
1527 case AArch64::STRBroX:
1528 case AArch64::STRDroW:
1529 case AArch64::STRDroX:
1530 case AArch64::STRHHroW:
1531 case AArch64::STRHHroX:
1532 case AArch64::STRHroW:
1533 case AArch64::STRHroX:
1534 case AArch64::STRQroW:
1535 case AArch64::STRQroX:
1536 case AArch64::STRSroW:
1537 case AArch64::STRSroX:
1538 case AArch64::STRWroW:
1539 case AArch64::STRWroX:
1540 case AArch64::STRXroW:
1541 case AArch64::STRXroX: {
1542 unsigned IsSigned = MI.getOperand(3).getImm();
1543 return !IsSigned;
1544 }
1545 }
1546}
1547
1548bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
1549 unsigned Opc = MI.getOpcode();
1550 switch (Opc) {
1551 default:
1552 return false;
1553 case AArch64::SEH_EndC:
1554 case AArch64::SEH_StackAlloc:
1555 case AArch64::SEH_SaveFPLR:
1556 case AArch64::SEH_SaveFPLR_X:
1557 case AArch64::SEH_SaveReg:
1558 case AArch64::SEH_SaveReg_X:
1559 case AArch64::SEH_SaveRegP:
1560 case AArch64::SEH_SaveRegP_X:
1561 case AArch64::SEH_SaveFReg:
1562 case AArch64::SEH_SaveFReg_X:
1563 case AArch64::SEH_SaveFRegP:
1564 case AArch64::SEH_SaveFRegP_X:
1565 case AArch64::SEH_SetFP:
1566 case AArch64::SEH_AddFP:
1567 case AArch64::SEH_Nop:
1568 case AArch64::SEH_PrologEnd:
1569 case AArch64::SEH_EpilogStart:
1570 case AArch64::SEH_EpilogEnd:
1571 case AArch64::SEH_PACSignLR:
1572 case AArch64::SEH_SaveAnyRegI:
1573 case AArch64::SEH_SaveAnyRegIP:
1574 case AArch64::SEH_SaveAnyRegQ:
1575 case AArch64::SEH_SaveAnyRegQX:
1576 case AArch64::SEH_SaveAnyRegQP:
1577 case AArch64::SEH_SaveAnyRegQPX:
1578 case AArch64::SEH_AllocZ:
1579 case AArch64::SEH_SaveZReg:
1580 case AArch64::SEH_SavePReg:
1581 return true;
1582 }
1583}
1584
1586 Register &SrcReg, Register &DstReg,
1587 unsigned &SubIdx) const {
1588 switch (MI.getOpcode()) {
1589 default:
1590 return false;
1591 case AArch64::SBFMXri: // aka sxtw
1592 case AArch64::UBFMXri: // aka uxtw
1593 // Check for the 32 -> 64 bit extension case, these instructions can do
1594 // much more.
1595 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1596 return false;
1597 // This is a signed or unsigned 32 -> 64 bit extension.
1598 SrcReg = MI.getOperand(1).getReg();
1599 DstReg = MI.getOperand(0).getReg();
1600 SubIdx = AArch64::sub_32;
1601 return true;
1602 }
1603}
1604
1606 const MachineInstr &MIa, const MachineInstr &MIb) const {
1607 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1608 int64_t OffsetA = 0, OffsetB = 0;
1609 TypeSize WidthA(0, false), WidthB(0, false);
1610 bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1611
1612 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1613 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1614
1617 return false;
1618
1619 // Retrieve the base, offset from the base and width. Width
1620 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
1621 // base are identical, and the offset of a lower memory access +
1622 // the width doesn't overlap the offset of a higher memory access,
1623 // then the memory accesses are different.
1624 // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1625 // are assumed to have the same scale (vscale).
1626 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1627 WidthA) &&
1628 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1629 WidthB)) {
1630 if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1631 OffsetAIsScalable == OffsetBIsScalable) {
1632 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1633 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1634 TypeSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1635 if (LowWidth.isScalable() == OffsetAIsScalable &&
1636 LowOffset + (int)LowWidth.getKnownMinValue() <= HighOffset)
1637 return true;
1638 }
1639 }
1640 return false;
1641}
1642
1644 const MachineBasicBlock *MBB,
1645 const MachineFunction &MF) const {
1647 return true;
1648
1649 // Do not move an instruction that can be recognized as a branch target.
1650 if (hasBTISemantics(MI))
1651 return true;
1652
1653 switch (MI.getOpcode()) {
1654 case AArch64::HINT:
1655 // CSDB hints are scheduling barriers.
1656 if (MI.getOperand(0).getImm() == 0x14)
1657 return true;
1658 break;
1659 case AArch64::DSB:
1660 case AArch64::ISB:
1661 // DSB and ISB also are scheduling barriers.
1662 return true;
1663 case AArch64::MSRpstatesvcrImm1:
1664 // SMSTART and SMSTOP are also scheduling barriers.
1665 return true;
1666 default:;
1667 }
1668 if (isSEHInstruction(MI))
1669 return true;
1670 // Skip debug instructions and pseudo probes so they do not change
1671 // scheduling regions.
1672 auto Next = next_nodbg(MI.getIterator(), MBB->instr_end());
1673 return Next != MBB->instr_end() && Next->isCFIInstruction();
1674}
1675
1676/// analyzeCompare - For a comparison instruction, return the source registers
1677/// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1678/// Return true if the comparison instruction can be analyzed.
1680 Register &SrcReg2, int64_t &CmpMask,
1681 int64_t &CmpValue) const {
1682 // The first operand can be a frame index where we'd normally expect a
1683 // register.
1684 // FIXME: Pass subregisters out of analyzeCompare
1685 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1686 if (!MI.getOperand(1).isReg() || MI.getOperand(1).getSubReg())
1687 return false;
1688
1689 switch (MI.getOpcode()) {
1690 default:
1691 break;
1692 case AArch64::PTEST_PP:
1693 case AArch64::PTEST_PP_ANY:
1694 case AArch64::PTEST_PP_FIRST:
1695 SrcReg = MI.getOperand(0).getReg();
1696 SrcReg2 = MI.getOperand(1).getReg();
1697 if (MI.getOperand(2).getSubReg())
1698 return false;
1699
1700 // Not sure about the mask and value for now...
1701 CmpMask = ~0;
1702 CmpValue = 0;
1703 return true;
1704 case AArch64::SUBSWrr:
1705 case AArch64::SUBSWrs:
1706 case AArch64::SUBSWrx:
1707 case AArch64::SUBSXrr:
1708 case AArch64::SUBSXrs:
1709 case AArch64::SUBSXrx:
1710 case AArch64::ADDSWrr:
1711 case AArch64::ADDSWrs:
1712 case AArch64::ADDSWrx:
1713 case AArch64::ADDSXrr:
1714 case AArch64::ADDSXrs:
1715 case AArch64::ADDSXrx:
1716 // Replace SUBSWrr with SUBWrr if NZCV is not used.
1717 SrcReg = MI.getOperand(1).getReg();
1718 SrcReg2 = MI.getOperand(2).getReg();
1719
1720 // FIXME: Pass subregisters out of analyzeCompare
1721 if (MI.getOperand(2).getSubReg())
1722 return false;
1723
1724 CmpMask = ~0;
1725 CmpValue = 0;
1726 return true;
1727 case AArch64::SUBSWri:
1728 case AArch64::ADDSWri:
1729 case AArch64::SUBSXri:
1730 case AArch64::ADDSXri:
1731 SrcReg = MI.getOperand(1).getReg();
1732 SrcReg2 = 0;
1733 CmpMask = ~0;
1734 CmpValue = MI.getOperand(2).getImm();
1735 return true;
1736 case AArch64::ANDSWri:
1737 case AArch64::ANDSXri:
1738 // ANDS does not use the same encoding scheme as the others xxxS
1739 // instructions.
1740 SrcReg = MI.getOperand(1).getReg();
1741 SrcReg2 = 0;
1742 CmpMask = ~0;
1744 MI.getOperand(2).getImm(),
1745 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1746 return true;
1747 }
1748
1749 return false;
1750}
1751
1753 MachineBasicBlock *MBB = Instr.getParent();
1754 assert(MBB && "Can't get MachineBasicBlock here");
1755 MachineFunction *MF = MBB->getParent();
1756 assert(MF && "Can't get MachineFunction here");
1760
1761 for (const auto &[OpIdx, MO] : enumerate(Instr.operands())) {
1762 if (!MO.isReg() || !MO.getReg().isVirtual())
1763 continue;
1764
1765 Register Reg = MO.getReg();
1766 const TargetRegisterClass *NewRC = Instr.getRegClassConstraintEffect(
1767 OpIdx, MRI->getRegClass(Reg), TII, TRI);
1768 if (!NewRC || !MRI->constrainRegClass(Reg, NewRC))
1769 llvm_unreachable("Operand register classes are incompatible");
1770 }
1771}
1772
1773/// Return the opcode that does not set flags when possible - otherwise
1774/// return the original opcode. The caller is responsible to do the actual
1775/// substitution and legality checking.
1777 // Don't convert all compare instructions, because for some the zero register
1778 // encoding becomes the sp register.
1779 bool MIDefinesZeroReg = false;
1780 if (MI.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
1781 MI.definesRegister(AArch64::XZR, /*TRI=*/nullptr))
1782 MIDefinesZeroReg = true;
1783
1784 switch (MI.getOpcode()) {
1785 default:
1786 return MI.getOpcode();
1787 case AArch64::ADDSWrr:
1788 return AArch64::ADDWrr;
1789 case AArch64::ADDSWri:
1790 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1791 case AArch64::ADDSWrs:
1792 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1793 case AArch64::ADDSWrx:
1794 return AArch64::ADDWrx;
1795 case AArch64::ADDSXrr:
1796 return AArch64::ADDXrr;
1797 case AArch64::ADDSXri:
1798 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1799 case AArch64::ADDSXrs:
1800 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1801 case AArch64::ADDSXrx:
1802 return AArch64::ADDXrx;
1803 case AArch64::SUBSWrr:
1804 return AArch64::SUBWrr;
1805 case AArch64::SUBSWri:
1806 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1807 case AArch64::SUBSWrs:
1808 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1809 case AArch64::SUBSWrx:
1810 return AArch64::SUBWrx;
1811 case AArch64::SUBSXrr:
1812 return AArch64::SUBXrr;
1813 case AArch64::SUBSXri:
1814 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1815 case AArch64::SUBSXrs:
1816 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1817 case AArch64::SUBSXrx:
1818 return AArch64::SUBXrx;
1819 }
1820}
1821
1822enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1823
1824/// True when condition flags are accessed (either by writing or reading)
1825/// on the instruction trace starting at From and ending at To.
1826///
1827/// Note: If From and To are from different blocks it's assumed CC are accessed
1828/// on the path.
1831 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1832 // Early exit if To is at the beginning of the BB.
1833 if (To == To->getParent()->begin())
1834 return true;
1835
1836 // Check whether the instructions are in the same basic block
1837 // If not, assume the condition flags might get modified somewhere.
1838 if (To->getParent() != From->getParent())
1839 return true;
1840
1841 // From must be above To.
1842 assert(std::any_of(
1843 ++To.getReverse(), To->getParent()->rend(),
1844 [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1845
1846 // We iterate backward starting at \p To until we hit \p From.
1847 for (const MachineInstr &Instr :
1849 if (((AccessToCheck & AK_Write) &&
1850 Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1851 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1852 return true;
1853 }
1854 return false;
1855}
1856
1857std::optional<unsigned>
1858AArch64InstrInfo::canRemovePTestInstr(MachineInstr *PTest, MachineInstr *Mask,
1860 const MachineRegisterInfo *MRI) const {
1861 unsigned MaskOpcode = Mask->getOpcode();
1862 unsigned PredOpcode = Pred->getOpcode();
1863 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1864 bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1865
1866 if (PredIsWhileLike) {
1867 // For PTEST(PG, PG), PTEST is redundant when PG is the result of a WHILEcc
1868 // instruction and the condition is "any" since WHILcc does an implicit
1869 // PTEST(ALL, PG) check and PG is always a subset of ALL.
1870 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1871 return PredOpcode;
1872
1873 // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
1874 // redundant since WHILE performs an implicit PTEST with an all active
1875 // mask.
1876 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1877 getElementSizeForOpcode(MaskOpcode) ==
1878 getElementSizeForOpcode(PredOpcode))
1879 return PredOpcode;
1880
1881 // For PTEST_FIRST(PTRUE_ALL, WHILE), the PTEST_FIRST is redundant since
1882 // WHILEcc performs an implicit PTEST with an all active mask, setting
1883 // the N flag as the PTEST_FIRST would.
1884 if (PTest->getOpcode() == AArch64::PTEST_PP_FIRST &&
1885 isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31)
1886 return PredOpcode;
1887
1888 return {};
1889 }
1890
1891 if (PredIsPTestLike) {
1892 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1893 // instruction that sets the flags as PTEST would and the condition is
1894 // "any" since PG is always a subset of the governing predicate of the
1895 // ptest-like instruction.
1896 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1897 return PredOpcode;
1898
1899 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1900
1901 // If the PTEST like instruction's general predicate is not `Mask`, attempt
1902 // to look through a copy and try again. This is because some instructions
1903 // take a predicate whose register class is a subset of its result class.
1904 if (Mask != PTestLikeMask && PTestLikeMask->isFullCopy() &&
1905 PTestLikeMask->getOperand(1).getReg().isVirtual())
1906 PTestLikeMask =
1907 MRI->getUniqueVRegDef(PTestLikeMask->getOperand(1).getReg());
1908
1909 // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
1910 // the element size matches and either the PTEST_LIKE instruction uses
1911 // the same all active mask or the condition is "any".
1912 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1913 getElementSizeForOpcode(MaskOpcode) ==
1914 getElementSizeForOpcode(PredOpcode)) {
1915 if (Mask == PTestLikeMask || PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1916 return PredOpcode;
1917 }
1918
1919 // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
1920 // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
1921 // on 8-bit predicates like the PTEST. Otherwise, for instructions like
1922 // compare that also support 16/32/64-bit predicates, the implicit PTEST
1923 // performed by the compare could consider fewer lanes for these element
1924 // sizes.
1925 //
1926 // For example, consider
1927 //
1928 // ptrue p0.b ; P0=1111-1111-1111-1111
1929 // index z0.s, #0, #1 ; Z0=<0,1,2,3>
1930 // index z1.s, #1, #1 ; Z1=<1,2,3,4>
1931 // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
1932 // ; ^ last active
1933 // ptest p0, p1.b ; P1=0001-0001-0001-0001
1934 // ; ^ last active
1935 //
1936 // where the compare generates a canonical all active 32-bit predicate
1937 // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
1938 // active flag, whereas the PTEST instruction with the same mask doesn't.
1939 // For PTEST_ANY this doesn't apply as the flags in this case would be
1940 // identical regardless of element size.
1941 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1942 if (Mask == PTestLikeMask && (PredElementSize == AArch64::ElementSizeB ||
1943 PTest->getOpcode() == AArch64::PTEST_PP_ANY))
1944 return PredOpcode;
1945
1946 return {};
1947 }
1948
1949 // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
1950 // opcode so the PTEST becomes redundant.
1951 switch (PredOpcode) {
1952 case AArch64::AND_PPzPP:
1953 case AArch64::BIC_PPzPP:
1954 case AArch64::EOR_PPzPP:
1955 case AArch64::NAND_PPzPP:
1956 case AArch64::NOR_PPzPP:
1957 case AArch64::ORN_PPzPP:
1958 case AArch64::ORR_PPzPP:
1959 case AArch64::BRKA_PPzP:
1960 case AArch64::BRKPA_PPzPP:
1961 case AArch64::BRKB_PPzP:
1962 case AArch64::BRKPB_PPzPP:
1963 case AArch64::RDFFR_PPz: {
1964 // Check to see if our mask is the same. If not the resulting flag bits
1965 // may be different and we can't remove the ptest.
1966 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1967 if (Mask != PredMask)
1968 return {};
1969 break;
1970 }
1971 case AArch64::BRKN_PPzP: {
1972 // BRKN uses an all active implicit mask to set flags unlike the other
1973 // flag-setting instructions.
1974 // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
1975 if ((MaskOpcode != AArch64::PTRUE_B) ||
1976 (Mask->getOperand(1).getImm() != 31))
1977 return {};
1978 break;
1979 }
1980 case AArch64::PTRUE_B:
1981 // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
1982 break;
1983 default:
1984 // Bail out if we don't recognize the input
1985 return {};
1986 }
1987
1988 return convertToFlagSettingOpc(PredOpcode);
1989}
1990
1991/// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
1992/// operation which could set the flags in an identical manner
1993bool AArch64InstrInfo::optimizePTestInstr(
1994 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
1995 const MachineRegisterInfo *MRI) const {
1996 auto *Mask = MRI->getUniqueVRegDef(MaskReg);
1997 auto *Pred = MRI->getUniqueVRegDef(PredReg);
1998
1999 if (Pred->isCopy() && PTest->getOpcode() == AArch64::PTEST_PP_FIRST) {
2000 // Instructions which return a multi-vector (e.g. WHILECC_x2) require copies
2001 // before the branch to extract each subregister.
2002 auto Op = Pred->getOperand(1);
2003 if (Op.isReg() && Op.getReg().isVirtual() &&
2004 Op.getSubReg() == AArch64::psub0)
2005 Pred = MRI->getUniqueVRegDef(Op.getReg());
2006 }
2007
2008 unsigned PredOpcode = Pred->getOpcode();
2009 auto NewOp = canRemovePTestInstr(PTest, Mask, Pred, MRI);
2010 if (!NewOp)
2011 return false;
2012
2013 const TargetRegisterInfo *TRI = &getRegisterInfo();
2014
2015 // If another instruction between Pred and PTest accesses flags, don't remove
2016 // the ptest or update the earlier instruction to modify them.
2018 return false;
2019
2020 // If we pass all the checks, it's safe to remove the PTEST and use the flags
2021 // as they are prior to PTEST. Sometimes this requires the tested PTEST
2022 // operand to be replaced with an equivalent instruction that also sets the
2023 // flags.
2024 PTest->eraseFromParent();
2025 if (*NewOp != PredOpcode) {
2026 Pred->setDesc(get(*NewOp));
2028 Pred->addRegisterDefined(AArch64::NZCV, TRI);
2029 }
2030
2031 // Ensure that the flags def is live.
2032 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
2033 unsigned i = 0, e = Pred->getNumOperands();
2034 for (; i != e; ++i) {
2035 MachineOperand &MO = Pred->getOperand(i);
2036 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
2037 MO.setIsDead(false);
2038 break;
2039 }
2040 }
2041 }
2042 return true;
2043}
2044
2045/// Try to optimize a compare instruction. A compare instruction is an
2046/// instruction which produces AArch64::NZCV. It can be truly compare
2047/// instruction
2048/// when there are no uses of its destination register.
2049///
2050/// The following steps are tried in order:
2051/// 1. Convert CmpInstr into an unconditional version.
2052/// 2. Remove CmpInstr if above there is an instruction producing a needed
2053/// condition code or an instruction which can be converted into such an
2054/// instruction.
2055/// Only comparison with zero is supported.
2057 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
2058 int64_t CmpValue, const MachineRegisterInfo *MRI) const {
2059 assert(CmpInstr.getParent());
2060 assert(MRI);
2061
2062 // Replace SUBSWrr with SUBWrr if NZCV is not used.
2063 int DeadNZCVIdx =
2064 CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
2065 if (DeadNZCVIdx != -1) {
2066 if (CmpInstr.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
2067 CmpInstr.definesRegister(AArch64::XZR, /*TRI=*/nullptr)) {
2068 CmpInstr.eraseFromParent();
2069 return true;
2070 }
2071 unsigned Opc = CmpInstr.getOpcode();
2072 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
2073 if (NewOpc == Opc)
2074 return false;
2075 const MCInstrDesc &MCID = get(NewOpc);
2076 CmpInstr.setDesc(MCID);
2077 CmpInstr.removeOperand(DeadNZCVIdx);
2078 updateOperandRegClass(CmpInstr);
2079 return true;
2080 }
2081
2082 if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
2083 CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY ||
2084 CmpInstr.getOpcode() == AArch64::PTEST_PP_FIRST)
2085 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
2086
2087 if (SrcReg2 != 0)
2088 return false;
2089
2090 // CmpInstr is a Compare instruction if destination register is not used.
2091 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
2092 return false;
2093
2094 if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
2095 return true;
2096 return (CmpValue == 0 || CmpValue == 1) &&
2097 removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
2098}
2099
2100/// Get opcode of S version of Instr.
2101/// If Instr is S version its opcode is returned.
2102/// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
2103/// or we are not interested in it.
2104static unsigned sForm(MachineInstr &Instr) {
2105 switch (Instr.getOpcode()) {
2106 default:
2107 return AArch64::INSTRUCTION_LIST_END;
2108
2109 case AArch64::ADDSWrr:
2110 case AArch64::ADDSWri:
2111 case AArch64::ADDSXrr:
2112 case AArch64::ADDSXri:
2113 case AArch64::ADDSWrx:
2114 case AArch64::ADDSXrx:
2115 case AArch64::ADDSWrs:
2116 case AArch64::ADDSXrs:
2117 case AArch64::SUBSWrr:
2118 case AArch64::SUBSWri:
2119 case AArch64::SUBSWrx:
2120 case AArch64::SUBSWrs:
2121 case AArch64::SUBSXrr:
2122 case AArch64::SUBSXri:
2123 case AArch64::SUBSXrx:
2124 case AArch64::SUBSXrs:
2125 case AArch64::ANDSWri:
2126 case AArch64::ANDSWrr:
2127 case AArch64::ANDSWrs:
2128 case AArch64::ANDSXri:
2129 case AArch64::ANDSXrr:
2130 case AArch64::ANDSXrs:
2131 case AArch64::BICSWrr:
2132 case AArch64::BICSXrr:
2133 case AArch64::BICSWrs:
2134 case AArch64::BICSXrs:
2135 case AArch64::ADCSWr:
2136 case AArch64::ADCSXr:
2137 case AArch64::SBCSWr:
2138 case AArch64::SBCSXr:
2139 return Instr.getOpcode();
2140
2141 case AArch64::ADDWrr:
2142 return AArch64::ADDSWrr;
2143 case AArch64::ADDWri:
2144 return AArch64::ADDSWri;
2145 case AArch64::ADDXrr:
2146 return AArch64::ADDSXrr;
2147 case AArch64::ADDXri:
2148 return AArch64::ADDSXri;
2149 case AArch64::ADDWrx:
2150 return AArch64::ADDSWrx;
2151 case AArch64::ADDXrx:
2152 return AArch64::ADDSXrx;
2153 case AArch64::ADDWrs:
2154 return AArch64::ADDSWrs;
2155 case AArch64::ADDXrs:
2156 return AArch64::ADDSXrs;
2157 case AArch64::ADCWr:
2158 return AArch64::ADCSWr;
2159 case AArch64::ADCXr:
2160 return AArch64::ADCSXr;
2161 case AArch64::SUBWrr:
2162 return AArch64::SUBSWrr;
2163 case AArch64::SUBWri:
2164 return AArch64::SUBSWri;
2165 case AArch64::SUBXrr:
2166 return AArch64::SUBSXrr;
2167 case AArch64::SUBXri:
2168 return AArch64::SUBSXri;
2169 case AArch64::SUBWrx:
2170 return AArch64::SUBSWrx;
2171 case AArch64::SUBXrx:
2172 return AArch64::SUBSXrx;
2173 case AArch64::SUBWrs:
2174 return AArch64::SUBSWrs;
2175 case AArch64::SUBXrs:
2176 return AArch64::SUBSXrs;
2177 case AArch64::SBCWr:
2178 return AArch64::SBCSWr;
2179 case AArch64::SBCXr:
2180 return AArch64::SBCSXr;
2181 case AArch64::ANDWri:
2182 return AArch64::ANDSWri;
2183 case AArch64::ANDXri:
2184 return AArch64::ANDSXri;
2185 case AArch64::ANDWrr:
2186 return AArch64::ANDSWrr;
2187 case AArch64::ANDWrs:
2188 return AArch64::ANDSWrs;
2189 case AArch64::ANDXrr:
2190 return AArch64::ANDSXrr;
2191 case AArch64::ANDXrs:
2192 return AArch64::ANDSXrs;
2193 case AArch64::BICWrr:
2194 return AArch64::BICSWrr;
2195 case AArch64::BICXrr:
2196 return AArch64::BICSXrr;
2197 case AArch64::BICWrs:
2198 return AArch64::BICSWrs;
2199 case AArch64::BICXrs:
2200 return AArch64::BICSXrs;
2201 }
2202}
2203
2204/// Check if AArch64::NZCV should be alive in successors of MBB.
2206 for (auto *BB : MBB->successors())
2207 if (BB->isLiveIn(AArch64::NZCV))
2208 return true;
2209 return false;
2210}
2211
2212/// \returns The condition code operand index for \p Instr if it is a branch
2213/// or select and -1 otherwise.
2214int AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
2215 const MachineInstr &Instr) {
2216 switch (Instr.getOpcode()) {
2217 default:
2218 return -1;
2219
2220 case AArch64::Bcc: {
2221 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2222 assert(Idx >= 2);
2223 return Idx - 2;
2224 }
2225
2226 case AArch64::CSINVWr:
2227 case AArch64::CSINVXr:
2228 case AArch64::CSINCWr:
2229 case AArch64::CSINCXr:
2230 case AArch64::CSELWr:
2231 case AArch64::CSELXr:
2232 case AArch64::CSNEGWr:
2233 case AArch64::CSNEGXr:
2234 case AArch64::FCSELSrrr:
2235 case AArch64::FCSELDrrr: {
2236 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2237 assert(Idx >= 1);
2238 return Idx - 1;
2239 }
2240 }
2241}
2242
2243/// Find a condition code used by the instruction.
2244/// Returns AArch64CC::Invalid if either the instruction does not use condition
2245/// codes or we don't optimize CmpInstr in the presence of such instructions.
2247 int CCIdx =
2248 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(Instr);
2249 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
2250 Instr.getOperand(CCIdx).getImm())
2252}
2253
2256 UsedNZCV UsedFlags;
2257 switch (CC) {
2258 default:
2259 break;
2260
2261 case AArch64CC::EQ: // Z set
2262 case AArch64CC::NE: // Z clear
2263 UsedFlags.Z = true;
2264 break;
2265
2266 case AArch64CC::HI: // Z clear and C set
2267 case AArch64CC::LS: // Z set or C clear
2268 UsedFlags.Z = true;
2269 [[fallthrough]];
2270 case AArch64CC::HS: // C set
2271 case AArch64CC::LO: // C clear
2272 UsedFlags.C = true;
2273 break;
2274
2275 case AArch64CC::MI: // N set
2276 case AArch64CC::PL: // N clear
2277 UsedFlags.N = true;
2278 break;
2279
2280 case AArch64CC::VS: // V set
2281 case AArch64CC::VC: // V clear
2282 UsedFlags.V = true;
2283 break;
2284
2285 case AArch64CC::GT: // Z clear, N and V the same
2286 case AArch64CC::LE: // Z set, N and V differ
2287 UsedFlags.Z = true;
2288 [[fallthrough]];
2289 case AArch64CC::GE: // N and V the same
2290 case AArch64CC::LT: // N and V differ
2291 UsedFlags.N = true;
2292 UsedFlags.V = true;
2293 break;
2294 }
2295 return UsedFlags;
2296}
2297
2298/// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
2299/// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
2300/// \returns std::nullopt otherwise.
2301///
2302/// Collect instructions using that flags in \p CCUseInstrs if provided.
2303std::optional<UsedNZCV>
2305 const TargetRegisterInfo &TRI,
2306 SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
2307 MachineBasicBlock *CmpParent = CmpInstr.getParent();
2308 if (MI.getParent() != CmpParent)
2309 return std::nullopt;
2310
2311 if (areCFlagsAliveInSuccessors(CmpParent))
2312 return std::nullopt;
2313
2314 UsedNZCV NZCVUsedAfterCmp;
2316 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
2317 if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
2319 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
2320 return std::nullopt;
2321 NZCVUsedAfterCmp |= getUsedNZCV(CC);
2322 if (CCUseInstrs)
2323 CCUseInstrs->push_back(&Instr);
2324 }
2325 if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
2326 break;
2327 }
2328 return NZCVUsedAfterCmp;
2329}
2330
2331static bool isADDSRegImm(unsigned Opcode) {
2332 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
2333}
2334
2335static bool isSUBSRegImm(unsigned Opcode) {
2336 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
2337}
2338
2340 unsigned Opc = sForm(MI);
2341 switch (Opc) {
2342 case AArch64::ANDSWri:
2343 case AArch64::ANDSWrr:
2344 case AArch64::ANDSWrs:
2345 case AArch64::ANDSXri:
2346 case AArch64::ANDSXrr:
2347 case AArch64::ANDSXrs:
2348 case AArch64::BICSWrr:
2349 case AArch64::BICSXrr:
2350 case AArch64::BICSWrs:
2351 case AArch64::BICSXrs:
2352 return true;
2353 default:
2354 return false;
2355 }
2356}
2357
2358/// Check if CmpInstr can be substituted by MI.
2359///
2360/// CmpInstr can be substituted:
2361/// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2362/// - and, MI and CmpInstr are from the same MachineBB
2363/// - and, condition flags are not alive in successors of the CmpInstr parent
2364/// - and, if MI opcode is the S form there must be no defs of flags between
2365/// MI and CmpInstr
2366/// or if MI opcode is not the S form there must be neither defs of flags
2367/// nor uses of flags between MI and CmpInstr.
2368/// - and, C is not used after CmpInstr; CmpInstr's C is from adds/subs #0 on
2369/// SrcReg and can differ from MI (e.g. carry out of ADCS/SBCS).
2370/// - and, V is not used after CmpInstr unless MI is AND/BIC (V cleared) or MI
2371/// has NoSWrap (overflow is poison and the fold is still safe).
2373 const TargetRegisterInfo &TRI) {
2374 // MI is an opcode sForm maps (add/sub/adc/sbc/and/bic and their S forms).
2375 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
2376
2377 const unsigned CmpOpcode = CmpInstr.getOpcode();
2378 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
2379 return false;
2380
2381 assert((CmpInstr.getOperand(2).isImm() &&
2382 CmpInstr.getOperand(2).getImm() == 0) &&
2383 "Caller guarantees that CmpInstr compares with constant 0");
2384
2385 std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
2386 if (!NZVCUsed || NZVCUsed->C)
2387 return false;
2388
2389 // CmpInstr is ADDS/SUBS with immediate 0 on SrcReg (compare SrcReg to zero).
2390 // After the fold, users see NZCV from MI (or its S form), not from CmpInstr.
2391 // N/Z match CmpInstr for the value in SrcReg; C/V need not match in general
2392 // (e.g. ADCS vs adds #0), so we require C unused after CmpInstr and gate V
2393 // as below. NoSWrap makes signed overflow poison; AND/BIC clear V.
2394 if (NZVCUsed->V && !MI.getFlag(MachineInstr::NoSWrap) && !isANDOpcode(MI))
2395 return false;
2396
2397 AccessKind AccessToCheck = AK_Write;
2398 if (sForm(MI) != MI.getOpcode())
2399 AccessToCheck = AK_All;
2400 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
2401}
2402
2403/// Substitute an instruction comparing to zero with another instruction
2404/// which produces needed condition flags.
2405///
2406/// Return true on success.
2407bool AArch64InstrInfo::substituteCmpToZero(
2408 MachineInstr &CmpInstr, unsigned SrcReg,
2409 const MachineRegisterInfo &MRI) const {
2410 // Get the unique definition of SrcReg.
2411 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2412 if (!MI)
2413 return false;
2414
2415 const TargetRegisterInfo &TRI = getRegisterInfo();
2416
2417 unsigned NewOpc = sForm(*MI);
2418 if (NewOpc == AArch64::INSTRUCTION_LIST_END)
2419 return false;
2420
2421 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
2422 return false;
2423
2424 // Update the instruction to set NZCV.
2425 MI->setDesc(get(NewOpc));
2426 CmpInstr.eraseFromParent();
2428 MI->addRegisterDefined(AArch64::NZCV, &TRI);
2429 return true;
2430}
2431
2432/// \returns True if \p CmpInstr can be removed.
2433///
2434/// \p IsInvertCC is true if, after removing \p CmpInstr, condition
2435/// codes used in \p CCUseInstrs must be inverted.
2437 int CmpValue, const TargetRegisterInfo &TRI,
2439 bool &IsInvertCC) {
2440 assert((CmpValue == 0 || CmpValue == 1) &&
2441 "Only comparisons to 0 or 1 considered for removal!");
2442
2443 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
2444 unsigned MIOpc = MI.getOpcode();
2445 if (MIOpc == AArch64::CSINCWr) {
2446 if (MI.getOperand(1).getReg() != AArch64::WZR ||
2447 MI.getOperand(2).getReg() != AArch64::WZR)
2448 return false;
2449 } else if (MIOpc == AArch64::CSINCXr) {
2450 if (MI.getOperand(1).getReg() != AArch64::XZR ||
2451 MI.getOperand(2).getReg() != AArch64::XZR)
2452 return false;
2453 } else {
2454 return false;
2455 }
2457 if (MICC == AArch64CC::Invalid)
2458 return false;
2459
2460 // NZCV needs to be defined
2461 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) != -1)
2462 return false;
2463
2464 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
2465 const unsigned CmpOpcode = CmpInstr.getOpcode();
2466 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
2467 if (CmpValue && !IsSubsRegImm)
2468 return false;
2469 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
2470 return false;
2471
2472 // MI conditions allowed: eq, ne, mi, pl
2473 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
2474 if (MIUsedNZCV.C || MIUsedNZCV.V)
2475 return false;
2476
2477 std::optional<UsedNZCV> NZCVUsedAfterCmp =
2478 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
2479 // Condition flags are not used in CmpInstr basic block successors and only
2480 // Z or N flags allowed to be used after CmpInstr within its basic block
2481 if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
2482 return false;
2483 // Z or N flag used after CmpInstr must correspond to the flag used in MI
2484 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
2485 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
2486 return false;
2487 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
2488 if (MIUsedNZCV.N && !CmpValue)
2489 return false;
2490
2491 // There must be no defs of flags between MI and CmpInstr
2492 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
2493 return false;
2494
2495 // Condition code is inverted in the following cases:
2496 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2497 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
2498 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
2499 (!CmpValue && MICC == AArch64CC::NE);
2500 return true;
2501}
2502
2503/// Remove comparison in csinc-cmp sequence
2504///
2505/// Examples:
2506/// 1. \code
2507/// csinc w9, wzr, wzr, ne
2508/// cmp w9, #0
2509/// b.eq
2510/// \endcode
2511/// to
2512/// \code
2513/// csinc w9, wzr, wzr, ne
2514/// b.ne
2515/// \endcode
2516///
2517/// 2. \code
2518/// csinc x2, xzr, xzr, mi
2519/// cmp x2, #1
2520/// b.pl
2521/// \endcode
2522/// to
2523/// \code
2524/// csinc x2, xzr, xzr, mi
2525/// b.pl
2526/// \endcode
2527///
2528/// \param CmpInstr comparison instruction
2529/// \return True when comparison removed
2530bool AArch64InstrInfo::removeCmpToZeroOrOne(
2531 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
2532 const MachineRegisterInfo &MRI) const {
2533 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2534 if (!MI)
2535 return false;
2536 const TargetRegisterInfo &TRI = getRegisterInfo();
2537 SmallVector<MachineInstr *, 4> CCUseInstrs;
2538 bool IsInvertCC = false;
2539 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
2540 IsInvertCC))
2541 return false;
2542 // Make transformation
2543 CmpInstr.eraseFromParent();
2544 if (IsInvertCC) {
2545 // Invert condition codes in CmpInstr CC users
2546 for (MachineInstr *CCUseInstr : CCUseInstrs) {
2547 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
2548 assert(Idx >= 0 && "Unexpected instruction using CC.");
2549 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
2551 static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
2552 CCOperand.setImm(CCUse);
2553 }
2554 }
2555 return true;
2556}
2557
2558bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2559 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
2560 MI.getOpcode() != AArch64::CATCHRET &&
2561 MI.getOpcode() != AArch64::STACK_GUARD_UNMIX)
2562 return false;
2563
2564 MachineBasicBlock &MBB = *MI.getParent();
2565 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
2566 auto TRI = Subtarget.getRegisterInfo();
2567 DebugLoc DL = MI.getDebugLoc();
2568
2569 if (MI.getOpcode() == AArch64::STACK_GUARD_UNMIX) {
2570 // Expand STACK_GUARD_UNMIX to: sub Rd, fp, Rs
2571 // This computes FP - stored_mixed_value to unmix the cookie
2572 Register DstReg = MI.getOperand(0).getReg();
2573 Register SrcReg = MI.getOperand(1).getReg();
2574
2575 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), DstReg)
2576 .addReg(AArch64::FP)
2577 .addReg(SrcReg);
2578
2579 MBB.erase(MI);
2580 return true;
2581 }
2582
2583 if (MI.getOpcode() == AArch64::CATCHRET) {
2584 // Skip to the first instruction before the epilog.
2585 const TargetInstrInfo *TII =
2587 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
2589 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
2590 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
2591 FirstEpilogSEH != MBB.begin())
2592 FirstEpilogSEH = std::prev(FirstEpilogSEH);
2593 if (FirstEpilogSEH != MBB.begin())
2594 FirstEpilogSEH = std::next(FirstEpilogSEH);
2595 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
2596 .addReg(AArch64::X0, RegState::Define)
2597 .addMBB(TargetMBB, AArch64II::MO_PAGE);
2598 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
2599 .addReg(AArch64::X0, RegState::Define)
2600 .addReg(AArch64::X0)
2602 .addImm(0);
2603 TargetMBB->setMachineBlockAddressTaken();
2604 return true;
2605 }
2606
2607 Register Reg = MI.getOperand(0).getReg();
2609 if (M.getStackProtectorGuard() == "sysreg") {
2610 const AArch64SysReg::SysReg *SrcReg =
2611 AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
2612 if (!SrcReg)
2613 report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
2614
2615 // mrs xN, sysreg
2616 BuildMI(MBB, MI, DL, get(AArch64::MRS))
2618 .addImm(SrcReg->Encoding);
2619 int Offset = M.getStackProtectorGuardOffset();
2620 if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
2621 // ldr xN, [xN, #offset]
2622 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2623 .addDef(Reg)
2625 .addImm(Offset / 8);
2626 } else if (Offset >= -256 && Offset <= 255) {
2627 // ldur xN, [xN, #offset]
2628 BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
2629 .addDef(Reg)
2631 .addImm(Offset);
2632 } else if (Offset >= -4095 && Offset <= 4095) {
2633 if (Offset > 0) {
2634 // add xN, xN, #offset
2635 BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
2636 .addDef(Reg)
2638 .addImm(Offset)
2639 .addImm(0);
2640 } else {
2641 // sub xN, xN, #offset
2642 BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
2643 .addDef(Reg)
2645 .addImm(-Offset)
2646 .addImm(0);
2647 }
2648 // ldr xN, [xN]
2649 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2650 .addDef(Reg)
2652 .addImm(0);
2653 } else {
2654 // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
2655 // than 23760.
2656 // It might be nice to use AArch64::MOVi32imm here, which would get
2657 // expanded in PreSched2 after PostRA, but our lone scratch Reg already
2658 // contains the MRS result. findScratchNonCalleeSaveRegister() in
2659 // AArch64FrameLowering might help us find such a scratch register
2660 // though. If we failed to find a scratch register, we could emit a
2661 // stream of add instructions to build up the immediate. Or, we could try
2662 // to insert a AArch64::MOVi32imm before register allocation so that we
2663 // didn't need to scavenge for a scratch register.
2664 report_fatal_error("Unable to encode Stack Protector Guard Offset");
2665 }
2666 MBB.erase(MI);
2667 return true;
2668 }
2669
2670 const GlobalValue *GV =
2671 cast<GlobalValue>((*MI.memoperands_begin())->getValue());
2672 const TargetMachine &TM = MBB.getParent()->getTarget();
2673 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
2674 const unsigned char MO_NC = AArch64II::MO_NC;
2675
2676 unsigned GuardWidth = M.getStackProtectorGuardValueWidth().value_or(
2677 Subtarget.isTargetILP32() ? 4 : 8);
2678 if (GuardWidth != 4 && GuardWidth != 8)
2679 report_fatal_error("Unsupported stack protector value width");
2680 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2681 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
2682 .addGlobalAddress(GV, 0, OpFlags);
2683 if (GuardWidth == 4) {
2684 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2685 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2686 .addDef(Reg32)
2688 .addImm(0)
2689 .addMemOperand(*MI.memoperands_begin())
2691 } else {
2692 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2694 .addImm(0)
2695 .addMemOperand(*MI.memoperands_begin());
2696 }
2697 } else if (TM.getCodeModel() == CodeModel::Large) {
2698 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
2699 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
2700 .addImm(0);
2701 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2703 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
2704 .addImm(16);
2705 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2707 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
2708 .addImm(32);
2709 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2712 .addImm(48);
2713 if (GuardWidth == 4) {
2714 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2715 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2716 .addDef(Reg32)
2718 .addImm(0)
2719 .addMemOperand(*MI.memoperands_begin())
2721 } else {
2722 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2724 .addImm(0)
2725 .addMemOperand(*MI.memoperands_begin());
2726 }
2727 } else {
2728 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
2729 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
2730 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2731 if (GuardWidth == 4) {
2732 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2733 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2734 .addDef(Reg32)
2736 .addGlobalAddress(GV, 0, LoFlags)
2737 .addMemOperand(*MI.memoperands_begin())
2739 } else {
2740 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2742 .addGlobalAddress(GV, 0, LoFlags)
2743 .addMemOperand(*MI.memoperands_begin());
2744 }
2745 }
2746 // To match MSVC. Unlike x86_64 which uses xor instruction to mix the cookie,
2747 // we use sub instruction to mix the cookie on aarch64.
2748 // The mixing happens here in expandPostRAPseudo (after RA) to ensure we use
2749 // the final frame pointer value.
2750 if (Subtarget.getTargetTriple().isOSMSVCRT())
2751 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), Reg)
2752 .addReg(AArch64::FP)
2754
2755 MBB.erase(MI);
2756
2757 return true;
2758}
2759
2760// Return true if this instruction simply sets its single destination register
2761// to zero. This is equivalent to a register rename of the zero-register.
2763 switch (MI.getOpcode()) {
2764 default:
2765 break;
2766 case AArch64::MOVZWi:
2767 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2768 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2769 assert(MI.getDesc().getNumOperands() == 3 &&
2770 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2771 return true;
2772 }
2773 break;
2774 case AArch64::ANDWri: // and Rd, Rzr, #imm
2775 return MI.getOperand(1).getReg() == AArch64::WZR;
2776 case AArch64::ANDXri:
2777 return MI.getOperand(1).getReg() == AArch64::XZR;
2778 case TargetOpcode::COPY:
2779 return MI.getOperand(1).getReg() == AArch64::WZR;
2780 }
2781 return false;
2782}
2783
2784// Return true if this instruction simply renames a general register without
2785// modifying bits.
2787 switch (MI.getOpcode()) {
2788 default:
2789 break;
2790 case TargetOpcode::COPY: {
2791 // GPR32 copies will by lowered to ORRXrs
2792 Register DstReg = MI.getOperand(0).getReg();
2793 return (AArch64::GPR32RegClass.contains(DstReg) ||
2794 AArch64::GPR64RegClass.contains(DstReg));
2795 }
2796 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2797 if (MI.getOperand(1).getReg() == AArch64::XZR) {
2798 assert(MI.getDesc().getNumOperands() == 4 &&
2799 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2800 return true;
2801 }
2802 break;
2803 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2804 if (MI.getOperand(2).getImm() == 0) {
2805 assert(MI.getDesc().getNumOperands() == 4 &&
2806 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2807 return true;
2808 }
2809 break;
2810 }
2811 return false;
2812}
2813
2814// Return true if this instruction simply renames a general register without
2815// modifying bits.
2817 switch (MI.getOpcode()) {
2818 default:
2819 break;
2820 case TargetOpcode::COPY: {
2821 Register DstReg = MI.getOperand(0).getReg();
2822 return AArch64::FPR128RegClass.contains(DstReg);
2823 }
2824 case AArch64::ORRv16i8:
2825 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2826 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2827 "invalid ORRv16i8 operands");
2828 return true;
2829 }
2830 break;
2831 }
2832 return false;
2833}
2834
2835static bool isFrameLoadOpcode(int Opcode) {
2836 switch (Opcode) {
2837 default:
2838 return false;
2839 case AArch64::LDRWui:
2840 case AArch64::LDRXui:
2841 case AArch64::LDRBui:
2842 case AArch64::LDRHui:
2843 case AArch64::LDRSui:
2844 case AArch64::LDRDui:
2845 case AArch64::LDRQui:
2846 case AArch64::LDR_PXI:
2847 return true;
2848 }
2849}
2850
2852 int &FrameIndex) const {
2853 if (!isFrameLoadOpcode(MI.getOpcode()))
2854 return Register();
2855
2856 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2857 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2858 FrameIndex = MI.getOperand(1).getIndex();
2859 return MI.getOperand(0).getReg();
2860 }
2861 return Register();
2862}
2863
2864static bool isFrameStoreOpcode(int Opcode) {
2865 switch (Opcode) {
2866 default:
2867 return false;
2868 case AArch64::STRWui:
2869 case AArch64::STRXui:
2870 case AArch64::STRBui:
2871 case AArch64::STRHui:
2872 case AArch64::STRSui:
2873 case AArch64::STRDui:
2874 case AArch64::STRQui:
2875 case AArch64::STR_PXI:
2876 return true;
2877 }
2878}
2879
2881 int &FrameIndex) const {
2882 if (!isFrameStoreOpcode(MI.getOpcode()))
2883 return Register();
2884
2885 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2886 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2887 FrameIndex = MI.getOperand(1).getIndex();
2888 return MI.getOperand(0).getReg();
2889 }
2890 return Register();
2891}
2892
2894 int &FrameIndex) const {
2895 if (!isFrameStoreOpcode(MI.getOpcode()))
2896 return Register();
2897
2898 if (Register Reg = isStoreToStackSlot(MI, FrameIndex))
2899 return Reg;
2900
2902 if (hasStoreToStackSlot(MI, Accesses)) {
2903 if (Accesses.size() > 1)
2904 return Register();
2905
2906 FrameIndex =
2907 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2908 ->getFrameIndex();
2909 return MI.getOperand(0).getReg();
2910 }
2911 return Register();
2912}
2913
2915 int &FrameIndex) const {
2916 if (!isFrameLoadOpcode(MI.getOpcode()))
2917 return Register();
2918
2919 if (Register Reg = isLoadFromStackSlot(MI, FrameIndex))
2920 return Reg;
2921
2923 if (hasLoadFromStackSlot(MI, Accesses)) {
2924 if (Accesses.size() > 1)
2925 return Register();
2926
2927 FrameIndex =
2928 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2929 ->getFrameIndex();
2930 return MI.getOperand(0).getReg();
2931 }
2932 return Register();
2933}
2934
2935/// Check all MachineMemOperands for a hint to suppress pairing.
2937 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2938 return MMO->getFlags() & MOSuppressPair;
2939 });
2940}
2941
2942/// Set a flag on the first MachineMemOperand to suppress pairing.
2944 if (MI.memoperands_empty())
2945 return;
2946 (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2947}
2948
2949/// Check all MachineMemOperands for a hint that the load/store is strided.
2951 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2952 return MMO->getFlags() & MOStridedAccess;
2953 });
2954}
2955
2957 switch (Opc) {
2958 default:
2959 return false;
2960 case AArch64::STURSi:
2961 case AArch64::STRSpre:
2962 case AArch64::STURDi:
2963 case AArch64::STRDpre:
2964 case AArch64::STURQi:
2965 case AArch64::STRQpre:
2966 case AArch64::STURBBi:
2967 case AArch64::STURHHi:
2968 case AArch64::STURWi:
2969 case AArch64::STRWpre:
2970 case AArch64::STURXi:
2971 case AArch64::STRXpre:
2972 case AArch64::LDURSi:
2973 case AArch64::LDRSpre:
2974 case AArch64::LDURDi:
2975 case AArch64::LDRDpre:
2976 case AArch64::LDURQi:
2977 case AArch64::LDRQpre:
2978 case AArch64::LDURWi:
2979 case AArch64::LDRWpre:
2980 case AArch64::LDURXi:
2981 case AArch64::LDRXpre:
2982 case AArch64::LDRSWpre:
2983 case AArch64::LDURSWi:
2984 case AArch64::LDURHHi:
2985 case AArch64::LDURBBi:
2986 case AArch64::LDURSBWi:
2987 case AArch64::LDURSHWi:
2988 return true;
2989 }
2990}
2991
2992std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
2993 switch (Opc) {
2994 default: return {};
2995 case AArch64::PRFMui: return AArch64::PRFUMi;
2996 case AArch64::LDRXui: return AArch64::LDURXi;
2997 case AArch64::LDRWui: return AArch64::LDURWi;
2998 case AArch64::LDRBui: return AArch64::LDURBi;
2999 case AArch64::LDRHui: return AArch64::LDURHi;
3000 case AArch64::LDRSui: return AArch64::LDURSi;
3001 case AArch64::LDRDui: return AArch64::LDURDi;
3002 case AArch64::LDRQui: return AArch64::LDURQi;
3003 case AArch64::LDRBBui: return AArch64::LDURBBi;
3004 case AArch64::LDRHHui: return AArch64::LDURHHi;
3005 case AArch64::LDRSBXui: return AArch64::LDURSBXi;
3006 case AArch64::LDRSBWui: return AArch64::LDURSBWi;
3007 case AArch64::LDRSHXui: return AArch64::LDURSHXi;
3008 case AArch64::LDRSHWui: return AArch64::LDURSHWi;
3009 case AArch64::LDRSWui: return AArch64::LDURSWi;
3010 case AArch64::STRXui: return AArch64::STURXi;
3011 case AArch64::STRWui: return AArch64::STURWi;
3012 case AArch64::STRBui: return AArch64::STURBi;
3013 case AArch64::STRHui: return AArch64::STURHi;
3014 case AArch64::STRSui: return AArch64::STURSi;
3015 case AArch64::STRDui: return AArch64::STURDi;
3016 case AArch64::STRQui: return AArch64::STURQi;
3017 case AArch64::STRBBui: return AArch64::STURBBi;
3018 case AArch64::STRHHui: return AArch64::STURHHi;
3019 }
3020}
3021
3023 switch (Opc) {
3024 default:
3025 llvm_unreachable("Unhandled Opcode in getLoadStoreImmIdx");
3026 case AArch64::ADDG:
3027 case AArch64::LDAPURBi:
3028 case AArch64::LDAPURHi:
3029 case AArch64::LDAPURi:
3030 case AArch64::LDAPURSBWi:
3031 case AArch64::LDAPURSBXi:
3032 case AArch64::LDAPURSHWi:
3033 case AArch64::LDAPURSHXi:
3034 case AArch64::LDAPURSWi:
3035 case AArch64::LDAPURXi:
3036 case AArch64::LDR_PPXI:
3037 case AArch64::LDR_PXI:
3038 case AArch64::LDR_ZXI:
3039 case AArch64::LDR_ZZXI:
3040 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
3041 case AArch64::LDR_ZZZXI:
3042 case AArch64::LDR_ZZZZXI:
3043 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
3044 case AArch64::LDRBBui:
3045 case AArch64::LDRBui:
3046 case AArch64::LDRDui:
3047 case AArch64::LDRHHui:
3048 case AArch64::LDRHui:
3049 case AArch64::LDRQui:
3050 case AArch64::LDRSBWui:
3051 case AArch64::LDRSBXui:
3052 case AArch64::LDRSHWui:
3053 case AArch64::LDRSHXui:
3054 case AArch64::LDRSui:
3055 case AArch64::LDRSWui:
3056 case AArch64::LDRWui:
3057 case AArch64::LDRXui:
3058 case AArch64::LDURBBi:
3059 case AArch64::LDURBi:
3060 case AArch64::LDURDi:
3061 case AArch64::LDURHHi:
3062 case AArch64::LDURHi:
3063 case AArch64::LDURQi:
3064 case AArch64::LDURSBWi:
3065 case AArch64::LDURSBXi:
3066 case AArch64::LDURSHWi:
3067 case AArch64::LDURSHXi:
3068 case AArch64::LDURSi:
3069 case AArch64::LDURSWi:
3070 case AArch64::LDURWi:
3071 case AArch64::LDURXi:
3072 case AArch64::PRFMui:
3073 case AArch64::PRFUMi:
3074 case AArch64::ST2Gi:
3075 case AArch64::STGi:
3076 case AArch64::STLURBi:
3077 case AArch64::STLURHi:
3078 case AArch64::STLURWi:
3079 case AArch64::STLURXi:
3080 case AArch64::StoreSwiftAsyncContext:
3081 case AArch64::STR_PPXI:
3082 case AArch64::STR_PXI:
3083 case AArch64::STR_ZXI:
3084 case AArch64::STR_ZZXI:
3085 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
3086 case AArch64::STR_ZZZXI:
3087 case AArch64::STR_ZZZZXI:
3088 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
3089 case AArch64::STRBBui:
3090 case AArch64::STRBui:
3091 case AArch64::STRDui:
3092 case AArch64::STRHHui:
3093 case AArch64::STRHui:
3094 case AArch64::STRQui:
3095 case AArch64::STRSui:
3096 case AArch64::STRWui:
3097 case AArch64::STRXui:
3098 case AArch64::STURBBi:
3099 case AArch64::STURBi:
3100 case AArch64::STURDi:
3101 case AArch64::STURHHi:
3102 case AArch64::STURHi:
3103 case AArch64::STURQi:
3104 case AArch64::STURSi:
3105 case AArch64::STURWi:
3106 case AArch64::STURXi:
3107 case AArch64::STZ2Gi:
3108 case AArch64::STZGi:
3109 case AArch64::TAGPstack:
3110 case AArch64::ATOMIC_STORE_HINT_Bi:
3111 case AArch64::ATOMIC_STORE_HINT_Hi:
3112 case AArch64::ATOMIC_STORE_HINT_Wi:
3113 case AArch64::ATOMIC_STORE_HINT_Si:
3114 case AArch64::ATOMIC_STORE_HINT_Xi:
3115 case AArch64::ATOMIC_STORE_HINT_Di:
3116 case AArch64::ATOMIC_STORE_HINT_Bui:
3117 case AArch64::ATOMIC_STORE_HINT_Hui:
3118 case AArch64::ATOMIC_STORE_HINT_Wui:
3119 case AArch64::ATOMIC_STORE_HINT_Sui:
3120 case AArch64::ATOMIC_STORE_HINT_Xui:
3121 case AArch64::ATOMIC_STORE_HINT_Dui:
3122 return 2;
3123 case AArch64::LD1B_D_IMM:
3124 case AArch64::LD1B_H_IMM:
3125 case AArch64::LD1B_IMM:
3126 case AArch64::LD1B_S_IMM:
3127 case AArch64::LD1D_IMM:
3128 case AArch64::LD1H_D_IMM:
3129 case AArch64::LD1H_IMM:
3130 case AArch64::LD1H_S_IMM:
3131 case AArch64::LD1RB_D_IMM:
3132 case AArch64::LD1RB_H_IMM:
3133 case AArch64::LD1RB_IMM:
3134 case AArch64::LD1RB_S_IMM:
3135 case AArch64::LD1RD_IMM:
3136 case AArch64::LD1RH_D_IMM:
3137 case AArch64::LD1RH_IMM:
3138 case AArch64::LD1RH_S_IMM:
3139 case AArch64::LD1RSB_D_IMM:
3140 case AArch64::LD1RSB_H_IMM:
3141 case AArch64::LD1RSB_S_IMM:
3142 case AArch64::LD1RSH_D_IMM:
3143 case AArch64::LD1RSH_S_IMM:
3144 case AArch64::LD1RSW_IMM:
3145 case AArch64::LD1RW_D_IMM:
3146 case AArch64::LD1RW_IMM:
3147 case AArch64::LD1SB_D_IMM:
3148 case AArch64::LD1SB_H_IMM:
3149 case AArch64::LD1SB_S_IMM:
3150 case AArch64::LD1SH_D_IMM:
3151 case AArch64::LD1SH_S_IMM:
3152 case AArch64::LD1SW_D_IMM:
3153 case AArch64::LD1W_D_IMM:
3154 case AArch64::LD1W_IMM:
3155 case AArch64::LD2B_IMM:
3156 case AArch64::LD2D_IMM:
3157 case AArch64::LD2H_IMM:
3158 case AArch64::LD2W_IMM:
3159 case AArch64::LD3B_IMM:
3160 case AArch64::LD3D_IMM:
3161 case AArch64::LD3H_IMM:
3162 case AArch64::LD3W_IMM:
3163 case AArch64::LD4B_IMM:
3164 case AArch64::LD4D_IMM:
3165 case AArch64::LD4H_IMM:
3166 case AArch64::LD4W_IMM:
3167 case AArch64::LDG:
3168 case AArch64::LDNF1B_D_IMM:
3169 case AArch64::LDNF1B_H_IMM:
3170 case AArch64::LDNF1B_IMM:
3171 case AArch64::LDNF1B_S_IMM:
3172 case AArch64::LDNF1D_IMM:
3173 case AArch64::LDNF1H_D_IMM:
3174 case AArch64::LDNF1H_IMM:
3175 case AArch64::LDNF1H_S_IMM:
3176 case AArch64::LDNF1SB_D_IMM:
3177 case AArch64::LDNF1SB_H_IMM:
3178 case AArch64::LDNF1SB_S_IMM:
3179 case AArch64::LDNF1SH_D_IMM:
3180 case AArch64::LDNF1SH_S_IMM:
3181 case AArch64::LDNF1SW_D_IMM:
3182 case AArch64::LDNF1W_D_IMM:
3183 case AArch64::LDNF1W_IMM:
3184 case AArch64::LDNPDi:
3185 case AArch64::LDNPQi:
3186 case AArch64::LDNPSi:
3187 case AArch64::LDNPWi:
3188 case AArch64::LDNPXi:
3189 case AArch64::LDNT1B_ZRI:
3190 case AArch64::LDNT1D_ZRI:
3191 case AArch64::LDNT1H_ZRI:
3192 case AArch64::LDNT1W_ZRI:
3193 case AArch64::LDPDi:
3194 case AArch64::LDPQi:
3195 case AArch64::LDPSi:
3196 case AArch64::LDPWi:
3197 case AArch64::LDPXi:
3198 case AArch64::LDRBBpost:
3199 case AArch64::LDRBBpre:
3200 case AArch64::LDRBpost:
3201 case AArch64::LDRBpre:
3202 case AArch64::LDRDpost:
3203 case AArch64::LDRDpre:
3204 case AArch64::LDRHHpost:
3205 case AArch64::LDRHHpre:
3206 case AArch64::LDRHpost:
3207 case AArch64::LDRHpre:
3208 case AArch64::LDRQpost:
3209 case AArch64::LDRQpre:
3210 case AArch64::LDRSpost:
3211 case AArch64::LDRSpre:
3212 case AArch64::LDRWpost:
3213 case AArch64::LDRWpre:
3214 case AArch64::LDRXpost:
3215 case AArch64::LDRXpre:
3216 case AArch64::ST1B_D_IMM:
3217 case AArch64::ST1B_H_IMM:
3218 case AArch64::ST1B_IMM:
3219 case AArch64::ST1B_S_IMM:
3220 case AArch64::ST1D_IMM:
3221 case AArch64::ST1H_D_IMM:
3222 case AArch64::ST1H_IMM:
3223 case AArch64::ST1H_S_IMM:
3224 case AArch64::ST1W_D_IMM:
3225 case AArch64::ST1W_IMM:
3226 case AArch64::ST2B_IMM:
3227 case AArch64::ST2D_IMM:
3228 case AArch64::ST2H_IMM:
3229 case AArch64::ST2W_IMM:
3230 case AArch64::ST3B_IMM:
3231 case AArch64::ST3D_IMM:
3232 case AArch64::ST3H_IMM:
3233 case AArch64::ST3W_IMM:
3234 case AArch64::ST4B_IMM:
3235 case AArch64::ST4D_IMM:
3236 case AArch64::ST4H_IMM:
3237 case AArch64::ST4W_IMM:
3238 case AArch64::STGPi:
3239 case AArch64::STGPreIndex:
3240 case AArch64::STZGPreIndex:
3241 case AArch64::ST2GPreIndex:
3242 case AArch64::STZ2GPreIndex:
3243 case AArch64::STGPostIndex:
3244 case AArch64::STZGPostIndex:
3245 case AArch64::ST2GPostIndex:
3246 case AArch64::STZ2GPostIndex:
3247 case AArch64::STNPDi:
3248 case AArch64::STNPQi:
3249 case AArch64::STNPSi:
3250 case AArch64::STNPWi:
3251 case AArch64::STNPXi:
3252 case AArch64::STNT1B_ZRI:
3253 case AArch64::STNT1D_ZRI:
3254 case AArch64::STNT1H_ZRI:
3255 case AArch64::STNT1W_ZRI:
3256 case AArch64::STPDi:
3257 case AArch64::STPQi:
3258 case AArch64::STPSi:
3259 case AArch64::STPWi:
3260 case AArch64::STPXi:
3261 case AArch64::STRBBpost:
3262 case AArch64::STRBBpre:
3263 case AArch64::STRBpost:
3264 case AArch64::STRBpre:
3265 case AArch64::STRDpost:
3266 case AArch64::STRDpre:
3267 case AArch64::STRHHpost:
3268 case AArch64::STRHHpre:
3269 case AArch64::STRHpost:
3270 case AArch64::STRHpre:
3271 case AArch64::STRQpost:
3272 case AArch64::STRQpre:
3273 case AArch64::STRSpost:
3274 case AArch64::STRSpre:
3275 case AArch64::STRWpost:
3276 case AArch64::STRWpre:
3277 case AArch64::STRXpost:
3278 case AArch64::STRXpre:
3279 case AArch64::LD1B_2Z_IMM:
3280 case AArch64::LD1B_2Z_STRIDED_IMM:
3281 case AArch64::LD1H_2Z_IMM:
3282 case AArch64::LD1H_2Z_STRIDED_IMM:
3283 case AArch64::LD1W_2Z_IMM:
3284 case AArch64::LD1W_2Z_STRIDED_IMM:
3285 case AArch64::LD1D_2Z_IMM:
3286 case AArch64::LD1D_2Z_STRIDED_IMM:
3287 case AArch64::LD1B_4Z_IMM:
3288 case AArch64::LD1B_4Z_STRIDED_IMM:
3289 case AArch64::LD1H_4Z_IMM:
3290 case AArch64::LD1H_4Z_STRIDED_IMM:
3291 case AArch64::LD1W_4Z_IMM:
3292 case AArch64::LD1W_4Z_STRIDED_IMM:
3293 case AArch64::LD1D_4Z_IMM:
3294 case AArch64::LD1D_4Z_STRIDED_IMM:
3295 case AArch64::LD1B_2Z_IMM_PSEUDO:
3296 case AArch64::LD1H_2Z_IMM_PSEUDO:
3297 case AArch64::LD1W_2Z_IMM_PSEUDO:
3298 case AArch64::LD1D_2Z_IMM_PSEUDO:
3299 case AArch64::LD1B_4Z_IMM_PSEUDO:
3300 case AArch64::LD1H_4Z_IMM_PSEUDO:
3301 case AArch64::LD1W_4Z_IMM_PSEUDO:
3302 case AArch64::LD1D_4Z_IMM_PSEUDO:
3303 case AArch64::ST1B_2Z_IMM:
3304 case AArch64::ST1B_2Z_STRIDED_IMM:
3305 case AArch64::ST1H_2Z_IMM:
3306 case AArch64::ST1H_2Z_STRIDED_IMM:
3307 case AArch64::ST1W_2Z_IMM:
3308 case AArch64::ST1W_2Z_STRIDED_IMM:
3309 case AArch64::ST1D_2Z_IMM:
3310 case AArch64::ST1D_2Z_STRIDED_IMM:
3311 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
3312 case AArch64::LDNT1B_2Z_IMM:
3313 case AArch64::LDNT1B_2Z_STRIDED_IMM:
3314 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
3315 case AArch64::LDNT1H_2Z_IMM:
3316 case AArch64::LDNT1H_2Z_STRIDED_IMM:
3317 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
3318 case AArch64::LDNT1W_2Z_IMM:
3319 case AArch64::LDNT1W_2Z_STRIDED_IMM:
3320 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
3321 case AArch64::LDNT1D_2Z_IMM:
3322 case AArch64::LDNT1D_2Z_STRIDED_IMM:
3323 case AArch64::STNT1B_2Z_IMM:
3324 case AArch64::STNT1B_2Z_STRIDED_IMM:
3325 case AArch64::STNT1H_2Z_IMM:
3326 case AArch64::STNT1H_2Z_STRIDED_IMM:
3327 case AArch64::STNT1W_2Z_IMM:
3328 case AArch64::STNT1W_2Z_STRIDED_IMM:
3329 case AArch64::STNT1D_2Z_IMM:
3330 case AArch64::STNT1D_2Z_STRIDED_IMM:
3331 case AArch64::ST1B_2Z_IMM_PSEUDO:
3332 case AArch64::ST1H_2Z_IMM_PSEUDO:
3333 case AArch64::ST1W_2Z_IMM_PSEUDO:
3334 case AArch64::ST1D_2Z_IMM_PSEUDO:
3335 case AArch64::STNT1B_2Z_IMM_PSEUDO:
3336 case AArch64::STNT1H_2Z_IMM_PSEUDO:
3337 case AArch64::STNT1W_2Z_IMM_PSEUDO:
3338 case AArch64::STNT1D_2Z_IMM_PSEUDO:
3339 case AArch64::ST1B_4Z_IMM:
3340 case AArch64::ST1B_4Z_STRIDED_IMM:
3341 case AArch64::ST1H_4Z_IMM:
3342 case AArch64::ST1H_4Z_STRIDED_IMM:
3343 case AArch64::ST1W_4Z_IMM:
3344 case AArch64::ST1W_4Z_STRIDED_IMM:
3345 case AArch64::ST1D_4Z_IMM:
3346 case AArch64::ST1D_4Z_STRIDED_IMM:
3347 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
3348 case AArch64::LDNT1B_4Z_IMM:
3349 case AArch64::LDNT1B_4Z_STRIDED_IMM:
3350 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
3351 case AArch64::LDNT1H_4Z_IMM:
3352 case AArch64::LDNT1H_4Z_STRIDED_IMM:
3353 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
3354 case AArch64::LDNT1W_4Z_IMM:
3355 case AArch64::LDNT1W_4Z_STRIDED_IMM:
3356 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
3357 case AArch64::LDNT1D_4Z_IMM:
3358 case AArch64::LDNT1D_4Z_STRIDED_IMM:
3359 case AArch64::STNT1B_4Z_IMM:
3360 case AArch64::STNT1B_4Z_STRIDED_IMM:
3361 case AArch64::STNT1H_4Z_IMM:
3362 case AArch64::STNT1H_4Z_STRIDED_IMM:
3363 case AArch64::STNT1W_4Z_IMM:
3364 case AArch64::STNT1W_4Z_STRIDED_IMM:
3365 case AArch64::STNT1D_4Z_IMM:
3366 case AArch64::STNT1D_4Z_STRIDED_IMM:
3367 case AArch64::ST1B_4Z_IMM_PSEUDO:
3368 case AArch64::ST1H_4Z_IMM_PSEUDO:
3369 case AArch64::ST1W_4Z_IMM_PSEUDO:
3370 case AArch64::ST1D_4Z_IMM_PSEUDO:
3371 case AArch64::STNT1B_4Z_IMM_PSEUDO:
3372 case AArch64::STNT1H_4Z_IMM_PSEUDO:
3373 case AArch64::STNT1W_4Z_IMM_PSEUDO:
3374 case AArch64::STNT1D_4Z_IMM_PSEUDO:
3375 return 3;
3376 case AArch64::LDPDpost:
3377 case AArch64::LDPDpre:
3378 case AArch64::LDPQpost:
3379 case AArch64::LDPQpre:
3380 case AArch64::LDPSpost:
3381 case AArch64::LDPSpre:
3382 case AArch64::LDPWpost:
3383 case AArch64::LDPWpre:
3384 case AArch64::LDPXpost:
3385 case AArch64::LDPXpre:
3386 case AArch64::STGPpre:
3387 case AArch64::STGPpost:
3388 case AArch64::STPDpost:
3389 case AArch64::STPDpre:
3390 case AArch64::STPQpost:
3391 case AArch64::STPQpre:
3392 case AArch64::STPSpost:
3393 case AArch64::STPSpre:
3394 case AArch64::STPWpost:
3395 case AArch64::STPWpre:
3396 case AArch64::STPXpost:
3397 case AArch64::STPXpre:
3398 return 4;
3399 }
3400}
3401
3403 switch (MI.getOpcode()) {
3404 default:
3405 return false;
3406 // Scaled instructions.
3407 case AArch64::STRSui:
3408 case AArch64::STRDui:
3409 case AArch64::STRQui:
3410 case AArch64::STRXui:
3411 case AArch64::STRWui:
3412 case AArch64::LDRSui:
3413 case AArch64::LDRDui:
3414 case AArch64::LDRQui:
3415 case AArch64::LDRXui:
3416 case AArch64::LDRWui:
3417 case AArch64::LDRSWui:
3418 // Unscaled instructions.
3419 case AArch64::STURSi:
3420 case AArch64::STRSpre:
3421 case AArch64::STURDi:
3422 case AArch64::STRDpre:
3423 case AArch64::STURQi:
3424 case AArch64::STRQpre:
3425 case AArch64::STURWi:
3426 case AArch64::STRWpre:
3427 case AArch64::STURXi:
3428 case AArch64::STRXpre:
3429 case AArch64::LDURSi:
3430 case AArch64::LDRSpre:
3431 case AArch64::LDURDi:
3432 case AArch64::LDRDpre:
3433 case AArch64::LDURQi:
3434 case AArch64::LDRQpre:
3435 case AArch64::LDURWi:
3436 case AArch64::LDRWpre:
3437 case AArch64::LDURXi:
3438 case AArch64::LDRXpre:
3439 case AArch64::LDURSWi:
3440 case AArch64::LDRSWpre:
3441 // SVE instructions.
3442 case AArch64::LDR_ZXI:
3443 case AArch64::STR_ZXI:
3444 return true;
3445 }
3446}
3447
3449 switch (MI.getOpcode()) {
3450 default:
3451 assert((!MI.isCall() || !MI.isReturn()) &&
3452 "Unexpected instruction - was a new tail call opcode introduced?");
3453 return false;
3454 case AArch64::TCRETURNdi:
3455 case AArch64::TCRETURNri:
3456 case AArch64::TCRETURNrix16x17:
3457 case AArch64::TCRETURNrix17:
3458 case AArch64::TCRETURNrinotx16:
3459 case AArch64::TCRETURNriALL:
3460 case AArch64::AUTH_TCRETURN:
3461 case AArch64::AUTH_TCRETURN_BTI:
3462 return true;
3463 }
3464}
3465
3467 switch (Opc) {
3468 default:
3469 llvm_unreachable("Opcode has no flag setting equivalent!");
3470 // 32-bit cases:
3471 case AArch64::ADDWri:
3472 return AArch64::ADDSWri;
3473 case AArch64::ADDWrr:
3474 return AArch64::ADDSWrr;
3475 case AArch64::ADDWrs:
3476 return AArch64::ADDSWrs;
3477 case AArch64::ADDWrx:
3478 return AArch64::ADDSWrx;
3479 case AArch64::ANDWri:
3480 return AArch64::ANDSWri;
3481 case AArch64::ANDWrr:
3482 return AArch64::ANDSWrr;
3483 case AArch64::ANDWrs:
3484 return AArch64::ANDSWrs;
3485 case AArch64::BICWrr:
3486 return AArch64::BICSWrr;
3487 case AArch64::BICWrs:
3488 return AArch64::BICSWrs;
3489 case AArch64::SUBWri:
3490 return AArch64::SUBSWri;
3491 case AArch64::SUBWrr:
3492 return AArch64::SUBSWrr;
3493 case AArch64::SUBWrs:
3494 return AArch64::SUBSWrs;
3495 case AArch64::SUBWrx:
3496 return AArch64::SUBSWrx;
3497 // 64-bit cases:
3498 case AArch64::ADDXri:
3499 return AArch64::ADDSXri;
3500 case AArch64::ADDXrr:
3501 return AArch64::ADDSXrr;
3502 case AArch64::ADDXrs:
3503 return AArch64::ADDSXrs;
3504 case AArch64::ADDXrx:
3505 return AArch64::ADDSXrx;
3506 case AArch64::ANDXri:
3507 return AArch64::ANDSXri;
3508 case AArch64::ANDXrr:
3509 return AArch64::ANDSXrr;
3510 case AArch64::ANDXrs:
3511 return AArch64::ANDSXrs;
3512 case AArch64::BICXrr:
3513 return AArch64::BICSXrr;
3514 case AArch64::BICXrs:
3515 return AArch64::BICSXrs;
3516 case AArch64::SUBXri:
3517 return AArch64::SUBSXri;
3518 case AArch64::SUBXrr:
3519 return AArch64::SUBSXrr;
3520 case AArch64::SUBXrs:
3521 return AArch64::SUBSXrs;
3522 case AArch64::SUBXrx:
3523 return AArch64::SUBSXrx;
3524 // SVE instructions:
3525 case AArch64::AND_PPzPP:
3526 return AArch64::ANDS_PPzPP;
3527 case AArch64::BIC_PPzPP:
3528 return AArch64::BICS_PPzPP;
3529 case AArch64::EOR_PPzPP:
3530 return AArch64::EORS_PPzPP;
3531 case AArch64::NAND_PPzPP:
3532 return AArch64::NANDS_PPzPP;
3533 case AArch64::NOR_PPzPP:
3534 return AArch64::NORS_PPzPP;
3535 case AArch64::ORN_PPzPP:
3536 return AArch64::ORNS_PPzPP;
3537 case AArch64::ORR_PPzPP:
3538 return AArch64::ORRS_PPzPP;
3539 case AArch64::BRKA_PPzP:
3540 return AArch64::BRKAS_PPzP;
3541 case AArch64::BRKPA_PPzPP:
3542 return AArch64::BRKPAS_PPzPP;
3543 case AArch64::BRKB_PPzP:
3544 return AArch64::BRKBS_PPzP;
3545 case AArch64::BRKPB_PPzPP:
3546 return AArch64::BRKPBS_PPzPP;
3547 case AArch64::BRKN_PPzP:
3548 return AArch64::BRKNS_PPzP;
3549 case AArch64::RDFFR_PPz:
3550 return AArch64::RDFFRS_PPz;
3551 case AArch64::PTRUE_B:
3552 return AArch64::PTRUES_B;
3553 }
3554}
3555
3556// Is this a candidate for ld/st merging or pairing? For example, we don't
3557// touch volatiles or load/stores that have a hint to avoid pair formation.
3559
3560 bool IsPreLdSt = isPreLdSt(MI);
3561
3562 // If this is a volatile load/store, don't mess with it.
3563 if (MI.hasOrderedMemoryRef())
3564 return false;
3565
3566 // Make sure this is a reg/fi+imm (as opposed to an address reloc).
3567 // For Pre-inc LD/ST, the operand is shifted by one.
3568 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
3569 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
3570 "Expected a reg or frame index operand.");
3571
3572 // For Pre-indexed addressing quadword instructions, the third operand is the
3573 // immediate value.
3574 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
3575
3576 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
3577 return false;
3578
3579 // Can't merge/pair if the instruction modifies the base register.
3580 // e.g., ldr x0, [x0]
3581 // This case will never occur with an FI base.
3582 // However, if the instruction is an LDR<S,D,Q,W,X,SW>pre or
3583 // STR<S,D,Q,W,X>pre, it can be merged.
3584 // For example:
3585 // ldr q0, [x11, #32]!
3586 // ldr q1, [x11, #16]
3587 // to
3588 // ldp q0, q1, [x11, #32]!
3589 if (MI.getOperand(1).isReg() && !IsPreLdSt) {
3590 Register BaseReg = MI.getOperand(1).getReg();
3592 if (MI.modifiesRegister(BaseReg, TRI))
3593 return false;
3594 }
3595
3596 // Pairing SVE fills/spills is only valid for little-endian targets that
3597 // implement VLS 128.
3598 switch (MI.getOpcode()) {
3599 default:
3600 break;
3601 case AArch64::LDR_ZXI:
3602 case AArch64::STR_ZXI:
3603 if (!Subtarget.isLittleEndian() ||
3604 Subtarget.getSVEVectorSizeInBits() != 128)
3605 return false;
3606 }
3607
3608 // Check if this load/store has a hint to avoid pair formation.
3609 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
3611 return false;
3612
3613 // Do not pair any callee-save store/reload instructions in the
3614 // prologue/epilogue if the CFI information encoded the operations as separate
3615 // instructions, as that will cause the size of the actual prologue to mismatch
3616 // with the prologue size recorded in the Windows CFI.
3617 if ((MI.getFlag(MachineInstr::FrameSetup) ||
3618 MI.getFlag(MachineInstr::FrameDestroy)) &&
3619 MI.getMF()->needsWinCFI())
3620 return false;
3621
3622 // On some CPUs quad load/store pairs are slower than two single load/stores.
3623 if (Subtarget.isPaired128Slow()) {
3624 switch (MI.getOpcode()) {
3625 default:
3626 break;
3627 case AArch64::LDURQi:
3628 case AArch64::STURQi:
3629 case AArch64::LDRQui:
3630 case AArch64::STRQui:
3631 return false;
3632 }
3633 }
3634
3635 return true;
3636}
3637
3640 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const {
3641 if (!LdSt.mayLoadOrStore())
3642 return false;
3643
3644 const MachineOperand *BaseOp;
3645 TypeSize WidthN(0, false);
3646 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
3647 WidthN))
3648 return false;
3649 // The maximum vscale is 16 under AArch64, return the maximal extent for the
3650 // vector.
3651 Width = LocationSize::precise(WidthN);
3652 BaseOps.push_back(BaseOp);
3653 return true;
3654}
3655
3656std::optional<ExtAddrMode>
3658 const MachineOperand *Base; // Filled with the base operand of MI.
3659 int64_t Offset; // Filled with the offset of MI.
3660 bool OffsetIsScalable;
3661 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable))
3662 return std::nullopt;
3663
3664 if (!Base->isReg())
3665 return std::nullopt;
3666 ExtAddrMode AM;
3667 AM.BaseReg = Base->getReg();
3668 AM.Displacement = Offset;
3669 AM.ScaledReg = 0;
3670 AM.Scale = 0;
3671 return AM;
3672}
3673
3675 Register Reg,
3676 const MachineInstr &AddrI,
3677 ExtAddrMode &AM) const {
3678 // Filter out instructions into which we cannot fold.
3679 unsigned NumBytes;
3680 int64_t OffsetScale = 1;
3681 switch (MemI.getOpcode()) {
3682 default:
3683 return false;
3684
3685 case AArch64::LDURQi:
3686 case AArch64::STURQi:
3687 NumBytes = 16;
3688 break;
3689
3690 case AArch64::LDURDi:
3691 case AArch64::STURDi:
3692 case AArch64::LDURXi:
3693 case AArch64::STURXi:
3694 NumBytes = 8;
3695 break;
3696
3697 case AArch64::LDURWi:
3698 case AArch64::LDURSWi:
3699 case AArch64::STURWi:
3700 NumBytes = 4;
3701 break;
3702
3703 case AArch64::LDURHi:
3704 case AArch64::STURHi:
3705 case AArch64::LDURHHi:
3706 case AArch64::STURHHi:
3707 case AArch64::LDURSHXi:
3708 case AArch64::LDURSHWi:
3709 NumBytes = 2;
3710 break;
3711
3712 case AArch64::LDRBroX:
3713 case AArch64::LDRBBroX:
3714 case AArch64::LDRSBXroX:
3715 case AArch64::LDRSBWroX:
3716 case AArch64::STRBroX:
3717 case AArch64::STRBBroX:
3718 case AArch64::LDURBi:
3719 case AArch64::LDURBBi:
3720 case AArch64::LDURSBXi:
3721 case AArch64::LDURSBWi:
3722 case AArch64::STURBi:
3723 case AArch64::STURBBi:
3724 case AArch64::LDRBui:
3725 case AArch64::LDRBBui:
3726 case AArch64::LDRSBXui:
3727 case AArch64::LDRSBWui:
3728 case AArch64::STRBui:
3729 case AArch64::STRBBui:
3730 NumBytes = 1;
3731 break;
3732
3733 case AArch64::LDRQroX:
3734 case AArch64::STRQroX:
3735 case AArch64::LDRQui:
3736 case AArch64::STRQui:
3737 NumBytes = 16;
3738 OffsetScale = 16;
3739 break;
3740
3741 case AArch64::LDRDroX:
3742 case AArch64::STRDroX:
3743 case AArch64::LDRXroX:
3744 case AArch64::STRXroX:
3745 case AArch64::LDRDui:
3746 case AArch64::STRDui:
3747 case AArch64::LDRXui:
3748 case AArch64::STRXui:
3749 NumBytes = 8;
3750 OffsetScale = 8;
3751 break;
3752
3753 case AArch64::LDRWroX:
3754 case AArch64::LDRSWroX:
3755 case AArch64::STRWroX:
3756 case AArch64::LDRWui:
3757 case AArch64::LDRSWui:
3758 case AArch64::STRWui:
3759 NumBytes = 4;
3760 OffsetScale = 4;
3761 break;
3762
3763 case AArch64::LDRHroX:
3764 case AArch64::STRHroX:
3765 case AArch64::LDRHHroX:
3766 case AArch64::STRHHroX:
3767 case AArch64::LDRSHXroX:
3768 case AArch64::LDRSHWroX:
3769 case AArch64::LDRHui:
3770 case AArch64::STRHui:
3771 case AArch64::LDRHHui:
3772 case AArch64::STRHHui:
3773 case AArch64::LDRSHXui:
3774 case AArch64::LDRSHWui:
3775 NumBytes = 2;
3776 OffsetScale = 2;
3777 break;
3778 }
3779
3780 // Check the fold operand is not the loaded/stored value.
3781 const MachineOperand &BaseRegOp = MemI.getOperand(0);
3782 if (BaseRegOp.isReg() && BaseRegOp.getReg() == Reg)
3783 return false;
3784
3785 // Handle memory instructions with a [Reg, Reg] addressing mode.
3786 if (MemI.getOperand(2).isReg()) {
3787 // Bail if the addressing mode already includes extension of the offset
3788 // register.
3789 if (MemI.getOperand(3).getImm())
3790 return false;
3791
3792 // Check if we actually have a scaled offset.
3793 if (MemI.getOperand(4).getImm() == 0)
3794 OffsetScale = 1;
3795
3796 // If the address instructions is folded into the base register, then the
3797 // addressing mode must not have a scale. Then we can swap the base and the
3798 // scaled registers.
3799 if (MemI.getOperand(1).getReg() == Reg && OffsetScale != 1)
3800 return false;
3801
3802 switch (AddrI.getOpcode()) {
3803 default:
3804 return false;
3805
3806 case AArch64::SBFMXri:
3807 // sxtw Xa, Wm
3808 // ldr Xd, [Xn, Xa, lsl #N]
3809 // ->
3810 // ldr Xd, [Xn, Wm, sxtw #N]
3811 if (AddrI.getOperand(2).getImm() != 0 ||
3812 AddrI.getOperand(3).getImm() != 31)
3813 return false;
3814
3815 AM.BaseReg = MemI.getOperand(1).getReg();
3816 if (AM.BaseReg == Reg)
3817 AM.BaseReg = MemI.getOperand(2).getReg();
3818 AM.ScaledReg = AddrI.getOperand(1).getReg();
3819 AM.Scale = OffsetScale;
3820 AM.Displacement = 0;
3822 return true;
3823
3824 case TargetOpcode::SUBREG_TO_REG: {
3825 // mov Wa, Wm
3826 // ldr Xd, [Xn, Xa, lsl #N]
3827 // ->
3828 // ldr Xd, [Xn, Wm, uxtw #N]
3829
3830 // Zero-extension looks like an ORRWrs followed by a SUBREG_TO_REG.
3831 if (AddrI.getOperand(2).getImm() != AArch64::sub_32)
3832 return false;
3833
3834 const MachineRegisterInfo &MRI = AddrI.getMF()->getRegInfo();
3835 Register OffsetReg = AddrI.getOperand(1).getReg();
3836 if (!OffsetReg.isVirtual() || !MRI.hasOneNonDBGUse(OffsetReg))
3837 return false;
3838
3839 const MachineInstr &DefMI = *MRI.getVRegDef(OffsetReg);
3840 if (DefMI.getOpcode() != AArch64::ORRWrs ||
3841 DefMI.getOperand(1).getReg() != AArch64::WZR ||
3842 DefMI.getOperand(3).getImm() != 0)
3843 return false;
3844
3845 AM.BaseReg = MemI.getOperand(1).getReg();
3846 if (AM.BaseReg == Reg)
3847 AM.BaseReg = MemI.getOperand(2).getReg();
3848 AM.ScaledReg = DefMI.getOperand(2).getReg();
3849 AM.Scale = OffsetScale;
3850 AM.Displacement = 0;
3852 return true;
3853 }
3854 }
3855 }
3856
3857 // Handle memory instructions with a [Reg, #Imm] addressing mode.
3858
3859 // Check we are not breaking a potential conversion to an LDP.
3860 auto validateOffsetForLDP = [](unsigned NumBytes, int64_t OldOffset,
3861 int64_t NewOffset) -> bool {
3862 int64_t MinOffset, MaxOffset;
3863 switch (NumBytes) {
3864 default:
3865 return true;
3866 case 4:
3867 MinOffset = -256;
3868 MaxOffset = 252;
3869 break;
3870 case 8:
3871 MinOffset = -512;
3872 MaxOffset = 504;
3873 break;
3874 case 16:
3875 MinOffset = -1024;
3876 MaxOffset = 1008;
3877 break;
3878 }
3879 return OldOffset < MinOffset || OldOffset > MaxOffset ||
3880 (NewOffset >= MinOffset && NewOffset <= MaxOffset);
3881 };
3882 auto canFoldAddSubImmIntoAddrMode = [&](int64_t Disp) -> bool {
3883 int64_t OldOffset = MemI.getOperand(2).getImm() * OffsetScale;
3884 int64_t NewOffset = OldOffset + Disp;
3885 if (!isLegalAddressingMode(NumBytes, NewOffset, /* Scale */ 0))
3886 return false;
3887 // If the old offset would fit into an LDP, but the new offset wouldn't,
3888 // bail out.
3889 if (!validateOffsetForLDP(NumBytes, OldOffset, NewOffset))
3890 return false;
3891 AM.BaseReg = AddrI.getOperand(1).getReg();
3892 AM.ScaledReg = 0;
3893 AM.Scale = 0;
3894 AM.Displacement = NewOffset;
3896 return true;
3897 };
3898
3899 auto canFoldAddRegIntoAddrMode =
3900 [&](int64_t Scale,
3902 if (MemI.getOperand(2).getImm() != 0)
3903 return false;
3904 if ((unsigned)Scale != Scale)
3905 return false;
3906 if (!isLegalAddressingMode(NumBytes, /* Offset */ 0, Scale))
3907 return false;
3908 AM.BaseReg = AddrI.getOperand(1).getReg();
3909 AM.ScaledReg = AddrI.getOperand(2).getReg();
3910 AM.Scale = Scale;
3911 AM.Displacement = 0;
3912 AM.Form = Form;
3913 return true;
3914 };
3915
3916 auto avoidSlowSTRQ = [&](const MachineInstr &MemI) {
3917 unsigned Opcode = MemI.getOpcode();
3918 return (Opcode == AArch64::STURQi || Opcode == AArch64::STRQui) &&
3919 Subtarget.isSTRQroSlow();
3920 };
3921
3922 int64_t Disp = 0;
3923 const bool OptSize = MemI.getMF()->getFunction().hasOptSize();
3924 switch (AddrI.getOpcode()) {
3925 default:
3926 return false;
3927
3928 case AArch64::ADDXri:
3929 // add Xa, Xn, #N
3930 // ldr Xd, [Xa, #M]
3931 // ->
3932 // ldr Xd, [Xn, #N'+M]
3933 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3934 return canFoldAddSubImmIntoAddrMode(Disp);
3935
3936 case AArch64::SUBXri:
3937 // sub Xa, Xn, #N
3938 // ldr Xd, [Xa, #M]
3939 // ->
3940 // ldr Xd, [Xn, #N'+M]
3941 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3942 return canFoldAddSubImmIntoAddrMode(-Disp);
3943
3944 case AArch64::ADDXrs: {
3945 // add Xa, Xn, Xm, lsl #N
3946 // ldr Xd, [Xa]
3947 // ->
3948 // ldr Xd, [Xn, Xm, lsl #N]
3949
3950 // Don't fold the add if the result would be slower, unless optimising for
3951 // size.
3952 unsigned Shift = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3954 return false;
3955 Shift = AArch64_AM::getShiftValue(Shift);
3956 if (!OptSize) {
3957 if (Shift != 2 && Shift != 3 && Subtarget.hasAddrLSLSlow14())
3958 return false;
3959 if (avoidSlowSTRQ(MemI))
3960 return false;
3961 }
3962 return canFoldAddRegIntoAddrMode(1ULL << Shift);
3963 }
3964
3965 case AArch64::ADDXrr:
3966 // add Xa, Xn, Xm
3967 // ldr Xd, [Xa]
3968 // ->
3969 // ldr Xd, [Xn, Xm, lsl #0]
3970
3971 // Don't fold the add if the result would be slower, unless optimising for
3972 // size.
3973 if (!OptSize && avoidSlowSTRQ(MemI))
3974 return false;
3975 return canFoldAddRegIntoAddrMode(1);
3976
3977 case AArch64::ADDXrx:
3978 // add Xa, Xn, Wm, {s,u}xtw #N
3979 // ldr Xd, [Xa]
3980 // ->
3981 // ldr Xd, [Xn, Wm, {s,u}xtw #N]
3982
3983 // Don't fold the add if the result would be slower, unless optimising for
3984 // size.
3985 if (!OptSize && avoidSlowSTRQ(MemI))
3986 return false;
3987
3988 // Can fold only sign-/zero-extend of a word.
3989 unsigned Imm = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3991 if (Extend != AArch64_AM::UXTW && Extend != AArch64_AM::SXTW)
3992 return false;
3993
3994 return canFoldAddRegIntoAddrMode(
3998 }
3999}
4000
4001// Given an opcode for an instruction with a [Reg, #Imm] addressing mode,
4002// return the opcode of an instruction performing the same operation, but using
4003// the [Reg, Reg] addressing mode.
4004static unsigned regOffsetOpcode(unsigned Opcode) {
4005 switch (Opcode) {
4006 default:
4007 llvm_unreachable("Address folding not implemented for instruction");
4008
4009 case AArch64::LDURQi:
4010 case AArch64::LDRQui:
4011 return AArch64::LDRQroX;
4012 case AArch64::STURQi:
4013 case AArch64::STRQui:
4014 return AArch64::STRQroX;
4015 case AArch64::LDURDi:
4016 case AArch64::LDRDui:
4017 return AArch64::LDRDroX;
4018 case AArch64::STURDi:
4019 case AArch64::STRDui:
4020 return AArch64::STRDroX;
4021 case AArch64::LDURXi:
4022 case AArch64::LDRXui:
4023 return AArch64::LDRXroX;
4024 case AArch64::STURXi:
4025 case AArch64::STRXui:
4026 return AArch64::STRXroX;
4027 case AArch64::LDURWi:
4028 case AArch64::LDRWui:
4029 return AArch64::LDRWroX;
4030 case AArch64::LDURSWi:
4031 case AArch64::LDRSWui:
4032 return AArch64::LDRSWroX;
4033 case AArch64::STURWi:
4034 case AArch64::STRWui:
4035 return AArch64::STRWroX;
4036 case AArch64::LDURHi:
4037 case AArch64::LDRHui:
4038 return AArch64::LDRHroX;
4039 case AArch64::STURHi:
4040 case AArch64::STRHui:
4041 return AArch64::STRHroX;
4042 case AArch64::LDURHHi:
4043 case AArch64::LDRHHui:
4044 return AArch64::LDRHHroX;
4045 case AArch64::STURHHi:
4046 case AArch64::STRHHui:
4047 return AArch64::STRHHroX;
4048 case AArch64::LDURSHXi:
4049 case AArch64::LDRSHXui:
4050 return AArch64::LDRSHXroX;
4051 case AArch64::LDURSHWi:
4052 case AArch64::LDRSHWui:
4053 return AArch64::LDRSHWroX;
4054 case AArch64::LDURBi:
4055 case AArch64::LDRBui:
4056 return AArch64::LDRBroX;
4057 case AArch64::LDURBBi:
4058 case AArch64::LDRBBui:
4059 return AArch64::LDRBBroX;
4060 case AArch64::LDURSBXi:
4061 case AArch64::LDRSBXui:
4062 return AArch64::LDRSBXroX;
4063 case AArch64::LDURSBWi:
4064 case AArch64::LDRSBWui:
4065 return AArch64::LDRSBWroX;
4066 case AArch64::STURBi:
4067 case AArch64::STRBui:
4068 return AArch64::STRBroX;
4069 case AArch64::STURBBi:
4070 case AArch64::STRBBui:
4071 return AArch64::STRBBroX;
4072 }
4073}
4074
4075// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4076// the opcode of an instruction performing the same operation, but using the
4077// [Reg, #Imm] addressing mode with scaled offset.
4078unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale) {
4079 switch (Opcode) {
4080 default:
4081 llvm_unreachable("Address folding not implemented for instruction");
4082
4083 case AArch64::LDURQi:
4084 Scale = 16;
4085 return AArch64::LDRQui;
4086 case AArch64::STURQi:
4087 Scale = 16;
4088 return AArch64::STRQui;
4089 case AArch64::LDURDi:
4090 Scale = 8;
4091 return AArch64::LDRDui;
4092 case AArch64::STURDi:
4093 Scale = 8;
4094 return AArch64::STRDui;
4095 case AArch64::LDURXi:
4096 Scale = 8;
4097 return AArch64::LDRXui;
4098 case AArch64::STURXi:
4099 Scale = 8;
4100 return AArch64::STRXui;
4101 case AArch64::LDURWi:
4102 Scale = 4;
4103 return AArch64::LDRWui;
4104 case AArch64::LDURSWi:
4105 Scale = 4;
4106 return AArch64::LDRSWui;
4107 case AArch64::STURWi:
4108 Scale = 4;
4109 return AArch64::STRWui;
4110 case AArch64::LDURHi:
4111 Scale = 2;
4112 return AArch64::LDRHui;
4113 case AArch64::STURHi:
4114 Scale = 2;
4115 return AArch64::STRHui;
4116 case AArch64::LDURHHi:
4117 Scale = 2;
4118 return AArch64::LDRHHui;
4119 case AArch64::STURHHi:
4120 Scale = 2;
4121 return AArch64::STRHHui;
4122 case AArch64::LDURSHXi:
4123 Scale = 2;
4124 return AArch64::LDRSHXui;
4125 case AArch64::LDURSHWi:
4126 Scale = 2;
4127 return AArch64::LDRSHWui;
4128 case AArch64::LDURBi:
4129 Scale = 1;
4130 return AArch64::LDRBui;
4131 case AArch64::LDURBBi:
4132 Scale = 1;
4133 return AArch64::LDRBBui;
4134 case AArch64::LDURSBXi:
4135 Scale = 1;
4136 return AArch64::LDRSBXui;
4137 case AArch64::LDURSBWi:
4138 Scale = 1;
4139 return AArch64::LDRSBWui;
4140 case AArch64::STURBi:
4141 Scale = 1;
4142 return AArch64::STRBui;
4143 case AArch64::STURBBi:
4144 Scale = 1;
4145 return AArch64::STRBBui;
4146 case AArch64::LDRQui:
4147 case AArch64::STRQui:
4148 Scale = 16;
4149 return Opcode;
4150 case AArch64::LDRDui:
4151 case AArch64::STRDui:
4152 case AArch64::LDRXui:
4153 case AArch64::STRXui:
4154 Scale = 8;
4155 return Opcode;
4156 case AArch64::LDRWui:
4157 case AArch64::LDRSWui:
4158 case AArch64::STRWui:
4159 Scale = 4;
4160 return Opcode;
4161 case AArch64::LDRHui:
4162 case AArch64::STRHui:
4163 case AArch64::LDRHHui:
4164 case AArch64::STRHHui:
4165 case AArch64::LDRSHXui:
4166 case AArch64::LDRSHWui:
4167 Scale = 2;
4168 return Opcode;
4169 case AArch64::LDRBui:
4170 case AArch64::LDRBBui:
4171 case AArch64::LDRSBXui:
4172 case AArch64::LDRSBWui:
4173 case AArch64::STRBui:
4174 case AArch64::STRBBui:
4175 Scale = 1;
4176 return Opcode;
4177 }
4178}
4179
4180// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4181// the opcode of an instruction performing the same operation, but using the
4182// [Reg, #Imm] addressing mode with unscaled offset.
4183unsigned unscaledOffsetOpcode(unsigned Opcode) {
4184 switch (Opcode) {
4185 default:
4186 llvm_unreachable("Address folding not implemented for instruction");
4187
4188 case AArch64::LDURQi:
4189 case AArch64::STURQi:
4190 case AArch64::LDURDi:
4191 case AArch64::STURDi:
4192 case AArch64::LDURXi:
4193 case AArch64::STURXi:
4194 case AArch64::LDURWi:
4195 case AArch64::LDURSWi:
4196 case AArch64::STURWi:
4197 case AArch64::LDURHi:
4198 case AArch64::STURHi:
4199 case AArch64::LDURHHi:
4200 case AArch64::STURHHi:
4201 case AArch64::LDURSHXi:
4202 case AArch64::LDURSHWi:
4203 case AArch64::LDURBi:
4204 case AArch64::STURBi:
4205 case AArch64::LDURBBi:
4206 case AArch64::STURBBi:
4207 case AArch64::LDURSBWi:
4208 case AArch64::LDURSBXi:
4209 return Opcode;
4210 case AArch64::LDRQui:
4211 return AArch64::LDURQi;
4212 case AArch64::STRQui:
4213 return AArch64::STURQi;
4214 case AArch64::LDRDui:
4215 return AArch64::LDURDi;
4216 case AArch64::STRDui:
4217 return AArch64::STURDi;
4218 case AArch64::LDRXui:
4219 return AArch64::LDURXi;
4220 case AArch64::STRXui:
4221 return AArch64::STURXi;
4222 case AArch64::LDRWui:
4223 return AArch64::LDURWi;
4224 case AArch64::LDRSWui:
4225 return AArch64::LDURSWi;
4226 case AArch64::STRWui:
4227 return AArch64::STURWi;
4228 case AArch64::LDRHui:
4229 return AArch64::LDURHi;
4230 case AArch64::STRHui:
4231 return AArch64::STURHi;
4232 case AArch64::LDRHHui:
4233 return AArch64::LDURHHi;
4234 case AArch64::STRHHui:
4235 return AArch64::STURHHi;
4236 case AArch64::LDRSHXui:
4237 return AArch64::LDURSHXi;
4238 case AArch64::LDRSHWui:
4239 return AArch64::LDURSHWi;
4240 case AArch64::LDRBBui:
4241 return AArch64::LDURBBi;
4242 case AArch64::LDRBui:
4243 return AArch64::LDURBi;
4244 case AArch64::STRBBui:
4245 return AArch64::STURBBi;
4246 case AArch64::STRBui:
4247 return AArch64::STURBi;
4248 case AArch64::LDRSBWui:
4249 return AArch64::LDURSBWi;
4250 case AArch64::LDRSBXui:
4251 return AArch64::LDURSBXi;
4252 }
4253}
4254
4255// Given the opcode of a memory load/store instruction, return the opcode of an
4256// instruction performing the same operation, but using
4257// the [Reg, Reg, {s,u}xtw #N] addressing mode with sign-/zero-extend of the
4258// offset register.
4259static unsigned offsetExtendOpcode(unsigned Opcode) {
4260 switch (Opcode) {
4261 default:
4262 llvm_unreachable("Address folding not implemented for instruction");
4263
4264 case AArch64::LDRQroX:
4265 case AArch64::LDURQi:
4266 case AArch64::LDRQui:
4267 return AArch64::LDRQroW;
4268 case AArch64::STRQroX:
4269 case AArch64::STURQi:
4270 case AArch64::STRQui:
4271 return AArch64::STRQroW;
4272 case AArch64::LDRDroX:
4273 case AArch64::LDURDi:
4274 case AArch64::LDRDui:
4275 return AArch64::LDRDroW;
4276 case AArch64::STRDroX:
4277 case AArch64::STURDi:
4278 case AArch64::STRDui:
4279 return AArch64::STRDroW;
4280 case AArch64::LDRXroX:
4281 case AArch64::LDURXi:
4282 case AArch64::LDRXui:
4283 return AArch64::LDRXroW;
4284 case AArch64::STRXroX:
4285 case AArch64::STURXi:
4286 case AArch64::STRXui:
4287 return AArch64::STRXroW;
4288 case AArch64::LDRWroX:
4289 case AArch64::LDURWi:
4290 case AArch64::LDRWui:
4291 return AArch64::LDRWroW;
4292 case AArch64::LDRSWroX:
4293 case AArch64::LDURSWi:
4294 case AArch64::LDRSWui:
4295 return AArch64::LDRSWroW;
4296 case AArch64::STRWroX:
4297 case AArch64::STURWi:
4298 case AArch64::STRWui:
4299 return AArch64::STRWroW;
4300 case AArch64::LDRHroX:
4301 case AArch64::LDURHi:
4302 case AArch64::LDRHui:
4303 return AArch64::LDRHroW;
4304 case AArch64::STRHroX:
4305 case AArch64::STURHi:
4306 case AArch64::STRHui:
4307 return AArch64::STRHroW;
4308 case AArch64::LDRHHroX:
4309 case AArch64::LDURHHi:
4310 case AArch64::LDRHHui:
4311 return AArch64::LDRHHroW;
4312 case AArch64::STRHHroX:
4313 case AArch64::STURHHi:
4314 case AArch64::STRHHui:
4315 return AArch64::STRHHroW;
4316 case AArch64::LDRSHXroX:
4317 case AArch64::LDURSHXi:
4318 case AArch64::LDRSHXui:
4319 return AArch64::LDRSHXroW;
4320 case AArch64::LDRSHWroX:
4321 case AArch64::LDURSHWi:
4322 case AArch64::LDRSHWui:
4323 return AArch64::LDRSHWroW;
4324 case AArch64::LDRBroX:
4325 case AArch64::LDURBi:
4326 case AArch64::LDRBui:
4327 return AArch64::LDRBroW;
4328 case AArch64::LDRBBroX:
4329 case AArch64::LDURBBi:
4330 case AArch64::LDRBBui:
4331 return AArch64::LDRBBroW;
4332 case AArch64::LDRSBXroX:
4333 case AArch64::LDURSBXi:
4334 case AArch64::LDRSBXui:
4335 return AArch64::LDRSBXroW;
4336 case AArch64::LDRSBWroX:
4337 case AArch64::LDURSBWi:
4338 case AArch64::LDRSBWui:
4339 return AArch64::LDRSBWroW;
4340 case AArch64::STRBroX:
4341 case AArch64::STURBi:
4342 case AArch64::STRBui:
4343 return AArch64::STRBroW;
4344 case AArch64::STRBBroX:
4345 case AArch64::STURBBi:
4346 case AArch64::STRBBui:
4347 return AArch64::STRBBroW;
4348 }
4349}
4350
4352 const ExtAddrMode &AM) const {
4353
4354 const DebugLoc &DL = MemI.getDebugLoc();
4355 MachineBasicBlock &MBB = *MemI.getParent();
4357
4359 if (AM.ScaledReg) {
4360 // The new instruction will be in the form `ldr Rt, [Xn, Xm, lsl #imm]`.
4361 unsigned Opcode = regOffsetOpcode(MemI.getOpcode());
4362 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4363 auto B = BuildMI(MBB, MemI, DL, get(Opcode))
4364 .addReg(MemI.getOperand(0).getReg(),
4365 getDefRegState(MemI.mayLoad()))
4366 .addReg(AM.BaseReg)
4367 .addReg(AM.ScaledReg)
4368 .addImm(0)
4369 .addImm(AM.Scale > 1)
4370 .setMemRefs(MemI.memoperands())
4371 .setMIFlags(MemI.getFlags());
4372 return B.getInstr();
4373 }
4374
4375 assert(AM.ScaledReg == 0 && AM.Scale == 0 &&
4376 "Addressing mode not supported for folding");
4377
4378 // The new instruction will be in the form `ld[u]r Rt, [Xn, #imm]`.
4379 unsigned Scale = 1;
4380 unsigned Opcode = MemI.getOpcode();
4381 if (isInt<9>(AM.Displacement))
4382 Opcode = unscaledOffsetOpcode(Opcode);
4383 else
4384 Opcode = scaledOffsetOpcode(Opcode, Scale);
4385
4386 auto B =
4387 BuildMI(MBB, MemI, DL, get(Opcode))
4388 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4389 .addReg(AM.BaseReg)
4390 .addImm(AM.Displacement / Scale)
4391 .setMemRefs(MemI.memoperands())
4392 .setMIFlags(MemI.getFlags());
4393 return B.getInstr();
4394 }
4395
4398 // The new instruction will be in the form `ldr Rt, [Xn, Wm, {s,u}xtw #N]`.
4399 assert(AM.ScaledReg && !AM.Displacement &&
4400 "Address offset can be a register or an immediate, but not both");
4401 unsigned Opcode = offsetExtendOpcode(MemI.getOpcode());
4402 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4403 // Make sure the offset register is in the correct register class.
4404 Register OffsetReg = AM.ScaledReg;
4405 const TargetRegisterClass *RC = MRI.getRegClass(OffsetReg);
4406 if (RC->hasSuperClassEq(&AArch64::GPR64RegClass)) {
4407 OffsetReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
4408 BuildMI(MBB, MemI, DL, get(TargetOpcode::COPY), OffsetReg)
4409 .addReg(AM.ScaledReg, {}, AArch64::sub_32);
4410 }
4411 auto B =
4412 BuildMI(MBB, MemI, DL, get(Opcode))
4413 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4414 .addReg(AM.BaseReg)
4415 .addReg(OffsetReg)
4417 .addImm(AM.Scale != 1)
4418 .setMemRefs(MemI.memoperands())
4419 .setMIFlags(MemI.getFlags());
4420
4421 return B.getInstr();
4422 }
4423
4425 "Function must not be called with an addressing mode it can't handle");
4426}
4427
4428/// Return true if the opcode is a post-index ld/st instruction, which really
4429/// loads from base+0.
4430static bool isPostIndexLdStOpcode(unsigned Opcode) {
4431 switch (Opcode) {
4432 default:
4433 return false;
4434 case AArch64::LD1Fourv16b_POST:
4435 case AArch64::LD1Fourv1d_POST:
4436 case AArch64::LD1Fourv2d_POST:
4437 case AArch64::LD1Fourv2s_POST:
4438 case AArch64::LD1Fourv4h_POST:
4439 case AArch64::LD1Fourv4s_POST:
4440 case AArch64::LD1Fourv8b_POST:
4441 case AArch64::LD1Fourv8h_POST:
4442 case AArch64::LD1Onev16b_POST:
4443 case AArch64::LD1Onev1d_POST:
4444 case AArch64::LD1Onev2d_POST:
4445 case AArch64::LD1Onev2s_POST:
4446 case AArch64::LD1Onev4h_POST:
4447 case AArch64::LD1Onev4s_POST:
4448 case AArch64::LD1Onev8b_POST:
4449 case AArch64::LD1Onev8h_POST:
4450 case AArch64::LD1Rv16b_POST:
4451 case AArch64::LD1Rv1d_POST:
4452 case AArch64::LD1Rv2d_POST:
4453 case AArch64::LD1Rv2s_POST:
4454 case AArch64::LD1Rv4h_POST:
4455 case AArch64::LD1Rv4s_POST:
4456 case AArch64::LD1Rv8b_POST:
4457 case AArch64::LD1Rv8h_POST:
4458 case AArch64::LD1Threev16b_POST:
4459 case AArch64::LD1Threev1d_POST:
4460 case AArch64::LD1Threev2d_POST:
4461 case AArch64::LD1Threev2s_POST:
4462 case AArch64::LD1Threev4h_POST:
4463 case AArch64::LD1Threev4s_POST:
4464 case AArch64::LD1Threev8b_POST:
4465 case AArch64::LD1Threev8h_POST:
4466 case AArch64::LD1Twov16b_POST:
4467 case AArch64::LD1Twov1d_POST:
4468 case AArch64::LD1Twov2d_POST:
4469 case AArch64::LD1Twov2s_POST:
4470 case AArch64::LD1Twov4h_POST:
4471 case AArch64::LD1Twov4s_POST:
4472 case AArch64::LD1Twov8b_POST:
4473 case AArch64::LD1Twov8h_POST:
4474 case AArch64::LD1i16_POST:
4475 case AArch64::LD1i32_POST:
4476 case AArch64::LD1i64_POST:
4477 case AArch64::LD1i8_POST:
4478 case AArch64::LD2Rv16b_POST:
4479 case AArch64::LD2Rv1d_POST:
4480 case AArch64::LD2Rv2d_POST:
4481 case AArch64::LD2Rv2s_POST:
4482 case AArch64::LD2Rv4h_POST:
4483 case AArch64::LD2Rv4s_POST:
4484 case AArch64::LD2Rv8b_POST:
4485 case AArch64::LD2Rv8h_POST:
4486 case AArch64::LD2Twov16b_POST:
4487 case AArch64::LD2Twov2d_POST:
4488 case AArch64::LD2Twov2s_POST:
4489 case AArch64::LD2Twov4h_POST:
4490 case AArch64::LD2Twov4s_POST:
4491 case AArch64::LD2Twov8b_POST:
4492 case AArch64::LD2Twov8h_POST:
4493 case AArch64::LD2i16_POST:
4494 case AArch64::LD2i32_POST:
4495 case AArch64::LD2i64_POST:
4496 case AArch64::LD2i8_POST:
4497 case AArch64::LD3Rv16b_POST:
4498 case AArch64::LD3Rv1d_POST:
4499 case AArch64::LD3Rv2d_POST:
4500 case AArch64::LD3Rv2s_POST:
4501 case AArch64::LD3Rv4h_POST:
4502 case AArch64::LD3Rv4s_POST:
4503 case AArch64::LD3Rv8b_POST:
4504 case AArch64::LD3Rv8h_POST:
4505 case AArch64::LD3Threev16b_POST:
4506 case AArch64::LD3Threev2d_POST:
4507 case AArch64::LD3Threev2s_POST:
4508 case AArch64::LD3Threev4h_POST:
4509 case AArch64::LD3Threev4s_POST:
4510 case AArch64::LD3Threev8b_POST:
4511 case AArch64::LD3Threev8h_POST:
4512 case AArch64::LD3i16_POST:
4513 case AArch64::LD3i32_POST:
4514 case AArch64::LD3i64_POST:
4515 case AArch64::LD3i8_POST:
4516 case AArch64::LD4Fourv16b_POST:
4517 case AArch64::LD4Fourv2d_POST:
4518 case AArch64::LD4Fourv2s_POST:
4519 case AArch64::LD4Fourv4h_POST:
4520 case AArch64::LD4Fourv4s_POST:
4521 case AArch64::LD4Fourv8b_POST:
4522 case AArch64::LD4Fourv8h_POST:
4523 case AArch64::LD4Rv16b_POST:
4524 case AArch64::LD4Rv1d_POST:
4525 case AArch64::LD4Rv2d_POST:
4526 case AArch64::LD4Rv2s_POST:
4527 case AArch64::LD4Rv4h_POST:
4528 case AArch64::LD4Rv4s_POST:
4529 case AArch64::LD4Rv8b_POST:
4530 case AArch64::LD4Rv8h_POST:
4531 case AArch64::LD4i16_POST:
4532 case AArch64::LD4i32_POST:
4533 case AArch64::LD4i64_POST:
4534 case AArch64::LD4i8_POST:
4535 case AArch64::LDAPRWpost:
4536 case AArch64::LDAPRXpost:
4537 case AArch64::LDIAPPWpost:
4538 case AArch64::LDIAPPXpost:
4539 case AArch64::LDPDpost:
4540 case AArch64::LDPQpost:
4541 case AArch64::LDPSWpost:
4542 case AArch64::LDPSpost:
4543 case AArch64::LDPWpost:
4544 case AArch64::LDPXpost:
4545 case AArch64::LDRBBpost:
4546 case AArch64::LDRBpost:
4547 case AArch64::LDRDpost:
4548 case AArch64::LDRHHpost:
4549 case AArch64::LDRHpost:
4550 case AArch64::LDRQpost:
4551 case AArch64::LDRSBWpost:
4552 case AArch64::LDRSBXpost:
4553 case AArch64::LDRSHWpost:
4554 case AArch64::LDRSHXpost:
4555 case AArch64::LDRSWpost:
4556 case AArch64::LDRSpost:
4557 case AArch64::LDRWpost:
4558 case AArch64::LDRXpost:
4559 case AArch64::ST1Fourv16b_POST:
4560 case AArch64::ST1Fourv1d_POST:
4561 case AArch64::ST1Fourv2d_POST:
4562 case AArch64::ST1Fourv2s_POST:
4563 case AArch64::ST1Fourv4h_POST:
4564 case AArch64::ST1Fourv4s_POST:
4565 case AArch64::ST1Fourv8b_POST:
4566 case AArch64::ST1Fourv8h_POST:
4567 case AArch64::ST1Onev16b_POST:
4568 case AArch64::ST1Onev1d_POST:
4569 case AArch64::ST1Onev2d_POST:
4570 case AArch64::ST1Onev2s_POST:
4571 case AArch64::ST1Onev4h_POST:
4572 case AArch64::ST1Onev4s_POST:
4573 case AArch64::ST1Onev8b_POST:
4574 case AArch64::ST1Onev8h_POST:
4575 case AArch64::ST1Threev16b_POST:
4576 case AArch64::ST1Threev1d_POST:
4577 case AArch64::ST1Threev2d_POST:
4578 case AArch64::ST1Threev2s_POST:
4579 case AArch64::ST1Threev4h_POST:
4580 case AArch64::ST1Threev4s_POST:
4581 case AArch64::ST1Threev8b_POST:
4582 case AArch64::ST1Threev8h_POST:
4583 case AArch64::ST1Twov16b_POST:
4584 case AArch64::ST1Twov1d_POST:
4585 case AArch64::ST1Twov2d_POST:
4586 case AArch64::ST1Twov2s_POST:
4587 case AArch64::ST1Twov4h_POST:
4588 case AArch64::ST1Twov4s_POST:
4589 case AArch64::ST1Twov8b_POST:
4590 case AArch64::ST1Twov8h_POST:
4591 case AArch64::ST1i16_POST:
4592 case AArch64::ST1i32_POST:
4593 case AArch64::ST1i64_POST:
4594 case AArch64::ST1i8_POST:
4595 case AArch64::ST2GPostIndex:
4596 case AArch64::ST2Twov16b_POST:
4597 case AArch64::ST2Twov2d_POST:
4598 case AArch64::ST2Twov2s_POST:
4599 case AArch64::ST2Twov4h_POST:
4600 case AArch64::ST2Twov4s_POST:
4601 case AArch64::ST2Twov8b_POST:
4602 case AArch64::ST2Twov8h_POST:
4603 case AArch64::ST2i16_POST:
4604 case AArch64::ST2i32_POST:
4605 case AArch64::ST2i64_POST:
4606 case AArch64::ST2i8_POST:
4607 case AArch64::ST3Threev16b_POST:
4608 case AArch64::ST3Threev2d_POST:
4609 case AArch64::ST3Threev2s_POST:
4610 case AArch64::ST3Threev4h_POST:
4611 case AArch64::ST3Threev4s_POST:
4612 case AArch64::ST3Threev8b_POST:
4613 case AArch64::ST3Threev8h_POST:
4614 case AArch64::ST3i16_POST:
4615 case AArch64::ST3i32_POST:
4616 case AArch64::ST3i64_POST:
4617 case AArch64::ST3i8_POST:
4618 case AArch64::ST4Fourv16b_POST:
4619 case AArch64::ST4Fourv2d_POST:
4620 case AArch64::ST4Fourv2s_POST:
4621 case AArch64::ST4Fourv4h_POST:
4622 case AArch64::ST4Fourv4s_POST:
4623 case AArch64::ST4Fourv8b_POST:
4624 case AArch64::ST4Fourv8h_POST:
4625 case AArch64::ST4i16_POST:
4626 case AArch64::ST4i32_POST:
4627 case AArch64::ST4i64_POST:
4628 case AArch64::ST4i8_POST:
4629 case AArch64::STGPostIndex:
4630 case AArch64::STGPpost:
4631 case AArch64::STPDpost:
4632 case AArch64::STPQpost:
4633 case AArch64::STPSpost:
4634 case AArch64::STPWpost:
4635 case AArch64::STPXpost:
4636 case AArch64::STRBBpost:
4637 case AArch64::STRBpost:
4638 case AArch64::STRDpost:
4639 case AArch64::STRHHpost:
4640 case AArch64::STRHpost:
4641 case AArch64::STRQpost:
4642 case AArch64::STRSpost:
4643 case AArch64::STRWpost:
4644 case AArch64::STRXpost:
4645 case AArch64::STZ2GPostIndex:
4646 case AArch64::STZGPostIndex:
4647 return true;
4648 }
4649}
4650
4652 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
4653 bool &OffsetIsScalable, TypeSize &Width) const {
4654 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4655 // Handle only loads/stores with base register followed by immediate offset.
4656 if (LdSt.getNumExplicitOperands() == 3) {
4657 // Non-paired instruction (e.g., ldr x1, [x0, #8]).
4658 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
4659 !LdSt.getOperand(2).isImm())
4660 return false;
4661 } else if (LdSt.getNumExplicitOperands() == 4) {
4662 // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
4663 if (!LdSt.getOperand(1).isReg() ||
4664 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
4665 !LdSt.getOperand(3).isImm())
4666 return false;
4667 } else
4668 return false;
4669
4670 // Get the scaling factor for the instruction and set the width for the
4671 // instruction.
4672 TypeSize Scale(0U, false);
4673 int64_t Dummy1, Dummy2;
4674
4675 // If this returns false, then it's an instruction we don't want to handle.
4676 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
4677 return false;
4678
4679 // Compute the offset. Offset is calculated as the immediate operand
4680 // multiplied by the scaling factor. Unscaled instructions have scaling factor
4681 // set to 1. Postindex are a special case which have an offset of 0.
4682 if (isPostIndexLdStOpcode(LdSt.getOpcode())) {
4683 BaseOp = &LdSt.getOperand(2);
4684 Offset = 0;
4685 } else if (LdSt.getNumExplicitOperands() == 3) {
4686 BaseOp = &LdSt.getOperand(1);
4687 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
4688 } else {
4689 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
4690 BaseOp = &LdSt.getOperand(2);
4691 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
4692 }
4693 OffsetIsScalable = Scale.isScalable();
4694
4695 return BaseOp->isReg() || BaseOp->isFI();
4696}
4697
4700 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4701 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
4702 assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
4703 return OfsOp;
4704}
4705
4706bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
4707 TypeSize &Width, int64_t &MinOffset,
4708 int64_t &MaxOffset) {
4709 switch (Opcode) {
4710 // Not a memory operation or something we want to handle.
4711 default:
4712 Scale = Width = TypeSize::getFixed(0);
4713 MinOffset = MaxOffset = 0;
4714 return false;
4715 // LDR / STR
4716 case AArch64::LDRQui:
4717 case AArch64::STRQui:
4718 Scale = Width = TypeSize::getFixed(16);
4719 MinOffset = 0;
4720 MaxOffset = 4095;
4721 break;
4722 case AArch64::LDRXui:
4723 case AArch64::LDRDui:
4724 case AArch64::STRXui:
4725 case AArch64::STRDui:
4726 case AArch64::PRFMui:
4727 case AArch64::ATOMIC_STORE_HINT_Xui:
4728 case AArch64::ATOMIC_STORE_HINT_Dui:
4729 Scale = Width = TypeSize::getFixed(8);
4730 MinOffset = 0;
4731 MaxOffset = 4095;
4732 break;
4733 case AArch64::LDRWui:
4734 case AArch64::LDRSui:
4735 case AArch64::LDRSWui:
4736 case AArch64::STRWui:
4737 case AArch64::STRSui:
4738 case AArch64::ATOMIC_STORE_HINT_Wui:
4739 case AArch64::ATOMIC_STORE_HINT_Sui:
4740 Scale = Width = TypeSize::getFixed(4);
4741 MinOffset = 0;
4742 MaxOffset = 4095;
4743 break;
4744 case AArch64::LDRHui:
4745 case AArch64::LDRHHui:
4746 case AArch64::LDRSHWui:
4747 case AArch64::LDRSHXui:
4748 case AArch64::STRHui:
4749 case AArch64::STRHHui:
4750 case AArch64::ATOMIC_STORE_HINT_Hui:
4751 Scale = Width = TypeSize::getFixed(2);
4752 MinOffset = 0;
4753 MaxOffset = 4095;
4754 break;
4755 case AArch64::LDRBui:
4756 case AArch64::LDRBBui:
4757 case AArch64::LDRSBWui:
4758 case AArch64::LDRSBXui:
4759 case AArch64::STRBui:
4760 case AArch64::STRBBui:
4761 case AArch64::ATOMIC_STORE_HINT_Bui:
4762 Scale = Width = TypeSize::getFixed(1);
4763 MinOffset = 0;
4764 MaxOffset = 4095;
4765 break;
4766 // post/pre inc
4767 case AArch64::STRQpre:
4768 case AArch64::LDRQpost:
4769 Scale = TypeSize::getFixed(1);
4770 Width = TypeSize::getFixed(16);
4771 MinOffset = -256;
4772 MaxOffset = 255;
4773 break;
4774 case AArch64::LDRDpost:
4775 case AArch64::LDRDpre:
4776 case AArch64::LDRXpost:
4777 case AArch64::LDRXpre:
4778 case AArch64::STRDpost:
4779 case AArch64::STRDpre:
4780 case AArch64::STRXpost:
4781 case AArch64::STRXpre:
4782 Scale = TypeSize::getFixed(1);
4783 Width = TypeSize::getFixed(8);
4784 MinOffset = -256;
4785 MaxOffset = 255;
4786 break;
4787 case AArch64::STRWpost:
4788 case AArch64::STRWpre:
4789 case AArch64::LDRWpost:
4790 case AArch64::LDRWpre:
4791 case AArch64::STRSpost:
4792 case AArch64::STRSpre:
4793 case AArch64::LDRSpost:
4794 case AArch64::LDRSpre:
4795 Scale = TypeSize::getFixed(1);
4796 Width = TypeSize::getFixed(4);
4797 MinOffset = -256;
4798 MaxOffset = 255;
4799 break;
4800 case AArch64::LDRHpost:
4801 case AArch64::LDRHpre:
4802 case AArch64::STRHpost:
4803 case AArch64::STRHpre:
4804 case AArch64::LDRHHpost:
4805 case AArch64::LDRHHpre:
4806 case AArch64::STRHHpost:
4807 case AArch64::STRHHpre:
4808 Scale = TypeSize::getFixed(1);
4809 Width = TypeSize::getFixed(2);
4810 MinOffset = -256;
4811 MaxOffset = 255;
4812 break;
4813 case AArch64::LDRBpost:
4814 case AArch64::LDRBpre:
4815 case AArch64::STRBpost:
4816 case AArch64::STRBpre:
4817 case AArch64::LDRBBpost:
4818 case AArch64::LDRBBpre:
4819 case AArch64::STRBBpost:
4820 case AArch64::STRBBpre:
4821 Scale = Width = TypeSize::getFixed(1);
4822 MinOffset = -256;
4823 MaxOffset = 255;
4824 break;
4825 // Unscaled
4826 case AArch64::LDURQi:
4827 case AArch64::STURQi:
4828 Scale = TypeSize::getFixed(1);
4829 Width = TypeSize::getFixed(16);
4830 MinOffset = -256;
4831 MaxOffset = 255;
4832 break;
4833 case AArch64::LDURXi:
4834 case AArch64::LDURDi:
4835 case AArch64::LDAPURXi:
4836 case AArch64::STURXi:
4837 case AArch64::STURDi:
4838 case AArch64::STLURXi:
4839 case AArch64::PRFUMi:
4840 case AArch64::ATOMIC_STORE_HINT_Xi:
4841 case AArch64::ATOMIC_STORE_HINT_Di:
4842 Scale = TypeSize::getFixed(1);
4843 Width = TypeSize::getFixed(8);
4844 MinOffset = -256;
4845 MaxOffset = 255;
4846 break;
4847 case AArch64::LDURWi:
4848 case AArch64::LDURSi:
4849 case AArch64::LDURSWi:
4850 case AArch64::LDAPURi:
4851 case AArch64::LDAPURSWi:
4852 case AArch64::STURWi:
4853 case AArch64::STURSi:
4854 case AArch64::STLURWi:
4855 case AArch64::ATOMIC_STORE_HINT_Wi:
4856 case AArch64::ATOMIC_STORE_HINT_Si:
4857 Scale = TypeSize::getFixed(1);
4858 Width = TypeSize::getFixed(4);
4859 MinOffset = -256;
4860 MaxOffset = 255;
4861 break;
4862 case AArch64::LDURHi:
4863 case AArch64::LDURHHi:
4864 case AArch64::LDURSHXi:
4865 case AArch64::LDURSHWi:
4866 case AArch64::LDAPURHi:
4867 case AArch64::LDAPURSHWi:
4868 case AArch64::LDAPURSHXi:
4869 case AArch64::STURHi:
4870 case AArch64::STURHHi:
4871 case AArch64::STLURHi:
4872 case AArch64::ATOMIC_STORE_HINT_Hi:
4873 Scale = TypeSize::getFixed(1);
4874 Width = TypeSize::getFixed(2);
4875 MinOffset = -256;
4876 MaxOffset = 255;
4877 break;
4878 case AArch64::LDURBi:
4879 case AArch64::LDURBBi:
4880 case AArch64::LDURSBXi:
4881 case AArch64::LDURSBWi:
4882 case AArch64::LDAPURBi:
4883 case AArch64::LDAPURSBWi:
4884 case AArch64::LDAPURSBXi:
4885 case AArch64::STURBi:
4886 case AArch64::STURBBi:
4887 case AArch64::STLURBi:
4888 case AArch64::ATOMIC_STORE_HINT_Bi:
4889 Scale = Width = TypeSize::getFixed(1);
4890 MinOffset = -256;
4891 MaxOffset = 255;
4892 break;
4893 // LDP / STP (including pre/post inc)
4894 case AArch64::LDPQi:
4895 case AArch64::LDNPQi:
4896 case AArch64::STPQi:
4897 case AArch64::STNPQi:
4898 case AArch64::LDPQpost:
4899 case AArch64::LDPQpre:
4900 case AArch64::STPQpost:
4901 case AArch64::STPQpre:
4902 Scale = TypeSize::getFixed(16);
4903 Width = TypeSize::getFixed(16 * 2);
4904 MinOffset = -64;
4905 MaxOffset = 63;
4906 break;
4907 case AArch64::LDPXi:
4908 case AArch64::LDPDi:
4909 case AArch64::LDNPXi:
4910 case AArch64::LDNPDi:
4911 case AArch64::STPXi:
4912 case AArch64::STPDi:
4913 case AArch64::STNPXi:
4914 case AArch64::STNPDi:
4915 case AArch64::LDPDpost:
4916 case AArch64::LDPDpre:
4917 case AArch64::LDPXpost:
4918 case AArch64::LDPXpre:
4919 case AArch64::STPDpost:
4920 case AArch64::STPDpre:
4921 case AArch64::STPXpost:
4922 case AArch64::STPXpre:
4923 Scale = TypeSize::getFixed(8);
4924 Width = TypeSize::getFixed(8 * 2);
4925 MinOffset = -64;
4926 MaxOffset = 63;
4927 break;
4928 case AArch64::LDPWi:
4929 case AArch64::LDPSi:
4930 case AArch64::LDNPWi:
4931 case AArch64::LDNPSi:
4932 case AArch64::STPWi:
4933 case AArch64::STPSi:
4934 case AArch64::STNPWi:
4935 case AArch64::STNPSi:
4936 case AArch64::LDPSpost:
4937 case AArch64::LDPSpre:
4938 case AArch64::LDPWpost:
4939 case AArch64::LDPWpre:
4940 case AArch64::STPSpost:
4941 case AArch64::STPSpre:
4942 case AArch64::STPWpost:
4943 case AArch64::STPWpre:
4944 Scale = TypeSize::getFixed(4);
4945 Width = TypeSize::getFixed(4 * 2);
4946 MinOffset = -64;
4947 MaxOffset = 63;
4948 break;
4949 case AArch64::StoreSwiftAsyncContext:
4950 // Store is an STRXui, but there might be an ADDXri in the expansion too.
4951 Scale = TypeSize::getFixed(1);
4952 Width = TypeSize::getFixed(8);
4953 MinOffset = 0;
4954 MaxOffset = 4095;
4955 break;
4956 case AArch64::ADDG:
4957 Scale = TypeSize::getFixed(16);
4958 Width = TypeSize::getFixed(0);
4959 MinOffset = 0;
4960 MaxOffset = 63;
4961 break;
4962 case AArch64::TAGPstack:
4963 Scale = TypeSize::getFixed(16);
4964 Width = TypeSize::getFixed(0);
4965 // TAGP with a negative offset turns into SUBP, which has a maximum offset
4966 // of 63 (not 64!).
4967 MinOffset = -63;
4968 MaxOffset = 63;
4969 break;
4970 case AArch64::LDG:
4971 case AArch64::STGi:
4972 case AArch64::STGPreIndex:
4973 case AArch64::STGPostIndex:
4974 case AArch64::STZGi:
4975 case AArch64::STZGPreIndex:
4976 case AArch64::STZGPostIndex:
4977 Scale = Width = TypeSize::getFixed(16);
4978 MinOffset = -256;
4979 MaxOffset = 255;
4980 break;
4981 // SVE
4982 case AArch64::STR_ZZZZXI:
4983 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
4984 case AArch64::LDR_ZZZZXI:
4985 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
4986 Scale = TypeSize::getScalable(16);
4987 Width = TypeSize::getScalable(16 * 4);
4988 MinOffset = -256;
4989 MaxOffset = 252;
4990 break;
4991 case AArch64::STR_ZZZXI:
4992 case AArch64::LDR_ZZZXI:
4993 Scale = TypeSize::getScalable(16);
4994 Width = TypeSize::getScalable(16 * 3);
4995 MinOffset = -256;
4996 MaxOffset = 253;
4997 break;
4998 case AArch64::STR_ZZXI:
4999 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
5000 case AArch64::LDR_ZZXI:
5001 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
5002 Scale = TypeSize::getScalable(16);
5003 Width = TypeSize::getScalable(16 * 2);
5004 MinOffset = -256;
5005 MaxOffset = 254;
5006 break;
5007 case AArch64::LDR_PXI:
5008 case AArch64::STR_PXI:
5009 Scale = Width = TypeSize::getScalable(2);
5010 MinOffset = -256;
5011 MaxOffset = 255;
5012 break;
5013 case AArch64::LDR_PPXI:
5014 case AArch64::STR_PPXI:
5015 Scale = TypeSize::getScalable(2);
5016 Width = TypeSize::getScalable(2 * 2);
5017 MinOffset = -256;
5018 MaxOffset = 254;
5019 break;
5020 case AArch64::LDR_ZXI:
5021 case AArch64::STR_ZXI:
5022 Scale = Width = TypeSize::getScalable(16);
5023 MinOffset = -256;
5024 MaxOffset = 255;
5025 break;
5026 case AArch64::LD1B_IMM:
5027 case AArch64::LD1H_IMM:
5028 case AArch64::LD1W_IMM:
5029 case AArch64::LD1D_IMM:
5030 case AArch64::LDNT1B_ZRI:
5031 case AArch64::LDNT1H_ZRI:
5032 case AArch64::LDNT1W_ZRI:
5033 case AArch64::LDNT1D_ZRI:
5034 case AArch64::ST1B_IMM:
5035 case AArch64::ST1H_IMM:
5036 case AArch64::ST1W_IMM:
5037 case AArch64::ST1D_IMM:
5038 case AArch64::STNT1B_ZRI:
5039 case AArch64::STNT1H_ZRI:
5040 case AArch64::STNT1W_ZRI:
5041 case AArch64::STNT1D_ZRI:
5042 case AArch64::LDNF1B_IMM:
5043 case AArch64::LDNF1H_IMM:
5044 case AArch64::LDNF1W_IMM:
5045 case AArch64::LDNF1D_IMM:
5046 // A full vectors worth of data
5047 // Width = mbytes * elements
5048 Scale = Width = TypeSize::getScalable(16);
5049 MinOffset = -8;
5050 MaxOffset = 7;
5051 break;
5052 case AArch64::LD2B_IMM:
5053 case AArch64::LD2H_IMM:
5054 case AArch64::LD2W_IMM:
5055 case AArch64::LD2D_IMM:
5056 case AArch64::ST2B_IMM:
5057 case AArch64::ST2H_IMM:
5058 case AArch64::ST2W_IMM:
5059 case AArch64::ST2D_IMM:
5060 case AArch64::LD1B_2Z_IMM:
5061 case AArch64::LD1B_2Z_STRIDED_IMM:
5062 case AArch64::LD1H_2Z_IMM:
5063 case AArch64::LD1H_2Z_STRIDED_IMM:
5064 case AArch64::LD1W_2Z_IMM:
5065 case AArch64::LD1W_2Z_STRIDED_IMM:
5066 case AArch64::LD1D_2Z_IMM:
5067 case AArch64::LD1D_2Z_STRIDED_IMM:
5068 case AArch64::LD1B_2Z_IMM_PSEUDO:
5069 case AArch64::LD1H_2Z_IMM_PSEUDO:
5070 case AArch64::LD1W_2Z_IMM_PSEUDO:
5071 case AArch64::LD1D_2Z_IMM_PSEUDO:
5072 case AArch64::ST1B_2Z_IMM:
5073 case AArch64::ST1B_2Z_STRIDED_IMM:
5074 case AArch64::ST1H_2Z_IMM:
5075 case AArch64::ST1H_2Z_STRIDED_IMM:
5076 case AArch64::ST1W_2Z_IMM:
5077 case AArch64::ST1W_2Z_STRIDED_IMM:
5078 case AArch64::ST1D_2Z_IMM:
5079 case AArch64::ST1D_2Z_STRIDED_IMM:
5080 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
5081 case AArch64::LDNT1B_2Z_IMM:
5082 case AArch64::LDNT1B_2Z_STRIDED_IMM:
5083 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
5084 case AArch64::LDNT1H_2Z_IMM:
5085 case AArch64::LDNT1H_2Z_STRIDED_IMM:
5086 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
5087 case AArch64::LDNT1W_2Z_IMM:
5088 case AArch64::LDNT1W_2Z_STRIDED_IMM:
5089 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
5090 case AArch64::LDNT1D_2Z_IMM:
5091 case AArch64::LDNT1D_2Z_STRIDED_IMM:
5092 case AArch64::STNT1B_2Z_IMM:
5093 case AArch64::STNT1B_2Z_STRIDED_IMM:
5094 case AArch64::STNT1H_2Z_IMM:
5095 case AArch64::STNT1H_2Z_STRIDED_IMM:
5096 case AArch64::STNT1W_2Z_IMM:
5097 case AArch64::STNT1W_2Z_STRIDED_IMM:
5098 case AArch64::STNT1D_2Z_IMM:
5099 case AArch64::STNT1D_2Z_STRIDED_IMM:
5100 case AArch64::ST1B_2Z_IMM_PSEUDO:
5101 case AArch64::ST1H_2Z_IMM_PSEUDO:
5102 case AArch64::ST1W_2Z_IMM_PSEUDO:
5103 case AArch64::ST1D_2Z_IMM_PSEUDO:
5104 case AArch64::STNT1B_2Z_IMM_PSEUDO:
5105 case AArch64::STNT1H_2Z_IMM_PSEUDO:
5106 case AArch64::STNT1W_2Z_IMM_PSEUDO:
5107 case AArch64::STNT1D_2Z_IMM_PSEUDO:
5108 Scale = Width = TypeSize::getScalable(16 * 2);
5109 MinOffset = -8;
5110 MaxOffset = 7;
5111 break;
5112 case AArch64::LD3B_IMM:
5113 case AArch64::LD3H_IMM:
5114 case AArch64::LD3W_IMM:
5115 case AArch64::LD3D_IMM:
5116 case AArch64::ST3B_IMM:
5117 case AArch64::ST3H_IMM:
5118 case AArch64::ST3W_IMM:
5119 case AArch64::ST3D_IMM:
5120 Scale = Width = TypeSize::getScalable(16 * 3);
5121 MinOffset = -8;
5122 MaxOffset = 7;
5123 break;
5124 case AArch64::LD4B_IMM:
5125 case AArch64::LD4H_IMM:
5126 case AArch64::LD4W_IMM:
5127 case AArch64::LD4D_IMM:
5128 case AArch64::ST4B_IMM:
5129 case AArch64::ST4H_IMM:
5130 case AArch64::ST4W_IMM:
5131 case AArch64::ST4D_IMM:
5132 case AArch64::LD1B_4Z_IMM:
5133 case AArch64::LD1B_4Z_STRIDED_IMM:
5134 case AArch64::LD1H_4Z_IMM:
5135 case AArch64::LD1H_4Z_STRIDED_IMM:
5136 case AArch64::LD1W_4Z_IMM:
5137 case AArch64::LD1W_4Z_STRIDED_IMM:
5138 case AArch64::LD1D_4Z_IMM:
5139 case AArch64::LD1D_4Z_STRIDED_IMM:
5140 case AArch64::LD1B_4Z_IMM_PSEUDO:
5141 case AArch64::LD1H_4Z_IMM_PSEUDO:
5142 case AArch64::LD1W_4Z_IMM_PSEUDO:
5143 case AArch64::LD1D_4Z_IMM_PSEUDO:
5144 case AArch64::ST1B_4Z_IMM:
5145 case AArch64::ST1B_4Z_STRIDED_IMM:
5146 case AArch64::ST1H_4Z_IMM:
5147 case AArch64::ST1H_4Z_STRIDED_IMM:
5148 case AArch64::ST1W_4Z_IMM:
5149 case AArch64::ST1W_4Z_STRIDED_IMM:
5150 case AArch64::ST1D_4Z_IMM:
5151 case AArch64::ST1D_4Z_STRIDED_IMM:
5152 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
5153 case AArch64::LDNT1B_4Z_IMM:
5154 case AArch64::LDNT1B_4Z_STRIDED_IMM:
5155 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
5156 case AArch64::LDNT1H_4Z_IMM:
5157 case AArch64::LDNT1H_4Z_STRIDED_IMM:
5158 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
5159 case AArch64::LDNT1W_4Z_IMM:
5160 case AArch64::LDNT1W_4Z_STRIDED_IMM:
5161 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
5162 case AArch64::LDNT1D_4Z_IMM:
5163 case AArch64::LDNT1D_4Z_STRIDED_IMM:
5164 case AArch64::STNT1B_4Z_IMM:
5165 case AArch64::STNT1B_4Z_STRIDED_IMM:
5166 case AArch64::STNT1H_4Z_IMM:
5167 case AArch64::STNT1H_4Z_STRIDED_IMM:
5168 case AArch64::STNT1W_4Z_IMM:
5169 case AArch64::STNT1W_4Z_STRIDED_IMM:
5170 case AArch64::STNT1D_4Z_IMM:
5171 case AArch64::STNT1D_4Z_STRIDED_IMM:
5172 case AArch64::ST1B_4Z_IMM_PSEUDO:
5173 case AArch64::ST1H_4Z_IMM_PSEUDO:
5174 case AArch64::ST1W_4Z_IMM_PSEUDO:
5175 case AArch64::ST1D_4Z_IMM_PSEUDO:
5176 case AArch64::STNT1B_4Z_IMM_PSEUDO:
5177 case AArch64::STNT1H_4Z_IMM_PSEUDO:
5178 case AArch64::STNT1W_4Z_IMM_PSEUDO:
5179 case AArch64::STNT1D_4Z_IMM_PSEUDO:
5180 Scale = Width = TypeSize::getScalable(16 * 4);
5181 MinOffset = -8;
5182 MaxOffset = 7;
5183 break;
5184 case AArch64::LD1B_H_IMM:
5185 case AArch64::LD1SB_H_IMM:
5186 case AArch64::LD1H_S_IMM:
5187 case AArch64::LD1SH_S_IMM:
5188 case AArch64::LD1W_D_IMM:
5189 case AArch64::LD1SW_D_IMM:
5190 case AArch64::ST1B_H_IMM:
5191 case AArch64::ST1H_S_IMM:
5192 case AArch64::ST1W_D_IMM:
5193 case AArch64::LDNF1B_H_IMM:
5194 case AArch64::LDNF1SB_H_IMM:
5195 case AArch64::LDNF1H_S_IMM:
5196 case AArch64::LDNF1SH_S_IMM:
5197 case AArch64::LDNF1W_D_IMM:
5198 case AArch64::LDNF1SW_D_IMM:
5199 // A half vector worth of data
5200 // Width = mbytes * elements
5201 Scale = Width = TypeSize::getScalable(8);
5202 MinOffset = -8;
5203 MaxOffset = 7;
5204 break;
5205 case AArch64::LD1B_S_IMM:
5206 case AArch64::LD1SB_S_IMM:
5207 case AArch64::LD1H_D_IMM:
5208 case AArch64::LD1SH_D_IMM:
5209 case AArch64::ST1B_S_IMM:
5210 case AArch64::ST1H_D_IMM:
5211 case AArch64::LDNF1B_S_IMM:
5212 case AArch64::LDNF1SB_S_IMM:
5213 case AArch64::LDNF1H_D_IMM:
5214 case AArch64::LDNF1SH_D_IMM:
5215 // A quarter vector worth of data
5216 // Width = mbytes * elements
5217 Scale = Width = TypeSize::getScalable(4);
5218 MinOffset = -8;
5219 MaxOffset = 7;
5220 break;
5221 case AArch64::LD1B_D_IMM:
5222 case AArch64::LD1SB_D_IMM:
5223 case AArch64::ST1B_D_IMM:
5224 case AArch64::LDNF1B_D_IMM:
5225 case AArch64::LDNF1SB_D_IMM:
5226 // A eighth vector worth of data
5227 // Width = mbytes * elements
5228 Scale = Width = TypeSize::getScalable(2);
5229 MinOffset = -8;
5230 MaxOffset = 7;
5231 break;
5232 case AArch64::ST2Gi:
5233 case AArch64::ST2GPreIndex:
5234 case AArch64::ST2GPostIndex:
5235 case AArch64::STZ2Gi:
5236 case AArch64::STZ2GPreIndex:
5237 case AArch64::STZ2GPostIndex:
5238 Scale = TypeSize::getFixed(16);
5239 Width = TypeSize::getFixed(32);
5240 MinOffset = -256;
5241 MaxOffset = 255;
5242 break;
5243 case AArch64::STGPi:
5244 case AArch64::STGPpost:
5245 case AArch64::STGPpre:
5246 Scale = Width = TypeSize::getFixed(16);
5247 MinOffset = -64;
5248 MaxOffset = 63;
5249 break;
5250 case AArch64::LD1RB_IMM:
5251 case AArch64::LD1RB_H_IMM:
5252 case AArch64::LD1RB_S_IMM:
5253 case AArch64::LD1RB_D_IMM:
5254 case AArch64::LD1RSB_H_IMM:
5255 case AArch64::LD1RSB_S_IMM:
5256 case AArch64::LD1RSB_D_IMM:
5257 Scale = Width = TypeSize::getFixed(1);
5258 MinOffset = 0;
5259 MaxOffset = 63;
5260 break;
5261 case AArch64::LD1RH_IMM:
5262 case AArch64::LD1RH_S_IMM:
5263 case AArch64::LD1RH_D_IMM:
5264 case AArch64::LD1RSH_S_IMM:
5265 case AArch64::LD1RSH_D_IMM:
5266 Scale = Width = TypeSize::getFixed(2);
5267 MinOffset = 0;
5268 MaxOffset = 63;
5269 break;
5270 case AArch64::LD1RW_IMM:
5271 case AArch64::LD1RW_D_IMM:
5272 case AArch64::LD1RSW_IMM:
5273 Scale = Width = TypeSize::getFixed(4);
5274 MinOffset = 0;
5275 MaxOffset = 63;
5276 break;
5277 case AArch64::LD1RD_IMM:
5278 Scale = Width = TypeSize::getFixed(8);
5279 MinOffset = 0;
5280 MaxOffset = 63;
5281 break;
5282 }
5283
5284 return true;
5285}
5286
5287// Scaling factor for unscaled load or store.
5289 switch (Opc) {
5290 default:
5291 llvm_unreachable("Opcode has unknown scale!");
5292 case AArch64::LDRBui:
5293 case AArch64::LDRBBui:
5294 case AArch64::LDURBBi:
5295 case AArch64::LDRSBWui:
5296 case AArch64::LDURSBWi:
5297 case AArch64::STRBui:
5298 case AArch64::STRBBui:
5299 case AArch64::STURBBi:
5300 return 1;
5301 case AArch64::LDRHui:
5302 case AArch64::LDRHHui:
5303 case AArch64::LDURHHi:
5304 case AArch64::LDRSHWui:
5305 case AArch64::LDURSHWi:
5306 case AArch64::STRHui:
5307 case AArch64::STRHHui:
5308 case AArch64::STURHHi:
5309 return 2;
5310 case AArch64::LDRSui:
5311 case AArch64::LDURSi:
5312 case AArch64::LDRSpre:
5313 case AArch64::LDRSWui:
5314 case AArch64::LDURSWi:
5315 case AArch64::LDRSWpre:
5316 case AArch64::LDRWpre:
5317 case AArch64::LDRWui:
5318 case AArch64::LDURWi:
5319 case AArch64::STRSui:
5320 case AArch64::STURSi:
5321 case AArch64::STRSpre:
5322 case AArch64::STRWui:
5323 case AArch64::STURWi:
5324 case AArch64::STRWpre:
5325 case AArch64::LDPSi:
5326 case AArch64::LDPSWi:
5327 case AArch64::LDPWi:
5328 case AArch64::STPSi:
5329 case AArch64::STPWi:
5330 return 4;
5331 case AArch64::LDRDui:
5332 case AArch64::LDURDi:
5333 case AArch64::LDRDpre:
5334 case AArch64::LDRXui:
5335 case AArch64::LDURXi:
5336 case AArch64::LDRXpre:
5337 case AArch64::STRDui:
5338 case AArch64::STURDi:
5339 case AArch64::STRDpre:
5340 case AArch64::STRXui:
5341 case AArch64::STURXi:
5342 case AArch64::STRXpre:
5343 case AArch64::LDPDi:
5344 case AArch64::LDPXi:
5345 case AArch64::STPDi:
5346 case AArch64::STPXi:
5347 return 8;
5348 case AArch64::LDRQui:
5349 case AArch64::LDURQi:
5350 case AArch64::STRQui:
5351 case AArch64::STURQi:
5352 case AArch64::STRQpre:
5353 case AArch64::LDPQi:
5354 case AArch64::LDRQpre:
5355 case AArch64::STPQi:
5356 case AArch64::STGi:
5357 case AArch64::STZGi:
5358 case AArch64::ST2Gi:
5359 case AArch64::STZ2Gi:
5360 case AArch64::STGPi:
5361 return 16;
5362 }
5363}
5364
5366 switch (MI.getOpcode()) {
5367 default:
5368 return false;
5369 case AArch64::LDRWpre:
5370 case AArch64::LDRXpre:
5371 case AArch64::LDRSWpre:
5372 case AArch64::LDRSpre:
5373 case AArch64::LDRDpre:
5374 case AArch64::LDRQpre:
5375 return true;
5376 }
5377}
5378
5380 switch (MI.getOpcode()) {
5381 default:
5382 return false;
5383 case AArch64::STRWpre:
5384 case AArch64::STRXpre:
5385 case AArch64::STRSpre:
5386 case AArch64::STRDpre:
5387 case AArch64::STRQpre:
5388 return true;
5389 }
5390}
5391
5393 return isPreLd(MI) || isPreSt(MI);
5394}
5395
5397 switch (MI.getOpcode()) {
5398 default:
5399 return false;
5400 case AArch64::LDURBBi:
5401 case AArch64::LDURHHi:
5402 case AArch64::LDURWi:
5403 case AArch64::LDRBBui:
5404 case AArch64::LDRHHui:
5405 case AArch64::LDRWui:
5406 case AArch64::LDRBBroX:
5407 case AArch64::LDRHHroX:
5408 case AArch64::LDRWroX:
5409 case AArch64::LDRBBroW:
5410 case AArch64::LDRHHroW:
5411 case AArch64::LDRWroW:
5412 return true;
5413 }
5414}
5415
5417 switch (MI.getOpcode()) {
5418 default:
5419 return false;
5420 case AArch64::LDURSBWi:
5421 case AArch64::LDURSHWi:
5422 case AArch64::LDURSBXi:
5423 case AArch64::LDURSHXi:
5424 case AArch64::LDURSWi:
5425 case AArch64::LDRSBWui:
5426 case AArch64::LDRSHWui:
5427 case AArch64::LDRSBXui:
5428 case AArch64::LDRSHXui:
5429 case AArch64::LDRSWui:
5430 case AArch64::LDRSBWroX:
5431 case AArch64::LDRSHWroX:
5432 case AArch64::LDRSBXroX:
5433 case AArch64::LDRSHXroX:
5434 case AArch64::LDRSWroX:
5435 case AArch64::LDRSBWroW:
5436 case AArch64::LDRSHWroW:
5437 case AArch64::LDRSBXroW:
5438 case AArch64::LDRSHXroW:
5439 case AArch64::LDRSWroW:
5440 return true;
5441 }
5442}
5443
5445 switch (MI.getOpcode()) {
5446 default:
5447 return false;
5448 case AArch64::LDPSi:
5449 case AArch64::LDPSWi:
5450 case AArch64::LDPDi:
5451 case AArch64::LDPQi:
5452 case AArch64::LDPWi:
5453 case AArch64::LDPXi:
5454 case AArch64::STPSi:
5455 case AArch64::STPDi:
5456 case AArch64::STPQi:
5457 case AArch64::STPWi:
5458 case AArch64::STPXi:
5459 case AArch64::STGPi:
5460 return true;
5461 }
5462}
5463
5465 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5466 unsigned Idx =
5468 : 1;
5469 return MI.getOperand(Idx);
5470}
5471
5472const MachineOperand &
5474 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5475 unsigned Idx =
5477 : 2;
5478 return MI.getOperand(Idx);
5479}
5480
5481const MachineOperand &
5483 switch (MI.getOpcode()) {
5484 default:
5485 llvm_unreachable("Unexpected opcode");
5486 case AArch64::LDRBroX:
5487 case AArch64::LDRBBroX:
5488 case AArch64::LDRSBXroX:
5489 case AArch64::LDRSBWroX:
5490 case AArch64::LDRHroX:
5491 case AArch64::LDRHHroX:
5492 case AArch64::LDRSHXroX:
5493 case AArch64::LDRSHWroX:
5494 case AArch64::LDRWroX:
5495 case AArch64::LDRSroX:
5496 case AArch64::LDRSWroX:
5497 case AArch64::LDRDroX:
5498 case AArch64::LDRXroX:
5499 case AArch64::LDRQroX:
5500 return MI.getOperand(4);
5501 }
5502}
5503
5505 Register Reg) {
5506 if (MI.getParent() == nullptr)
5507 return nullptr;
5508 const MachineFunction *MF = MI.getParent()->getParent();
5509 return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
5510}
5511
5513 auto IsHFPR = [&](const MachineOperand &Op) {
5514 if (!Op.isReg())
5515 return false;
5516 auto Reg = Op.getReg();
5517 if (Reg.isPhysical())
5518 return AArch64::FPR16RegClass.contains(Reg);
5519 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5520 return TRC == &AArch64::FPR16RegClass ||
5521 TRC == &AArch64::FPR16_loRegClass;
5522 };
5523 return llvm::any_of(MI.operands(), IsHFPR);
5524}
5525
5527 auto IsQFPR = [&](const MachineOperand &Op) {
5528 if (!Op.isReg())
5529 return false;
5530 auto Reg = Op.getReg();
5531 if (Reg.isPhysical())
5532 return AArch64::FPR128RegClass.contains(Reg);
5533 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5534 return TRC == &AArch64::FPR128RegClass ||
5535 TRC == &AArch64::FPR128_loRegClass;
5536 };
5537 return llvm::any_of(MI.operands(), IsQFPR);
5538}
5539
5541 switch (MI.getOpcode()) {
5542 case AArch64::BRK:
5543 case AArch64::HLT:
5544 case AArch64::PACIASP:
5545 case AArch64::PACIBSP:
5546 case AArch64::PACIASPPC:
5547 case AArch64::PACIBSPPC:
5548 // Implicit BTI behavior.
5549 return true;
5550 case AArch64::PAUTH_PROLOGUE:
5551 // PAUTH_PROLOGUE expands to PACI(A|B)SP.
5552 return true;
5553 case AArch64::HINT: {
5554 unsigned Imm = MI.getOperand(0).getImm();
5555 // Explicit BTI instruction.
5556 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
5557 return true;
5558 // PACI(A|B)SP instructions.
5559 if (Imm == 25 || Imm == 27)
5560 return true;
5561 return false;
5562 }
5563 default:
5564 return false;
5565 }
5566}
5567
5569 if (Reg == 0)
5570 return false;
5571 assert(Reg.isPhysical() && "Expected physical register in isFpOrNEON");
5572 return AArch64::FPR128RegClass.contains(Reg) ||
5573 AArch64::FPR64RegClass.contains(Reg) ||
5574 AArch64::FPR32RegClass.contains(Reg) ||
5575 AArch64::FPR16RegClass.contains(Reg) ||
5576 AArch64::FPR8RegClass.contains(Reg);
5577}
5578
5580 auto IsFPR = [&](const MachineOperand &Op) {
5581 if (!Op.isReg())
5582 return false;
5583 auto Reg = Op.getReg();
5584 if (Reg.isPhysical())
5585 return isFpOrNEON(Reg);
5586
5587 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5588 return TRC == &AArch64::FPR128RegClass ||
5589 TRC == &AArch64::FPR128_loRegClass ||
5590 TRC == &AArch64::FPR64RegClass ||
5591 TRC == &AArch64::FPR64_loRegClass ||
5592 TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
5593 TRC == &AArch64::FPR8RegClass;
5594 };
5595 return llvm::any_of(MI.operands(), IsFPR);
5596}
5597
5598// Scale the unscaled offsets. Returns false if the unscaled offset can't be
5599// scaled.
5600static bool scaleOffset(unsigned Opc, int64_t &Offset) {
5602
5603 // If the byte-offset isn't a multiple of the stride, we can't scale this
5604 // offset.
5605 if (Offset % Scale != 0)
5606 return false;
5607
5608 // Convert the byte-offset used by unscaled into an "element" offset used
5609 // by the scaled pair load/store instructions.
5610 Offset /= Scale;
5611 return true;
5612}
5613
5614static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
5615 if (FirstOpc == SecondOpc)
5616 return true;
5617 // We can also pair sign-ext and zero-ext instructions.
5618 switch (FirstOpc) {
5619 default:
5620 return false;
5621 case AArch64::STRSui:
5622 case AArch64::STURSi:
5623 return SecondOpc == AArch64::STRSui || SecondOpc == AArch64::STURSi;
5624 case AArch64::STRDui:
5625 case AArch64::STURDi:
5626 return SecondOpc == AArch64::STRDui || SecondOpc == AArch64::STURDi;
5627 case AArch64::STRQui:
5628 case AArch64::STURQi:
5629 return SecondOpc == AArch64::STRQui || SecondOpc == AArch64::STURQi;
5630 case AArch64::STRWui:
5631 case AArch64::STURWi:
5632 return SecondOpc == AArch64::STRWui || SecondOpc == AArch64::STURWi;
5633 case AArch64::STRXui:
5634 case AArch64::STURXi:
5635 return SecondOpc == AArch64::STRXui || SecondOpc == AArch64::STURXi;
5636 case AArch64::LDRSui:
5637 case AArch64::LDURSi:
5638 return SecondOpc == AArch64::LDRSui || SecondOpc == AArch64::LDURSi;
5639 case AArch64::LDRDui:
5640 case AArch64::LDURDi:
5641 return SecondOpc == AArch64::LDRDui || SecondOpc == AArch64::LDURDi;
5642 case AArch64::LDRQui:
5643 case AArch64::LDURQi:
5644 return SecondOpc == AArch64::LDRQui || SecondOpc == AArch64::LDURQi;
5645 case AArch64::LDRWui:
5646 case AArch64::LDURWi:
5647 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
5648 case AArch64::LDRSWui:
5649 case AArch64::LDURSWi:
5650 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
5651 case AArch64::LDRXui:
5652 case AArch64::LDURXi:
5653 return SecondOpc == AArch64::LDRXui || SecondOpc == AArch64::LDURXi;
5654 }
5655 // These instructions can't be paired based on their opcodes.
5656 return false;
5657}
5658
5659static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
5660 int64_t Offset1, unsigned Opcode1, int FI2,
5661 int64_t Offset2, unsigned Opcode2) {
5662 // Accesses through fixed stack object frame indices may access a different
5663 // fixed stack slot. Check that the object offsets + offsets match.
5664 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
5665 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
5666 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
5667 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
5668 // Convert to scaled object offsets.
5669 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
5670 if (ObjectOffset1 % Scale1 != 0)
5671 return false;
5672 ObjectOffset1 /= Scale1;
5673 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
5674 if (ObjectOffset2 % Scale2 != 0)
5675 return false;
5676 ObjectOffset2 /= Scale2;
5677 ObjectOffset1 += Offset1;
5678 ObjectOffset2 += Offset2;
5679 return ObjectOffset1 + 1 == ObjectOffset2;
5680 }
5681
5682 return FI1 == FI2;
5683}
5684
5685/// Detect opportunities for ldp/stp formation.
5686///
5687/// Only called for LdSt for which getMemOperandWithOffset returns true.
5689 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
5690 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
5691 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
5692 unsigned NumBytes) const {
5693 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
5694 const MachineOperand &BaseOp1 = *BaseOps1.front();
5695 const MachineOperand &BaseOp2 = *BaseOps2.front();
5696 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
5697 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
5698 if (BaseOp1.getType() != BaseOp2.getType())
5699 return false;
5700
5701 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
5702 "Only base registers and frame indices are supported.");
5703
5704 // Check for both base regs and base FI.
5705 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
5706 return false;
5707
5708 // Only cluster up to a single pair.
5709 if (ClusterSize > 2)
5710 return false;
5711
5712 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
5713 return false;
5714
5715 // Can we pair these instructions based on their opcodes?
5716 unsigned FirstOpc = FirstLdSt.getOpcode();
5717 unsigned SecondOpc = SecondLdSt.getOpcode();
5718 if (!canPairLdStOpc(FirstOpc, SecondOpc))
5719 return false;
5720
5721 // Can't merge volatiles or load/stores that have a hint to avoid pair
5722 // formation, for example.
5723 if (!isCandidateToMergeOrPair(FirstLdSt) ||
5724 !isCandidateToMergeOrPair(SecondLdSt))
5725 return false;
5726
5727 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
5728 int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
5729 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
5730 return false;
5731
5732 int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
5733 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
5734 return false;
5735
5736 // Pairwise instructions have a 7-bit signed offset field.
5737 if (Offset1 > 63 || Offset1 < -64)
5738 return false;
5739
5740 // The caller should already have ordered First/SecondLdSt by offset.
5741 // Note: except for non-equal frame index bases
5742 if (BaseOp1.isFI()) {
5743 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
5744 "Caller should have ordered offsets.");
5745
5746 const MachineFrameInfo &MFI =
5747 FirstLdSt.getParent()->getParent()->getFrameInfo();
5748 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
5749 BaseOp2.getIndex(), Offset2, SecondOpc);
5750 }
5751
5752 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
5753
5754 return Offset1 + 1 == Offset2;
5755}
5756
5758 MCRegister Reg, unsigned SubIdx,
5759 RegState State,
5760 const TargetRegisterInfo *TRI) {
5761 if (!SubIdx)
5762 return MIB.addReg(Reg, State);
5763
5764 if (Reg.isPhysical())
5765 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
5766 return MIB.addReg(Reg, State, SubIdx);
5767}
5768
5771 const DebugLoc &DL, MCRegister DestReg,
5772 MCRegister SrcReg, bool KillSrc,
5773 ArrayRef<unsigned> Indices) const {
5774 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
5776 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5777 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5778 unsigned NumRegs = Indices.size();
5779 MCRegister DestSubReg = TRI->getSubReg(DestReg, Indices[0]);
5780 assert(!AArch64::PNRRegClass.contains(DestSubReg) &&
5781 "Unexpected predicate tuple copy");
5782 unsigned MaxRegs = AArch64::PPRRegClass.contains(DestSubReg) ? 15 : 31;
5783
5784 int SubReg = 0, End = NumRegs, Incr = 1;
5785 // Copy in reverse if a forward copy will clobber the tuple
5786 if (((DestEncoding - SrcEncoding) & MaxRegs) < NumRegs) {
5787 SubReg = NumRegs - 1;
5788 End = -1;
5789 Incr = -1;
5790 }
5791
5792 for (; SubReg != End; SubReg += Incr) {
5793 DestSubReg = TRI->getSubReg(DestReg, Indices[SubReg]);
5794 MCRegister SrcSubReg = TRI->getSubReg(SrcReg, Indices[SubReg]);
5795 copyPhysRegImpl(MBB, I, DL, DestSubReg, SrcSubReg, KillSrc);
5796 }
5797}
5798
5801 const DebugLoc &DL, MCRegister DestReg,
5802 MCRegister SrcReg, bool KillSrc,
5803 unsigned Opcode, unsigned ZeroReg,
5804 llvm::ArrayRef<unsigned> Indices) const {
5806 unsigned NumRegs = Indices.size();
5807
5808#ifndef NDEBUG
5809 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5810 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5811 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
5812 "GPR reg sequences should not be able to overlap");
5813#endif
5814
5815 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
5816 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5817 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5818 MIB.addReg(ZeroReg);
5819 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5820 MIB.addImm(0);
5821 }
5822}
5823
5824/// Returns true if the instruction at I is in a streaming call site region,
5825/// within a single basic block.
5826/// A "call site streaming region" starts after smstart and ends at smstop
5827/// around a call to a streaming function. This walks backward from I.
5830 MachineFunction &MF = *MBB.getParent();
5832 if (!AFI->hasStreamingModeChanges())
5833 return false;
5834 // Walk backwards to find smstart/smstop
5835 for (MachineInstr &MI : reverse(make_range(MBB.begin(), I))) {
5836 unsigned Opc = MI.getOpcode();
5837 if (Opc == AArch64::MSRpstatesvcrImm1 || Opc == AArch64::MSRpstatePseudo) {
5838 // Check if this is SM change (not ZA)
5839 int64_t PState = MI.getOperand(0).getImm();
5840 if (PState == AArch64SVCR::SVCRSM || PState == AArch64SVCR::SVCRSMZA) {
5841 // Operand 1 is 1 for start, 0 for stop
5842 return MI.getOperand(1).getImm() == 1;
5843 }
5844 }
5845 }
5846 return false;
5847}
5848
5849/// Returns true if in a streaming call site region without SME-FA64.
5855
5858 const DebugLoc &DL, Register DestReg,
5859 Register SrcReg, bool KillSrc,
5860 bool RenamableDest,
5861 bool RenamableSrc) const {
5862 if (AArch64::GPR32spRegClass.contains(DestReg) &&
5863 AArch64::GPR32spRegClass.contains(SrcReg)) {
5864 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
5865 // If either operand is WSP, expand to ADD #0.
5866 if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5867 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5868 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
5869 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5870 &AArch64::GPR64spRegClass);
5871 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5872 &AArch64::GPR64spRegClass);
5873 // This instruction is reading and writing X registers. This may upset
5874 // the register scavenger and machine verifier, so we need to indicate
5875 // that we are reading an undefined value from SrcRegX, but a proper
5876 // value from SrcReg.
5877 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
5878 .addReg(SrcRegX, RegState::Undef)
5879 .addImm(0)
5881 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5882 ++NumZCRegMoveInstrsGPR;
5883 } else {
5884 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
5885 .addReg(SrcReg, getKillRegState(KillSrc))
5886 .addImm(0)
5888 if (Subtarget.hasZeroCycleRegMoveGPR32())
5889 ++NumZCRegMoveInstrsGPR;
5890 }
5891 } else if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5892 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5893 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
5894 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5895 &AArch64::GPR64spRegClass);
5896 assert(DestRegX.isValid() && "Destination super-reg not valid");
5897 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5898 &AArch64::GPR64spRegClass);
5899 assert(SrcRegX.isValid() && "Source super-reg not valid");
5900 // This instruction is reading and writing X registers. This may upset
5901 // the register scavenger and machine verifier, so we need to indicate
5902 // that we are reading an undefined value from SrcRegX, but a proper
5903 // value from SrcReg.
5904 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
5905 .addReg(AArch64::XZR)
5906 .addReg(SrcRegX, RegState::Undef)
5907 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5908 ++NumZCRegMoveInstrsGPR;
5909 } else {
5910 // Otherwise, expand to ORR WZR.
5911 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5912 .addReg(AArch64::WZR)
5913 .addReg(SrcReg, getKillRegState(KillSrc));
5914 if (Subtarget.hasZeroCycleRegMoveGPR32())
5915 ++NumZCRegMoveInstrsGPR;
5916 }
5917 return;
5918 }
5919
5920 // GPR32 zeroing
5921 if (AArch64::GPR32spRegClass.contains(DestReg) && SrcReg == AArch64::WZR) {
5922 if (Subtarget.hasZeroCycleZeroingGPR64() &&
5923 !Subtarget.hasZeroCycleZeroingGPR32()) {
5924 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5925 &AArch64::GPR64spRegClass);
5926 assert(DestRegX.isValid() && "Destination super-reg not valid");
5927 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestRegX)
5928 .addImm(0)
5930 ++NumZCZeroingInstrsGPR;
5931 } else if (Subtarget.hasZeroCycleZeroingGPR32()) {
5932 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
5933 .addImm(0)
5935 ++NumZCZeroingInstrsGPR;
5936 } else {
5937 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5938 .addReg(AArch64::WZR)
5939 .addReg(AArch64::WZR);
5940 }
5941 return;
5942 }
5943
5944 if (AArch64::GPR64spRegClass.contains(DestReg) &&
5945 AArch64::GPR64spRegClass.contains(SrcReg)) {
5946 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
5947 // If either operand is SP, expand to ADD #0.
5948 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
5949 .addReg(SrcReg, getKillRegState(KillSrc))
5950 .addImm(0)
5952 if (Subtarget.hasZeroCycleRegMoveGPR64())
5953 ++NumZCRegMoveInstrsGPR;
5954 } else {
5955 // Otherwise, expand to ORR XZR.
5956 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5957 .addReg(AArch64::XZR)
5958 .addReg(SrcReg, getKillRegState(KillSrc));
5959 if (Subtarget.hasZeroCycleRegMoveGPR64())
5960 ++NumZCRegMoveInstrsGPR;
5961 }
5962 return;
5963 }
5964
5965 // GPR64 zeroing
5966 if (AArch64::GPR64spRegClass.contains(DestReg) && SrcReg == AArch64::XZR) {
5967 if (Subtarget.hasZeroCycleZeroingGPR64()) {
5968 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
5969 .addImm(0)
5971 ++NumZCZeroingInstrsGPR;
5972 } else {
5973 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5974 .addReg(AArch64::XZR)
5975 .addReg(AArch64::XZR);
5976 }
5977 return;
5978 }
5979
5980 // Copy a Predicate register by ORRing with itself.
5981 if (AArch64::PPRRegClass.contains(DestReg) &&
5982 AArch64::PPRRegClass.contains(SrcReg)) {
5983 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5984 "Unexpected SVE register.");
5985 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
5986 .addReg(SrcReg) // Pg
5987 .addReg(SrcReg)
5988 .addReg(SrcReg, getKillRegState(KillSrc));
5989 return;
5990 }
5991
5992 // Copy a predicate-as-counter register by ORRing with itself as if it
5993 // were a regular predicate (mask) register.
5994 bool DestIsPNR = AArch64::PNRRegClass.contains(DestReg);
5995 bool SrcIsPNR = AArch64::PNRRegClass.contains(SrcReg);
5996 if (DestIsPNR || SrcIsPNR) {
5997 auto ToPPR = [](MCRegister R) -> MCRegister {
5998 return (R - AArch64::PN0) + AArch64::P0;
5999 };
6000 MCRegister PPRSrcReg = SrcIsPNR ? ToPPR(SrcReg) : SrcReg.asMCReg();
6001 MCRegister PPRDestReg = DestIsPNR ? ToPPR(DestReg) : DestReg.asMCReg();
6002
6003 if (PPRSrcReg != PPRDestReg) {
6004 auto NewMI = BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), PPRDestReg)
6005 .addReg(PPRSrcReg) // Pg
6006 .addReg(PPRSrcReg)
6007 .addReg(PPRSrcReg, getKillRegState(KillSrc));
6008 if (DestIsPNR)
6009 NewMI.addDef(DestReg, RegState::Implicit);
6010 }
6011 return;
6012 }
6013
6014 // Copy a predicate register pair by copying the individual sub-registers.
6015 if (AArch64::PPR2RegClass.contains(DestReg) &&
6016 AArch64::PPR2RegClass.contains(SrcReg)) {
6017 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6018 "Unexpected SVE predicate register.");
6019 static const unsigned Indices[] = {AArch64::psub0, AArch64::psub1};
6020 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6021 return;
6022 }
6023
6024 // Copy a Z register by ORRing with itself.
6025 if (AArch64::ZPRRegClass.contains(DestReg) &&
6026 AArch64::ZPRRegClass.contains(SrcReg)) {
6027 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6028 "Unexpected SVE register.");
6029 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
6030 .addReg(SrcReg)
6031 .addReg(SrcReg, getKillRegState(KillSrc));
6032 return;
6033 }
6034
6035 // Copy a Z register pair by copying the individual sub-registers.
6036 if ((AArch64::ZPR2RegClass.contains(DestReg) ||
6037 AArch64::ZPR2StridedOrContiguousRegClass.contains(DestReg)) &&
6038 (AArch64::ZPR2RegClass.contains(SrcReg) ||
6039 AArch64::ZPR2StridedOrContiguousRegClass.contains(SrcReg))) {
6040 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6041 "Unexpected SVE register.");
6042 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
6043 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6044 return;
6045 }
6046
6047 // Copy a Z register triple by copying the individual sub-registers.
6048 if (AArch64::ZPR3RegClass.contains(DestReg) &&
6049 AArch64::ZPR3RegClass.contains(SrcReg)) {
6050 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6051 "Unexpected SVE register.");
6052 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6053 AArch64::zsub2};
6054 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6055 return;
6056 }
6057
6058 // Copy a Z register quad by copying the individual sub-registers.
6059 if ((AArch64::ZPR4RegClass.contains(DestReg) ||
6060 AArch64::ZPR4StridedOrContiguousRegClass.contains(DestReg)) &&
6061 (AArch64::ZPR4RegClass.contains(SrcReg) ||
6062 AArch64::ZPR4StridedOrContiguousRegClass.contains(SrcReg))) {
6063 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6064 "Unexpected SVE register.");
6065 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6066 AArch64::zsub2, AArch64::zsub3};
6067 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6068 return;
6069 }
6070
6071 // Copy a DDDD register quad by copying the individual sub-registers.
6072 if (AArch64::DDDDRegClass.contains(DestReg) &&
6073 AArch64::DDDDRegClass.contains(SrcReg)) {
6074 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6075 AArch64::dsub2, AArch64::dsub3};
6076 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6077 return;
6078 }
6079
6080 // Copy a DDD register triple by copying the individual sub-registers.
6081 if (AArch64::DDDRegClass.contains(DestReg) &&
6082 AArch64::DDDRegClass.contains(SrcReg)) {
6083 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6084 AArch64::dsub2};
6085 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6086 return;
6087 }
6088
6089 // Copy a DD register pair by copying the individual sub-registers.
6090 if (AArch64::DDRegClass.contains(DestReg) &&
6091 AArch64::DDRegClass.contains(SrcReg)) {
6092 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
6093 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6094 return;
6095 }
6096
6097 // Copy a QQQQ register quad by copying the individual sub-registers.
6098 if (AArch64::QQQQRegClass.contains(DestReg) &&
6099 AArch64::QQQQRegClass.contains(SrcReg)) {
6100 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6101 AArch64::qsub2, AArch64::qsub3};
6102 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6103 return;
6104 }
6105
6106 // Copy a QQQ register triple by copying the individual sub-registers.
6107 if (AArch64::QQQRegClass.contains(DestReg) &&
6108 AArch64::QQQRegClass.contains(SrcReg)) {
6109 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6110 AArch64::qsub2};
6111 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6112 return;
6113 }
6114
6115 // Copy a QQ register pair by copying the individual sub-registers.
6116 if (AArch64::QQRegClass.contains(DestReg) &&
6117 AArch64::QQRegClass.contains(SrcReg)) {
6118 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
6119 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6120 return;
6121 }
6122
6123 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
6124 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
6125 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
6126 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
6127 AArch64::XZR, Indices);
6128 return;
6129 }
6130
6131 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
6132 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
6133 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
6134 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
6135 AArch64::WZR, Indices);
6136 return;
6137 }
6138
6139 if (AArch64::FPR128RegClass.contains(DestReg) &&
6140 AArch64::FPR128RegClass.contains(SrcReg)) {
6141 // In streaming regions, NEON is illegal but streaming-SVE is available.
6142 // Use SVE for copies if we're in a streaming region and SME is available.
6143 // With +sme-fa64, NEON is legal in streaming mode so we can use it.
6144 if ((Subtarget.isSVEorStreamingSVEAvailable() &&
6145 !Subtarget.isNeonAvailable()) ||
6146 mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6147 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
6148 .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
6149 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
6150 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
6151 } else if (Subtarget.isNeonAvailable()) {
6152 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
6153 .addReg(SrcReg)
6154 .addReg(SrcReg, getKillRegState(KillSrc));
6155 if (Subtarget.hasZeroCycleRegMoveFPR128())
6156 ++NumZCRegMoveInstrsFPR;
6157 } else {
6158 BuildMI(MBB, I, DL, get(AArch64::STRQpre))
6159 .addReg(AArch64::SP, RegState::Define)
6160 .addReg(SrcReg, getKillRegState(KillSrc))
6161 .addReg(AArch64::SP)
6162 .addImm(-16);
6163 BuildMI(MBB, I, DL, get(AArch64::LDRQpost))
6164 .addReg(AArch64::SP, RegState::Define)
6165 .addReg(DestReg, RegState::Define)
6166 .addReg(AArch64::SP)
6167 .addImm(16);
6168 }
6169 return;
6170 }
6171
6172 if (AArch64::FPR64RegClass.contains(DestReg) &&
6173 AArch64::FPR64RegClass.contains(SrcReg)) {
6174 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6175 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6176 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6177 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6178 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::dsub,
6179 &AArch64::FPR128RegClass);
6180 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::dsub,
6181 &AArch64::FPR128RegClass);
6182 // This instruction is reading and writing Q registers. This may upset
6183 // the register scavenger and machine verifier, so we need to indicate
6184 // that we are reading an undefined value from SrcRegQ, but a proper
6185 // value from SrcReg.
6186 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6187 .addReg(SrcRegQ, RegState::Undef)
6188 .addReg(SrcRegQ, RegState::Undef)
6189 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6190 ++NumZCRegMoveInstrsFPR;
6191 } else {
6192 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
6193 .addReg(SrcReg, getKillRegState(KillSrc));
6194 if (Subtarget.hasZeroCycleRegMoveFPR64())
6195 ++NumZCRegMoveInstrsFPR;
6196 }
6197 return;
6198 }
6199
6200 if (AArch64::FPR32RegClass.contains(DestReg) &&
6201 AArch64::FPR32RegClass.contains(SrcReg)) {
6202 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6203 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6204 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6205 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6206 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6207 &AArch64::FPR128RegClass);
6208 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6209 &AArch64::FPR128RegClass);
6210 // This instruction is reading and writing Q registers. This may upset
6211 // the register scavenger and machine verifier, so we need to indicate
6212 // that we are reading an undefined value from SrcRegQ, but a proper
6213 // value from SrcReg.
6214 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6215 .addReg(SrcRegQ, RegState::Undef)
6216 .addReg(SrcRegQ, RegState::Undef)
6217 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6218 ++NumZCRegMoveInstrsFPR;
6219 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6220 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6221 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6222 &AArch64::FPR64RegClass);
6223 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6224 &AArch64::FPR64RegClass);
6225 // This instruction is reading and writing D registers. This may upset
6226 // the register scavenger and machine verifier, so we need to indicate
6227 // that we are reading an undefined value from SrcRegD, but a proper
6228 // value from SrcReg.
6229 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6230 .addReg(SrcRegD, RegState::Undef)
6231 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6232 ++NumZCRegMoveInstrsFPR;
6233 } else {
6234 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6235 .addReg(SrcReg, getKillRegState(KillSrc));
6236 if (Subtarget.hasZeroCycleRegMoveFPR32())
6237 ++NumZCRegMoveInstrsFPR;
6238 }
6239 return;
6240 }
6241
6242 if (AArch64::FPR16RegClass.contains(DestReg) &&
6243 AArch64::FPR16RegClass.contains(SrcReg)) {
6244 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6245 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6246 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6247 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6248 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6249 &AArch64::FPR128RegClass);
6250 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6251 &AArch64::FPR128RegClass);
6252 // This instruction is reading and writing Q registers. This may upset
6253 // the register scavenger and machine verifier, so we need to indicate
6254 // that we are reading an undefined value from SrcRegQ, but a proper
6255 // value from SrcReg.
6256 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6257 .addReg(SrcRegQ, RegState::Undef)
6258 .addReg(SrcRegQ, RegState::Undef)
6259 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6260 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6261 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6262 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6263 &AArch64::FPR64RegClass);
6264 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6265 &AArch64::FPR64RegClass);
6266 // This instruction is reading and writing D registers. This may upset
6267 // the register scavenger and machine verifier, so we need to indicate
6268 // that we are reading an undefined value from SrcRegD, but a proper
6269 // value from SrcReg.
6270 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6271 .addReg(SrcRegD, RegState::Undef)
6272 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6273 } else {
6274 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6275 &AArch64::FPR32RegClass);
6276 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6277 &AArch64::FPR32RegClass);
6278 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6279 .addReg(SrcReg, getKillRegState(KillSrc));
6280 }
6281 return;
6282 }
6283
6284 if (AArch64::FPR8RegClass.contains(DestReg) &&
6285 AArch64::FPR8RegClass.contains(SrcReg)) {
6286 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6287 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6288 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6289 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6290 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6291 &AArch64::FPR128RegClass);
6292 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6293 &AArch64::FPR128RegClass);
6294 // This instruction is reading and writing Q registers. This may upset
6295 // the register scavenger and machine verifier, so we need to indicate
6296 // that we are reading an undefined value from SrcRegQ, but a proper
6297 // value from SrcReg.
6298 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6299 .addReg(SrcRegQ, RegState::Undef)
6300 .addReg(SrcRegQ, RegState::Undef)
6301 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6302 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6303 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6304 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6305 &AArch64::FPR64RegClass);
6306 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6307 &AArch64::FPR64RegClass);
6308 // This instruction is reading and writing D registers. This may upset
6309 // the register scavenger and machine verifier, so we need to indicate
6310 // that we are reading an undefined value from SrcRegD, but a proper
6311 // value from SrcReg.
6312 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6313 .addReg(SrcRegD, RegState::Undef)
6314 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6315 } else {
6316 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6317 &AArch64::FPR32RegClass);
6318 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6319 &AArch64::FPR32RegClass);
6320 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6321 .addReg(SrcReg, getKillRegState(KillSrc));
6322 }
6323 return;
6324 }
6325
6326 // Copies between GPR64 and FPR64.
6327 if (AArch64::FPR64RegClass.contains(DestReg) &&
6328 AArch64::GPR64RegClass.contains(SrcReg)) {
6329 if (AArch64::XZR == SrcReg) {
6330 BuildMI(MBB, I, DL, get(AArch64::FMOVD0), DestReg);
6331 } else {
6332 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
6333 .addReg(SrcReg, getKillRegState(KillSrc));
6334 }
6335 return;
6336 }
6337 if (AArch64::GPR64RegClass.contains(DestReg) &&
6338 AArch64::FPR64RegClass.contains(SrcReg)) {
6339 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
6340 .addReg(SrcReg, getKillRegState(KillSrc));
6341 return;
6342 }
6343 // Copies between GPR32 and FPR32.
6344 if (AArch64::FPR32RegClass.contains(DestReg) &&
6345 AArch64::GPR32RegClass.contains(SrcReg)) {
6346 if (AArch64::WZR == SrcReg) {
6347 BuildMI(MBB, I, DL, get(AArch64::FMOVS0), DestReg);
6348 } else {
6349 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
6350 .addReg(SrcReg, getKillRegState(KillSrc));
6351 }
6352 return;
6353 }
6354 if (AArch64::GPR32RegClass.contains(DestReg) &&
6355 AArch64::FPR32RegClass.contains(SrcReg)) {
6356 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
6357 .addReg(SrcReg, getKillRegState(KillSrc));
6358 return;
6359 }
6360
6361 if (DestReg == AArch64::NZCV) {
6362 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
6363 BuildMI(MBB, I, DL, get(AArch64::MSR))
6364 .addImm(AArch64SysReg::NZCV)
6365 .addReg(SrcReg, getKillRegState(KillSrc))
6366 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
6367 return;
6368 }
6369
6370 if (SrcReg == AArch64::NZCV) {
6371 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
6372 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
6373 .addImm(AArch64SysReg::NZCV)
6374 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
6375 return;
6376 }
6377
6378#ifndef NDEBUG
6379 errs() << RI.getRegAsmName(DestReg) << " = COPY " << RI.getRegAsmName(SrcReg)
6380 << "\n";
6381#endif
6382 llvm_unreachable("unimplemented reg-to-reg copy");
6383}
6384
6387 const DebugLoc &DL, Register DestReg,
6388 Register SrcReg, bool KillSrc,
6389 bool RenamableDest,
6390 bool RenamableSrc) const {
6391 ++NumCopyInstrs;
6392 copyPhysRegImpl(MBB, I, DL, DestReg, SrcReg, KillSrc, RenamableDest,
6393 RenamableSrc);
6394 return;
6395}
6396
6399 MachineBasicBlock::iterator InsertBefore,
6400 const MCInstrDesc &MCID,
6401 Register SrcReg, bool IsKill,
6402 unsigned SubIdx0, unsigned SubIdx1, int FI,
6403 MachineMemOperand *MMO) {
6404 Register SrcReg0 = SrcReg;
6405 Register SrcReg1 = SrcReg;
6406 if (SrcReg.isPhysical()) {
6407 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
6408 SubIdx0 = 0;
6409 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
6410 SubIdx1 = 0;
6411 }
6412 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6413 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
6414 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
6415 .addFrameIndex(FI)
6416 .addImm(0)
6417 .addMemOperand(MMO);
6418}
6419
6422 Register SrcReg, bool isKill, int FI,
6423 const TargetRegisterClass *RC,
6424 Register VReg,
6425 MachineInstr::MIFlag Flags) const {
6426 MachineFunction &MF = *MBB.getParent();
6427 MachineFrameInfo &MFI = MF.getFrameInfo();
6428
6430 MachineMemOperand *MMO =
6432 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6433 unsigned Opc = 0;
6434 bool Offset = true;
6436 unsigned StackID = TargetStackID::Default;
6437 switch (RI.getSpillSize(*RC)) {
6438 case 1:
6439 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6440 Opc = AArch64::STRBui;
6441 break;
6442 case 2: {
6443 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6444 Opc = AArch64::STRHui;
6445 else if (AArch64::PNRRegClass.hasSubClassEq(RC) ||
6446 AArch64::PPRRegClass.hasSubClassEq(RC)) {
6447 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6448 "Unexpected register store without SVE store instructions");
6449 Opc = AArch64::STR_PXI;
6451 }
6452 break;
6453 }
6454 case 4:
6455 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6456 Opc = AArch64::STRWui;
6457 if (SrcReg.isVirtual())
6458 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
6459 else
6460 assert(SrcReg != AArch64::WSP);
6461 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6462 Opc = AArch64::STRSui;
6463 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6464 Opc = AArch64::STR_PPXI;
6466 }
6467 break;
6468 case 8:
6469 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6470 Opc = AArch64::STRXui;
6471 if (SrcReg.isVirtual())
6472 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
6473 else
6474 assert(SrcReg != AArch64::SP);
6475 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6476 Opc = AArch64::STRDui;
6477 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6479 get(AArch64::STPWi), SrcReg, isKill,
6480 AArch64::sube32, AArch64::subo32, FI, MMO);
6481 return;
6482 }
6483 break;
6484 case 16:
6485 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6486 Opc = AArch64::STRQui;
6487 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6488 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6489 Opc = AArch64::ST1Twov1d;
6490 Offset = false;
6491 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6493 get(AArch64::STPXi), SrcReg, isKill,
6494 AArch64::sube64, AArch64::subo64, FI, MMO);
6495 return;
6496 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6497 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6498 "Unexpected register store without SVE store instructions");
6499 Opc = AArch64::STR_ZXI;
6501 }
6502 break;
6503 case 24:
6504 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6505 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6506 Opc = AArch64::ST1Threev1d;
6507 Offset = false;
6508 }
6509 break;
6510 case 32:
6511 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6512 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6513 Opc = AArch64::ST1Fourv1d;
6514 Offset = false;
6515 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6516 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6517 Opc = AArch64::ST1Twov2d;
6518 Offset = false;
6519 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6520 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6521 "Unexpected register store without SVE store instructions");
6522 Opc = AArch64::STR_ZZXI_STRIDED_CONTIGUOUS;
6524 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6525 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6526 "Unexpected register store without SVE store instructions");
6527 Opc = AArch64::STR_ZZXI;
6529 }
6530 break;
6531 case 48:
6532 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6533 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6534 Opc = AArch64::ST1Threev2d;
6535 Offset = false;
6536 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6537 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6538 "Unexpected register store without SVE store instructions");
6539 Opc = AArch64::STR_ZZZXI;
6541 }
6542 break;
6543 case 64:
6544 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6545 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6546 Opc = AArch64::ST1Fourv2d;
6547 Offset = false;
6548 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6549 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6550 "Unexpected register store without SVE store instructions");
6551 Opc = AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS;
6553 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6554 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6555 "Unexpected register store without SVE store instructions");
6556 Opc = AArch64::STR_ZZZZXI;
6558 }
6559 break;
6560 }
6561 assert(Opc && "Unknown register class");
6562 MFI.setStackID(FI, StackID);
6563
6565 .addReg(SrcReg, getKillRegState(isKill))
6566 .addFrameIndex(FI);
6567
6568 if (Offset)
6569 MI.addImm(0);
6570 if (PNRReg.isValid())
6571 MI.addDef(PNRReg, RegState::Implicit);
6572 MI.addMemOperand(MMO);
6573}
6574
6577 MachineBasicBlock::iterator InsertBefore,
6578 const MCInstrDesc &MCID,
6579 Register DestReg, unsigned SubIdx0,
6580 unsigned SubIdx1, int FI,
6581 MachineMemOperand *MMO) {
6582 Register DestReg0 = DestReg;
6583 Register DestReg1 = DestReg;
6584 bool IsUndef = true;
6585 if (DestReg.isPhysical()) {
6586 DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
6587 SubIdx0 = 0;
6588 DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
6589 SubIdx1 = 0;
6590 IsUndef = false;
6591 }
6592 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6593 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
6594 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
6595 .addFrameIndex(FI)
6596 .addImm(0)
6597 .addMemOperand(MMO);
6598}
6599
6602 Register DestReg, int FI,
6603 const TargetRegisterClass *RC,
6604 Register VReg, unsigned SubReg,
6605 MachineInstr::MIFlag Flags) const {
6606 MachineFunction &MF = *MBB.getParent();
6607 MachineFrameInfo &MFI = MF.getFrameInfo();
6609 MachineMemOperand *MMO =
6611 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6612
6613 unsigned Opc = 0;
6614 bool Offset = true;
6615 unsigned StackID = TargetStackID::Default;
6616 Register PNRReg;
6617 switch (TRI.getSpillSize(*RC)) {
6618 case 1:
6619 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6620 Opc = AArch64::LDRBui;
6621 break;
6622 case 2: {
6623 bool IsPNR = AArch64::PNRRegClass.hasSubClassEq(RC);
6624 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6625 Opc = AArch64::LDRHui;
6626 else if (IsPNR || AArch64::PPRRegClass.hasSubClassEq(RC)) {
6627 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6628 "Unexpected register load without SVE load instructions");
6629 if (IsPNR)
6630 PNRReg = DestReg;
6631 Opc = AArch64::LDR_PXI;
6633 }
6634 break;
6635 }
6636 case 4:
6637 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6638 Opc = AArch64::LDRWui;
6639 if (DestReg.isVirtual())
6640 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
6641 else
6642 assert(DestReg != AArch64::WSP);
6643 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6644 Opc = AArch64::LDRSui;
6645 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6646 Opc = AArch64::LDR_PPXI;
6648 }
6649 break;
6650 case 8:
6651 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6652 Opc = AArch64::LDRXui;
6653 if (DestReg.isVirtual())
6654 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
6655 else
6656 assert(DestReg != AArch64::SP);
6657 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6658 Opc = AArch64::LDRDui;
6659 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6661 get(AArch64::LDPWi), DestReg, AArch64::sube32,
6662 AArch64::subo32, FI, MMO);
6663 return;
6664 }
6665 break;
6666 case 16:
6667 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6668 Opc = AArch64::LDRQui;
6669 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6670 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6671 Opc = AArch64::LD1Twov1d;
6672 Offset = false;
6673 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6675 get(AArch64::LDPXi), DestReg, AArch64::sube64,
6676 AArch64::subo64, FI, MMO);
6677 return;
6678 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6679 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6680 "Unexpected register load without SVE load instructions");
6681 Opc = AArch64::LDR_ZXI;
6683 }
6684 break;
6685 case 24:
6686 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6687 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6688 Opc = AArch64::LD1Threev1d;
6689 Offset = false;
6690 }
6691 break;
6692 case 32:
6693 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6694 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6695 Opc = AArch64::LD1Fourv1d;
6696 Offset = false;
6697 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6698 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6699 Opc = AArch64::LD1Twov2d;
6700 Offset = false;
6701 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6702 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6703 "Unexpected register load without SVE load instructions");
6704 Opc = AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS;
6706 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6707 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6708 "Unexpected register load without SVE load instructions");
6709 Opc = AArch64::LDR_ZZXI;
6711 }
6712 break;
6713 case 48:
6714 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6715 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6716 Opc = AArch64::LD1Threev2d;
6717 Offset = false;
6718 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6719 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6720 "Unexpected register load without SVE load instructions");
6721 Opc = AArch64::LDR_ZZZXI;
6723 }
6724 break;
6725 case 64:
6726 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6727 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6728 Opc = AArch64::LD1Fourv2d;
6729 Offset = false;
6730 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6731 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6732 "Unexpected register load without SVE load instructions");
6733 Opc = AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS;
6735 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6736 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6737 "Unexpected register load without SVE load instructions");
6738 Opc = AArch64::LDR_ZZZZXI;
6740 }
6741 break;
6742 }
6743
6744 assert(Opc && "Unknown register class");
6745 MFI.setStackID(FI, StackID);
6746
6748 .addReg(DestReg, getDefRegState(true))
6749 .addFrameIndex(FI);
6750 if (Offset)
6751 MI.addImm(0);
6752 if (PNRReg.isValid() && !PNRReg.isVirtual())
6753 MI.addDef(PNRReg, RegState::Implicit);
6754 MI.addMemOperand(MMO);
6755}
6756
6758 const MachineInstr &UseMI,
6759 const TargetRegisterInfo *TRI) {
6760 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
6761 UseMI.getIterator()),
6762 [TRI](const MachineInstr &I) {
6763 return I.modifiesRegister(AArch64::NZCV, TRI) ||
6764 I.readsRegister(AArch64::NZCV, TRI);
6765 });
6766}
6767
6768void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6769 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
6770 // The smallest scalable element supported by scaled SVE addressing
6771 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6772 // byte offset must always be a multiple of 2.
6773 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6774
6775 // VGSized offsets are divided by '2', because the VG register is the
6776 // the number of 64bit granules as opposed to 128bit vector chunks,
6777 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
6778 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
6779 // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
6780 ByteSized = Offset.getFixed();
6781 VGSized = Offset.getScalable() / 2;
6782}
6783
6784/// Returns the offset in parts to which this frame offset can be
6785/// decomposed for the purpose of describing a frame offset.
6786/// For non-scalable offsets this is simply its byte size.
6787void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
6788 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
6789 int64_t &NumDataVectors) {
6790 // The smallest scalable element supported by scaled SVE addressing
6791 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6792 // byte offset must always be a multiple of 2.
6793 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6794
6795 NumBytes = Offset.getFixed();
6796 NumDataVectors = 0;
6797 NumPredicateVectors = Offset.getScalable() / 2;
6798 // This method is used to get the offsets to adjust the frame offset.
6799 // If the function requires ADDPL to be used and needs more than two ADDPL
6800 // instructions, part of the offset is folded into NumDataVectors so that it
6801 // uses ADDVL for part of it, reducing the number of ADDPL instructions.
6802 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
6803 NumPredicateVectors > 62) {
6804 NumDataVectors = NumPredicateVectors / 8;
6805 NumPredicateVectors -= NumDataVectors * 8;
6806 }
6807}
6808
6809// Convenience function to create a DWARF expression for: Constant `Operation`.
6810// This helper emits compact sequences for common cases. For example, for`-15
6811// DW_OP_plus`, this helper would create DW_OP_lit15 DW_OP_minus.
6814 if (Operation == dwarf::DW_OP_plus && Constant < 0 && -Constant <= 31) {
6815 // -Constant (1 to 31)
6816 Expr.push_back(dwarf::DW_OP_lit0 - Constant);
6817 Operation = dwarf::DW_OP_minus;
6818 } else if (Constant >= 0 && Constant <= 31) {
6819 // Literal value 0 to 31
6820 Expr.push_back(dwarf::DW_OP_lit0 + Constant);
6821 } else {
6822 // Signed constant
6823 Expr.push_back(dwarf::DW_OP_consts);
6825 }
6826 return Expr.push_back(Operation);
6827}
6828
6829// Convenience function to create a DWARF expression for a register.
6830static void appendReadRegExpr(SmallVectorImpl<char> &Expr, unsigned RegNum) {
6831 Expr.push_back((char)dwarf::DW_OP_bregx);
6833 Expr.push_back(0);
6834}
6835
6836// Convenience function to create a DWARF expression for loading a register from
6837// a CFA offset.
6839 int64_t OffsetFromDefCFA) {
6840 // This assumes the top of the DWARF stack contains the CFA.
6841 Expr.push_back(dwarf::DW_OP_dup);
6842 // Add the offset to the register.
6843 appendConstantExpr(Expr, OffsetFromDefCFA, dwarf::DW_OP_plus);
6844 // Dereference the address (loads a 64 bit value)..
6845 Expr.push_back(dwarf::DW_OP_deref);
6846}
6847
6848// Convenience function to create a comment for
6849// (+/-) NumBytes (* RegScale)?
6850static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment,
6851 StringRef RegScale = {}) {
6852 if (NumBytes) {
6853 Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
6854 if (!RegScale.empty())
6855 Comment << ' ' << RegScale;
6856 }
6857}
6858
6859// Creates an MCCFIInstruction:
6860// { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
6862 unsigned Reg,
6863 const StackOffset &Offset) {
6864 int64_t NumBytes, NumVGScaledBytes;
6865 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
6866 NumVGScaledBytes);
6867 std::string CommentBuffer;
6868 llvm::raw_string_ostream Comment(CommentBuffer);
6869
6870 if (Reg == AArch64::SP)
6871 Comment << "sp";
6872 else if (Reg == AArch64::FP)
6873 Comment << "fp";
6874 else
6875 Comment << printReg(Reg, &TRI);
6876
6877 // Build up the expression (Reg + NumBytes + VG * NumVGScaledBytes)
6878 SmallString<64> Expr;
6879 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6880 assert(DwarfReg <= 31 && "DwarfReg out of bounds (0..31)");
6881 // Reg + NumBytes
6882 Expr.push_back(dwarf::DW_OP_breg0 + DwarfReg);
6883 appendLEB128<LEB128Sign::Signed>(Expr, NumBytes);
6884 appendOffsetComment(NumBytes, Comment);
6885 if (NumVGScaledBytes) {
6886 // + VG * NumVGScaledBytes
6887 appendOffsetComment(NumVGScaledBytes, Comment, "* VG");
6888 appendReadRegExpr(Expr, TRI.getDwarfRegNum(AArch64::VG, true));
6889 appendConstantExpr(Expr, NumVGScaledBytes, dwarf::DW_OP_mul);
6890 Expr.push_back(dwarf::DW_OP_plus);
6891 }
6892
6893 // Wrap this into DW_CFA_def_cfa.
6894 SmallString<64> DefCfaExpr;
6895 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
6896 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
6897 DefCfaExpr.append(Expr.str());
6898 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
6899 Comment.str());
6900}
6901
6903 unsigned FrameReg, unsigned Reg,
6904 const StackOffset &Offset,
6905 bool LastAdjustmentWasScalable) {
6906 if (Offset.getScalable())
6907 return createDefCFAExpression(TRI, Reg, Offset);
6908
6909 if (FrameReg == Reg && !LastAdjustmentWasScalable)
6910 return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
6911
6912 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6913 return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
6914}
6915
6918 const StackOffset &OffsetFromDefCFA,
6919 std::optional<int64_t> IncomingVGOffsetFromDefCFA) {
6920 int64_t NumBytes, NumVGScaledBytes;
6921 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6922 OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
6923
6924 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6925
6926 // Non-scalable offsets can use DW_CFA_offset directly.
6927 if (!NumVGScaledBytes)
6928 return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
6929
6930 std::string CommentBuffer;
6931 llvm::raw_string_ostream Comment(CommentBuffer);
6932 Comment << printReg(Reg, &TRI) << " @ cfa";
6933
6934 // Build up expression (CFA + VG * NumVGScaledBytes + NumBytes)
6935 assert(NumVGScaledBytes && "Expected scalable offset");
6936 SmallString<64> OffsetExpr;
6937 // + VG * NumVGScaledBytes
6938 StringRef VGRegScale;
6939 if (IncomingVGOffsetFromDefCFA) {
6940 appendLoadRegExpr(OffsetExpr, *IncomingVGOffsetFromDefCFA);
6941 VGRegScale = "* IncomingVG";
6942 } else {
6943 appendReadRegExpr(OffsetExpr, TRI.getDwarfRegNum(AArch64::VG, true));
6944 VGRegScale = "* VG";
6945 }
6946 appendConstantExpr(OffsetExpr, NumVGScaledBytes, dwarf::DW_OP_mul);
6947 appendOffsetComment(NumVGScaledBytes, Comment, VGRegScale);
6948 OffsetExpr.push_back(dwarf::DW_OP_plus);
6949 if (NumBytes) {
6950 // + NumBytes
6951 appendOffsetComment(NumBytes, Comment);
6952 appendConstantExpr(OffsetExpr, NumBytes, dwarf::DW_OP_plus);
6953 }
6954
6955 // Wrap this into DW_CFA_expression
6956 SmallString<64> CfaExpr;
6957 CfaExpr.push_back(dwarf::DW_CFA_expression);
6958 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, DwarfReg);
6959 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, OffsetExpr.size());
6960 CfaExpr.append(OffsetExpr.str());
6961
6962 return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), SMLoc(),
6963 Comment.str());
6964}
6965
6966// Helper function to emit a frame offset adjustment from a given
6967// pointer (SrcReg), stored into DestReg. This function is explicit
6968// in that it requires the opcode.
6971 const DebugLoc &DL, unsigned DestReg,
6972 unsigned SrcReg, int64_t Offset, unsigned Opc,
6973 const TargetInstrInfo *TII,
6974 MachineInstr::MIFlag Flag, bool NeedsWinCFI,
6975 bool *HasWinCFI, bool EmitCFAOffset,
6976 StackOffset CFAOffset, unsigned FrameReg) {
6977 int Sign = 1;
6978 unsigned MaxEncoding, ShiftSize;
6979 switch (Opc) {
6980 case AArch64::ADDXri:
6981 case AArch64::ADDSXri:
6982 case AArch64::SUBXri:
6983 case AArch64::SUBSXri:
6984 MaxEncoding = 0xfff;
6985 ShiftSize = 12;
6986 break;
6987 case AArch64::ADDVL_XXI:
6988 case AArch64::ADDPL_XXI:
6989 case AArch64::ADDSVL_XXI:
6990 case AArch64::ADDSPL_XXI:
6991 MaxEncoding = 31;
6992 ShiftSize = 0;
6993 if (Offset < 0) {
6994 MaxEncoding = 32;
6995 Sign = -1;
6996 Offset = -Offset;
6997 }
6998 break;
6999 default:
7000 llvm_unreachable("Unsupported opcode");
7001 }
7002
7003 // `Offset` can be in bytes or in "scalable bytes".
7004 int VScale = 1;
7005 if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
7006 VScale = 16;
7007 else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
7008 VScale = 2;
7009
7010 // FIXME: If the offset won't fit in 24-bits, compute the offset into a
7011 // scratch register. If DestReg is a virtual register, use it as the
7012 // scratch register; otherwise, create a new virtual register (to be
7013 // replaced by the scavenger at the end of PEI). That case can be optimized
7014 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
7015 // register can be loaded with offset%8 and the add/sub can use an extending
7016 // instruction with LSL#3.
7017 // Currently the function handles any offsets but generates a poor sequence
7018 // of code.
7019 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
7020
7021 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
7022 Register TmpReg = DestReg;
7023 if (TmpReg == AArch64::XZR)
7024 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
7025 &AArch64::GPR64RegClass);
7026 do {
7027 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
7028 unsigned LocalShiftSize = 0;
7029 if (ThisVal > MaxEncoding) {
7030 ThisVal = ThisVal >> ShiftSize;
7031 LocalShiftSize = ShiftSize;
7032 }
7033 assert((ThisVal >> ShiftSize) <= MaxEncoding &&
7034 "Encoding cannot handle value that big");
7035
7036 Offset -= ThisVal << LocalShiftSize;
7037 if (Offset == 0)
7038 TmpReg = DestReg;
7039 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
7040 .addReg(SrcReg)
7041 .addImm(Sign * (int)ThisVal);
7042 if (ShiftSize)
7043 MBI = MBI.addImm(
7045 MBI = MBI.setMIFlag(Flag);
7046
7047 auto Change =
7048 VScale == 1
7049 ? StackOffset::getFixed(ThisVal << LocalShiftSize)
7050 : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
7051 if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
7052 CFAOffset += Change;
7053 else
7054 CFAOffset -= Change;
7055 if (EmitCFAOffset && DestReg == TmpReg) {
7056 MachineFunction &MF = *MBB.getParent();
7057 const TargetSubtargetInfo &STI = MF.getSubtarget();
7058 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
7059
7060 unsigned CFIIndex = MF.addFrameInst(
7061 createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
7062 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
7063 .addCFIIndex(CFIIndex)
7064 .setMIFlags(Flag);
7065 }
7066
7067 if (NeedsWinCFI) {
7068 int Imm = (int)(ThisVal << LocalShiftSize);
7069 if (VScale != 1 && DestReg == AArch64::SP) {
7070 if (HasWinCFI)
7071 *HasWinCFI = true;
7072 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AllocZ))
7073 .addImm(ThisVal)
7074 .setMIFlag(Flag);
7075 } else if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
7076 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
7077 assert(VScale == 1 && "Expected non-scalable operation");
7078 if (HasWinCFI)
7079 *HasWinCFI = true;
7080 if (Imm == 0)
7081 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
7082 else
7083 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
7084 .addImm(Imm)
7085 .setMIFlag(Flag);
7086 assert(Offset == 0 && "Expected remaining offset to be zero to "
7087 "emit a single SEH directive");
7088 } else if (DestReg == AArch64::SP) {
7089 assert(VScale == 1 && "Expected non-scalable operation");
7090 if (HasWinCFI)
7091 *HasWinCFI = true;
7092 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
7093 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
7094 .addImm(Imm)
7095 .setMIFlag(Flag);
7096 }
7097 }
7098
7099 SrcReg = TmpReg;
7100 } while (Offset);
7101}
7102
7105 unsigned DestReg, unsigned SrcReg,
7107 MachineInstr::MIFlag Flag, bool SetNZCV,
7108 bool NeedsWinCFI, bool *HasWinCFI,
7109 bool EmitCFAOffset, StackOffset CFAOffset,
7110 unsigned FrameReg) {
7111 // If a function is marked as arm_locally_streaming, then the runtime value of
7112 // vscale in the prologue/epilogue is different the runtime value of vscale
7113 // in the function's body. To avoid having to consider multiple vscales,
7114 // we can use `addsvl` to allocate any scalable stack-slots, which under
7115 // most circumstances will be only locals, not callee-save slots.
7116 const Function &F = MBB.getParent()->getFunction();
7117 bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
7118
7119 int64_t Bytes, NumPredicateVectors, NumDataVectors;
7120 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
7121 Offset, Bytes, NumPredicateVectors, NumDataVectors);
7122
7123 // Insert ADDSXri for scalable offset at the end.
7124 bool NeedsFinalDefNZCV = SetNZCV && (NumPredicateVectors || NumDataVectors);
7125 if (NeedsFinalDefNZCV)
7126 SetNZCV = false;
7127
7128 // First emit non-scalable frame offsets, or a simple 'mov'.
7129 if (Bytes || (!Offset && SrcReg != DestReg)) {
7130 assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
7131 "SP increment/decrement not 8-byte aligned");
7132 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
7133 if (Bytes < 0) {
7134 Bytes = -Bytes;
7135 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
7136 }
7137 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
7138 NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7139 FrameReg);
7140 CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
7141 ? StackOffset::getFixed(-Bytes)
7142 : StackOffset::getFixed(Bytes);
7143 SrcReg = DestReg;
7144 FrameReg = DestReg;
7145 }
7146
7147 assert(!(NeedsWinCFI && NumPredicateVectors) &&
7148 "WinCFI can't allocate fractions of an SVE data vector");
7149
7150 if (NumDataVectors) {
7151 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
7152 UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI, TII,
7153 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7154 FrameReg);
7155 CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
7156 SrcReg = DestReg;
7157 }
7158
7159 if (NumPredicateVectors) {
7160 assert(DestReg != AArch64::SP && "Unaligned access to SP");
7161 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
7162 UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI, TII,
7163 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7164 FrameReg);
7165 }
7166
7167 if (NeedsFinalDefNZCV)
7168 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDSXri), DestReg)
7169 .addReg(DestReg)
7170 .addImm(0)
7171 .addImm(0);
7172}
7173
7176 int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS,
7177 VirtRegMap *VRM) const {
7179 // This is a bit of a hack. Consider this instruction:
7180 //
7181 // %0 = COPY %sp; GPR64all:%0
7182 //
7183 // We explicitly chose GPR64all for the virtual register so such a copy might
7184 // be eliminated by RegisterCoalescer. However, that may not be possible, and
7185 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
7186 // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
7187 //
7188 // To prevent that, we are going to constrain the %0 register class here.
7189 if (MI.isFullCopy()) {
7190 Register DstReg = MI.getOperand(0).getReg();
7191 Register SrcReg = MI.getOperand(1).getReg();
7192 if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
7193 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
7194 return nullptr;
7195 }
7196 if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
7197 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
7198 return nullptr;
7199 }
7200 // Nothing can folded with copy from/to NZCV.
7201 if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
7202 return nullptr;
7203 }
7204
7205 // Handle the case where a copy is being spilled or filled but the source
7206 // and destination register class don't match. For example:
7207 //
7208 // %0 = COPY %xzr; GPR64common:%0
7209 //
7210 // In this case we can still safely fold away the COPY and generate the
7211 // following spill code:
7212 //
7213 // STRXui %xzr, %stack.0
7214 //
7215 // This also eliminates spilled cross register class COPYs (e.g. between x and
7216 // d regs) of the same size. For example:
7217 //
7218 // %0 = COPY %1; GPR64:%0, FPR64:%1
7219 //
7220 // will be filled as
7221 //
7222 // LDRDui %0, fi<#0>
7223 //
7224 // instead of
7225 //
7226 // LDRXui %Temp, fi<#0>
7227 // %0 = FMOV %Temp
7228 //
7229 if (MI.isCopy() && Ops.size() == 1 &&
7230 // Make sure we're only folding the explicit COPY defs/uses.
7231 (Ops[0] == 0 || Ops[0] == 1)) {
7232 bool IsSpill = Ops[0] == 0;
7233 bool IsFill = !IsSpill;
7235 const MachineRegisterInfo &MRI = MF.getRegInfo();
7236 MachineBasicBlock &MBB = *MI.getParent();
7237 const MachineOperand &DstMO = MI.getOperand(0);
7238 const MachineOperand &SrcMO = MI.getOperand(1);
7239 Register DstReg = DstMO.getReg();
7240 Register SrcReg = SrcMO.getReg();
7241 // This is slightly expensive to compute for physical regs since
7242 // getMinimalPhysRegClass is slow.
7243 auto getRegClass = [&](unsigned Reg) {
7244 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
7245 : TRI.getMinimalPhysRegClass(Reg);
7246 };
7247
7248 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
7249 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
7250 TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
7251 "Mismatched register size in non subreg COPY");
7252 if (IsSpill)
7253 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
7254 getRegClass(SrcReg), Register());
7255 else
7256 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
7257 getRegClass(DstReg), Register());
7258 return &*--InsertPt;
7259 }
7260
7261 // Handle cases like spilling def of:
7262 //
7263 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
7264 //
7265 // where the physical register source can be widened and stored to the full
7266 // virtual reg destination stack slot, in this case producing:
7267 //
7268 // STRXui %xzr, %stack.0
7269 //
7270 if (IsSpill && DstMO.isUndef() && SrcReg == AArch64::WZR &&
7271 TRI.getRegSizeInBits(*getRegClass(DstReg)) == 64) {
7272 assert(SrcMO.getSubReg() == 0 &&
7273 "Unexpected subreg on physical register");
7274 storeRegToStackSlot(MBB, InsertPt, AArch64::XZR, SrcMO.isKill(),
7275 FrameIndex, &AArch64::GPR64RegClass, Register());
7276 return &*--InsertPt;
7277 }
7278
7279 // Handle cases like filling use of:
7280 //
7281 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
7282 //
7283 // where we can load the full virtual reg source stack slot, into the subreg
7284 // destination, in this case producing:
7285 //
7286 // LDRWui %0:sub_32<def,read-undef>, %stack.0
7287 //
7288 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
7289 const TargetRegisterClass *FillRC = nullptr;
7290 switch (DstMO.getSubReg()) {
7291 default:
7292 break;
7293 case AArch64::sub_32:
7294 if (AArch64::GPR64RegClass.hasSubClassEq(getRegClass(DstReg)))
7295 FillRC = &AArch64::GPR32RegClass;
7296 break;
7297 case AArch64::ssub:
7298 FillRC = &AArch64::FPR32RegClass;
7299 break;
7300 case AArch64::dsub:
7301 FillRC = &AArch64::FPR64RegClass;
7302 break;
7303 }
7304
7305 if (FillRC) {
7306 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
7307 TRI.getRegSizeInBits(*FillRC) &&
7308 "Mismatched regclass size on folded subreg COPY");
7309 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC,
7310 Register());
7311 MachineInstr &LoadMI = *--InsertPt;
7312 MachineOperand &LoadDst = LoadMI.getOperand(0);
7313 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
7314 LoadDst.setSubReg(DstMO.getSubReg());
7315 LoadDst.setIsUndef();
7316 return &LoadMI;
7317 }
7318 }
7319 }
7320
7321 // Cannot fold.
7322 return nullptr;
7323}
7324
7326 StackOffset &SOffset,
7327 bool *OutUseUnscaledOp,
7328 unsigned *OutUnscaledOp,
7329 int64_t *EmittableOffset) {
7330 // Set output values in case of early exit.
7331 if (EmittableOffset)
7332 *EmittableOffset = 0;
7333 if (OutUseUnscaledOp)
7334 *OutUseUnscaledOp = false;
7335 if (OutUnscaledOp)
7336 *OutUnscaledOp = 0;
7337
7338 // Exit early for structured vector spills/fills as they can't take an
7339 // immediate offset.
7340 switch (MI.getOpcode()) {
7341 default:
7342 break;
7343 case AArch64::LD1Rv1d:
7344 case AArch64::LD1Rv2s:
7345 case AArch64::LD1Rv2d:
7346 case AArch64::LD1Rv4h:
7347 case AArch64::LD1Rv4s:
7348 case AArch64::LD1Rv8b:
7349 case AArch64::LD1Rv8h:
7350 case AArch64::LD1Rv16b:
7351 case AArch64::LD1Twov2d:
7352 case AArch64::LD1Threev2d:
7353 case AArch64::LD1Fourv2d:
7354 case AArch64::LD1Twov1d:
7355 case AArch64::LD1Threev1d:
7356 case AArch64::LD1Fourv1d:
7357 case AArch64::ST1Twov2d:
7358 case AArch64::ST1Threev2d:
7359 case AArch64::ST1Fourv2d:
7360 case AArch64::ST1Twov1d:
7361 case AArch64::ST1Threev1d:
7362 case AArch64::ST1Fourv1d:
7363 case AArch64::ST1i8:
7364 case AArch64::ST1i16:
7365 case AArch64::ST1i32:
7366 case AArch64::ST1i64:
7367 case AArch64::IRG:
7368 case AArch64::IRGstack:
7369 case AArch64::STGloop:
7370 case AArch64::STZGloop:
7372 }
7373
7374 // Get the min/max offset and the scale.
7375 TypeSize ScaleValue(0U, false), Width(0U, false);
7376 int64_t MinOff, MaxOff;
7377 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
7378 MaxOff))
7379 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7380
7381 // Construct the complete offset.
7382 bool IsMulVL = ScaleValue.isScalable();
7383 unsigned Scale = ScaleValue.getKnownMinValue();
7384 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
7385
7386 const MachineOperand &ImmOpnd =
7387 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
7388 Offset += ImmOpnd.getImm() * Scale;
7389
7390 // If the offset doesn't match the scale, we rewrite the instruction to
7391 // use the unscaled instruction instead. Likewise, if we have a negative
7392 // offset and there is an unscaled op to use.
7393 std::optional<unsigned> UnscaledOp =
7395 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
7396 if (useUnscaledOp &&
7397 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
7398 MaxOff))
7399 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7400
7401 Scale = ScaleValue.getKnownMinValue();
7402 assert(IsMulVL == ScaleValue.isScalable() &&
7403 "Unscaled opcode has different value for scalable");
7404
7405 int64_t Remainder = Offset % Scale;
7406 assert(!(Remainder && useUnscaledOp) &&
7407 "Cannot have remainder when using unscaled op");
7408
7409 assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
7410 int64_t NewOffset = Offset / Scale;
7411 if (MinOff <= NewOffset && NewOffset <= MaxOff)
7412 Offset = Remainder;
7413 else {
7414 // Try to minimise the number of instructions required to materialise the
7415 // offset calculation. Specifically, for fixed offsets, if masking out the
7416 // low 12 bits leaves a legal add immediate, we can realise the offset
7417 // calculation with a single add instruction. Whenever this is possible,
7418 // prefer this split.
7419 int64_t HighPart = Offset & ~0xFFF;
7420 int64_t LowPart = Offset & 0xFFF;
7421 int64_t LowScaled = LowPart / Scale;
7422 if (!IsMulVL && NewOffset >= 0 && LowPart % Scale == 0 &&
7423 MinOff <= LowScaled && LowScaled <= MaxOff &&
7425 NewOffset = LowScaled;
7426 Offset = HighPart;
7427 } else {
7428 // Default to a greedy split: take the memop immediate to be maximum /
7429 // minimum expressible offset and materialise the remainder.
7430 NewOffset = NewOffset < 0 ? MinOff : MaxOff;
7431 Offset = Offset - (NewOffset * Scale);
7432 }
7433 }
7434
7435 if (EmittableOffset)
7436 *EmittableOffset = NewOffset;
7437 if (OutUseUnscaledOp)
7438 *OutUseUnscaledOp = useUnscaledOp;
7439 if (OutUnscaledOp && UnscaledOp)
7440 *OutUnscaledOp = *UnscaledOp;
7441
7442 if (IsMulVL)
7443 SOffset = StackOffset::get(SOffset.getFixed(), Offset);
7444 else
7445 SOffset = StackOffset::get(Offset, SOffset.getScalable());
7447 (SOffset ? 0 : AArch64FrameOffsetIsLegal);
7448}
7449
7451 unsigned FrameReg, StackOffset &Offset,
7452 const AArch64InstrInfo *TII) {
7453 unsigned Opcode = MI.getOpcode();
7454 unsigned ImmIdx = FrameRegIdx + 1;
7455
7456 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
7457 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
7458 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
7459 MI.getOperand(0).getReg(), FrameReg, Offset, TII,
7460 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
7461 MI.eraseFromParent();
7462 Offset = StackOffset();
7463 return true;
7464 }
7465
7466 int64_t NewOffset;
7467 unsigned UnscaledOp;
7468 bool UseUnscaledOp;
7469 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
7470 &UnscaledOp, &NewOffset);
7473 // Replace the FrameIndex with FrameReg.
7474 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
7475 if (UseUnscaledOp)
7476 MI.setDesc(TII->get(UnscaledOp));
7477
7478 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
7479 return !Offset;
7480 }
7481
7482 return false;
7483}
7484
7490
7491MCInst AArch64InstrInfo::getNop() const { return MCInstBuilder(AArch64::NOP); }
7492
7493// AArch64 supports MachineCombiner.
7494bool AArch64InstrInfo::useMachineCombiner() const { return true; }
7495
7496// True when Opc sets flag
7497static bool isCombineInstrSettingFlag(unsigned Opc) {
7498 switch (Opc) {
7499 case AArch64::ADDSWrr:
7500 case AArch64::ADDSWri:
7501 case AArch64::ADDSXrr:
7502 case AArch64::ADDSXri:
7503 case AArch64::SUBSWrr:
7504 case AArch64::SUBSXrr:
7505 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7506 case AArch64::SUBSWri:
7507 case AArch64::SUBSXri:
7508 return true;
7509 default:
7510 break;
7511 }
7512 return false;
7513}
7514
7515// 32b Opcodes that can be combined with a MUL
7516static bool isCombineInstrCandidate32(unsigned Opc) {
7517 switch (Opc) {
7518 case AArch64::ADDWrr:
7519 case AArch64::ADDWri:
7520 case AArch64::ADDWrs:
7521 case AArch64::SUBWrr:
7522 case AArch64::ADDSWrr:
7523 case AArch64::ADDSWri:
7524 case AArch64::SUBSWrr:
7525 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7526 case AArch64::SUBWri:
7527 case AArch64::SUBSWri:
7528 return true;
7529 default:
7530 break;
7531 }
7532 return false;
7533}
7534
7535// 64b Opcodes that can be combined with a MUL
7536static bool isCombineInstrCandidate64(unsigned Opc) {
7537 switch (Opc) {
7538 case AArch64::ADDXrr:
7539 case AArch64::ADDXri:
7540 case AArch64::ADDXrs:
7541 case AArch64::SUBXrr:
7542 case AArch64::ADDSXrr:
7543 case AArch64::ADDSXri:
7544 case AArch64::SUBSXrr:
7545 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7546 case AArch64::SUBXri:
7547 case AArch64::SUBSXri:
7548 case AArch64::ADDv8i8:
7549 case AArch64::ADDv16i8:
7550 case AArch64::ADDv4i16:
7551 case AArch64::ADDv8i16:
7552 case AArch64::ADDv2i32:
7553 case AArch64::ADDv4i32:
7554 case AArch64::SUBv8i8:
7555 case AArch64::SUBv16i8:
7556 case AArch64::SUBv4i16:
7557 case AArch64::SUBv8i16:
7558 case AArch64::SUBv2i32:
7559 case AArch64::SUBv4i32:
7560 return true;
7561 default:
7562 break;
7563 }
7564 return false;
7565}
7566
7567// FP Opcodes that can be combined with a FMUL.
7568static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
7569 switch (Inst.getOpcode()) {
7570 default:
7571 break;
7572 case AArch64::FADDHrr:
7573 case AArch64::FADDSrr:
7574 case AArch64::FADDDrr:
7575 case AArch64::FADDv4f16:
7576 case AArch64::FADDv8f16:
7577 case AArch64::FADDv2f32:
7578 case AArch64::FADDv2f64:
7579 case AArch64::FADDv4f32:
7580 case AArch64::FSUBHrr:
7581 case AArch64::FSUBSrr:
7582 case AArch64::FSUBDrr:
7583 case AArch64::FSUBv4f16:
7584 case AArch64::FSUBv8f16:
7585 case AArch64::FSUBv2f32:
7586 case AArch64::FSUBv2f64:
7587 case AArch64::FSUBv4f32:
7588 // We can fuse FADD/FSUB with FMUL, if FADD/FSUB has the contract fast-math
7589 // flag.
7590 return Inst.getFlag(MachineInstr::FmContract);
7591 }
7592 return false;
7593}
7594
7595// Opcodes that can be combined with a MUL
7599
7600//
7601// Utility routine that checks if \param MO is defined by an
7602// \param CombineOpc instruction in the basic block \param MBB
7604 unsigned CombineOpc, unsigned ZeroReg = 0,
7605 bool CheckZeroReg = false) {
7606 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7607 MachineInstr *MI = nullptr;
7608
7609 if (MO.isReg() && MO.getReg().isVirtual())
7610 MI = MRI.getUniqueVRegDef(MO.getReg());
7611 // And it needs to be in the trace (otherwise, it won't have a depth).
7612 if (!MI || MI->getParent() != &MBB || MI->getOpcode() != CombineOpc)
7613 return false;
7614 // Must only used by the user we combine with.
7615 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
7616 return false;
7617
7618 if (CheckZeroReg) {
7619 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
7620 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
7621 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
7622 // The third input reg must be zero.
7623 if (MI->getOperand(3).getReg() != ZeroReg)
7624 return false;
7625 }
7626
7627 if (isCombineInstrSettingFlag(CombineOpc) &&
7628 MI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) == -1)
7629 return false;
7630
7631 return true;
7632}
7633
7634//
7635// Is \param MO defined by an integer multiply and can be combined?
7637 unsigned MulOpc, unsigned ZeroReg) {
7638 return canCombine(MBB, MO, MulOpc, ZeroReg, true);
7639}
7640
7641//
7642// Is \param MO defined by a floating-point multiply and can be combined?
7644 unsigned MulOpc) {
7645 return canCombine(MBB, MO, MulOpc);
7646}
7647
7648// TODO: There are many more machine instruction opcodes to match:
7649// 1. Other data types (integer, vectors)
7650// 2. Other math / logic operations (xor, or)
7651// 3. Other forms of the same operation (intrinsics and other variants)
7652bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
7653 bool Invert) const {
7654 if (Invert)
7655 return false;
7656 switch (Inst.getOpcode()) {
7657 // == Floating-point types ==
7658 // -- Floating-point instructions --
7659 case AArch64::FADDHrr:
7660 case AArch64::FADDSrr:
7661 case AArch64::FADDDrr:
7662 case AArch64::FMULHrr:
7663 case AArch64::FMULSrr:
7664 case AArch64::FMULDrr:
7665 case AArch64::FMULX16:
7666 case AArch64::FMULX32:
7667 case AArch64::FMULX64:
7668 // -- Advanced SIMD instructions --
7669 case AArch64::FADDv4f16:
7670 case AArch64::FADDv8f16:
7671 case AArch64::FADDv2f32:
7672 case AArch64::FADDv4f32:
7673 case AArch64::FADDv2f64:
7674 case AArch64::FMULv4f16:
7675 case AArch64::FMULv8f16:
7676 case AArch64::FMULv2f32:
7677 case AArch64::FMULv4f32:
7678 case AArch64::FMULv2f64:
7679 case AArch64::FMULXv4f16:
7680 case AArch64::FMULXv8f16:
7681 case AArch64::FMULXv2f32:
7682 case AArch64::FMULXv4f32:
7683 case AArch64::FMULXv2f64:
7684 // -- SVE instructions --
7685 // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
7686 // in the SVE instruction set (though there are predicated ones).
7687 case AArch64::FADD_ZZZ_H:
7688 case AArch64::FADD_ZZZ_S:
7689 case AArch64::FADD_ZZZ_D:
7690 case AArch64::FMUL_ZZZ_H:
7691 case AArch64::FMUL_ZZZ_S:
7692 case AArch64::FMUL_ZZZ_D:
7695
7696 // == Integer types ==
7697 // -- Base instructions --
7698 // Opcodes MULWrr and MULXrr don't exist because
7699 // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
7700 // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
7701 // The machine-combiner does not support three-source-operands machine
7702 // instruction. So we cannot reassociate MULs.
7703 case AArch64::ADDWrr:
7704 case AArch64::ADDXrr:
7705 case AArch64::ANDWrr:
7706 case AArch64::ANDXrr:
7707 case AArch64::ORRWrr:
7708 case AArch64::ORRXrr:
7709 case AArch64::EORWrr:
7710 case AArch64::EORXrr:
7711 case AArch64::EONWrr:
7712 case AArch64::EONXrr:
7713 // -- Advanced SIMD instructions --
7714 // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
7715 // in the Advanced SIMD instruction set.
7716 case AArch64::ADDv8i8:
7717 case AArch64::ADDv16i8:
7718 case AArch64::ADDv4i16:
7719 case AArch64::ADDv8i16:
7720 case AArch64::ADDv2i32:
7721 case AArch64::ADDv4i32:
7722 case AArch64::ADDv1i64:
7723 case AArch64::ADDv2i64:
7724 case AArch64::MULv8i8:
7725 case AArch64::MULv16i8:
7726 case AArch64::MULv4i16:
7727 case AArch64::MULv8i16:
7728 case AArch64::MULv2i32:
7729 case AArch64::MULv4i32:
7730 case AArch64::ANDv8i8:
7731 case AArch64::ANDv16i8:
7732 case AArch64::ORRv8i8:
7733 case AArch64::ORRv16i8:
7734 case AArch64::EORv8i8:
7735 case AArch64::EORv16i8:
7736 // -- SVE instructions --
7737 case AArch64::ADD_ZZZ_B:
7738 case AArch64::ADD_ZZZ_H:
7739 case AArch64::ADD_ZZZ_S:
7740 case AArch64::ADD_ZZZ_D:
7741 case AArch64::MUL_ZZZ_B:
7742 case AArch64::MUL_ZZZ_H:
7743 case AArch64::MUL_ZZZ_S:
7744 case AArch64::MUL_ZZZ_D:
7745 case AArch64::AND_ZZZ:
7746 case AArch64::ORR_ZZZ:
7747 case AArch64::EOR_ZZZ:
7748 return true;
7749
7750 default:
7751 return false;
7752 }
7753}
7754
7755/// Find instructions that can be turned into madd.
7757 SmallVectorImpl<unsigned> &Patterns) {
7758 unsigned Opc = Root.getOpcode();
7759 MachineBasicBlock &MBB = *Root.getParent();
7760 bool Found = false;
7761
7763 return false;
7765 int Cmp_NZCV =
7766 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
7767 // When NZCV is live bail out.
7768 if (Cmp_NZCV == -1)
7769 return false;
7770 unsigned NewOpc = convertToNonFlagSettingOpc(Root);
7771 // When opcode can't change bail out.
7772 // CHECKME: do we miss any cases for opcode conversion?
7773 if (NewOpc == Opc)
7774 return false;
7775 Opc = NewOpc;
7776 }
7777
7778 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
7779 unsigned Pattern) {
7780 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
7781 Patterns.push_back(Pattern);
7782 Found = true;
7783 }
7784 };
7785
7786 const AArch64Subtarget &STI =
7787 MBB.getParent()->getSubtarget<AArch64Subtarget>();
7788 auto setShfFound = [&](int Opcode, unsigned ZeroReg, unsigned Pattern) {
7789 // TODO: Currently its not possible to reject the combine for Apple targets
7790 // based on the scheduling model, because we have gaps in modeling and
7791 // analysis. Once we fill the gaps, remove the subtarget feature and the
7792 // associated check here.
7793 if (STI.hasShiftMaddSlow())
7794 return;
7795
7796 unsigned ShiftImm = Root.getOperand(3).getImm();
7798
7799 if ((ShiftTy != AArch64_AM::LSL && ShiftTy != AArch64_AM::LSR &&
7800 ShiftTy != AArch64_AM::ASR) ||
7801 AArch64_AM::getShiftValue(ShiftImm) == 0)
7802 return;
7803
7804 if (!canCombineWithMUL(MBB, Root.getOperand(1), Opcode, ZeroReg))
7805 return;
7806
7807 Patterns.push_back(Pattern);
7808 Found = true;
7809 };
7810
7811 auto setVFound = [&](int Opcode, int Operand, unsigned Pattern) {
7812 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
7813 Patterns.push_back(Pattern);
7814 Found = true;
7815 }
7816 };
7817
7819
7820 switch (Opc) {
7821 default:
7822 break;
7823 case AArch64::ADDWrr:
7824 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7825 "ADDWrr does not have register operands");
7826 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
7827 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
7828 break;
7829 case AArch64::ADDXrr:
7830 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
7831 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
7832 break;
7833 case AArch64::SUBWrr:
7834 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
7835 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
7836 break;
7837 case AArch64::SUBXrr:
7838 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
7839 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
7840 break;
7841 case AArch64::ADDWri:
7842 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
7843 break;
7844 case AArch64::ADDXri:
7845 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
7846 break;
7847 case AArch64::SUBWri:
7848 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
7849 break;
7850 case AArch64::SUBXri:
7851 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
7852 break;
7853 case AArch64::ADDWrs:
7854 setShfFound(AArch64::MADDWrrr, AArch64::WZR, MCP::MULADDWS_OP1);
7855 break;
7856 case AArch64::ADDXrs:
7857 setShfFound(AArch64::MADDXrrr, AArch64::XZR, MCP::MULADDXS_OP1);
7858 break;
7859 case AArch64::ADDv8i8:
7860 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
7861 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
7862 break;
7863 case AArch64::ADDv16i8:
7864 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
7865 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
7866 break;
7867 case AArch64::ADDv4i16:
7868 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
7869 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
7870 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
7871 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
7872 break;
7873 case AArch64::ADDv8i16:
7874 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
7875 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
7876 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
7877 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
7878 break;
7879 case AArch64::ADDv2i32:
7880 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
7881 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
7882 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
7883 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
7884 break;
7885 case AArch64::ADDv4i32:
7886 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
7887 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
7888 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
7889 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
7890 break;
7891 case AArch64::SUBv8i8:
7892 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
7893 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
7894 break;
7895 case AArch64::SUBv16i8:
7896 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
7897 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
7898 break;
7899 case AArch64::SUBv4i16:
7900 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
7901 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
7902 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
7903 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
7904 break;
7905 case AArch64::SUBv8i16:
7906 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
7907 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
7908 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
7909 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
7910 break;
7911 case AArch64::SUBv2i32:
7912 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
7913 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
7914 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
7915 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
7916 break;
7917 case AArch64::SUBv4i32:
7918 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
7919 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
7920 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
7921 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
7922 break;
7923 }
7924 return Found;
7925}
7926
7927bool AArch64InstrInfo::isAccumulationOpcode(unsigned Opcode) const {
7928 switch (Opcode) {
7929 default:
7930 break;
7931 case AArch64::UABALB_ZZZ_D:
7932 case AArch64::UABALB_ZZZ_H:
7933 case AArch64::UABALB_ZZZ_S:
7934 case AArch64::UABALT_ZZZ_D:
7935 case AArch64::UABALT_ZZZ_H:
7936 case AArch64::UABALT_ZZZ_S:
7937 case AArch64::SABALB_ZZZ_D:
7938 case AArch64::SABALB_ZZZ_S:
7939 case AArch64::SABALB_ZZZ_H:
7940 case AArch64::SABALT_ZZZ_D:
7941 case AArch64::SABALT_ZZZ_S:
7942 case AArch64::SABALT_ZZZ_H:
7943 case AArch64::UABALv16i8_v8i16:
7944 case AArch64::UABALv2i32_v2i64:
7945 case AArch64::UABALv4i16_v4i32:
7946 case AArch64::UABALv4i32_v2i64:
7947 case AArch64::UABALv8i16_v4i32:
7948 case AArch64::UABALv8i8_v8i16:
7949 case AArch64::UABAv16i8:
7950 case AArch64::UABAv2i32:
7951 case AArch64::UABAv4i16:
7952 case AArch64::UABAv4i32:
7953 case AArch64::UABAv8i16:
7954 case AArch64::UABAv8i8:
7955 case AArch64::SABALv16i8_v8i16:
7956 case AArch64::SABALv2i32_v2i64:
7957 case AArch64::SABALv4i16_v4i32:
7958 case AArch64::SABALv4i32_v2i64:
7959 case AArch64::SABALv8i16_v4i32:
7960 case AArch64::SABALv8i8_v8i16:
7961 case AArch64::SABAv16i8:
7962 case AArch64::SABAv2i32:
7963 case AArch64::SABAv4i16:
7964 case AArch64::SABAv4i32:
7965 case AArch64::SABAv8i16:
7966 case AArch64::SABAv8i8:
7967 return true;
7968 }
7969
7970 return false;
7971}
7972
7973unsigned AArch64InstrInfo::getAccumulationStartOpcode(
7974 unsigned AccumulationOpcode) const {
7975 switch (AccumulationOpcode) {
7976 default:
7977 llvm_unreachable("Unsupported accumulation Opcode!");
7978 case AArch64::UABALB_ZZZ_D:
7979 return AArch64::UABDLB_ZZZ_D;
7980 case AArch64::UABALB_ZZZ_H:
7981 return AArch64::UABDLB_ZZZ_H;
7982 case AArch64::UABALB_ZZZ_S:
7983 return AArch64::UABDLB_ZZZ_S;
7984 case AArch64::UABALT_ZZZ_D:
7985 return AArch64::UABDLT_ZZZ_D;
7986 case AArch64::UABALT_ZZZ_H:
7987 return AArch64::UABDLT_ZZZ_H;
7988 case AArch64::UABALT_ZZZ_S:
7989 return AArch64::UABDLT_ZZZ_S;
7990 case AArch64::UABALv16i8_v8i16:
7991 return AArch64::UABDLv16i8_v8i16;
7992 case AArch64::UABALv2i32_v2i64:
7993 return AArch64::UABDLv2i32_v2i64;
7994 case AArch64::UABALv4i16_v4i32:
7995 return AArch64::UABDLv4i16_v4i32;
7996 case AArch64::UABALv4i32_v2i64:
7997 return AArch64::UABDLv4i32_v2i64;
7998 case AArch64::UABALv8i16_v4i32:
7999 return AArch64::UABDLv8i16_v4i32;
8000 case AArch64::UABALv8i8_v8i16:
8001 return AArch64::UABDLv8i8_v8i16;
8002 case AArch64::UABAv16i8:
8003 return AArch64::UABDv16i8;
8004 case AArch64::UABAv2i32:
8005 return AArch64::UABDv2i32;
8006 case AArch64::UABAv4i16:
8007 return AArch64::UABDv4i16;
8008 case AArch64::UABAv4i32:
8009 return AArch64::UABDv4i32;
8010 case AArch64::UABAv8i16:
8011 return AArch64::UABDv8i16;
8012 case AArch64::UABAv8i8:
8013 return AArch64::UABDv8i8;
8014 case AArch64::SABALB_ZZZ_D:
8015 return AArch64::SABDLB_ZZZ_D;
8016 case AArch64::SABALB_ZZZ_S:
8017 return AArch64::SABDLB_ZZZ_S;
8018 case AArch64::SABALB_ZZZ_H:
8019 return AArch64::SABDLB_ZZZ_H;
8020 case AArch64::SABALT_ZZZ_D:
8021 return AArch64::SABDLT_ZZZ_D;
8022 case AArch64::SABALT_ZZZ_S:
8023 return AArch64::SABDLT_ZZZ_S;
8024 case AArch64::SABALT_ZZZ_H:
8025 return AArch64::SABDLT_ZZZ_H;
8026 case AArch64::SABALv16i8_v8i16:
8027 return AArch64::SABDLv16i8_v8i16;
8028 case AArch64::SABALv2i32_v2i64:
8029 return AArch64::SABDLv2i32_v2i64;
8030 case AArch64::SABALv4i16_v4i32:
8031 return AArch64::SABDLv4i16_v4i32;
8032 case AArch64::SABALv4i32_v2i64:
8033 return AArch64::SABDLv4i32_v2i64;
8034 case AArch64::SABALv8i16_v4i32:
8035 return AArch64::SABDLv8i16_v4i32;
8036 case AArch64::SABALv8i8_v8i16:
8037 return AArch64::SABDLv8i8_v8i16;
8038 case AArch64::SABAv16i8:
8039 return AArch64::SABDv16i8;
8040 case AArch64::SABAv2i32:
8041 return AArch64::SABDv2i32;
8042 case AArch64::SABAv4i16:
8043 return AArch64::SABDv4i16;
8044 case AArch64::SABAv4i32:
8045 return AArch64::SABDv4i32;
8046 case AArch64::SABAv8i16:
8047 return AArch64::SABDv8i16;
8048 case AArch64::SABAv8i8:
8049 return AArch64::SABDv8i8;
8050 }
8051}
8052
8053/// Floating-Point Support
8054
8055/// Find instructions that can be turned into madd.
8057 SmallVectorImpl<unsigned> &Patterns) {
8058
8059 if (!isCombineInstrCandidateFP(Root))
8060 return false;
8061
8062 MachineBasicBlock &MBB = *Root.getParent();
8063 bool Found = false;
8064
8065 auto Match = [&](int Opcode, int Operand, unsigned Pattern) -> bool {
8066 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
8067 Patterns.push_back(Pattern);
8068 return true;
8069 }
8070 return false;
8071 };
8072
8074
8075 switch (Root.getOpcode()) {
8076 default:
8077 assert(false && "Unsupported FP instruction in combiner\n");
8078 break;
8079 case AArch64::FADDHrr:
8080 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8081 "FADDHrr does not have register operands");
8082
8083 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
8084 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
8085 break;
8086 case AArch64::FADDSrr:
8087 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8088 "FADDSrr does not have register operands");
8089
8090 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
8091 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
8092
8093 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
8094 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
8095 break;
8096 case AArch64::FADDDrr:
8097 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
8098 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
8099
8100 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
8101 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
8102 break;
8103 case AArch64::FADDv4f16:
8104 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
8105 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
8106
8107 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
8108 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
8109 break;
8110 case AArch64::FADDv8f16:
8111 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
8112 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
8113
8114 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
8115 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
8116 break;
8117 case AArch64::FADDv2f32:
8118 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
8119 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
8120
8121 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
8122 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
8123 break;
8124 case AArch64::FADDv2f64:
8125 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
8126 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
8127
8128 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
8129 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
8130 break;
8131 case AArch64::FADDv4f32:
8132 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
8133 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
8134
8135 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
8136 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
8137 break;
8138 case AArch64::FSUBHrr:
8139 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
8140 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
8141 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
8142 break;
8143 case AArch64::FSUBSrr:
8144 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
8145
8146 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
8147 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
8148
8149 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
8150 break;
8151 case AArch64::FSUBDrr:
8152 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
8153
8154 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
8155 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
8156
8157 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
8158 break;
8159 case AArch64::FSUBv4f16:
8160 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
8161 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
8162
8163 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
8164 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
8165 break;
8166 case AArch64::FSUBv8f16:
8167 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
8168 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
8169
8170 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
8171 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
8172 break;
8173 case AArch64::FSUBv2f32:
8174 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
8175 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
8176
8177 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
8178 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
8179 break;
8180 case AArch64::FSUBv2f64:
8181 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
8182 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
8183
8184 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
8185 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
8186 break;
8187 case AArch64::FSUBv4f32:
8188 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
8189 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
8190
8191 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
8192 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
8193 break;
8194 }
8195 return Found;
8196}
8197
8199 SmallVectorImpl<unsigned> &Patterns) {
8200 MachineBasicBlock &MBB = *Root.getParent();
8201 bool Found = false;
8202
8203 auto Match = [&](unsigned Opcode, int Operand, unsigned Pattern) -> bool {
8204 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8205 MachineOperand &MO = Root.getOperand(Operand);
8206 MachineInstr *MI = nullptr;
8207 if (MO.isReg() && MO.getReg().isVirtual())
8208 MI = MRI.getUniqueVRegDef(MO.getReg());
8209 // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
8210 if (MI && MI->getOpcode() == TargetOpcode::COPY &&
8211 MI->getOperand(1).getReg().isVirtual())
8212 MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
8213 if (MI && MI->getOpcode() == Opcode) {
8214 Patterns.push_back(Pattern);
8215 return true;
8216 }
8217 return false;
8218 };
8219
8221
8222 switch (Root.getOpcode()) {
8223 default:
8224 return false;
8225 case AArch64::FMULv2f32:
8226 Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
8227 Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
8228 break;
8229 case AArch64::FMULv2f64:
8230 Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
8231 Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
8232 break;
8233 case AArch64::FMULv4f16:
8234 Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
8235 Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
8236 break;
8237 case AArch64::FMULv4f32:
8238 Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
8239 Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
8240 break;
8241 case AArch64::FMULv8f16:
8242 Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
8243 Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
8244 break;
8245 }
8246
8247 return Found;
8248}
8249
8251 SmallVectorImpl<unsigned> &Patterns) {
8252 unsigned Opc = Root.getOpcode();
8253 MachineBasicBlock &MBB = *Root.getParent();
8254 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8255
8256 auto Match = [&](unsigned Opcode, unsigned Pattern) -> bool {
8257 MachineOperand &MO = Root.getOperand(1);
8258 MachineInstr *MI = MRI.getUniqueVRegDef(MO.getReg());
8259 if (MI != nullptr && (MI->getOpcode() == Opcode) &&
8260 MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()) &&
8264 MI->getFlag(MachineInstr::MIFlag::FmNsz)) {
8265 Patterns.push_back(Pattern);
8266 return true;
8267 }
8268 return false;
8269 };
8270
8271 switch (Opc) {
8272 default:
8273 break;
8274 case AArch64::FNEGDr:
8275 return Match(AArch64::FMADDDrrr, AArch64MachineCombinerPattern::FNMADD);
8276 case AArch64::FNEGSr:
8277 return Match(AArch64::FMADDSrrr, AArch64MachineCombinerPattern::FNMADD);
8278 }
8279
8280 return false;
8281}
8282
8283/// Return true when a code sequence can improve throughput. It
8284/// should be called only for instructions in loops.
8285/// \param Pattern - combiner pattern
8287 switch (Pattern) {
8288 default:
8289 break;
8395 return true;
8396 } // end switch (Pattern)
8397 return false;
8398}
8399
8400/// Find other MI combine patterns.
8402 SmallVectorImpl<unsigned> &Patterns) {
8403 // A - (B + C) ==> (A - B) - C or (A - C) - B
8404 unsigned Opc = Root.getOpcode();
8405 MachineBasicBlock &MBB = *Root.getParent();
8406
8407 switch (Opc) {
8408 case AArch64::SUBWrr:
8409 case AArch64::SUBSWrr:
8410 case AArch64::SUBXrr:
8411 case AArch64::SUBSXrr:
8412 // Found candidate root.
8413 break;
8414 default:
8415 return false;
8416 }
8417
8419 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) ==
8420 -1)
8421 return false;
8422
8423 if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
8424 canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
8425 canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
8426 canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
8429 return true;
8430 }
8431
8432 return false;
8433}
8434
8435/// Check if the given instruction forms a gather load pattern that can be
8436/// optimized for better Memory-Level Parallelism (MLP). This function
8437/// identifies chains of NEON lane load instructions that load data from
8438/// different memory addresses into individual lanes of a 128-bit vector
8439/// register, then attempts to split the pattern into parallel loads to break
8440/// the serial dependency between instructions.
8441///
8442/// Pattern Matched:
8443/// Initial scalar load -> SUBREG_TO_REG (lane 0) -> LD1i* (lane 1) ->
8444/// LD1i* (lane 2) -> ... -> LD1i* (lane N-1, Root)
8445///
8446/// Transformed Into:
8447/// Two parallel vector loads using fewer lanes each, followed by ZIP1v2i64
8448/// to combine the results, enabling better memory-level parallelism.
8449///
8450/// Supported Element Types:
8451/// - 32-bit elements (LD1i32, 4 lanes total)
8452/// - 16-bit elements (LD1i16, 8 lanes total)
8453/// - 8-bit elements (LD1i8, 16 lanes total)
8455 SmallVectorImpl<unsigned> &Patterns,
8456 unsigned LoadLaneOpCode, unsigned NumLanes) {
8457 const MachineFunction *MF = Root.getMF();
8458
8459 // Early exit if optimizing for size.
8460 if (MF->getFunction().hasMinSize())
8461 return false;
8462
8463 const MachineRegisterInfo &MRI = MF->getRegInfo();
8465
8466 // The root of the pattern must load into the last lane of the vector.
8467 if (Root.getOperand(2).getImm() != NumLanes - 1)
8468 return false;
8469
8470 // Check that we have load into all lanes except lane 0.
8471 // For each load we also want to check that:
8472 // 1. It has a single non-debug use (since we will be replacing the virtual
8473 // register)
8474 // 2. That the addressing mode only uses a single pointer operand
8475 auto *CurrInstr = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8476 auto Range = llvm::seq<unsigned>(1, NumLanes - 1);
8477 SmallSet<unsigned, 16> RemainingLanes(Range.begin(), Range.end());
8479 while (!RemainingLanes.empty() && CurrInstr &&
8480 CurrInstr->getOpcode() == LoadLaneOpCode &&
8481 MRI.hasOneNonDBGUse(CurrInstr->getOperand(0).getReg()) &&
8482 CurrInstr->getNumOperands() == 4) {
8483 RemainingLanes.erase(CurrInstr->getOperand(2).getImm());
8484 LoadInstrs.push_back(CurrInstr);
8485 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8486 }
8487
8488 // Check that we have found a match for lanes N-1.. 1.
8489 if (!RemainingLanes.empty())
8490 return false;
8491
8492 // Match the SUBREG_TO_REG sequence.
8493 if (CurrInstr->getOpcode() != TargetOpcode::SUBREG_TO_REG)
8494 return false;
8495
8496 // Verify that the subreg to reg loads an integer into the first lane.
8497 auto Lane0LoadReg = CurrInstr->getOperand(1).getReg();
8498 unsigned SingleLaneSizeInBits = 128 / NumLanes;
8499 if (TRI->getRegSizeInBits(Lane0LoadReg, MRI) != SingleLaneSizeInBits)
8500 return false;
8501
8502 // Verify that it also has a single non debug use.
8503 if (!MRI.hasOneNonDBGUse(Lane0LoadReg))
8504 return false;
8505
8506 LoadInstrs.push_back(MRI.getUniqueVRegDef(Lane0LoadReg));
8507
8508 // If there is any chance of aliasing, do not apply the pattern.
8509 // Walk backward through the MBB starting from Root.
8510 // Exit early if we've encountered all load instructions or hit the search
8511 // limit.
8512 auto MBBItr = Root.getIterator();
8513 unsigned RemainingSteps =
8514 MF->getSubtarget<AArch64Subtarget>().getCLOpts().search_limit;
8515 SmallPtrSet<const MachineInstr *, 16> RemainingLoadInstrs;
8516 RemainingLoadInstrs.insert(LoadInstrs.begin(), LoadInstrs.end());
8517 const MachineBasicBlock *MBB = Root.getParent();
8518
8519 for (; MBBItr != MBB->begin() && RemainingSteps > 0 &&
8520 !RemainingLoadInstrs.empty();
8521 --MBBItr, --RemainingSteps) {
8522 const MachineInstr &CurrInstr = *MBBItr;
8523
8524 // Remove this instruction from remaining loads if it's one we're tracking.
8525 RemainingLoadInstrs.erase(&CurrInstr);
8526
8527 // Check for potential aliasing with any of the load instructions to
8528 // optimize.
8529 if (CurrInstr.isLoadFoldBarrier())
8530 return false;
8531 }
8532
8533 // If we hit the search limit without finding all load instructions,
8534 // don't match the pattern.
8535 if (RemainingSteps == 0 && !RemainingLoadInstrs.empty())
8536 return false;
8537
8538 switch (NumLanes) {
8539 case 4:
8541 break;
8542 case 8:
8544 break;
8545 case 16:
8547 break;
8548 default:
8549 llvm_unreachable("Got bad number of lanes for gather pattern.");
8550 }
8551
8552 return true;
8553}
8554
8555/// Search for patterns of LD instructions we can optimize.
8557 SmallVectorImpl<unsigned> &Patterns) {
8558
8559 // The pattern searches for loads into single lanes.
8560 switch (Root.getOpcode()) {
8561 case AArch64::LD1i32:
8562 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 4);
8563 case AArch64::LD1i16:
8564 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 8);
8565 case AArch64::LD1i8:
8566 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 16);
8567 default:
8568 return false;
8569 }
8570}
8571
8572/// Generate optimized instruction sequence for gather load patterns to improve
8573/// Memory-Level Parallelism (MLP). This function transforms a chain of
8574/// sequential NEON lane loads into parallel vector loads that can execute
8575/// concurrently.
8576static void
8580 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8581 unsigned Pattern, unsigned NumLanes) {
8582 MachineFunction &MF = *Root.getParent()->getParent();
8585
8586 // Gather the initial load instructions to build the pattern.
8587 SmallVector<MachineInstr *, 16> LoadToLaneInstrs;
8588 MachineInstr *CurrInstr = &Root;
8589 for (unsigned i = 0; i < NumLanes - 1; ++i) {
8590 LoadToLaneInstrs.push_back(CurrInstr);
8591 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8592 }
8593
8594 // Sort the load instructions according to the lane.
8595 llvm::sort(LoadToLaneInstrs,
8596 [](const MachineInstr *A, const MachineInstr *B) {
8597 return A->getOperand(2).getImm() > B->getOperand(2).getImm();
8598 });
8599
8600 MachineInstr *SubregToReg = CurrInstr;
8601 LoadToLaneInstrs.push_back(
8602 MRI.getUniqueVRegDef(SubregToReg->getOperand(1).getReg()));
8603 auto LoadToLaneInstrsAscending = llvm::reverse(LoadToLaneInstrs);
8604
8605 const TargetRegisterClass *FPR128RegClass =
8606 MRI.getRegClass(Root.getOperand(0).getReg());
8607
8608 // Helper lambda to create a LD1 instruction.
8609 auto CreateLD1Instruction = [&](MachineInstr *OriginalInstr,
8610 Register SrcRegister, unsigned Lane,
8611 Register OffsetRegister) {
8612 auto NewRegister = MRI.createVirtualRegister(FPR128RegClass);
8613 MachineInstrBuilder LoadIndexIntoRegister =
8614 BuildMI(MF, MIMetadata(*OriginalInstr), TII->get(Root.getOpcode()),
8615 NewRegister)
8616 .addReg(SrcRegister)
8617 .addImm(Lane)
8618 .addReg(OffsetRegister)
8619 .setMemRefs(OriginalInstr->memoperands());
8620 InstrIdxForVirtReg.insert(std::make_pair(NewRegister, InsInstrs.size()));
8621 InsInstrs.push_back(LoadIndexIntoRegister);
8622 return NewRegister;
8623 };
8624
8625 // Helper to create load instruction based on the NumLanes in the NEON
8626 // register we are rewriting.
8627 auto CreateLDRInstruction =
8628 [&](unsigned NumLanes, Register DestReg, Register OffsetReg,
8630 unsigned Opcode;
8631 switch (NumLanes) {
8632 case 4:
8633 Opcode = AArch64::LDRSui;
8634 break;
8635 case 8:
8636 Opcode = AArch64::LDRHui;
8637 break;
8638 case 16:
8639 Opcode = AArch64::LDRBui;
8640 break;
8641 default:
8643 "Got unsupported number of lanes in machine-combiner gather pattern");
8644 }
8645 // Immediate offset load
8646 return BuildMI(MF, MIMetadata(Root), TII->get(Opcode), DestReg)
8647 .addReg(OffsetReg)
8648 .addImm(0)
8649 .setMemRefs(MMOs);
8650 };
8651
8652 // Load the remaining lanes into register 0.
8653 auto LanesToLoadToReg0 =
8654 llvm::make_range(LoadToLaneInstrsAscending.begin() + 1,
8655 LoadToLaneInstrsAscending.begin() + NumLanes / 2);
8656 Register PrevReg = SubregToReg->getOperand(0).getReg();
8657 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg0)) {
8658 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8659 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8660 OffsetRegOperand.getReg());
8661 DelInstrs.push_back(LoadInstr);
8662 }
8663 Register LastLoadReg0 = PrevReg;
8664
8665 // First load into register 1. Perform an integer load to zero out the upper
8666 // lanes in a single instruction.
8667 MachineInstr *Lane0Load = *LoadToLaneInstrsAscending.begin();
8668 MachineInstr *OriginalSplitLoad =
8669 *std::next(LoadToLaneInstrsAscending.begin(), NumLanes / 2);
8670 Register DestRegForMiddleIndex = MRI.createVirtualRegister(
8671 MRI.getRegClass(Lane0Load->getOperand(0).getReg()));
8672
8673 const MachineOperand &OriginalSplitToLoadOffsetOperand =
8674 OriginalSplitLoad->getOperand(3);
8675 MachineInstrBuilder MiddleIndexLoadInstr =
8676 CreateLDRInstruction(NumLanes, DestRegForMiddleIndex,
8677 OriginalSplitToLoadOffsetOperand.getReg(),
8678 OriginalSplitLoad->memoperands());
8679
8680 InstrIdxForVirtReg.insert(
8681 std::make_pair(DestRegForMiddleIndex, InsInstrs.size()));
8682 InsInstrs.push_back(MiddleIndexLoadInstr);
8683 DelInstrs.push_back(OriginalSplitLoad);
8684
8685 // Subreg To Reg instruction for register 1.
8686 Register DestRegForSubregToReg = MRI.createVirtualRegister(FPR128RegClass);
8687 unsigned SubregType;
8688 switch (NumLanes) {
8689 case 4:
8690 SubregType = AArch64::ssub;
8691 break;
8692 case 8:
8693 SubregType = AArch64::hsub;
8694 break;
8695 case 16:
8696 SubregType = AArch64::bsub;
8697 break;
8698 default:
8700 "Got invalid NumLanes for machine-combiner gather pattern");
8701 }
8702
8703 auto SubRegToRegInstr =
8704 BuildMI(MF, MIMetadata(Root), TII->get(SubregToReg->getOpcode()),
8705 DestRegForSubregToReg)
8706 .addReg(DestRegForMiddleIndex)
8707 .addImm(SubregType);
8708 InstrIdxForVirtReg.insert(
8709 std::make_pair(DestRegForSubregToReg, InsInstrs.size()));
8710 InsInstrs.push_back(SubRegToRegInstr);
8711
8712 // Load remaining lanes into register 1.
8713 auto LanesToLoadToReg1 =
8714 llvm::make_range(LoadToLaneInstrsAscending.begin() + NumLanes / 2 + 1,
8715 LoadToLaneInstrsAscending.end());
8716 PrevReg = SubRegToRegInstr->getOperand(0).getReg();
8717 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg1)) {
8718 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8719 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8720 OffsetRegOperand.getReg());
8721
8722 // Do not add the last reg to DelInstrs - it will be removed later.
8723 if (Index == NumLanes / 2 - 2) {
8724 break;
8725 }
8726 DelInstrs.push_back(LoadInstr);
8727 }
8728 Register LastLoadReg1 = PrevReg;
8729
8730 // Create the final zip instruction to combine the results.
8731 MachineInstrBuilder ZipInstr =
8732 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::ZIP1v2i64),
8733 Root.getOperand(0).getReg())
8734 .addReg(LastLoadReg0)
8735 .addReg(LastLoadReg1);
8736 InsInstrs.push_back(ZipInstr);
8737}
8738
8752
8753/// Return true when there is potentially a faster code sequence for an
8754/// instruction chain ending in \p Root. All potential patterns are listed in
8755/// the \p Pattern vector. Pattern should be sorted in priority order since the
8756/// pattern evaluator stops checking as soon as it finds a faster sequence.
8757
8758bool AArch64InstrInfo::getMachineCombinerPatterns(
8759 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
8760 bool DoRegPressureReduce) const {
8761 // Integer patterns
8762 if (getMaddPatterns(Root, Patterns))
8763 return true;
8764 // Floating point patterns
8765 if (getFMULPatterns(Root, Patterns))
8766 return true;
8767 if (getFMAPatterns(Root, Patterns))
8768 return true;
8769 if (getFNEGPatterns(Root, Patterns))
8770 return true;
8771
8772 // Other patterns
8773 if (getMiscPatterns(Root, Patterns))
8774 return true;
8775
8776 // Load patterns
8777 if (getLoadPatterns(Root, Patterns))
8778 return true;
8779
8780 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
8781 DoRegPressureReduce);
8782}
8783
8785/// genFusedMultiply - Generate fused multiply instructions.
8786/// This function supports both integer and floating point instructions.
8787/// A typical example:
8788/// F|MUL I=A,B,0
8789/// F|ADD R,I,C
8790/// ==> F|MADD R,A,B,C
8791/// \param MF Containing MachineFunction
8792/// \param MRI Register information
8793/// \param TII Target information
8794/// \param Root is the F|ADD instruction
8795/// \param [out] InsInstrs is a vector of machine instructions and will
8796/// contain the generated madd instruction
8797/// \param IdxMulOpd is index of operand in Root that is the result of
8798/// the F|MUL. In the example above IdxMulOpd is 1.
8799/// \param MaddOpc the opcode fo the f|madd instruction
8800/// \param RC Register class of operands
8801/// \param kind of fma instruction (addressing mode) to be generated
8802/// \param ReplacedAddend is the result register from the instruction
8803/// replacing the non-combined operand, if any.
8804static MachineInstr *
8806 const TargetInstrInfo *TII, MachineInstr &Root,
8807 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
8808 unsigned MaddOpc, const TargetRegisterClass *RC,
8810 const Register *ReplacedAddend = nullptr) {
8811 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8812
8813 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
8814 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8815 Register ResultReg = Root.getOperand(0).getReg();
8816 Register SrcReg0 = MUL->getOperand(1).getReg();
8817 Register SrcReg1 = MUL->getOperand(2).getReg();
8818
8819 Register SrcReg2 =
8820 ReplacedAddend ? *ReplacedAddend : Root.getOperand(IdxOtherOpd).getReg();
8821
8822 if (ResultReg.isVirtual())
8823 MRI.constrainRegClass(ResultReg, RC);
8824 if (SrcReg0.isVirtual())
8825 MRI.constrainRegClass(SrcReg0, RC);
8826 if (SrcReg1.isVirtual())
8827 MRI.constrainRegClass(SrcReg1, RC);
8828 if (SrcReg2.isVirtual())
8829 MRI.constrainRegClass(SrcReg2, RC);
8830
8832 if (kind == FMAInstKind::Default)
8833 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8834 .addReg(SrcReg0)
8835 .addReg(SrcReg1)
8836 .addReg(SrcReg2);
8837 else if (kind == FMAInstKind::Indexed)
8838 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8839 .addReg(SrcReg2)
8840 .addReg(SrcReg0)
8841 .addReg(SrcReg1)
8842 .addImm(MUL->getOperand(3).getImm());
8843 else if (kind == FMAInstKind::Accumulator)
8844 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8845 .addReg(SrcReg2)
8846 .addReg(SrcReg0)
8847 .addReg(SrcReg1);
8848 else
8849 assert(false && "Invalid FMA instruction kind \n");
8850 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
8851 InsInstrs.push_back(MIB);
8852 return MUL;
8853}
8854
8855/// MUL I=A,B,0
8856/// ADDrs R,I,C,shift
8857/// ==>
8858/// SBFM/UBFM J=C,shift
8859/// MADD R,A,B,J
8861 const TargetInstrInfo *TII, MachineInstr &Root,
8864 unsigned MaddOpc, bool Is64Bit,
8865 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
8866 const TargetRegisterClass *RC =
8867 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
8868 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8869 Register ResultReg = Root.getOperand(0).getReg();
8870 Register SrcReg0 = MUL->getOperand(1).getReg();
8871 Register SrcReg1 = MUL->getOperand(2).getReg();
8872 Register ShiftedReg = Root.getOperand(2).getReg();
8873
8874 if (ResultReg.isVirtual())
8875 MRI.constrainRegClass(ResultReg, RC);
8876 if (SrcReg0.isVirtual())
8877 MRI.constrainRegClass(SrcReg0, RC);
8878 if (SrcReg1.isVirtual())
8879 MRI.constrainRegClass(SrcReg1, RC);
8880 if (ShiftedReg.isVirtual())
8881 MRI.constrainRegClass(ShiftedReg, RC);
8882
8883 unsigned ShiftImm = Root.getOperand(3).getImm();
8884 unsigned ShiftVal = AArch64_AM::getShiftValue(ShiftImm);
8885 unsigned RegSize = Is64Bit ? 64 : 32;
8886 unsigned BFMOpc;
8887 unsigned ImmR, ImmS;
8888 switch (AArch64_AM::getShiftType(ShiftImm)) {
8889 case AArch64_AM::ASR:
8890 BFMOpc = Is64Bit ? AArch64::SBFMXri : AArch64::SBFMWri;
8891 ImmR = ShiftVal;
8892 ImmS = RegSize - 1;
8893 break;
8894 case AArch64_AM::LSR:
8895 BFMOpc = Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri;
8896 ImmR = ShiftVal;
8897 ImmS = RegSize - 1;
8898 break;
8899 case AArch64_AM::LSL:
8900 BFMOpc = Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri;
8901 ImmR = (RegSize - ShiftVal) % RegSize;
8902 ImmS = RegSize - 1 - ShiftVal;
8903 break;
8904 default:
8905 llvm_unreachable("Unexpected shift type");
8906 }
8907
8908 Register ShiftReg = MRI.createVirtualRegister(RC);
8909 MachineInstrBuilder MIB1 =
8910 BuildMI(MF, MIMetadata(Root), TII->get(BFMOpc), ShiftReg)
8911 .addReg(ShiftedReg)
8912 .addImm(ImmR)
8913 .addImm(ImmS);
8914 InstrIdxForVirtReg.insert(std::make_pair(ShiftReg, InsInstrs.size()));
8915 InsInstrs.push_back(MIB1);
8916
8917 uint32_t Flags = Root.getFlags() & MUL->getFlags() &
8919
8920 MachineInstrBuilder MIB2 =
8921 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8922 .addReg(SrcReg0)
8923 .addReg(SrcReg1)
8924 .addReg(ShiftReg)
8925 .setMIFlags(Flags);
8926
8927 InsInstrs.push_back(MIB2);
8928 DelInstrs.push_back(MUL);
8929 DelInstrs.push_back(&Root);
8930}
8931
8932static MachineInstr *
8934 const TargetInstrInfo *TII, MachineInstr &Root,
8936 MachineInstr *MAD = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8937
8938 unsigned Opc = 0;
8939 const TargetRegisterClass *RC = MRI.getRegClass(MAD->getOperand(0).getReg());
8940 if (AArch64::FPR32RegClass.hasSubClassEq(RC))
8941 Opc = AArch64::FNMADDSrrr;
8942 else if (AArch64::FPR64RegClass.hasSubClassEq(RC))
8943 Opc = AArch64::FNMADDDrrr;
8944 else
8945 return nullptr;
8946
8947 Register ResultReg = Root.getOperand(0).getReg();
8948 Register SrcReg0 = MAD->getOperand(1).getReg();
8949 Register SrcReg1 = MAD->getOperand(2).getReg();
8950 Register SrcReg2 = MAD->getOperand(3).getReg();
8951 if (ResultReg.isVirtual())
8952 MRI.constrainRegClass(ResultReg, RC);
8953 if (SrcReg0.isVirtual())
8954 MRI.constrainRegClass(SrcReg0, RC);
8955 if (SrcReg1.isVirtual())
8956 MRI.constrainRegClass(SrcReg1, RC);
8957 if (SrcReg2.isVirtual())
8958 MRI.constrainRegClass(SrcReg2, RC);
8959
8961 BuildMI(MF, MIMetadata(Root), TII->get(Opc), ResultReg)
8962 .addReg(SrcReg0)
8963 .addReg(SrcReg1)
8964 .addReg(SrcReg2);
8965 InsInstrs.push_back(MIB);
8966
8967 return MAD;
8968}
8969
8970/// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
8971static MachineInstr *
8974 unsigned IdxDupOp, unsigned MulOpc,
8976 assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
8977 "Invalid index of FMUL operand");
8978
8979 MachineFunction &MF = *Root.getMF();
8981
8982 MachineInstr *Dup =
8983 MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
8984
8985 if (Dup->getOpcode() == TargetOpcode::COPY)
8986 Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
8987
8988 Register DupSrcReg = Dup->getOperand(1).getReg();
8989 MRI.clearKillFlags(DupSrcReg);
8990 MRI.constrainRegClass(DupSrcReg, RC);
8991
8992 unsigned DupSrcLane = Dup->getOperand(2).getImm();
8993
8994 unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
8995 MachineOperand &MulOp = Root.getOperand(IdxMulOp);
8996
8997 Register ResultReg = Root.getOperand(0).getReg();
8998
9000 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
9001 .add(MulOp)
9002 .addReg(DupSrcReg)
9003 .addImm(DupSrcLane);
9004
9005 InsInstrs.push_back(MIB);
9006 return &Root;
9007}
9008
9009/// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
9010/// instructions.
9011///
9012/// \see genFusedMultiply
9016 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
9017 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9019}
9020
9021/// genNeg - Helper to generate an intermediate negation of the second operand
9022/// of Root
9024 const TargetInstrInfo *TII, MachineInstr &Root,
9026 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
9027 unsigned MnegOpc, const TargetRegisterClass *RC) {
9028 Register NewVR = MRI.createVirtualRegister(RC);
9030 BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
9031 .add(Root.getOperand(2));
9032 InsInstrs.push_back(MIB);
9033
9034 assert(InstrIdxForVirtReg.empty());
9035 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9036
9037 return NewVR;
9038}
9039
9040/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
9041/// instructions with an additional negation of the accumulator
9045 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
9046 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
9047 assert(IdxMulOpd == 1);
9048
9049 Register NewVR =
9050 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
9051 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9052 FMAInstKind::Accumulator, &NewVR);
9053}
9054
9055/// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
9056/// instructions.
9057///
9058/// \see genFusedMultiply
9062 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
9063 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9065}
9066
9067/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
9068/// instructions with an additional negation of the accumulator
9072 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
9073 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
9074 assert(IdxMulOpd == 1);
9075
9076 Register NewVR =
9077 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
9078
9079 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
9080 FMAInstKind::Indexed, &NewVR);
9081}
9082
9083/// genMaddR - Generate madd instruction and combine mul and add using
9084/// an extra virtual register
9085/// Example - an ADD intermediate needs to be stored in a register:
9086/// MUL I=A,B,0
9087/// ADD R,I,Imm
9088/// ==> ORR V, ZR, Imm
9089/// ==> MADD R,A,B,V
9090/// \param MF Containing MachineFunction
9091/// \param MRI Register information
9092/// \param TII Target information
9093/// \param Root is the ADD instruction
9094/// \param [out] InsInstrs is a vector of machine instructions and will
9095/// contain the generated madd instruction
9096/// \param IdxMulOpd is index of operand in Root that is the result of
9097/// the MUL. In the example above IdxMulOpd is 1.
9098/// \param MaddOpc the opcode fo the madd instruction
9099/// \param VR is a virtual register that holds the value of an ADD operand
9100/// (V in the example above).
9101/// \param RC Register class of operands
9103 const TargetInstrInfo *TII, MachineInstr &Root,
9105 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
9106 const TargetRegisterClass *RC) {
9107 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
9108
9109 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
9110 Register ResultReg = Root.getOperand(0).getReg();
9111 Register SrcReg0 = MUL->getOperand(1).getReg();
9112 Register SrcReg1 = MUL->getOperand(2).getReg();
9113
9114 if (ResultReg.isVirtual())
9115 MRI.constrainRegClass(ResultReg, RC);
9116 if (SrcReg0.isVirtual())
9117 MRI.constrainRegClass(SrcReg0, RC);
9118 if (SrcReg1.isVirtual())
9119 MRI.constrainRegClass(SrcReg1, RC);
9121 MRI.constrainRegClass(VR, RC);
9122
9124 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
9125 .addReg(SrcReg0)
9126 .addReg(SrcReg1)
9127 .addReg(VR);
9128 // Insert the MADD
9129 InsInstrs.push_back(MIB);
9130 return MUL;
9131}
9132
9133/// Do the following transformation
9134/// A - (B + C) ==> (A - B) - C
9135/// A - (B + C) ==> (A - C) - B
9137 const TargetInstrInfo *TII, MachineInstr &Root,
9140 unsigned IdxOpd1,
9141 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
9142 assert(IdxOpd1 == 1 || IdxOpd1 == 2);
9143 unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
9144 MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
9145
9146 Register ResultReg = Root.getOperand(0).getReg();
9147 Register RegA = Root.getOperand(1).getReg();
9148 Register RegB = AddMI->getOperand(IdxOpd1).getReg();
9149 Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
9150 Register NewVR =
9151 MRI.createVirtualRegister(MRI.getRegClass(Root.getOperand(2).getReg()));
9152
9153 unsigned Opcode = Root.getOpcode();
9154 if (Opcode == AArch64::SUBSWrr)
9155 Opcode = AArch64::SUBWrr;
9156 else if (Opcode == AArch64::SUBSXrr)
9157 Opcode = AArch64::SUBXrr;
9158 else
9159 assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
9160 "Unexpected instruction opcode.");
9161
9162 uint32_t Flags = Root.mergeFlagsWith(*AddMI);
9163 Flags &= ~MachineInstr::NoSWrap;
9164 Flags &= ~MachineInstr::NoUWrap;
9165
9166 MachineInstrBuilder MIB1 =
9167 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
9168 .addReg(RegA)
9169 .addReg(RegB)
9170 .setMIFlags(Flags);
9171 MachineInstrBuilder MIB2 =
9172 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
9173 .addReg(NewVR)
9174 .addReg(RegC)
9175 .setMIFlags(Flags);
9176
9177 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9178 InsInstrs.push_back(MIB1);
9179 InsInstrs.push_back(MIB2);
9180 DelInstrs.push_back(AddMI);
9181 DelInstrs.push_back(&Root);
9182}
9183
9184unsigned AArch64InstrInfo::getReduceOpcodeForAccumulator(
9185 unsigned int AccumulatorOpCode) const {
9186 switch (AccumulatorOpCode) {
9187 case AArch64::UABALB_ZZZ_D:
9188 case AArch64::SABALB_ZZZ_D:
9189 case AArch64::UABALT_ZZZ_D:
9190 case AArch64::SABALT_ZZZ_D:
9191 return AArch64::ADD_ZZZ_D;
9192 case AArch64::UABALB_ZZZ_H:
9193 case AArch64::SABALB_ZZZ_H:
9194 case AArch64::UABALT_ZZZ_H:
9195 case AArch64::SABALT_ZZZ_H:
9196 return AArch64::ADD_ZZZ_H;
9197 case AArch64::UABALB_ZZZ_S:
9198 case AArch64::SABALB_ZZZ_S:
9199 case AArch64::UABALT_ZZZ_S:
9200 case AArch64::SABALT_ZZZ_S:
9201 return AArch64::ADD_ZZZ_S;
9202 case AArch64::UABALv16i8_v8i16:
9203 case AArch64::SABALv8i8_v8i16:
9204 case AArch64::SABAv8i16:
9205 case AArch64::UABAv8i16:
9206 return AArch64::ADDv8i16;
9207 case AArch64::SABALv2i32_v2i64:
9208 case AArch64::UABALv2i32_v2i64:
9209 case AArch64::SABALv4i32_v2i64:
9210 return AArch64::ADDv2i64;
9211 case AArch64::UABALv4i16_v4i32:
9212 case AArch64::SABALv4i16_v4i32:
9213 case AArch64::SABALv8i16_v4i32:
9214 case AArch64::SABAv4i32:
9215 case AArch64::UABAv4i32:
9216 return AArch64::ADDv4i32;
9217 case AArch64::UABALv4i32_v2i64:
9218 return AArch64::ADDv2i64;
9219 case AArch64::UABALv8i16_v4i32:
9220 return AArch64::ADDv4i32;
9221 case AArch64::UABALv8i8_v8i16:
9222 case AArch64::SABALv16i8_v8i16:
9223 return AArch64::ADDv8i16;
9224 case AArch64::UABAv16i8:
9225 case AArch64::SABAv16i8:
9226 return AArch64::ADDv16i8;
9227 case AArch64::UABAv4i16:
9228 case AArch64::SABAv4i16:
9229 return AArch64::ADDv4i16;
9230 case AArch64::UABAv2i32:
9231 case AArch64::SABAv2i32:
9232 return AArch64::ADDv2i32;
9233 case AArch64::UABAv8i8:
9234 case AArch64::SABAv8i8:
9235 return AArch64::ADDv8i8;
9236 default:
9237 llvm_unreachable("Unknown accumulator opcode");
9238 }
9239}
9240
9241/// When getMachineCombinerPatterns() finds potential patterns,
9242/// this function generates the instructions that could replace the
9243/// original code sequence
9244void AArch64InstrInfo::genAlternativeCodeSequence(
9245 MachineInstr &Root, unsigned Pattern,
9248 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
9249 MachineBasicBlock &MBB = *Root.getParent();
9250 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9251 MachineFunction &MF = *MBB.getParent();
9252 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9253
9254 MachineInstr *MUL = nullptr;
9255 const TargetRegisterClass *RC;
9256 unsigned Opc;
9257 switch (Pattern) {
9258 default:
9259 // Reassociate instructions.
9260 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9261 DelInstrs, InstrIdxForVirtReg);
9262 return;
9264 // A - (B + C)
9265 // ==> (A - B) - C
9266 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
9267 InstrIdxForVirtReg);
9268 return;
9270 // A - (B + C)
9271 // ==> (A - C) - B
9272 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
9273 InstrIdxForVirtReg);
9274 return;
9277 // MUL I=A,B,0
9278 // ADD R,I,C
9279 // ==> MADD R,A,B,C
9280 // --- Create(MADD);
9282 Opc = AArch64::MADDWrrr;
9283 RC = &AArch64::GPR32RegClass;
9284 } else {
9285 Opc = AArch64::MADDXrrr;
9286 RC = &AArch64::GPR64RegClass;
9287 }
9288 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9289 break;
9292 // MUL I=A,B,0
9293 // ADD R,C,I
9294 // ==> MADD R,A,B,C
9295 // --- Create(MADD);
9297 Opc = AArch64::MADDWrrr;
9298 RC = &AArch64::GPR32RegClass;
9299 } else {
9300 Opc = AArch64::MADDXrrr;
9301 RC = &AArch64::GPR64RegClass;
9302 }
9303 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9304 break;
9309 // MUL I=A,B,0
9310 // ADD/SUB R,I,Imm
9311 // ==> MOV V, Imm/-Imm
9312 // ==> MADD R,A,B,V
9313 // --- Create(MADD);
9314 const TargetRegisterClass *RC;
9315 unsigned BitSize, MovImm;
9318 MovImm = AArch64::MOVi32imm;
9319 RC = &AArch64::GPR32spRegClass;
9320 BitSize = 32;
9321 Opc = AArch64::MADDWrrr;
9322 RC = &AArch64::GPR32RegClass;
9323 } else {
9324 MovImm = AArch64::MOVi64imm;
9325 RC = &AArch64::GPR64spRegClass;
9326 BitSize = 64;
9327 Opc = AArch64::MADDXrrr;
9328 RC = &AArch64::GPR64RegClass;
9329 }
9331 uint64_t Imm = Root.getOperand(2).getImm();
9332
9333 if (Root.getOperand(3).isImm()) {
9334 unsigned Val = Root.getOperand(3).getImm();
9335 Imm = Imm << Val;
9336 }
9337 bool IsSub = Pattern == AArch64MachineCombinerPattern::MULSUBWI_OP1 ||
9339 uint64_t UImm = SignExtend64(IsSub ? -Imm : Imm, BitSize);
9340 // Check that the immediate can be composed via a single instruction.
9342 AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
9343 if (Insn.size() != 1)
9344 return;
9345 MachineInstrBuilder MIB1 =
9346 BuildMI(MF, MIMetadata(Root), TII->get(MovImm), NewVR)
9347 .addImm(IsSub ? -Imm : Imm);
9348 InsInstrs.push_back(MIB1);
9349 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9350 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9351 break;
9352 }
9355 // MUL I=A,B,0
9356 // SUB R,I, C
9357 // ==> SUB V, 0, C
9358 // ==> MADD R,A,B,V // = -C + A*B
9359 // --- Create(MADD);
9360 const TargetRegisterClass *SubRC;
9361 unsigned SubOpc, ZeroReg;
9363 SubOpc = AArch64::SUBWrr;
9364 SubRC = &AArch64::GPR32spRegClass;
9365 ZeroReg = AArch64::WZR;
9366 Opc = AArch64::MADDWrrr;
9367 RC = &AArch64::GPR32RegClass;
9368 } else {
9369 SubOpc = AArch64::SUBXrr;
9370 SubRC = &AArch64::GPR64spRegClass;
9371 ZeroReg = AArch64::XZR;
9372 Opc = AArch64::MADDXrrr;
9373 RC = &AArch64::GPR64RegClass;
9374 }
9375 Register NewVR = MRI.createVirtualRegister(SubRC);
9376 // SUB NewVR, 0, C
9377 MachineInstrBuilder MIB1 =
9378 BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
9379 .addReg(ZeroReg)
9380 .add(Root.getOperand(2));
9381 InsInstrs.push_back(MIB1);
9382 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9383 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9384 break;
9385 }
9388 // MUL I=A,B,0
9389 // SUB R,C,I
9390 // ==> MSUB R,A,B,C (computes C - A*B)
9391 // --- Create(MSUB);
9393 Opc = AArch64::MSUBWrrr;
9394 RC = &AArch64::GPR32RegClass;
9395 } else {
9396 Opc = AArch64::MSUBXrrr;
9397 RC = &AArch64::GPR64RegClass;
9398 }
9399 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9400 break;
9402 genMaddShf(MF, MRI, TII, Root, InsInstrs, DelInstrs, AArch64::MADDWrrr,
9403 false, InstrIdxForVirtReg);
9404 return;
9406 genMaddShf(MF, MRI, TII, Root, InsInstrs, DelInstrs, AArch64::MADDXrrr,
9407 true, InstrIdxForVirtReg);
9408 return;
9410 Opc = AArch64::MLAv8i8;
9411 RC = &AArch64::FPR64RegClass;
9412 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9413 break;
9415 Opc = AArch64::MLAv8i8;
9416 RC = &AArch64::FPR64RegClass;
9417 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9418 break;
9420 Opc = AArch64::MLAv16i8;
9421 RC = &AArch64::FPR128RegClass;
9422 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9423 break;
9425 Opc = AArch64::MLAv16i8;
9426 RC = &AArch64::FPR128RegClass;
9427 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9428 break;
9430 Opc = AArch64::MLAv4i16;
9431 RC = &AArch64::FPR64RegClass;
9432 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9433 break;
9435 Opc = AArch64::MLAv4i16;
9436 RC = &AArch64::FPR64RegClass;
9437 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9438 break;
9440 Opc = AArch64::MLAv8i16;
9441 RC = &AArch64::FPR128RegClass;
9442 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9443 break;
9445 Opc = AArch64::MLAv8i16;
9446 RC = &AArch64::FPR128RegClass;
9447 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9448 break;
9450 Opc = AArch64::MLAv2i32;
9451 RC = &AArch64::FPR64RegClass;
9452 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9453 break;
9455 Opc = AArch64::MLAv2i32;
9456 RC = &AArch64::FPR64RegClass;
9457 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9458 break;
9460 Opc = AArch64::MLAv4i32;
9461 RC = &AArch64::FPR128RegClass;
9462 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9463 break;
9465 Opc = AArch64::MLAv4i32;
9466 RC = &AArch64::FPR128RegClass;
9467 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9468 break;
9469
9471 Opc = AArch64::MLAv8i8;
9472 RC = &AArch64::FPR64RegClass;
9473 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9474 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
9475 RC);
9476 break;
9478 Opc = AArch64::MLSv8i8;
9479 RC = &AArch64::FPR64RegClass;
9480 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9481 break;
9483 Opc = AArch64::MLAv16i8;
9484 RC = &AArch64::FPR128RegClass;
9485 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9486 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
9487 RC);
9488 break;
9490 Opc = AArch64::MLSv16i8;
9491 RC = &AArch64::FPR128RegClass;
9492 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9493 break;
9495 Opc = AArch64::MLAv4i16;
9496 RC = &AArch64::FPR64RegClass;
9497 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9498 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9499 RC);
9500 break;
9502 Opc = AArch64::MLSv4i16;
9503 RC = &AArch64::FPR64RegClass;
9504 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9505 break;
9507 Opc = AArch64::MLAv8i16;
9508 RC = &AArch64::FPR128RegClass;
9509 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9510 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9511 RC);
9512 break;
9514 Opc = AArch64::MLSv8i16;
9515 RC = &AArch64::FPR128RegClass;
9516 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9517 break;
9519 Opc = AArch64::MLAv2i32;
9520 RC = &AArch64::FPR64RegClass;
9521 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9522 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9523 RC);
9524 break;
9526 Opc = AArch64::MLSv2i32;
9527 RC = &AArch64::FPR64RegClass;
9528 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9529 break;
9531 Opc = AArch64::MLAv4i32;
9532 RC = &AArch64::FPR128RegClass;
9533 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9534 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9535 RC);
9536 break;
9538 Opc = AArch64::MLSv4i32;
9539 RC = &AArch64::FPR128RegClass;
9540 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9541 break;
9542
9544 Opc = AArch64::MLAv4i16_indexed;
9545 RC = &AArch64::FPR64RegClass;
9546 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9547 break;
9549 Opc = AArch64::MLAv4i16_indexed;
9550 RC = &AArch64::FPR64RegClass;
9551 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9552 break;
9554 Opc = AArch64::MLAv8i16_indexed;
9555 RC = &AArch64::FPR128RegClass;
9556 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9557 break;
9559 Opc = AArch64::MLAv8i16_indexed;
9560 RC = &AArch64::FPR128RegClass;
9561 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9562 break;
9564 Opc = AArch64::MLAv2i32_indexed;
9565 RC = &AArch64::FPR64RegClass;
9566 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9567 break;
9569 Opc = AArch64::MLAv2i32_indexed;
9570 RC = &AArch64::FPR64RegClass;
9571 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9572 break;
9574 Opc = AArch64::MLAv4i32_indexed;
9575 RC = &AArch64::FPR128RegClass;
9576 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9577 break;
9579 Opc = AArch64::MLAv4i32_indexed;
9580 RC = &AArch64::FPR128RegClass;
9581 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9582 break;
9583
9585 Opc = AArch64::MLAv4i16_indexed;
9586 RC = &AArch64::FPR64RegClass;
9587 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9588 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9589 RC);
9590 break;
9592 Opc = AArch64::MLSv4i16_indexed;
9593 RC = &AArch64::FPR64RegClass;
9594 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9595 break;
9597 Opc = AArch64::MLAv8i16_indexed;
9598 RC = &AArch64::FPR128RegClass;
9599 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9600 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9601 RC);
9602 break;
9604 Opc = AArch64::MLSv8i16_indexed;
9605 RC = &AArch64::FPR128RegClass;
9606 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9607 break;
9609 Opc = AArch64::MLAv2i32_indexed;
9610 RC = &AArch64::FPR64RegClass;
9611 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9612 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9613 RC);
9614 break;
9616 Opc = AArch64::MLSv2i32_indexed;
9617 RC = &AArch64::FPR64RegClass;
9618 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9619 break;
9621 Opc = AArch64::MLAv4i32_indexed;
9622 RC = &AArch64::FPR128RegClass;
9623 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9624 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9625 RC);
9626 break;
9628 Opc = AArch64::MLSv4i32_indexed;
9629 RC = &AArch64::FPR128RegClass;
9630 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9631 break;
9632
9633 // Floating Point Support
9635 Opc = AArch64::FMADDHrrr;
9636 RC = &AArch64::FPR16RegClass;
9637 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9638 break;
9640 Opc = AArch64::FMADDSrrr;
9641 RC = &AArch64::FPR32RegClass;
9642 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9643 break;
9645 Opc = AArch64::FMADDDrrr;
9646 RC = &AArch64::FPR64RegClass;
9647 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9648 break;
9649
9651 Opc = AArch64::FMADDHrrr;
9652 RC = &AArch64::FPR16RegClass;
9653 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9654 break;
9656 Opc = AArch64::FMADDSrrr;
9657 RC = &AArch64::FPR32RegClass;
9658 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9659 break;
9661 Opc = AArch64::FMADDDrrr;
9662 RC = &AArch64::FPR64RegClass;
9663 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9664 break;
9665
9667 Opc = AArch64::FMLAv1i32_indexed;
9668 RC = &AArch64::FPR32RegClass;
9669 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9671 break;
9673 Opc = AArch64::FMLAv1i32_indexed;
9674 RC = &AArch64::FPR32RegClass;
9675 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9677 break;
9678
9680 Opc = AArch64::FMLAv1i64_indexed;
9681 RC = &AArch64::FPR64RegClass;
9682 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9684 break;
9686 Opc = AArch64::FMLAv1i64_indexed;
9687 RC = &AArch64::FPR64RegClass;
9688 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9690 break;
9691
9693 RC = &AArch64::FPR64RegClass;
9694 Opc = AArch64::FMLAv4i16_indexed;
9695 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9697 break;
9699 RC = &AArch64::FPR64RegClass;
9700 Opc = AArch64::FMLAv4f16;
9701 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9703 break;
9705 RC = &AArch64::FPR64RegClass;
9706 Opc = AArch64::FMLAv4i16_indexed;
9707 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9709 break;
9711 RC = &AArch64::FPR64RegClass;
9712 Opc = AArch64::FMLAv4f16;
9713 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9715 break;
9716
9719 RC = &AArch64::FPR64RegClass;
9721 Opc = AArch64::FMLAv2i32_indexed;
9722 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9724 } else {
9725 Opc = AArch64::FMLAv2f32;
9726 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9728 }
9729 break;
9732 RC = &AArch64::FPR64RegClass;
9734 Opc = AArch64::FMLAv2i32_indexed;
9735 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9737 } else {
9738 Opc = AArch64::FMLAv2f32;
9739 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9741 }
9742 break;
9743
9745 RC = &AArch64::FPR128RegClass;
9746 Opc = AArch64::FMLAv8i16_indexed;
9747 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9749 break;
9751 RC = &AArch64::FPR128RegClass;
9752 Opc = AArch64::FMLAv8f16;
9753 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9755 break;
9757 RC = &AArch64::FPR128RegClass;
9758 Opc = AArch64::FMLAv8i16_indexed;
9759 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9761 break;
9763 RC = &AArch64::FPR128RegClass;
9764 Opc = AArch64::FMLAv8f16;
9765 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9767 break;
9768
9771 RC = &AArch64::FPR128RegClass;
9773 Opc = AArch64::FMLAv2i64_indexed;
9774 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9776 } else {
9777 Opc = AArch64::FMLAv2f64;
9778 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9780 }
9781 break;
9784 RC = &AArch64::FPR128RegClass;
9786 Opc = AArch64::FMLAv2i64_indexed;
9787 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9789 } else {
9790 Opc = AArch64::FMLAv2f64;
9791 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9793 }
9794 break;
9795
9798 RC = &AArch64::FPR128RegClass;
9800 Opc = AArch64::FMLAv4i32_indexed;
9801 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9803 } else {
9804 Opc = AArch64::FMLAv4f32;
9805 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9807 }
9808 break;
9809
9812 RC = &AArch64::FPR128RegClass;
9814 Opc = AArch64::FMLAv4i32_indexed;
9815 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9817 } else {
9818 Opc = AArch64::FMLAv4f32;
9819 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9821 }
9822 break;
9823
9825 Opc = AArch64::FNMSUBHrrr;
9826 RC = &AArch64::FPR16RegClass;
9827 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9828 break;
9830 Opc = AArch64::FNMSUBSrrr;
9831 RC = &AArch64::FPR32RegClass;
9832 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9833 break;
9835 Opc = AArch64::FNMSUBDrrr;
9836 RC = &AArch64::FPR64RegClass;
9837 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9838 break;
9839
9841 Opc = AArch64::FNMADDHrrr;
9842 RC = &AArch64::FPR16RegClass;
9843 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9844 break;
9846 Opc = AArch64::FNMADDSrrr;
9847 RC = &AArch64::FPR32RegClass;
9848 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9849 break;
9851 Opc = AArch64::FNMADDDrrr;
9852 RC = &AArch64::FPR64RegClass;
9853 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9854 break;
9855
9857 Opc = AArch64::FMSUBHrrr;
9858 RC = &AArch64::FPR16RegClass;
9859 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9860 break;
9862 Opc = AArch64::FMSUBSrrr;
9863 RC = &AArch64::FPR32RegClass;
9864 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9865 break;
9867 Opc = AArch64::FMSUBDrrr;
9868 RC = &AArch64::FPR64RegClass;
9869 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9870 break;
9871
9873 Opc = AArch64::FMLSv1i32_indexed;
9874 RC = &AArch64::FPR32RegClass;
9875 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9877 break;
9878
9880 Opc = AArch64::FMLSv1i64_indexed;
9881 RC = &AArch64::FPR64RegClass;
9882 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9884 break;
9885
9888 RC = &AArch64::FPR64RegClass;
9890 MachineInstrBuilder MIB1 =
9891 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
9892 .add(Root.getOperand(2));
9893 InsInstrs.push_back(MIB1);
9894 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9896 Opc = AArch64::FMLAv4f16;
9897 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9898 FMAInstKind::Accumulator, &NewVR);
9899 } else {
9900 Opc = AArch64::FMLAv4i16_indexed;
9901 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9902 FMAInstKind::Indexed, &NewVR);
9903 }
9904 break;
9905 }
9907 RC = &AArch64::FPR64RegClass;
9908 Opc = AArch64::FMLSv4f16;
9909 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9911 break;
9913 RC = &AArch64::FPR64RegClass;
9914 Opc = AArch64::FMLSv4i16_indexed;
9915 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9917 break;
9918
9921 RC = &AArch64::FPR64RegClass;
9923 Opc = AArch64::FMLSv2i32_indexed;
9924 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9926 } else {
9927 Opc = AArch64::FMLSv2f32;
9928 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9930 }
9931 break;
9932
9935 RC = &AArch64::FPR128RegClass;
9937 MachineInstrBuilder MIB1 =
9938 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
9939 .add(Root.getOperand(2));
9940 InsInstrs.push_back(MIB1);
9941 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9943 Opc = AArch64::FMLAv8f16;
9944 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9945 FMAInstKind::Accumulator, &NewVR);
9946 } else {
9947 Opc = AArch64::FMLAv8i16_indexed;
9948 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9949 FMAInstKind::Indexed, &NewVR);
9950 }
9951 break;
9952 }
9954 RC = &AArch64::FPR128RegClass;
9955 Opc = AArch64::FMLSv8f16;
9956 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9958 break;
9960 RC = &AArch64::FPR128RegClass;
9961 Opc = AArch64::FMLSv8i16_indexed;
9962 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9964 break;
9965
9968 RC = &AArch64::FPR128RegClass;
9970 Opc = AArch64::FMLSv2i64_indexed;
9971 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9973 } else {
9974 Opc = AArch64::FMLSv2f64;
9975 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9977 }
9978 break;
9979
9982 RC = &AArch64::FPR128RegClass;
9984 Opc = AArch64::FMLSv4i32_indexed;
9985 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9987 } else {
9988 Opc = AArch64::FMLSv4f32;
9989 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9991 }
9992 break;
9995 RC = &AArch64::FPR64RegClass;
9997 MachineInstrBuilder MIB1 =
9998 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
9999 .add(Root.getOperand(2));
10000 InsInstrs.push_back(MIB1);
10001 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10003 Opc = AArch64::FMLAv2i32_indexed;
10004 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10005 FMAInstKind::Indexed, &NewVR);
10006 } else {
10007 Opc = AArch64::FMLAv2f32;
10008 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10009 FMAInstKind::Accumulator, &NewVR);
10010 }
10011 break;
10012 }
10015 RC = &AArch64::FPR128RegClass;
10017 MachineInstrBuilder MIB1 =
10018 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
10019 .add(Root.getOperand(2));
10020 InsInstrs.push_back(MIB1);
10021 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10023 Opc = AArch64::FMLAv4i32_indexed;
10024 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10025 FMAInstKind::Indexed, &NewVR);
10026 } else {
10027 Opc = AArch64::FMLAv4f32;
10028 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10029 FMAInstKind::Accumulator, &NewVR);
10030 }
10031 break;
10032 }
10035 RC = &AArch64::FPR128RegClass;
10037 MachineInstrBuilder MIB1 =
10038 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
10039 .add(Root.getOperand(2));
10040 InsInstrs.push_back(MIB1);
10041 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
10043 Opc = AArch64::FMLAv2i64_indexed;
10044 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10045 FMAInstKind::Indexed, &NewVR);
10046 } else {
10047 Opc = AArch64::FMLAv2f64;
10048 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
10049 FMAInstKind::Accumulator, &NewVR);
10050 }
10051 break;
10052 }
10055 unsigned IdxDupOp =
10057 : 2;
10058 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
10059 &AArch64::FPR128RegClass, MRI);
10060 break;
10061 }
10064 unsigned IdxDupOp =
10066 : 2;
10067 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
10068 &AArch64::FPR128RegClass, MRI);
10069 break;
10070 }
10073 unsigned IdxDupOp =
10075 : 2;
10076 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
10077 &AArch64::FPR128_loRegClass, MRI);
10078 break;
10079 }
10082 unsigned IdxDupOp =
10084 : 2;
10085 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
10086 &AArch64::FPR128RegClass, MRI);
10087 break;
10088 }
10091 unsigned IdxDupOp =
10093 : 2;
10094 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
10095 &AArch64::FPR128_loRegClass, MRI);
10096 break;
10097 }
10099 MUL = genFNegatedMAD(MF, MRI, TII, Root, InsInstrs);
10100 break;
10101 }
10103 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10104 Pattern, 4);
10105 break;
10106 }
10108 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10109 Pattern, 8);
10110 break;
10111 }
10113 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10114 Pattern, 16);
10115 break;
10116 }
10117
10118 } // end switch (Pattern)
10119 // Record MUL and ADD/SUB for deletion
10120 if (MUL)
10121 DelInstrs.push_back(MUL);
10122 DelInstrs.push_back(&Root);
10123
10124 // Set the flags on the inserted instructions to be the merged flags of the
10125 // instructions that we have combined.
10126 uint32_t Flags = Root.getFlags();
10127 if (MUL)
10128 Flags = Root.mergeFlagsWith(*MUL);
10129 for (auto *MI : InsInstrs)
10130 MI->setFlags(Flags);
10131}
10132
10133/// Replace csincr-branch sequence by simple conditional branch
10134///
10135/// Examples:
10136/// 1. \code
10137/// csinc w9, wzr, wzr, <condition code>
10138/// tbnz w9, #0, 0x44
10139/// \endcode
10140/// to
10141/// \code
10142/// b.<inverted condition code>
10143/// \endcode
10144///
10145/// 2. \code
10146/// csinc w9, wzr, wzr, <condition code>
10147/// tbz w9, #0, 0x44
10148/// \endcode
10149/// to
10150/// \code
10151/// b.<condition code>
10152/// \endcode
10153///
10154/// Replace compare and branch sequence by TBZ/TBNZ instruction when the
10155/// compare's constant operand is power of 2.
10156///
10157/// Examples:
10158/// \code
10159/// and w8, w8, #0x400
10160/// cbnz w8, L1
10161/// \endcode
10162/// to
10163/// \code
10164/// tbnz w8, #10, L1
10165/// \endcode
10166///
10167/// \param MI Conditional Branch
10168/// \return True when the simple conditional branch is generated
10169///
10171 bool IsNegativeBranch = false;
10172 bool IsTestAndBranch = false;
10173 unsigned TargetBBInMI = 0;
10174 switch (MI.getOpcode()) {
10175 default:
10176 llvm_unreachable("Unknown branch instruction?");
10177 case AArch64::Bcc:
10178 case AArch64::CBWPri:
10179 case AArch64::CBXPri:
10180 case AArch64::CBBAssertExt:
10181 case AArch64::CBHAssertExt:
10182 case AArch64::CBWPrr:
10183 case AArch64::CBXPrr:
10184 return false;
10185 case AArch64::CBZW:
10186 case AArch64::CBZX:
10187 TargetBBInMI = 1;
10188 break;
10189 case AArch64::CBNZW:
10190 case AArch64::CBNZX:
10191 TargetBBInMI = 1;
10192 IsNegativeBranch = true;
10193 break;
10194 case AArch64::TBZW:
10195 case AArch64::TBZX:
10196 TargetBBInMI = 2;
10197 IsTestAndBranch = true;
10198 break;
10199 case AArch64::TBNZW:
10200 case AArch64::TBNZX:
10201 TargetBBInMI = 2;
10202 IsNegativeBranch = true;
10203 IsTestAndBranch = true;
10204 break;
10205 }
10206 // So we increment a zero register and test for bits other
10207 // than bit 0? Conservatively bail out in case the verifier
10208 // missed this case.
10209 if (IsTestAndBranch && MI.getOperand(1).getImm())
10210 return false;
10211
10212 // Find Definition.
10213 assert(MI.getParent() && "Incomplete machine instruction\n");
10214 MachineBasicBlock *MBB = MI.getParent();
10215 MachineFunction *MF = MBB->getParent();
10217 Register VReg = MI.getOperand(0).getReg();
10218 if (!VReg.isVirtual())
10219 return false;
10220
10221 MachineInstr *DefMI = MRI->getVRegDef(VReg);
10222 if (!DefMI)
10223 return false;
10224
10225 // Look through COPY instructions to find definition.
10226 while (DefMI->isCopy()) {
10227 Register CopyVReg = DefMI->getOperand(1).getReg();
10228 if (!CopyVReg.isVirtual())
10229 return false;
10230 if (!MRI->hasOneNonDBGUse(CopyVReg))
10231 return false;
10232 DefMI = MRI->getVRegDef(CopyVReg);
10233 if (!DefMI)
10234 return false;
10235 }
10236
10237 switch (DefMI->getOpcode()) {
10238 default:
10239 return false;
10240 // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
10241 case AArch64::ANDWri:
10242 case AArch64::ANDXri: {
10243 if (IsTestAndBranch)
10244 return false;
10245 if (DefMI->getParent() != MBB)
10246 return false;
10247 if (!MRI->hasOneNonDBGUse(VReg))
10248 return false;
10249
10250 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
10251 uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
10252 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
10253 if (!isPowerOf2_64(Mask))
10254 return false;
10255
10256 MachineOperand &MO = DefMI->getOperand(1);
10257 Register NewReg = MO.getReg();
10258 if (!NewReg.isVirtual())
10259 return false;
10260
10261 if (!MRI->getVRegDef(NewReg))
10262 return false;
10263
10264 MachineBasicBlock &RefToMBB = *MBB;
10265 MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
10266 DebugLoc DL = MI.getDebugLoc();
10267 unsigned Imm = Log2_64(Mask);
10268 unsigned Opc = (Imm < 32)
10269 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
10270 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
10271 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
10272 .addReg(NewReg)
10273 .addImm(Imm)
10274 .addMBB(TBB);
10275 // Register lives on to the CBZ now.
10276 MO.setIsKill(false);
10277
10278 // For immediate smaller than 32, we need to use the 32-bit
10279 // variant (W) in all cases. Indeed the 64-bit variant does not
10280 // allow to encode them.
10281 // Therefore, if the input register is 64-bit, we need to take the
10282 // 32-bit sub-part.
10283 if (!Is32Bit && Imm < 32)
10284 NewMI->getOperand(0).setSubReg(AArch64::sub_32);
10285 MI.eraseFromParent();
10286 return true;
10287 }
10288 // Look for CSINC
10289 case AArch64::CSINCWr:
10290 case AArch64::CSINCXr: {
10291 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
10292 DefMI->getOperand(2).getReg() == AArch64::WZR) &&
10293 !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
10294 DefMI->getOperand(2).getReg() == AArch64::XZR))
10295 return false;
10296
10297 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
10298 true) != -1)
10299 return false;
10300
10301 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
10302 // Convert only when the condition code is not modified between
10303 // the CSINC and the branch. The CC may be used by other
10304 // instructions in between.
10306 return false;
10307 MachineBasicBlock &RefToMBB = *MBB;
10308 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
10309 DebugLoc DL = MI.getDebugLoc();
10310 if (IsNegativeBranch)
10312 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
10313 MI.eraseFromParent();
10314 return true;
10315 }
10316 }
10317}
10318
10319std::pair<unsigned, unsigned>
10320AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
10321 const unsigned Mask = AArch64II::MO_FRAGMENT;
10322 return std::make_pair(TF & Mask, TF & ~Mask);
10323}
10324
10326AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
10327 using namespace AArch64II;
10328
10329 static const std::pair<unsigned, const char *> TargetFlags[] = {
10330 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
10331 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
10332 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
10333 {MO_HI12, "aarch64-hi12"}};
10334 return ArrayRef(TargetFlags);
10335}
10336
10338AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
10339 using namespace AArch64II;
10340
10341 static const std::pair<unsigned, const char *> TargetFlags[] = {
10342 {MO_COFFSTUB, "aarch64-coffstub"},
10343 {MO_GOT, "aarch64-got"},
10344 {MO_NC, "aarch64-nc"},
10345 {MO_S, "aarch64-s"},
10346 {MO_TLS, "aarch64-tls"},
10347 {MO_DLLIMPORT, "aarch64-dllimport"},
10348 {MO_PREL, "aarch64-prel"},
10349 {MO_TAGGED, "aarch64-tagged"},
10350 {MO_ARM64EC_CALLMANGLE, "aarch64-arm64ec-callmangle"},
10351 };
10352 return ArrayRef(TargetFlags);
10353}
10354
10356AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
10357 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10358 {{MOSuppressPair, "aarch64-suppress-pair"},
10359 {MOStridedAccess, "aarch64-strided-access"}};
10360 return ArrayRef(TargetFlags);
10361}
10362
10363/// Constants defining how certain sequences should be outlined.
10364/// This encompasses how an outlined function should be called, and what kind of
10365/// frame should be emitted for that outlined function.
10366///
10367/// \p MachineOutlinerDefault implies that the function should be called with
10368/// a save and restore of LR to the stack.
10369///
10370/// That is,
10371///
10372/// I1 Save LR OUTLINED_FUNCTION:
10373/// I2 --> BL OUTLINED_FUNCTION I1
10374/// I3 Restore LR I2
10375/// I3
10376/// RET
10377///
10378/// * Call construction overhead: 3 (save + BL + restore)
10379/// * Frame construction overhead: 1 (ret)
10380/// * Requires stack fixups? Yes
10381///
10382/// \p MachineOutlinerTailCall implies that the function is being created from
10383/// a sequence of instructions ending in a return.
10384///
10385/// That is,
10386///
10387/// I1 OUTLINED_FUNCTION:
10388/// I2 --> B OUTLINED_FUNCTION I1
10389/// RET I2
10390/// RET
10391///
10392/// * Call construction overhead: 1 (B)
10393/// * Frame construction overhead: 0 (Return included in sequence)
10394/// * Requires stack fixups? No
10395///
10396/// \p MachineOutlinerNoLRSave implies that the function should be called using
10397/// a BL instruction, but doesn't require LR to be saved and restored. This
10398/// happens when LR is known to be dead.
10399///
10400/// That is,
10401///
10402/// I1 OUTLINED_FUNCTION:
10403/// I2 --> BL OUTLINED_FUNCTION I1
10404/// I3 I2
10405/// I3
10406/// RET
10407///
10408/// * Call construction overhead: 1 (BL)
10409/// * Frame construction overhead: 1 (RET)
10410/// * Requires stack fixups? No
10411///
10412/// \p MachineOutlinerThunk implies that the function is being created from
10413/// a sequence of instructions ending in a call. The outlined function is
10414/// called with a BL instruction, and the outlined function tail-calls the
10415/// original call destination.
10416///
10417/// That is,
10418///
10419/// I1 OUTLINED_FUNCTION:
10420/// I2 --> BL OUTLINED_FUNCTION I1
10421/// BL f I2
10422/// B f
10423/// * Call construction overhead: 1 (BL)
10424/// * Frame construction overhead: 0
10425/// * Requires stack fixups? No
10426///
10427/// \p MachineOutlinerRegSave implies that the function should be called with a
10428/// save and restore of LR to an available register. This allows us to avoid
10429/// stack fixups. Note that this outlining variant is compatible with the
10430/// NoLRSave case.
10431///
10432/// That is,
10433///
10434/// I1 Save LR OUTLINED_FUNCTION:
10435/// I2 --> BL OUTLINED_FUNCTION I1
10436/// I3 Restore LR I2
10437/// I3
10438/// RET
10439///
10440/// * Call construction overhead: 3 (save + BL + restore)
10441/// * Frame construction overhead: 1 (ret)
10442/// * Requires stack fixups? No
10444 MachineOutlinerDefault, /// Emit a save, restore, call, and return.
10445 MachineOutlinerTailCall, /// Only emit a branch.
10446 MachineOutlinerNoLRSave, /// Emit a call and return.
10447 MachineOutlinerThunk, /// Emit a call and tail-call.
10448 MachineOutlinerRegSave /// Same as default, but save to a register.
10449};
10450
10456
10457/// Return true if the frame-record form of the outlined prologue is enabled for
10458/// the target of \p MF.
10459///
10460/// A non-leaf outlined function must save LR. On MachO, saving LR alone
10461/// (str x30) has no compact unwind encoding, so we get a large DWARF FDE
10462/// instead. Saving FP and LR as a frame record (stp x29, x30 ; mov x29, sp)
10463/// gets the small FRAME encoding, and costs one extra instruction.
10465 return MF.getSubtarget<AArch64Subtarget>()
10466 .getCLOpts()
10467 .outliner_compact_unwind_frame &&
10469}
10470
10471/// Return true if the outlined function in \p MBB should save FP and LR as a
10472/// frame record instead of saving LR alone.
10474 const MachineBasicBlock &MBB) {
10475 const MachineFunction &MF = *MBB.getParent();
10476
10477 // Only worth it if the function has unwind info to shrink.
10480 return false;
10481
10482 // Only safe if the outlined code never touches FP, since we overwrite it.
10484 for (const MachineInstr &MI : MBB.instrs())
10485 LRU.accumulate(MI);
10486 return LRU.available(AArch64::FP);
10487}
10488
10489/// Predict what the above will answer, for use while costing candidates. The
10490/// outlined function does not exist yet, so answer from \p RepeatedSequenceLocs
10491/// instead. This is only an estimate; buildOutlinedFrame() makes the call.
10493 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10494 const TargetRegisterInfo &TRI) {
10495 if (!isCompactUnwindFrameRecordEnabled(*RepeatedSequenceLocs.front().getMF()))
10496 return false;
10497
10498 // The outlined function is nounwind only if every candidate is, so it has
10499 // unwind info if any candidate does.
10500 if (llvm::none_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10501 const MachineFunction &MF = *C.getMF();
10502 return MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF);
10503 }))
10504 return false;
10505
10506 // FP is free in the outlined function only if it is free in every candidate.
10507 return llvm::all_of(RepeatedSequenceLocs, [&TRI](outliner::Candidate &C) {
10508 return C.isAvailableInsideSeq(AArch64::FP, TRI);
10509 });
10510}
10511
10513AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
10514 MachineFunction *MF = C.getMF();
10515 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
10516 const AArch64RegisterInfo *ARI =
10517 static_cast<const AArch64RegisterInfo *>(&TRI);
10518 // Check if there is an available register across the sequence that we can
10519 // use.
10520 for (unsigned Reg : AArch64::GPR64RegClass) {
10521 if (!ARI->isReservedReg(*MF, Reg) &&
10522 Reg != AArch64::LR && // LR is not reserved, but don't use it.
10523 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
10524 Reg != AArch64::X17 && // Ditto for X17.
10525 C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
10526 C.isAvailableInsideSeq(Reg, TRI))
10527 return Reg;
10528 }
10529 return Register();
10530}
10531
10532static bool
10534 const outliner::Candidate &b) {
10535 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10536 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10537
10538 return MFIa->getSignReturnAddressCondition() ==
10540}
10541
10542static bool
10544 const outliner::Candidate &b) {
10545 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10546 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10547
10548 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
10549}
10550
10552 const outliner::Candidate &b) {
10553 const AArch64Subtarget &SubtargetA =
10555 const AArch64Subtarget &SubtargetB =
10556 b.getMF()->getSubtarget<AArch64Subtarget>();
10557 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
10558}
10559
10560namespace {
10561struct SPAddSubImmEncoding {
10562 unsigned Opcode;
10563 int64_t Imm;
10564 int64_t Shift;
10565};
10566} // namespace
10567
10568/// Returns true if \p MI is an ADD/SUBXri with an immediate offset that reads
10569/// SP but does not write SP (e.g. "add x0, sp, #48").
10570static bool isSPAddSubImm(const MachineInstr &MI) {
10571 if (MI.getOpcode() != AArch64::ADDXri && MI.getOpcode() != AArch64::SUBXri)
10572 return false;
10573
10574 assert(MI.getNumExplicitOperands() == 4 && "Wrong number of operands");
10575 assert(MI.getOperand(0).isReg() && MI.getOperand(1).isReg() &&
10576 MI.getOperand(3).isImm() && "Unexpected add/sub immediate operands");
10577
10578 if (MI.getOperand(0).getReg() == AArch64::SP)
10579 return false;
10580 if (MI.getOperand(1).getReg() != AArch64::SP)
10581 return false;
10582
10583 return MI.getOperand(2).isImm();
10584}
10585
10586/// Adjust the signed byte offset of \p MI, which must satisfy isSPAddSubImm,
10587/// by \p Delta and re-encode the result. Returns std::nullopt if the adjusted
10588/// offset is not encodable.
10589static std::optional<SPAddSubImmEncoding>
10590adjustSPAddSubImm(const MachineInstr &MI, int64_t Delta) {
10591 assert(isSPAddSubImm(MI) && "Expected an SP-based add/sub immediate");
10592 bool IsSub = MI.getOpcode() == AArch64::SUBXri;
10593
10594 // ADD/SUBXri encode a 12-bit unsigned immediate with an optional left shift
10595 // which can only be 12.
10596 int64_t ShiftImm = MI.getOperand(3).getImm();
10598 "Unexpected add/sub immediate shift type");
10599 unsigned Shift = AArch64_AM::getShiftValue(ShiftImm);
10600 assert((Shift == 0 || Shift == 12) && "Unexpected add/sub immediate shift");
10601
10602 int64_t Offset = MI.getOperand(2).getImm() << Shift;
10603 if (IsSub)
10604 Offset = -Offset;
10605
10606 // Apply the adjustment and try to re-encode.
10607 int64_t NewOffset = Offset + Delta;
10608 int64_t AbsOffset = std::abs(NewOffset);
10609
10610 SPAddSubImmEncoding Enc;
10611 Enc.Opcode = NewOffset < 0 ? AArch64::SUBXri : AArch64::ADDXri;
10612
10613 // Try to encode as a 12-bit immediate with shift=0 first.
10614 if (AbsOffset <= 0xfff) {
10615 Enc.Imm = AbsOffset;
10617 } else if ((AbsOffset & 0xfff) == 0 && (AbsOffset >> 12) <= 0xfff) {
10618 Enc.Imm = AbsOffset >> 12;
10620 } else {
10621 return std::nullopt;
10622 }
10623
10624 return Enc;
10625}
10626
10627std::optional<std::unique_ptr<outliner::OutlinedFunction>>
10628AArch64InstrInfo::getOutliningCandidateInfo(
10629 const MachineModuleInfo &MMI,
10630 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10631 unsigned MinRepeats) const {
10632 unsigned SequenceSize = 0;
10633 for (auto &MI : RepeatedSequenceLocs[0])
10634 SequenceSize += getInstSizeInBytes(MI);
10635
10636 unsigned NumBytesToCreateFrame = 0;
10637
10638 // Avoid splitting ADRP ADD/LDR pair into outlined functions.
10639 // These instructions are fused together by the scheduler.
10640 // Any candidate where ADRP is the last instruction should be rejected
10641 // as that will lead to splitting ADRP pair.
10642 MachineInstr &LastMI = RepeatedSequenceLocs[0].back();
10643 MachineInstr &FirstMI = RepeatedSequenceLocs[0].front();
10644 if (LastMI.getOpcode() == AArch64::ADRP &&
10645 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_PAGE) != 0 &&
10646 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10647 return std::nullopt;
10648 }
10649
10650 // Similarly any candidate where the first instruction is ADD/LDR with a
10651 // page offset should be rejected to avoid ADRP splitting.
10652 if ((FirstMI.getOpcode() == AArch64::ADDXri ||
10653 FirstMI.getOpcode() == AArch64::LDRXui) &&
10654 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_PAGEOFF) != 0 &&
10655 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10656 return std::nullopt;
10657 }
10658
10659 // We only allow outlining for functions having exactly matching return
10660 // address signing attributes, i.e., all share the same value for the
10661 // attribute "sign-return-address" and all share the same type of key they
10662 // are signed with.
10663 // Additionally we require all functions to simultaneously either support
10664 // v8.3a features or not. Otherwise an outlined function could get signed
10665 // using dedicated v8.3 instructions and a call from a function that doesn't
10666 // support v8.3 instructions would therefore be invalid.
10667 if (std::adjacent_find(
10668 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
10669 [](const outliner::Candidate &a, const outliner::Candidate &b) {
10670 // Return true if a and b are non-equal w.r.t. return address
10671 // signing or support of v8.3a features
10672 if (outliningCandidatesSigningScopeConsensus(a, b) &&
10673 outliningCandidatesSigningKeyConsensus(a, b) &&
10674 outliningCandidatesV8_3OpsConsensus(a, b)) {
10675 return false;
10676 }
10677 return true;
10678 }) != RepeatedSequenceLocs.end()) {
10679 return std::nullopt;
10680 }
10681
10682 // Since at this point all candidates agree on their return address signing
10683 // picking just one is fine. If the candidate functions potentially sign their
10684 // return addresses, the outlined function should do the same. Note that in
10685 // the case of "sign-return-address"="non-leaf" this is an assumption: It is
10686 // not certainly true that the outlined function will have to sign its return
10687 // address but this decision is made later, when the decision to outline
10688 // has already been made.
10689 // The same holds for the number of additional instructions we need: On
10690 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
10691 // necessary. However, at this point we don't know if the outlined function
10692 // will have a RET instruction so we assume the worst.
10693 const TargetRegisterInfo &TRI = getRegisterInfo();
10694 // Performing a tail call may require extra checks when PAuth is enabled.
10695 // If PAuth is disabled, set it to zero for uniformity.
10696 unsigned NumBytesToCheckLRInTCEpilogue = 0;
10697 const auto RASignCondition = RepeatedSequenceLocs[0]
10698 .getMF()
10699 ->getInfo<AArch64FunctionInfo>()
10700 ->getSignReturnAddressCondition();
10701 if (RASignCondition != SignReturnAddress::None) {
10702 // Candidates that have Return Address Authentication Hardening enabled are
10703 // discarded.
10704 //
10705 // In its current form, the machine outliner does not preserve X16/X17
10706 // across outlined function calls, even though it should as they are
10707 // caller-saved registers. And since the hardening based on load from the
10708 // return address may clobber one of these registers, if they are alive
10709 // across a call their value would be lost due to the hardening mechanism.
10710 llvm::erase_if(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10711 return C.getMF()
10712 ->getInfo<AArch64FunctionInfo>()
10713 ->shouldHardenSignReturnAddress();
10714 });
10715 // If the sequence doesn't have enough candidates left, then we're done.
10716 if (RepeatedSequenceLocs.size() < MinRepeats)
10717 return std::nullopt;
10718
10719 // One PAC and one AUT instructions
10720 NumBytesToCreateFrame += 8;
10721
10722 // PAuth is enabled - set extra tail call cost, if any.
10723 auto LRCheckMethod = Subtarget.getAuthenticatedLRCheckMethod(
10724 *RepeatedSequenceLocs[0].getMF());
10725 NumBytesToCheckLRInTCEpilogue =
10727 // Checking the authenticated LR value may significantly impact
10728 // SequenceSize, so account for it for more precise results.
10729 if (isTailCallReturnInst(RepeatedSequenceLocs[0].back()))
10730 SequenceSize += NumBytesToCheckLRInTCEpilogue;
10731
10732 // We have to check if sp modifying instructions would get outlined.
10733 // If so we only allow outlining if sp is unchanged overall, so matching
10734 // sub and add instructions are okay to outline, all other sp modifications
10735 // are not
10736 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
10737 int SPValue = 0;
10738 for (auto &MI : C) {
10739 if (MI.modifiesRegister(AArch64::SP, &TRI)) {
10740 switch (MI.getOpcode()) {
10741 case AArch64::ADDXri:
10742 case AArch64::ADDWri:
10743 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10744 assert(MI.getOperand(2).isImm() &&
10745 "Expected operand to be immediate");
10746 assert(MI.getOperand(1).isReg() &&
10747 "Expected operand to be a register");
10748 // Check if the add just increments sp. If so, we search for
10749 // matching sub instructions that decrement sp. If not, the
10750 // modification is illegal
10751 if (MI.getOperand(1).getReg() == AArch64::SP)
10752 SPValue += MI.getOperand(2).getImm();
10753 else
10754 return true;
10755 break;
10756 case AArch64::SUBXri:
10757 case AArch64::SUBWri:
10758 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10759 assert(MI.getOperand(2).isImm() &&
10760 "Expected operand to be immediate");
10761 assert(MI.getOperand(1).isReg() &&
10762 "Expected operand to be a register");
10763 // Check if the sub just decrements sp. If so, we search for
10764 // matching add instructions that increment sp. If not, the
10765 // modification is illegal
10766 if (MI.getOperand(1).getReg() == AArch64::SP)
10767 SPValue -= MI.getOperand(2).getImm();
10768 else
10769 return true;
10770 break;
10771 default:
10772 return true;
10773 }
10774 }
10775 }
10776 if (SPValue)
10777 return true;
10778 return false;
10779 };
10780 // Remove candidates with illegal stack modifying instructions
10781 llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
10782
10783 // If the sequence doesn't have enough candidates left, then we're done.
10784 if (RepeatedSequenceLocs.size() < MinRepeats)
10785 return std::nullopt;
10786 }
10787
10788 // Properties about candidate MBBs that hold for all of them.
10789 unsigned FlagsSetInAll = 0xF;
10790
10791 // Compute liveness information for each candidate, and set FlagsSetInAll.
10792 for (outliner::Candidate &C : RepeatedSequenceLocs)
10793 FlagsSetInAll &= C.Flags;
10794
10795 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back().getOpcode();
10796
10797 // Helper lambda which sets call information for every candidate.
10798 auto SetCandidateCallInfo =
10799 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
10800 for (outliner::Candidate &C : RepeatedSequenceLocs)
10801 C.setCallInfo(CallID, NumBytesForCall);
10802 };
10803
10804 unsigned FrameID = MachineOutlinerDefault;
10805 NumBytesToCreateFrame += 4;
10806
10807 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10808 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
10809 });
10810
10811 // We check to see if CFI Instructions are present, and if they are
10812 // we find the number of CFI Instructions in the candidates.
10813 unsigned CFICount = 0;
10814 for (auto &I : RepeatedSequenceLocs[0]) {
10815 if (I.isCFIInstruction())
10816 CFICount++;
10817 }
10818
10819 // We compare the number of found CFI Instructions to the number of CFI
10820 // instructions in the parent function for each candidate. We must check this
10821 // since if we outline one of the CFI instructions in a function, we have to
10822 // outline them all for correctness. If we do not, the address offsets will be
10823 // incorrect between the two sections of the program.
10824 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10825 std::vector<MCCFIInstruction> CFIInstructions =
10826 C.getMF()->getFrameInstructions();
10827
10828 if (CFICount > 0 && CFICount != CFIInstructions.size())
10829 return std::nullopt;
10830 }
10831
10832 // Returns true if an instructions is safe to fix up, false otherwise.
10833 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
10834 if (MI.isCall())
10835 return true;
10836
10837 if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
10838 !MI.readsRegister(AArch64::SP, &TRI))
10839 return true;
10840
10841 // Any modification of SP will break our code to save/restore LR.
10842 // FIXME: We could handle some instructions which add a constant
10843 // offset to SP, with a bit more work.
10844 if (MI.modifiesRegister(AArch64::SP, &TRI))
10845 return false;
10846
10847 // At this point, we have a stack instruction that we might need to
10848 // fix up. We'll handle it if it's a load or store.
10849 if (MI.mayLoadOrStore()) {
10850 const MachineOperand *Base; // Filled with the base operand of MI.
10851 int64_t Offset; // Filled with the offset of MI.
10852 bool OffsetIsScalable;
10853
10854 // Does it allow us to offset the base operand and is the base the
10855 // register SP?
10856 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable) ||
10857 !Base->isReg() || Base->getReg() != AArch64::SP)
10858 return false;
10859
10860 // Fixe-up code below assumes bytes.
10861 if (OffsetIsScalable)
10862 return false;
10863
10864 // Find the minimum/maximum offset for this instruction and check
10865 // if fixing it up would be in range.
10866 int64_t MinOffset,
10867 MaxOffset; // Unscaled offsets for the instruction.
10868 // The scale to multiply the offsets by.
10869 TypeSize Scale(0U, false), DummyWidth(0U, false);
10870 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
10871
10872 Offset += 16; // Update the offset to what it would be if we outlined.
10873 if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
10874 Offset > MaxOffset * (int64_t)Scale.getFixedValue())
10875 return false;
10876
10877 // It's in range, so we can outline it.
10878 return true;
10879 }
10880
10881 if (isSPAddSubImm(MI))
10882 return adjustSPAddSubImm(MI, 16).has_value();
10883
10884 // FIXME: Add handling for other SP-based address calculations that can be
10885 // adjusted after outlining.
10886 return false;
10887 };
10888
10889 // True if it's possible to fix up each stack instruction in this sequence.
10890 // Important for frames/call variants that modify the stack.
10891 bool AllStackInstrsSafe =
10892 llvm::all_of(RepeatedSequenceLocs[0], IsSafeToFixup);
10893
10894 // If the last instruction in any candidate is a terminator, then we should
10895 // tail call all of the candidates.
10896 if (RepeatedSequenceLocs[0].back().isTerminator()) {
10897 FrameID = MachineOutlinerTailCall;
10898 NumBytesToCreateFrame = 0;
10899 unsigned NumBytesForCall = 4 + NumBytesToCheckLRInTCEpilogue;
10900 SetCandidateCallInfo(MachineOutlinerTailCall, NumBytesForCall);
10901 }
10902
10903 else if (LastInstrOpcode == AArch64::BL ||
10904 ((LastInstrOpcode == AArch64::BLR ||
10905 LastInstrOpcode == AArch64::BLRNoIP) &&
10906 !HasBTI)) {
10907 // FIXME: Do we need to check if the code after this uses the value of LR?
10908 FrameID = MachineOutlinerThunk;
10909 NumBytesToCreateFrame = NumBytesToCheckLRInTCEpilogue;
10910 SetCandidateCallInfo(MachineOutlinerThunk, 4);
10911 }
10912
10913 else {
10914 // We need to decide how to emit calls + frames. We can always emit the same
10915 // frame if we don't need to save to the stack. If we have to save to the
10916 // stack, then we need a different frame.
10917 unsigned NumBytesNoStackCalls = 0;
10918 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
10919
10920 // Check if we have to save LR.
10921 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10922 bool LRAvailable =
10924 ? C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI)
10925 : true;
10926 // If we have a noreturn caller, then we're going to be conservative and
10927 // say that we have to save LR. If we don't have a ret at the end of the
10928 // block, then we can't reason about liveness accurately.
10929 //
10930 // FIXME: We can probably do better than always disabling this in
10931 // noreturn functions by fixing up the liveness info.
10932 bool IsNoReturn =
10933 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
10934
10935 // Is LR available? If so, we don't need a save.
10936 if (LRAvailable && !IsNoReturn) {
10937 NumBytesNoStackCalls += 4;
10938 C.setCallInfo(MachineOutlinerNoLRSave, 4);
10939 CandidatesWithoutStackFixups.push_back(C);
10940 }
10941
10942 // Is an unused register available? If so, we won't modify the stack, so
10943 // we can outline with the same frame type as those that don't save LR.
10944 else if (findRegisterToSaveLRTo(C)) {
10945 NumBytesNoStackCalls += 12;
10946 C.setCallInfo(MachineOutlinerRegSave, 12);
10947 CandidatesWithoutStackFixups.push_back(C);
10948 }
10949
10950 // Is SP used in the sequence at all? If not, we don't have to modify
10951 // the stack, so we are guaranteed to get the same frame.
10952 else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
10953 NumBytesNoStackCalls += 12;
10954 C.setCallInfo(MachineOutlinerDefault, 12);
10955 CandidatesWithoutStackFixups.push_back(C);
10956 }
10957
10958 // If we outline this, we need to modify the stack. Pretend we don't
10959 // outline this by saving all of its bytes.
10960 else {
10961 NumBytesNoStackCalls += SequenceSize;
10962 }
10963 }
10964
10965 // If there are no places where we have to save LR, then note that we
10966 // don't have to update the stack. Otherwise, give every candidate the
10967 // default call type, as long as it's safe to do so.
10968 if (!AllStackInstrsSafe ||
10969 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
10970 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
10971 FrameID = MachineOutlinerNoLRSave;
10972 if (RepeatedSequenceLocs.size() < MinRepeats)
10973 return std::nullopt;
10974 } else {
10975 SetCandidateCallInfo(MachineOutlinerDefault, 12);
10976
10977 // Bugzilla ID: 46767
10978 // TODO: Check if fixing up the stack more than once is safe so we can
10979 // outline these.
10980 //
10981 // An outline resulting in a caller that requires stack fixups at the
10982 // callsite to a callee that also requires stack fixups can happen when
10983 // there are no available registers at the candidate callsite for a
10984 // candidate that itself also has calls.
10985 //
10986 // In other words if function_containing_sequence in the following pseudo
10987 // assembly requires that we save LR at the point of the call, but there
10988 // are no available registers: in this case we save using SP and as a
10989 // result the SP offsets requires stack fixups by multiples of 16.
10990 //
10991 // function_containing_sequence:
10992 // ...
10993 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10994 // call OUTLINED_FUNCTION_N
10995 // restore LR from SP
10996 // ...
10997 //
10998 // OUTLINED_FUNCTION_N:
10999 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
11000 // ...
11001 // bl foo
11002 // restore LR from SP
11003 // ret
11004 //
11005 // Because the code to handle more than one stack fixup does not
11006 // currently have the proper checks for legality, these cases will assert
11007 // in the AArch64 MachineOutliner. This is because the code to do this
11008 // needs more hardening, testing, better checks that generated code is
11009 // legal, etc and because it is only verified to handle a single pass of
11010 // stack fixup.
11011 //
11012 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
11013 // these cases until they are known to be handled. Bugzilla 46767 is
11014 // referenced in comments at the assert site.
11015 //
11016 // To avoid asserting (or generating non-legal code on noassert builds)
11017 // we remove all candidates which would need more than one stack fixup by
11018 // pruning the cases where the candidate has calls while also having no
11019 // available LR and having no available general purpose registers to copy
11020 // LR to (ie one extra stack save/restore).
11021 //
11022 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
11023 erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
11024 auto IsCall = [](const MachineInstr &MI) { return MI.isCall(); };
11025 return (llvm::any_of(C, IsCall)) &&
11026 (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
11027 !findRegisterToSaveLRTo(C));
11028 });
11029 }
11030 }
11031
11032 // If we dropped all of the candidates, bail out here.
11033 if (RepeatedSequenceLocs.size() < MinRepeats)
11034 return std::nullopt;
11035 }
11036
11037 // Does every candidate's MBB contain a call? If so, then we might have a call
11038 // in the range.
11039 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
11040 // Check if the range contains a call. These require a save + restore of the
11041 // link register.
11042 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
11043 bool ModStackToSaveLR = false;
11044 if (any_of(drop_end(FirstCand),
11045 [](const MachineInstr &MI) { return MI.isCall(); }))
11046 ModStackToSaveLR = true;
11047
11048 // Handle the last instruction separately. If this is a tail call, then the
11049 // last instruction is a call. We don't want to save + restore in this case.
11050 // However, it could be possible that the last instruction is a call without
11051 // it being valid to tail call this sequence. We should consider this as
11052 // well.
11053 else if (FrameID != MachineOutlinerThunk &&
11054 FrameID != MachineOutlinerTailCall && FirstCand.back().isCall())
11055 ModStackToSaveLR = true;
11056
11057 if (ModStackToSaveLR) {
11058 // We can't fix up the stack. Bail out.
11059 if (!AllStackInstrsSafe)
11060 return std::nullopt;
11061
11062 // Save + restore LR.
11063 NumBytesToCreateFrame += 8;
11064
11065 // Add the extra mov if we will save a frame record instead of just LR.
11067 RepeatedSequenceLocs, TRI))
11068 NumBytesToCreateFrame += 4;
11069 }
11070 }
11071
11072 // If we have CFI instructions, we can only outline if the outlined section
11073 // can be a tail call
11074 if (FrameID != MachineOutlinerTailCall && CFICount > 0)
11075 return std::nullopt;
11076
11077 return std::make_unique<outliner::OutlinedFunction>(
11078 RepeatedSequenceLocs, SequenceSize, NumBytesToCreateFrame, FrameID);
11079}
11080
11081void AArch64InstrInfo::mergeOutliningCandidateAttributes(
11082 Function &F, std::vector<outliner::Candidate> &Candidates) const {
11083 // If a bunch of candidates reach this point they must agree on their return
11084 // address signing. It is therefore enough to just consider the signing
11085 // behaviour of one of them
11086 const auto &CFn = Candidates.front().getMF()->getFunction();
11087
11088 if (CFn.hasFnAttribute("ptrauth-returns"))
11089 F.addFnAttr(CFn.getFnAttribute("ptrauth-returns"));
11090 if (CFn.hasFnAttribute("ptrauth-auth-traps"))
11091 F.addFnAttr(CFn.getFnAttribute("ptrauth-auth-traps"));
11092 // Since all candidates belong to the same module, just copy the
11093 // function-level attributes of an arbitrary function.
11094 if (CFn.hasFnAttribute("sign-return-address"))
11095 F.addFnAttr(CFn.getFnAttribute("sign-return-address"));
11096 if (CFn.hasFnAttribute("sign-return-address-key"))
11097 F.addFnAttr(CFn.getFnAttribute("sign-return-address-key"));
11098 // The "sign-return-address-harden" attribute is not included because no
11099 // candidate is supposed to have hardening enabled.
11100 assert(llvm::none_of(Candidates, [](const outliner::Candidate &C) {
11101 return C.getMF()
11102 ->getInfo<AArch64FunctionInfo>()
11103 ->shouldHardenSignReturnAddress();
11104 }));
11105
11106 AArch64GenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
11107}
11108
11109bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
11110 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
11112 OutlineFromLinkOnceODRs))
11113 return false;
11114
11115 // Outlining from functions with redzones is unsafe since the outliner may
11116 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
11117 // outline from it.
11118 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
11119 if (!AFI || AFI->hasRedZone().value_or(true))
11120 return false;
11121
11122 // FIXME: Determine whether it is safe to outline from functions which contain
11123 // streaming-mode changes. We may need to ensure any smstart/smstop pairs are
11124 // outlined together and ensure it is safe to outline with async unwind info,
11125 // required for saving & restoring VG around calls.
11126 if (AFI->hasStreamingModeChanges())
11127 return false;
11128
11129 // FIXME: Teach the outliner to generate/handle Windows unwind info.
11130 if (MF.usesWindowsUnwindInfo())
11131 return false;
11132
11133 // It's safe to outline from MF.
11134 return true;
11135}
11136
11138AArch64InstrInfo::getOutlinableRanges(MachineBasicBlock &MBB,
11139 unsigned &Flags) const {
11141 "Must track liveness!");
11143 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
11144 Ranges;
11145 // According to the AArch64 Procedure Call Standard, the following are
11146 // undefined on entry/exit from a function call:
11147 //
11148 // * Registers x16, x17, (and thus w16, w17)
11149 // * Condition codes (and thus the NZCV register)
11150 //
11151 // If any of these registers are used inside or live across an outlined
11152 // function, then they may be modified later, either by the compiler or
11153 // some other tool (like the linker).
11154 //
11155 // To avoid outlining in these situations, partition each block into ranges
11156 // where these registers are dead. We will only outline from those ranges.
11157 LiveRegUnits LRU(getRegisterInfo());
11158 auto AreAllUnsafeRegsDead = [&LRU]() {
11159 return LRU.available(AArch64::W16) && LRU.available(AArch64::W17) &&
11160 LRU.available(AArch64::NZCV);
11161 };
11162
11163 // We need to know if LR is live across an outlining boundary later on in
11164 // order to decide how we'll create the outlined call, frame, etc.
11165 //
11166 // It's pretty expensive to check this for *every candidate* within a block.
11167 // That's some potentially n^2 behaviour, since in the worst case, we'd need
11168 // to compute liveness from the end of the block for O(n) candidates within
11169 // the block.
11170 //
11171 // So, to improve the average case, let's keep track of liveness from the end
11172 // of the block to the beginning of *every outlinable range*. If we know that
11173 // LR is available in every range we could outline from, then we know that
11174 // we don't need to check liveness for any candidate within that range.
11175 bool LRAvailableEverywhere = true;
11176 // Compute liveness bottom-up.
11177 LRU.addLiveOuts(MBB);
11178 // Update flags that require info about the entire MBB.
11179 auto UpdateWholeMBBFlags = [&Flags](const MachineInstr &MI) {
11180 if (MI.isCall() && !MI.isTerminator())
11182 };
11183 // Range: [RangeBegin, RangeEnd)
11184 MachineBasicBlock::instr_iterator RangeBegin, RangeEnd;
11185 unsigned RangeLen;
11186 auto CreateNewRangeStartingAt =
11187 [&RangeBegin, &RangeEnd,
11188 &RangeLen](MachineBasicBlock::instr_iterator NewBegin) {
11189 RangeBegin = NewBegin;
11190 RangeEnd = std::next(RangeBegin);
11191 RangeLen = 0;
11192 };
11193 auto SaveRangeIfNonEmpty = [&RangeLen, &Ranges, &RangeBegin, &RangeEnd]() {
11194 // At least one unsafe register is not dead. We do not want to outline at
11195 // this point. If it is long enough to outline from and does not cross a
11196 // bundle boundary, save the range [RangeBegin, RangeEnd).
11197 if (RangeLen <= 1)
11198 return;
11199 if (!RangeBegin.isEnd() && RangeBegin->isBundledWithPred())
11200 return;
11201 if (!RangeEnd.isEnd() && RangeEnd->isBundledWithPred())
11202 return;
11203 Ranges.emplace_back(RangeBegin, RangeEnd);
11204 };
11205 // Find the first point where all unsafe registers are dead.
11206 // FIND: <safe instr> <-- end of first potential range
11207 // SKIP: <unsafe def>
11208 // SKIP: ... everything between ...
11209 // SKIP: <unsafe use>
11210 auto FirstPossibleEndPt = MBB.instr_rbegin();
11211 for (; FirstPossibleEndPt != MBB.instr_rend(); ++FirstPossibleEndPt) {
11212 if (!FirstPossibleEndPt->isDebugInstr())
11213 LRU.stepBackward(*FirstPossibleEndPt);
11214 // Update flags that impact how we outline across the entire block,
11215 // regardless of safety.
11216 UpdateWholeMBBFlags(*FirstPossibleEndPt);
11217 if (AreAllUnsafeRegsDead())
11218 break;
11219 }
11220 // If we exhausted the entire block, we have no safe ranges to outline.
11221 if (FirstPossibleEndPt == MBB.instr_rend())
11222 return Ranges;
11223 // Current range.
11224 CreateNewRangeStartingAt(FirstPossibleEndPt->getIterator());
11225 // StartPt points to the first place where all unsafe registers
11226 // are dead (if there is any such point). Begin partitioning the MBB into
11227 // ranges.
11228 // Pseudo probes are ordinary instructions to the mapper, so only skip debug
11229 // instructions here.
11230 for (auto &MI : instructionsWithoutDebug(FirstPossibleEndPt, MBB.instr_rend(),
11231 /*SkipPseudoOp=*/false)) {
11232 LRU.stepBackward(MI);
11233 UpdateWholeMBBFlags(MI);
11234 if (!AreAllUnsafeRegsDead()) {
11235 SaveRangeIfNonEmpty();
11236 CreateNewRangeStartingAt(MI.getIterator());
11237 continue;
11238 }
11239 LRAvailableEverywhere &= LRU.available(AArch64::LR);
11240 // Pseudo probes count because the mapper treats them as ordinary
11241 // instructions.
11242 RangeBegin = MI.getIterator();
11243 ++RangeLen;
11244 }
11245 // Above loop misses the last (or only) range. If we are still safe, then
11246 // let's save the range.
11247 if (AreAllUnsafeRegsDead())
11248 SaveRangeIfNonEmpty();
11249 if (Ranges.empty())
11250 return Ranges;
11251 // We found the ranges bottom-up. Mapping expects the top-down. Reverse
11252 // the order.
11253 std::reverse(Ranges.begin(), Ranges.end());
11254 // If there is at least one outlinable range where LR is unavailable
11255 // somewhere, remember that.
11256 if (!LRAvailableEverywhere)
11258 return Ranges;
11259}
11260
11262AArch64InstrInfo::getOutliningTypeImpl(const MachineModuleInfo &MMI,
11264 unsigned Flags) const {
11265 MachineInstr &MI = *MIT;
11266
11267 // Don't outline anything used for return address signing. The outlined
11268 // function will get signed later if needed
11269 switch (MI.getOpcode()) {
11270 case AArch64::PACM:
11271 case AArch64::PACIASP:
11272 case AArch64::PACIBSP:
11273 case AArch64::PACIASPPC:
11274 case AArch64::PACIBSPPC:
11275 case AArch64::AUTIASP:
11276 case AArch64::AUTIBSP:
11277 case AArch64::AUTIASPPCi:
11278 case AArch64::AUTIASPPCr:
11279 case AArch64::AUTIBSPPCi:
11280 case AArch64::AUTIBSPPCr:
11281 case AArch64::RETAA:
11282 case AArch64::RETAB:
11283 case AArch64::RETAASPPCi:
11284 case AArch64::RETAASPPCr:
11285 case AArch64::RETABSPPCi:
11286 case AArch64::RETABSPPCr:
11287 case AArch64::EMITBKEY:
11288 case AArch64::PAUTH_PROLOGUE:
11289 case AArch64::PAUTH_EPILOGUE:
11290 case AArch64::PAUTH_EPILOGUE_ENTRY_SP:
11292 }
11293
11294 // We can only outline these if we will tail call the outlined function, or
11295 // fix up the CFI offsets. Currently, CFI instructions are outlined only if
11296 // in a tail call.
11297 //
11298 // FIXME: If the proper fixups for the offset are implemented, this should be
11299 // possible.
11300 if (MI.isCFIInstruction())
11302
11303 // Is this a terminator for a basic block?
11304 if (MI.isTerminator())
11305 // TargetInstrInfo::getOutliningType has already filtered out anything
11306 // that would break this, so we can allow it here.
11308
11309 // Make sure none of the operands are un-outlinable.
11310 for (const MachineOperand &MOP : MI.operands()) {
11311 // A check preventing CFI indices was here before, but only CFI
11312 // instructions should have those.
11313 assert(!MOP.isCFIIndex());
11314
11315 // If it uses LR or W30 explicitly, then don't touch it.
11316 if (MOP.isReg() && !MOP.isImplicit() &&
11317 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
11319 }
11320
11321 // Special cases for instructions that can always be outlined, but will fail
11322 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
11323 // be outlined because they don't require a *specific* value to be in LR.
11324 if (MI.getOpcode() == AArch64::ADRP)
11326
11327 // If MI is a call we might be able to outline it. We don't want to outline
11328 // any calls that rely on the position of items on the stack. When we outline
11329 // something containing a call, we have to emit a save and restore of LR in
11330 // the outlined function. Currently, this always happens by saving LR to the
11331 // stack. Thus, if we outline, say, half the parameters for a function call
11332 // plus the call, then we'll break the callee's expectations for the layout
11333 // of the stack.
11334 //
11335 // FIXME: Allow calls to functions which construct a stack frame, as long
11336 // as they don't access arguments on the stack.
11337 // FIXME: Figure out some way to analyze functions defined in other modules.
11338 // We should be able to compute the memory usage based on the IR calling
11339 // convention, even if we can't see the definition.
11340 if (MI.isCall()) {
11341 // Get the function associated with the call. Look at each operand and find
11342 // the one that represents the callee and get its name.
11343 const Function *Callee = nullptr;
11344 for (const MachineOperand &MOP : MI.operands()) {
11345 if (MOP.isGlobal()) {
11346 Callee = dyn_cast<Function>(MOP.getGlobal());
11347 break;
11348 }
11349 }
11350
11351 // Never outline calls to mcount. There isn't any rule that would require
11352 // this, but the Linux kernel's "ftrace" feature depends on it.
11353 if (Callee && Callee->getName() == "\01_mcount")
11355
11356 // If we don't know anything about the callee, assume it depends on the
11357 // stack layout of the caller. In that case, it's only legal to outline
11358 // as a tail-call. Explicitly list the call instructions we know about so we
11359 // don't get unexpected results with call pseudo-instructions.
11360 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
11361 if (MI.getOpcode() == AArch64::BLR ||
11362 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
11363 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
11364
11365 if (!Callee)
11366 return UnknownCallOutlineType;
11367
11368 // We have a function we have information about. Check it if it's something
11369 // can safely outline.
11370 MachineFunction *CalleeMF = MMI.getMachineFunction(*Callee);
11371
11372 // We don't know what's going on with the callee at all. Don't touch it.
11373 if (!CalleeMF)
11374 return UnknownCallOutlineType;
11375
11376 // Check if we know anything about the callee saves on the function. If we
11377 // don't, then don't touch it, since that implies that we haven't
11378 // computed anything about its stack frame yet.
11379 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
11380 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
11381 MFI.getNumObjects() > 0)
11382 return UnknownCallOutlineType;
11383
11384 // At this point, we can say that CalleeMF ought to not pass anything on the
11385 // stack. Therefore, we can outline it.
11387 }
11388
11389 // Don't touch the link register or W30.
11390 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
11391 MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
11393
11394 // Don't outline BTI instructions, because that will prevent the outlining
11395 // site from being indirectly callable.
11396 if (hasBTISemantics(MI))
11398
11400}
11401
11402void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
11403 for (MachineInstr &MI : MBB) {
11404 const MachineOperand *Base;
11405 TypeSize Width(0, false);
11406 int64_t Offset;
11407 bool OffsetIsScalable;
11408
11409 // Is this a load or store with an immediate offset with SP as the base?
11410 if (MI.mayLoadOrStore() &&
11411 getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable,
11412 Width) &&
11413 Base->isReg() && Base->getReg() == AArch64::SP) {
11414 TypeSize Scale(0U, false);
11415 int64_t Dummy1, Dummy2;
11416
11417 MachineOperand &StackOffsetOperand =
11419 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
11420 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
11421 assert(Scale != 0 && "Unexpected opcode!");
11422 assert(!OffsetIsScalable && "Expected offset to be a byte offset");
11423
11424 // We've pushed the return address to the stack, so add 16 to the offset.
11425 // This is safe, since we already checked if it would overflow when we
11426 // checked if this instruction was legal to outline.
11427 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
11428 StackOffsetOperand.setImm(NewImm);
11429 continue;
11430 }
11431
11432 if (isSPAddSubImm(MI)) {
11433 auto Enc = adjustSPAddSubImm(MI, 16);
11434 assert(Enc && "Unencodable SP add/sub should not have been outlined");
11435 MI.setDesc(get(Enc->Opcode));
11436 MI.getOperand(2).setImm(Enc->Imm);
11437 MI.getOperand(3).setImm(Enc->Shift);
11438 }
11439 }
11440}
11441
11443 const AArch64InstrInfo *TII,
11444 bool ShouldSignReturnAddr) {
11445 if (!ShouldSignReturnAddr)
11446 return;
11447
11448 BuildMI(MBB, MBB.begin(), DebugLoc(), TII->get(AArch64::PAUTH_PROLOGUE))
11450 TII->createPauthEpilogueInstr(MBB, DebugLoc());
11451}
11452
11453void AArch64InstrInfo::buildOutlinedFrame(
11455 const outliner::OutlinedFunction &OF) const {
11456
11457 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
11458
11459 if (OF.FrameConstructionID == MachineOutlinerTailCall)
11460 FI->setOutliningStyle("Tail Call");
11461 else if (OF.FrameConstructionID == MachineOutlinerThunk) {
11462 // For thunk outlining, rewrite the last instruction from a call to a
11463 // tail-call.
11464 MachineInstr *Call = &*--MBB.instr_end();
11465 unsigned TailOpcode;
11466 if (Call->getOpcode() == AArch64::BL) {
11467 TailOpcode = AArch64::TCRETURNdi;
11468 } else {
11469 assert(Call->getOpcode() == AArch64::BLR ||
11470 Call->getOpcode() == AArch64::BLRNoIP);
11471 TailOpcode = AArch64::TCRETURNriALL;
11472 }
11473 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
11474 .add(Call->getOperand(0))
11475 .addImm(0);
11476 MBB.insert(MBB.end(), TC);
11478
11479 FI->setOutliningStyle("Thunk");
11480 }
11481
11482 bool IsLeafFunction = true;
11483
11484 // Is there a call in the outlined range?
11485 auto IsNonTailCall = [](const MachineInstr &MI) {
11486 return MI.isCall() && !MI.isReturn();
11487 };
11488
11489 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
11490 // Fix up the instructions in the range, since we're going to modify the
11491 // stack.
11492
11493 // Bugzilla ID: 46767
11494 // TODO: Check if fixing up twice is safe so we can outline these.
11495 assert(OF.FrameConstructionID != MachineOutlinerDefault &&
11496 "Can only fix up stack references once");
11497 fixupPostOutline(MBB);
11498
11499 IsLeafFunction = false;
11500
11501 // LR has to be a live in so that we can save it.
11502 if (!MBB.isLiveIn(AArch64::LR))
11503 MBB.addLiveIn(AArch64::LR);
11504
11507
11508 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11509 OF.FrameConstructionID == MachineOutlinerThunk)
11510 Et = std::prev(MBB.end());
11511
11512 // There is a call in the range, so we must save LR. Save it as part of a
11513 // frame record when that gives us a smaller compact unwind encoding.
11515 // FP is saved here, so it must be live-in.
11516 if (!MBB.isLiveIn(AArch64::FP))
11517 MBB.addLiveIn(AArch64::FP);
11518
11519 // stp x29, x30, [sp, #-16]! (the pre-index imm is scaled by 8: -2 * 8)
11520 MachineInstr *STPXpre = BuildMI(MF, DebugLoc(), get(AArch64::STPXpre))
11521 .addReg(AArch64::SP, RegState::Define)
11522 .addReg(AArch64::FP)
11523 .addReg(AArch64::LR)
11524 .addReg(AArch64::SP)
11525 .addImm(-2);
11526 It = MBB.insert(It, STPXpre);
11527
11528 // mov x29, sp (add x29, sp, #0), so x29 points at the frame record.
11529 MachineInstr *SetFP = BuildMI(MF, DebugLoc(), get(AArch64::ADDXri))
11530 .addReg(AArch64::FP, RegState::Define)
11531 .addReg(AArch64::SP)
11532 .addImm(0)
11533 .addImm(0);
11534 MBB.insertAfter(It, SetFP);
11535
11536 // Describe the frame record with FP as the CFA. The encoder needs all
11537 // three to pick FRAME. No need to check for unwind info here: we only
11538 // get here if the function has it.
11539 CFIInstBuilder CFIBuilder(MBB, std::next(SetFP->getIterator()),
11541 CFIBuilder.buildDefCFA(AArch64::FP, 16);
11542 CFIBuilder.buildOffset(AArch64::LR, -8);
11543 CFIBuilder.buildOffset(AArch64::FP, -16);
11544
11545 // ldp x29, x30, [sp], #16
11546 MachineInstr *LDPXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDPXpost))
11547 .addReg(AArch64::SP, RegState::Define)
11548 .addReg(AArch64::FP, RegState::Define)
11549 .addReg(AArch64::LR, RegState::Define)
11550 .addReg(AArch64::SP)
11551 .addImm(2);
11552 Et = MBB.insert(Et, LDPXpost);
11553 } else {
11554 // Insert a save before the outlined region
11555 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11556 .addReg(AArch64::SP, RegState::Define)
11557 .addReg(AArch64::LR)
11558 .addReg(AArch64::SP)
11559 .addImm(-16);
11560 It = MBB.insert(It, STRXpre);
11561
11562 if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
11563 CFIInstBuilder CFIBuilder(MBB, It, MachineInstr::FrameSetup);
11564
11565 // Add a CFI saying the stack was moved 16 B down.
11566 CFIBuilder.buildDefCFAOffset(16);
11567
11568 // Add a CFI saying that the LR that we want to find is now 16 B higher
11569 // than before.
11570 CFIBuilder.buildOffset(AArch64::LR, -16);
11571 }
11572
11573 // Insert a restore before the terminator for the function.
11574 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11575 .addReg(AArch64::SP, RegState::Define)
11576 .addReg(AArch64::LR, RegState::Define)
11577 .addReg(AArch64::SP)
11578 .addImm(16);
11579 Et = MBB.insert(Et, LDRXpost);
11580 }
11581 }
11582
11583 auto RASignCondition = FI->getSignReturnAddressCondition();
11584 bool ShouldSignReturnAddr = AArch64FunctionInfo::shouldSignReturnAddress(
11585 RASignCondition, !IsLeafFunction);
11586
11587 // If this is a tail call outlined function, then there's already a return.
11588 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11589 OF.FrameConstructionID == MachineOutlinerThunk) {
11590 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11591 return;
11592 }
11593
11594 // It's not a tail call, so we have to insert the return ourselves.
11595
11596 // LR has to be a live in so that we can return to it.
11597 if (!MBB.isLiveIn(AArch64::LR))
11598 MBB.addLiveIn(AArch64::LR);
11599
11600 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
11601 .addReg(AArch64::LR);
11602 MBB.insert(MBB.end(), ret);
11603
11604 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11605
11606 FI->setOutliningStyle("Function");
11607
11608 // Did we have to modify the stack by saving the link register?
11609 if (OF.FrameConstructionID != MachineOutlinerDefault)
11610 return;
11611
11612 // We modified the stack.
11613 // Walk over the basic block and fix up all the stack accesses.
11614 fixupPostOutline(MBB);
11615}
11616
11617MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
11620
11621 // Are we tail calling?
11622 if (C.CallConstructionID == MachineOutlinerTailCall) {
11623 // If yes, then we can just branch to the label.
11624 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
11625 .addGlobalAddress(M.getNamedValue(MF.getName()))
11626 .addImm(0));
11627 return It;
11628 }
11629
11630 // Are we saving the link register?
11631 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
11632 C.CallConstructionID == MachineOutlinerThunk) {
11633 // No, so just insert the call.
11634 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11635 .addGlobalAddress(M.getNamedValue(MF.getName())));
11636 return It;
11637 }
11638
11639 // We want to return the spot where we inserted the call.
11641
11642 // Instructions for saving and restoring LR around the call instruction we're
11643 // going to insert.
11644 MachineInstr *Save;
11645 MachineInstr *Restore;
11646 // Can we save to a register?
11647 if (C.CallConstructionID == MachineOutlinerRegSave) {
11648 // FIXME: This logic should be sunk into a target-specific interface so that
11649 // we don't have to recompute the register.
11650 Register Reg = findRegisterToSaveLRTo(C);
11651 assert(Reg && "No callee-saved register available?");
11652
11653 // LR has to be a live in so that we can save it.
11654 if (!MBB.isLiveIn(AArch64::LR))
11655 MBB.addLiveIn(AArch64::LR);
11656
11657 // Save and restore LR from Reg.
11658 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
11659 .addReg(AArch64::XZR)
11660 .addReg(AArch64::LR)
11661 .addImm(0);
11662 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
11663 .addReg(AArch64::XZR)
11664 .addReg(Reg)
11665 .addImm(0);
11666 } else {
11667 // We have the default case. Save and restore from SP.
11668 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11669 .addReg(AArch64::SP, RegState::Define)
11670 .addReg(AArch64::LR)
11671 .addReg(AArch64::SP)
11672 .addImm(-16);
11673 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11674 .addReg(AArch64::SP, RegState::Define)
11675 .addReg(AArch64::LR, RegState::Define)
11676 .addReg(AArch64::SP)
11677 .addImm(16);
11678 }
11679
11680 It = MBB.insert(It, Save);
11681 It++;
11682
11683 // Insert the call.
11684 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11685 .addGlobalAddress(M.getNamedValue(MF.getName())));
11686 CallPt = It;
11687 It++;
11688
11689 It = MBB.insert(It, Restore);
11690 return CallPt;
11691}
11692
11693bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
11694 MachineFunction &MF) const {
11695 return MF.getFunction().hasMinSize();
11696}
11697
11698void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock &MBB,
11700 DebugLoc &DL,
11701 bool AllowSideEffects) const {
11702 const MachineFunction &MF = *MBB.getParent();
11703 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
11704 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
11705
11706 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
11707 BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg).addImm(0).addImm(0);
11708 } else if (STI.isSVEorStreamingSVEAvailable()) {
11709 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
11710 .addImm(0)
11711 .addImm(0);
11712 } else if (STI.isNeonAvailable()) {
11713 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
11714 .addImm(0);
11715 } else {
11716 // No Advanced SIMD (streaming-compatible without SVE, or +nosimd), so use
11717 // `fmov d...` instead of `movi v...`; writing `d` also clears the upper
11718 // 64 bits.
11719 assert(STI.hasFPARMv8() && "Expected FP to be available.");
11720 Register Reg64 = TRI.getSubReg(Reg, AArch64::dsub);
11721 BuildMI(MBB, Iter, DL, get(AArch64::FMOVD0), Reg64);
11722 }
11723}
11724
11725std::optional<DestSourcePair>
11727
11728 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
11729 // and zero immediate operands used as an alias for mov instruction.
11730 if ((MI.getOpcode() == AArch64::ORRWrs &&
11731 MI.getOperand(1).getReg() == AArch64::WZR &&
11732 MI.getOperand(3).getImm() == 0x0) ||
11733 (MI.getOpcode() == AArch64::ORRWrr &&
11734 MI.getOperand(1).getReg() == AArch64::WZR)) {
11735 // Check that the w->w move is not a zero-extending w->x mov.
11736 if ((MI.getOperand(0).getReg().isPhysical() &&
11737 MI.findRegisterDefOperandIdx(
11738 getXRegFromWReg(MI.getOperand(0).getReg()),
11739 /*TRI=*/nullptr) == -1) ||
11740 (MI.getOperand(0).getReg().isVirtual() &&
11741 !MI.getOperand(0).getSubReg()))
11742 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11743 }
11744
11745 if (MI.getOpcode() == AArch64::ORRXrs &&
11746 MI.getOperand(1).getReg() == AArch64::XZR &&
11747 MI.getOperand(3).getImm() == 0x0)
11748 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11749
11750 return std::nullopt;
11751}
11752
11753std::optional<DestSourcePair>
11755 if ((MI.getOpcode() == AArch64::ORRWrs &&
11756 MI.getOperand(1).getReg() == AArch64::WZR &&
11757 MI.getOperand(3).getImm() == 0x0) ||
11758 (MI.getOpcode() == AArch64::ORRWrr &&
11759 MI.getOperand(1).getReg() == AArch64::WZR))
11760 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11761 return std::nullopt;
11762}
11763
11764std::optional<RegImmPair>
11765AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
11766 int Sign = 1;
11767 int64_t Offset = 0;
11768
11769 // TODO: Handle cases where Reg is a super- or sub-register of the
11770 // destination register.
11771 const MachineOperand &Op0 = MI.getOperand(0);
11772 if (!Op0.isReg() || Reg != Op0.getReg())
11773 return std::nullopt;
11774
11775 switch (MI.getOpcode()) {
11776 default:
11777 return std::nullopt;
11778 case AArch64::SUBWri:
11779 case AArch64::SUBXri:
11780 case AArch64::SUBSWri:
11781 case AArch64::SUBSXri:
11782 Sign *= -1;
11783 [[fallthrough]];
11784 case AArch64::ADDSWri:
11785 case AArch64::ADDSXri:
11786 case AArch64::ADDWri:
11787 case AArch64::ADDXri: {
11788 // TODO: Third operand can be global address (usually some string).
11789 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
11790 !MI.getOperand(2).isImm())
11791 return std::nullopt;
11792 int Shift = MI.getOperand(3).getImm();
11793 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
11794 Offset = Sign * (MI.getOperand(2).getImm() << Shift);
11795 }
11796 }
11797 return RegImmPair{MI.getOperand(1).getReg(), Offset};
11798}
11799
11800/// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
11801/// the destination register then, if possible, describe the value in terms of
11802/// the source register.
11803static std::optional<ParamLoadedValue>
11805 const TargetInstrInfo *TII,
11806 const TargetRegisterInfo *TRI) {
11807 auto DestSrc = TII->isCopyLikeInstr(MI);
11808 if (!DestSrc)
11809 return std::nullopt;
11810
11811 Register DestReg = DestSrc->Destination->getReg();
11812 Register SrcReg = DestSrc->Source->getReg();
11813
11814 if (!DestReg.isValid() || !SrcReg.isValid())
11815 return std::nullopt;
11816
11817 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
11818
11819 // If the described register is the destination, just return the source.
11820 if (DestReg == DescribedReg)
11821 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11822
11823 // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
11824 if (MI.getOpcode() == AArch64::ORRWrs &&
11825 TRI->isSuperRegister(DestReg, DescribedReg))
11826 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11827
11828 // We may need to describe the lower part of a ORRXrs move.
11829 if (MI.getOpcode() == AArch64::ORRXrs &&
11830 TRI->isSubRegister(DestReg, DescribedReg)) {
11831 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
11832 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
11833 }
11834
11835 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
11836 "Unhandled ORR[XW]rs copy case");
11837
11838 return std::nullopt;
11839}
11840
11841bool AArch64InstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
11842 // Functions cannot be split to different sections on AArch64 if they have
11843 // a red zone. This is because relaxing a cross-section branch may require
11844 // incrementing the stack pointer to spill a register, which would overwrite
11845 // the red zone.
11846 if (MF.getInfo<AArch64FunctionInfo>()->hasRedZone().value_or(true))
11847 return false;
11848
11850}
11851
11852bool AArch64InstrInfo::isMBBSafeToSplitToCold(
11853 const MachineBasicBlock &MBB) const {
11854 // Asm Goto blocks can contain conditional branches to goto labels, which can
11855 // get moved out of range of the branch instruction.
11856 auto isAsmGoto = [](const MachineInstr &MI) {
11857 return MI.getOpcode() == AArch64::INLINEASM_BR;
11858 };
11859 if (llvm::any_of(MBB, isAsmGoto) || MBB.isInlineAsmBrIndirectTarget())
11860 return false;
11861
11862 // Because jump tables are label-relative instead of table-relative, they all
11863 // must be in the same section or relocation fixup handling will fail.
11864
11865 // Check if MBB is a jump table target
11866 const MachineJumpTableInfo *MJTI = MBB.getParent()->getJumpTableInfo();
11867 auto containsMBB = [&MBB](const MachineJumpTableEntry &JTE) {
11868 return llvm::is_contained(JTE.MBBs, &MBB);
11869 };
11870 if (MJTI != nullptr && llvm::any_of(MJTI->getJumpTables(), containsMBB))
11871 return false;
11872
11873 // Check if MBB contains a jump table lookup
11874 for (const MachineInstr &MI : MBB) {
11875 switch (MI.getOpcode()) {
11876 case TargetOpcode::G_BRJT:
11877 case AArch64::JumpTableDest32:
11878 case AArch64::JumpTableDest16:
11879 case AArch64::JumpTableDest8:
11880 return false;
11881 default:
11882 continue;
11883 }
11884 }
11885
11886 // MBB isn't a special case, so it's safe to be split to the cold section.
11887 return true;
11888}
11889
11890std::optional<ParamLoadedValue>
11891AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
11892 Register Reg) const {
11893 const MachineFunction *MF = MI.getMF();
11894 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
11895 switch (MI.getOpcode()) {
11896 case AArch64::MOVZWi:
11897 case AArch64::MOVZXi: {
11898 // MOVZWi may be used for producing zero-extended 32-bit immediates in
11899 // 64-bit parameters, so we need to consider super-registers.
11900 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
11901 return std::nullopt;
11902
11903 if (!MI.getOperand(1).isImm())
11904 return std::nullopt;
11905 int64_t Immediate = MI.getOperand(1).getImm();
11906 int Shift = MI.getOperand(2).getImm();
11907 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
11908 nullptr);
11909 }
11910 case AArch64::ORRWrs:
11911 case AArch64::ORRXrs:
11912 return describeORRLoadedValue(MI, Reg, this, TRI);
11913 }
11914
11916}
11917
11918bool AArch64InstrInfo::isExtendLikelyToBeFolded(
11919 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
11920 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
11921 ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
11922 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
11923
11924 // Anyexts are nops.
11925 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
11926 return true;
11927
11928 Register DefReg = ExtMI.getOperand(0).getReg();
11929 if (!MRI.hasOneNonDBGUse(DefReg))
11930 return false;
11931
11932 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
11933 // addressing mode.
11934 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
11935 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
11936}
11937
11938uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
11939 return get(Opc).TSFlags & AArch64::ElementSizeMask;
11940}
11941
11942bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
11943 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
11944}
11945
11946bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
11947 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
11948}
11949
11950unsigned int
11951AArch64InstrInfo::getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
11952 return OptLevel >= CodeGenOptLevel::Aggressive ? 6 : 2;
11953}
11954
11955bool AArch64InstrInfo::isLegalAddressingMode(unsigned NumBytes, int64_t Offset,
11956 unsigned Scale) const {
11957 if (Offset && Scale)
11958 return false;
11959
11960 // Check Reg + Imm
11961 if (!Scale) {
11962 // 9-bit signed offset
11963 if (isInt<9>(Offset))
11964 return true;
11965
11966 // 12-bit unsigned offset
11967 unsigned Shift = Log2_64(NumBytes);
11968 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
11969 // Must be a multiple of NumBytes (NumBytes is a power of 2)
11970 (Offset >> Shift) << Shift == Offset)
11971 return true;
11972 return false;
11973 }
11974
11975 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
11976 return Scale == 1 || (Scale > 0 && Scale == NumBytes);
11977}
11978
11980 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
11981 return AArch64::BLRNoIP;
11982 else
11983 return AArch64::BLR;
11984}
11985
11987 DebugLoc DL) const {
11988 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
11989 auto Builder = BuildMI(MBB, InsertPt, DL, get(AArch64::PAUTH_EPILOGUE))
11991
11992 MachineFunction &MF = *MBB.getParent();
11993 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
11994 auto &AFL = *static_cast<const AArch64FrameLowering *>(
11995 MF.getSubtarget().getFrameLowering());
11996 if (AFL.getArgumentStackToRestore(MF, MBB)) {
11997 Builder.addReg(AArch64::X17, RegState::ImplicitDefine);
11998 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11999 if (AFI->branchProtectionPAuthLR())
12000 Builder.addReg(AArch64::X15, RegState::ImplicitDefine);
12001 return;
12002 }
12003
12004 if (AFI->branchProtectionPAuthLR() && !Subtarget.hasPAuthLR())
12005 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
12006}
12007
12009AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,
12010 Register TargetReg, bool FrameSetup) const {
12011 assert(TargetReg != AArch64::SP && "New top of stack cannot already be in SP");
12012
12013 MachineBasicBlock &MBB = *MBBI->getParent();
12014 MachineFunction &MF = *MBB.getParent();
12015 const AArch64InstrInfo *TII =
12016 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
12017 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
12018 DebugLoc DL = MBB.findDebugLoc(MBBI);
12019
12020 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
12021 MachineBasicBlock *LoopTestMBB =
12022 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12023 MF.insert(MBBInsertPoint, LoopTestMBB);
12024 MachineBasicBlock *LoopBodyMBB =
12025 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12026 MF.insert(MBBInsertPoint, LoopBodyMBB);
12027 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
12028 MF.insert(MBBInsertPoint, ExitMBB);
12029 MachineInstr::MIFlag Flags =
12031
12032 // LoopTest:
12033 // SUB SP, SP, #ProbeSize
12034 emitFrameOffset(*LoopTestMBB, LoopTestMBB->end(), DL, AArch64::SP,
12035 AArch64::SP, StackOffset::getFixed(-ProbeSize), TII, Flags);
12036
12037 // CMP SP, TargetReg
12038 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
12039 AArch64::XZR)
12040 .addReg(AArch64::SP)
12041 .addReg(TargetReg)
12043 .setMIFlags(Flags);
12044
12045 // B.<Cond> LoopExit
12046 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::Bcc))
12048 .addMBB(ExitMBB)
12049 .setMIFlags(Flags);
12050
12051 // LDR XZR, [SP]
12052 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::LDRXui))
12053 .addDef(AArch64::XZR)
12054 .addReg(AArch64::SP)
12055 .addImm(0)
12059 Align(8)))
12060 .setMIFlags(Flags);
12061
12062 // B loop
12063 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::B))
12064 .addMBB(LoopTestMBB)
12065 .setMIFlags(Flags);
12066
12067 // LoopExit:
12068 // MOV SP, TargetReg
12069 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::ADDXri), AArch64::SP)
12070 .addReg(TargetReg)
12071 .addImm(0)
12073 .setMIFlags(Flags);
12074
12075 // LDR XZR, [SP]
12076 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::LDRXui))
12077 .addReg(AArch64::XZR, RegState::Define)
12078 .addReg(AArch64::SP)
12079 .addImm(0)
12080 .setMIFlags(Flags);
12081
12082 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
12084
12085 LoopTestMBB->addSuccessor(ExitMBB);
12086 LoopTestMBB->addSuccessor(LoopBodyMBB);
12087 LoopBodyMBB->addSuccessor(LoopTestMBB);
12088 MBB.addSuccessor(LoopTestMBB);
12089
12090 // Update liveins.
12091 if (MF.getRegInfo().reservedRegsFrozen())
12092 fullyRecomputeLiveIns({ExitMBB, LoopBodyMBB, LoopTestMBB});
12093
12094 return ExitMBB->begin();
12095}
12096
12097namespace {
12098class AArch64PipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
12099 MachineFunction *MF;
12100 const TargetInstrInfo *TII;
12101 const TargetRegisterInfo *TRI;
12102 MachineRegisterInfo &MRI;
12103
12104 /// The block of the loop
12105 MachineBasicBlock *LoopBB;
12106 /// The conditional branch of the loop
12107 MachineInstr *CondBranch;
12108 /// The compare instruction for loop control
12109 MachineInstr *Comp;
12110 /// The number of the operand of the loop counter value in Comp
12111 unsigned CompCounterOprNum;
12112 /// The instruction that updates the loop counter value
12113 MachineInstr *Update;
12114 /// The number of the operand of the loop counter value in Update
12115 unsigned UpdateCounterOprNum;
12116 /// The initial value of the loop counter
12117 Register Init;
12118 /// True iff Update is a predecessor of Comp
12119 bool IsUpdatePriorComp;
12120
12121 /// The normalized condition used by createTripCountGreaterCondition()
12122 SmallVector<MachineOperand, 4> Cond;
12123
12124public:
12125 AArch64PipelinerLoopInfo(MachineBasicBlock *LoopBB, MachineInstr *CondBranch,
12126 MachineInstr *Comp, unsigned CompCounterOprNum,
12127 MachineInstr *Update, unsigned UpdateCounterOprNum,
12128 Register Init, bool IsUpdatePriorComp,
12129 const SmallVectorImpl<MachineOperand> &Cond)
12130 : MF(Comp->getParent()->getParent()),
12131 TII(MF->getSubtarget().getInstrInfo()),
12132 TRI(MF->getSubtarget().getRegisterInfo()), MRI(MF->getRegInfo()),
12133 LoopBB(LoopBB), CondBranch(CondBranch), Comp(Comp),
12134 CompCounterOprNum(CompCounterOprNum), Update(Update),
12135 UpdateCounterOprNum(UpdateCounterOprNum), Init(Init),
12136 IsUpdatePriorComp(IsUpdatePriorComp), Cond(Cond.begin(), Cond.end()) {}
12137
12138 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
12139 // Make the instructions for loop control be placed in stage 0.
12140 // The predecessors of Comp are considered by the caller.
12141 return MI == Comp;
12142 }
12143
12144 std::optional<bool> createTripCountGreaterCondition(
12145 int TC, MachineBasicBlock &MBB,
12146 SmallVectorImpl<MachineOperand> &CondParam) override {
12147 // A branch instruction will be inserted as "if (Cond) goto epilogue".
12148 // Cond is normalized for such use.
12149 // The predecessors of the branch are assumed to have already been inserted.
12150 CondParam = Cond;
12151 return {};
12152 }
12153
12154 void createRemainingIterationsGreaterCondition(
12155 int TC, MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &Cond,
12156 DenseMap<MachineInstr *, MachineInstr *> &LastStage0Insts) override;
12157
12158 void setPreheader(MachineBasicBlock *NewPreheader) override {}
12159
12160 void adjustTripCount(int TripCountAdjust) override {}
12161
12162 bool isMVEExpanderSupported() override { return true; }
12163};
12164} // namespace
12165
12166/// Clone an instruction from MI. The register of ReplaceOprNum-th operand
12167/// is replaced by ReplaceReg. The output register is newly created.
12168/// The other operands are unchanged from MI.
12169static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum,
12170 Register ReplaceReg, MachineBasicBlock &MBB,
12171 MachineBasicBlock::iterator InsertTo) {
12172 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
12173 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
12174 MachineInstr *NewMI = MBB.getParent()->CloneMachineInstr(MI);
12175 Register Result = 0;
12176 for (unsigned I = 0; I < NewMI->getNumOperands(); ++I) {
12177 if (I == 0 && NewMI->getOperand(0).getReg().isVirtual()) {
12178 Result = MRI.createVirtualRegister(
12179 MRI.getRegClass(NewMI->getOperand(0).getReg()));
12180 NewMI->getOperand(I).setReg(Result);
12181 } else if (I == ReplaceOprNum) {
12182 MRI.constrainRegClass(ReplaceReg, TII->getRegClass(NewMI->getDesc(), I));
12183 NewMI->getOperand(I).setReg(ReplaceReg);
12184 }
12185 }
12186 MBB.insert(InsertTo, NewMI);
12187 return Result;
12188}
12189
12190void AArch64PipelinerLoopInfo::createRemainingIterationsGreaterCondition(
12193 // Create and accumulate conditions for next TC iterations.
12194 // Example:
12195 // SUBSXrr N, counter, implicit-def $nzcv # compare instruction for the last
12196 // # iteration of the kernel
12197 //
12198 // # insert the following instructions
12199 // cond = CSINCXr 0, 0, C, implicit $nzcv
12200 // counter = ADDXri counter, 1 # clone from this->Update
12201 // SUBSXrr n, counter, implicit-def $nzcv # clone from this->Comp
12202 // cond = CSINCXr cond, cond, C, implicit $nzcv
12203 // ... (repeat TC times)
12204 // SUBSXri cond, 0, implicit-def $nzcv
12205
12206 assert(CondBranch->getOpcode() == AArch64::Bcc);
12207 // CondCode to exit the loop
12209 (AArch64CC::CondCode)CondBranch->getOperand(0).getImm();
12210 if (CondBranch->getOperand(1).getMBB() == LoopBB)
12212
12213 // Accumulate conditions to exit the loop
12214 Register AccCond = AArch64::XZR;
12215
12216 // If CC holds, CurCond+1 is returned; otherwise CurCond is returned.
12217 auto AccumulateCond = [&](Register CurCond,
12219 Register NewCond = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
12220 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::CSINCXr))
12221 .addReg(NewCond, RegState::Define)
12222 .addReg(CurCond)
12223 .addReg(CurCond)
12225 return NewCond;
12226 };
12227
12228 if (!LastStage0Insts.empty() && LastStage0Insts[Comp]->getParent() == &MBB) {
12229 // Update and Comp for I==0 are already exists in MBB
12230 // (MBB is an unrolled kernel)
12231 Register Counter;
12232 for (int I = 0; I <= TC; ++I) {
12233 Register NextCounter;
12234 if (I != 0)
12235 NextCounter =
12236 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12237
12238 AccCond = AccumulateCond(AccCond, CC);
12239
12240 if (I != TC) {
12241 if (I == 0) {
12242 if (Update != Comp && IsUpdatePriorComp) {
12243 Counter =
12244 LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12245 NextCounter = cloneInstr(Update, UpdateCounterOprNum, Counter, MBB,
12246 MBB.end());
12247 } else {
12248 // can use already calculated value
12249 NextCounter = LastStage0Insts[Update]->getOperand(0).getReg();
12250 }
12251 } else if (Update != Comp) {
12252 NextCounter =
12253 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12254 }
12255 }
12256 Counter = NextCounter;
12257 }
12258 } else {
12259 Register Counter;
12260 if (LastStage0Insts.empty()) {
12261 // use initial counter value (testing if the trip count is sufficient to
12262 // be executed by pipelined code)
12263 Counter = Init;
12264 if (IsUpdatePriorComp)
12265 Counter =
12266 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12267 } else {
12268 // MBB is an epilogue block. LastStage0Insts[Comp] is in the kernel block.
12269 Counter = LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12270 }
12271
12272 for (int I = 0; I <= TC; ++I) {
12273 Register NextCounter;
12274 NextCounter =
12275 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12276 AccCond = AccumulateCond(AccCond, CC);
12277 if (I != TC && Update != Comp)
12278 NextCounter =
12279 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12280 Counter = NextCounter;
12281 }
12282 }
12283
12284 // If AccCond == 0, the remainder is greater than TC.
12285 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::SUBSXri))
12286 .addReg(AArch64::XZR, RegState::Define | RegState::Dead)
12287 .addReg(AccCond)
12288 .addImm(0)
12289 .addImm(0);
12290 Cond.clear();
12292}
12293
12294static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB,
12295 Register &RegMBB, Register &RegOther) {
12296 assert(Phi.getNumOperands() == 5);
12297 if (Phi.getOperand(2).getMBB() == MBB) {
12298 RegMBB = Phi.getOperand(1).getReg();
12299 RegOther = Phi.getOperand(3).getReg();
12300 } else {
12301 assert(Phi.getOperand(4).getMBB() == MBB);
12302 RegMBB = Phi.getOperand(3).getReg();
12303 RegOther = Phi.getOperand(1).getReg();
12304 }
12305}
12306
12308 if (!Reg.isVirtual())
12309 return false;
12310 const MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
12311 return MRI.getDefBlock(Reg) != BB;
12312}
12313
12314/// If Reg is an induction variable, return true and set some parameters
12315static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB,
12316 MachineInstr *&UpdateInst,
12317 unsigned &UpdateCounterOprNum, Register &InitReg,
12318 bool &IsUpdatePriorComp) {
12319 // Example:
12320 //
12321 // Preheader:
12322 // InitReg = ...
12323 // LoopBB:
12324 // Reg0 = PHI (InitReg, Preheader), (Reg1, LoopBB)
12325 // Reg = COPY Reg0 ; COPY is ignored.
12326 // Reg1 = ADD Reg, #1; UpdateInst. Incremented by a loop invariant value.
12327 // ; Reg is the value calculated in the previous
12328 // ; iteration, so IsUpdatePriorComp == false.
12329
12330 if (LoopBB->pred_size() != 2)
12331 return false;
12332 if (!Reg.isVirtual())
12333 return false;
12334 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
12335 UpdateInst = nullptr;
12336 UpdateCounterOprNum = 0;
12337 InitReg = 0;
12338 IsUpdatePriorComp = true;
12339 Register CurReg = Reg;
12340 while (true) {
12341 MachineInstr *Def = MRI.getVRegDef(CurReg);
12342 if (Def->getParent() != LoopBB)
12343 return false;
12344 if (Def->isCopy()) {
12345 // Ignore copy instructions unless they contain subregisters
12346 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
12347 return false;
12348 CurReg = Def->getOperand(1).getReg();
12349 } else if (Def->isPHI()) {
12350 if (InitReg != 0)
12351 return false;
12352 if (!UpdateInst)
12353 IsUpdatePriorComp = false;
12354 extractPhiReg(*Def, LoopBB, CurReg, InitReg);
12355 } else {
12356 if (UpdateInst)
12357 return false;
12358 switch (Def->getOpcode()) {
12359 case AArch64::ADDSXri:
12360 case AArch64::ADDSWri:
12361 case AArch64::SUBSXri:
12362 case AArch64::SUBSWri:
12363 case AArch64::ADDXri:
12364 case AArch64::ADDWri:
12365 case AArch64::SUBXri:
12366 case AArch64::SUBWri:
12367 UpdateInst = Def;
12368 UpdateCounterOprNum = 1;
12369 break;
12370 case AArch64::ADDSXrr:
12371 case AArch64::ADDSWrr:
12372 case AArch64::SUBSXrr:
12373 case AArch64::SUBSWrr:
12374 case AArch64::ADDXrr:
12375 case AArch64::ADDWrr:
12376 case AArch64::SUBXrr:
12377 case AArch64::SUBWrr:
12378 UpdateInst = Def;
12379 if (isDefinedOutside(Def->getOperand(2).getReg(), LoopBB))
12380 UpdateCounterOprNum = 1;
12381 else if (isDefinedOutside(Def->getOperand(1).getReg(), LoopBB))
12382 UpdateCounterOprNum = 2;
12383 else
12384 return false;
12385 break;
12386 default:
12387 return false;
12388 }
12389 CurReg = Def->getOperand(UpdateCounterOprNum).getReg();
12390 }
12391
12392 if (!CurReg.isVirtual())
12393 return false;
12394 if (Reg == CurReg)
12395 break;
12396 }
12397
12398 if (!UpdateInst)
12399 return false;
12400
12401 return true;
12402}
12403
12404std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
12406 // Accept loops that meet the following conditions
12407 // * The conditional branch is BCC
12408 // * The compare instruction is ADDS/SUBS/WHILEXX
12409 // * One operand of the compare is an induction variable and the other is a
12410 // loop invariant value
12411 // * The induction variable is incremented/decremented by a single instruction
12412 // * Does not contain CALL or instructions which have unmodeled side effects
12413
12414 for (MachineInstr &MI : *LoopBB)
12415 if (MI.isCall() || MI.hasUnmodeledSideEffects())
12416 // This instruction may use NZCV, which interferes with the instruction to
12417 // be inserted for loop control.
12418 return nullptr;
12419
12420 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
12422 if (analyzeBranch(*LoopBB, TBB, FBB, Cond))
12423 return nullptr;
12424
12425 // Infinite loops are not supported
12426 if (TBB == LoopBB && FBB == LoopBB)
12427 return nullptr;
12428
12429 // Must be conditional branch
12430 if (TBB != LoopBB && FBB == nullptr)
12431 return nullptr;
12432
12433 assert((TBB == LoopBB || FBB == LoopBB) &&
12434 "The Loop must be a single-basic-block loop");
12435
12436 MachineInstr *CondBranch = &*LoopBB->getFirstTerminator();
12438
12439 if (CondBranch->getOpcode() != AArch64::Bcc)
12440 return nullptr;
12441
12442 // Normalization for createTripCountGreaterCondition()
12443 if (TBB == LoopBB)
12445
12446 MachineInstr *Comp = nullptr;
12447 unsigned CompCounterOprNum = 0;
12448 for (MachineInstr &MI : reverse(*LoopBB)) {
12449 if (MI.modifiesRegister(AArch64::NZCV, &TRI)) {
12450 // Guarantee that the compare is SUBS/ADDS/WHILEXX and that one of the
12451 // operands is a loop invariant value
12452
12453 switch (MI.getOpcode()) {
12454 case AArch64::SUBSXri:
12455 case AArch64::SUBSWri:
12456 case AArch64::ADDSXri:
12457 case AArch64::ADDSWri:
12458 Comp = &MI;
12459 CompCounterOprNum = 1;
12460 break;
12461 case AArch64::ADDSWrr:
12462 case AArch64::ADDSXrr:
12463 case AArch64::SUBSWrr:
12464 case AArch64::SUBSXrr:
12465 Comp = &MI;
12466 break;
12467 default:
12468 if (isWhileOpcode(MI.getOpcode())) {
12469 Comp = &MI;
12470 break;
12471 }
12472 return nullptr;
12473 }
12474
12475 if (CompCounterOprNum == 0) {
12476 if (isDefinedOutside(Comp->getOperand(1).getReg(), LoopBB))
12477 CompCounterOprNum = 2;
12478 else if (isDefinedOutside(Comp->getOperand(2).getReg(), LoopBB))
12479 CompCounterOprNum = 1;
12480 else
12481 return nullptr;
12482 }
12483 break;
12484 }
12485 }
12486 if (!Comp)
12487 return nullptr;
12488
12489 MachineInstr *Update = nullptr;
12490 Register Init;
12491 bool IsUpdatePriorComp;
12492 unsigned UpdateCounterOprNum;
12493 if (!getIndVarInfo(Comp->getOperand(CompCounterOprNum).getReg(), LoopBB,
12494 Update, UpdateCounterOprNum, Init, IsUpdatePriorComp))
12495 return nullptr;
12496
12497 return std::make_unique<AArch64PipelinerLoopInfo>(
12498 LoopBB, CondBranch, Comp, CompCounterOprNum, Update, UpdateCounterOprNum,
12499 Init, IsUpdatePriorComp, Cond);
12500}
12501
12502/// verifyInstruction - Perform target specific instruction verification.
12503bool AArch64InstrInfo::verifyInstruction(const MachineInstr &MI,
12504 StringRef &ErrInfo) const {
12505 // Verify that immediate offsets on load/store instructions are within range.
12506 // Stack objects with an FI operand are excluded as they can be fixed up
12507 // during PEI.
12508 TypeSize Scale(0U, false), Width(0U, false);
12509 int64_t MinOffset, MaxOffset;
12510 if (getMemOpInfo(MI.getOpcode(), Scale, Width, MinOffset, MaxOffset)) {
12511 unsigned ImmIdx = getLoadStoreImmIdx(MI.getOpcode());
12512 if (MI.getOperand(ImmIdx).isImm() && !MI.getOperand(ImmIdx - 1).isFI()) {
12513 int64_t Imm = MI.getOperand(ImmIdx).getImm();
12514 if (Imm < MinOffset || Imm > MaxOffset) {
12515 ErrInfo = "Unexpected immediate on load/store instruction";
12516 return false;
12517 }
12518 }
12519 }
12520
12521 const MCInstrDesc &MCID = MI.getDesc();
12522 for (unsigned Op = 0; Op < MCID.getNumOperands(); Op++) {
12523 const MachineOperand &MO = MI.getOperand(Op);
12524 switch (MCID.operands()[Op].OperandType) {
12526 if (!MO.isImm() || MO.getImm() != 0) {
12527 ErrInfo = "OPERAND_IMPLICIT_IMM_0 should be 0";
12528 return false;
12529 }
12530 break;
12532 if (!MO.isImm() ||
12534 (AArch64_AM::getShiftValue(MO.getImm()) != 8 &&
12535 AArch64_AM::getShiftValue(MO.getImm()) != 16)) {
12536 ErrInfo = "OPERAND_SHIFT_MSL should be msl shift of 8 or 16";
12537 return false;
12538 }
12539 break;
12541 if (!MO.isImm() || (MO.getImm() != 0 && MO.getImm() != 1)) {
12542 ErrInfo = "OPERAND_IMM_UINT1 should be 0 or 1";
12543 return false;
12544 }
12545 break;
12547 if (!MO.isImm() || MO.getImm() <= 0 || MO.getImm() > 16) {
12548 ErrInfo = "OPERAND_IMM_UINT4plus1 should be in the range 1 to 16";
12549 return false;
12550 }
12551 break;
12553 if (!MO.isImm() || !isUInt<5>(MO.getImm())) {
12554 ErrInfo = "OPERAND_IMM_UINT5 should be in the range 0 to 31";
12555 return false;
12556 }
12557 break;
12559 if (!MO.isImm() || !isUInt<8>(MO.getImm())) {
12560 ErrInfo = "OPERAND_IMM_UINT8 should be in the range 0 to 255";
12561 return false;
12562 }
12563 break;
12564 default:
12565 break;
12566 }
12567 }
12568 return true;
12569}
12570
12571#define GET_INSTRINFO_HELPERS
12572#define GET_INSTRMAP_INFO
12573#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 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!")
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
const HexagonInstrInfo * TII
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.
#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
SmallVector< MachineOperand, 4 > Cond
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:480
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:171
#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:699
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
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:67
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:628
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:670
static MCCFIInstruction cfiDefCfaOffset(MCSymbol *L, int64_t Offset, SMLoc Loc={})
.cfi_def_cfa_offset modifies a rule for computing CFA.
Definition MCDwarf.h:643
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:756
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
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. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isValid() const
Definition MCRegister.h:84
static constexpr unsigned NoRegister
Definition MCRegister.h:60
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
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
MI-level patchpoint operands.
Definition StackMaps.h:77
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given patchpoint should emit.
Definition StackMaps.h:105
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:112
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:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
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)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
MI-level stackmap operands.
Definition StackMaps.h:36
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given stackmap should emit.
Definition StackMaps.h:51
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
MI-level Statepoint operands.
Definition StackMaps.h:159
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given statepoint should emit.
Definition StackMaps.h:208
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:876
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.
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:2570
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:2208
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.