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
697 AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
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;
878 CC = AArch64CC::EQ;
879 break;
880 case AArch64::CBZX:
881 Is64Bit = true;
882 CC = AArch64CC::EQ;
883 break;
884 case AArch64::CBNZW:
885 Is64Bit = false;
886 CC = AArch64CC::NE;
887 break;
888 case AArch64::CBNZX:
889 Is64Bit = true;
890 CC = AArch64CC::NE;
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:
916 CC = AArch64CC::EQ;
917 break;
918 case AArch64::TBNZW:
919 case AArch64::TBNZX:
920 CC = AArch64CC::NE;
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, int &CondCycles,
1213 int &TrueCycles,
1214 int &FalseCycles) const {
1215 // Check register classes.
1216 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1217 const TargetRegisterClass *RC =
1218 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
1219 if (!RC)
1220 return false;
1221
1222 // Also need to check the dest regclass, in case we're trying to optimize
1223 // something like:
1224 // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
1225 if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
1226 return false;
1227
1228 // Expanding cbz/tbz requires an extra cycle of latency on the condition.
1229 unsigned ExtraCondLat = Cond.size() != 1;
1230
1231 // GPRs are handled by csel.
1232 // FIXME: Fold in x+1, -x, and ~x when applicable.
1233 if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
1234 AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
1235 // Single-cycle csel, csinc, csinv, and csneg.
1236 CondCycles = 1 + ExtraCondLat;
1237 TrueCycles = FalseCycles = 1;
1238 if (canFoldIntoCSel(MRI, TrueReg))
1239 TrueCycles = 0;
1240 else if (canFoldIntoCSel(MRI, FalseReg))
1241 FalseCycles = 0;
1242 return true;
1243 }
1244
1245 // Scalar floating point is handled by fcsel.
1246 // FIXME: Form fabs, fmin, and fmax when applicable.
1247 if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
1248 AArch64::FPR32RegClass.hasSubClassEq(RC)) {
1249 CondCycles = 5 + ExtraCondLat;
1250 TrueCycles = FalseCycles = 2;
1251 return true;
1252 }
1253
1254 // No single conditional move for a 128-bit vector, but we can emit a sequence
1255 // of csetm (~1), dup (~5, cross domain), bsl (~2).
1256 if (AArch64::FPR128RegClass.hasSubClassEq(RC) &&
1257 Subtarget.isNeonAvailable() &&
1258 !MBB.getParent()->getFunction().hasMinSize()) {
1259 CondCycles = 8 + ExtraCondLat;
1260 TrueCycles = FalseCycles = 2;
1261 return true;
1262 }
1263
1264 return false;
1265}
1266
1269 const DebugLoc &DL, Register DstReg,
1271 Register TrueReg, Register FalseReg) const {
1272
1273 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1275
1276 // A 128-bit vector has no conditional move so blend the operands with a mask
1277 // built from the flags.
1278 if (MRI.constrainRegClass(DstReg, &AArch64::FPR128RegClass)) {
1279 assert(Subtarget.isNeonAvailable() && "Expected NEON for a vector select");
1280 MRI.constrainRegClass(TrueReg, &AArch64::FPR128RegClass);
1281 MRI.constrainRegClass(FalseReg, &AArch64::FPR128RegClass);
1282 Register CondSet = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1283 BuildMI(MBB, I, DL, get(AArch64::CSINVXr), CondSet)
1284 .addReg(AArch64::XZR)
1285 .addReg(AArch64::XZR)
1287 Register Mask = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
1288 BuildMI(MBB, I, DL, get(AArch64::DUPv2i64gpr), Mask).addReg(CondSet);
1289 BuildMI(MBB, I, DL, get(AArch64::BSPv16i8), DstReg)
1290 .addReg(Mask)
1291 .addReg(TrueReg)
1292 .addReg(FalseReg);
1293 return;
1294 }
1295
1296 unsigned Opc = 0;
1297 const TargetRegisterClass *RC = nullptr;
1298 bool TryFold = false;
1299 if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
1300 RC = &AArch64::GPR64RegClass;
1301 Opc = AArch64::CSELXr;
1302 TryFold = true;
1303 } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
1304 RC = &AArch64::GPR32RegClass;
1305 Opc = AArch64::CSELWr;
1306 TryFold = true;
1307 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
1308 RC = &AArch64::FPR64RegClass;
1309 Opc = AArch64::FCSELDrrr;
1310 } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
1311 RC = &AArch64::FPR32RegClass;
1312 Opc = AArch64::FCSELSrrr;
1313 }
1314 assert(RC && "Unsupported regclass");
1315
1316 // Try folding simple instructions into the csel.
1317 if (TryFold) {
1318 unsigned NewReg = 0;
1319 unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewReg);
1320 if (FoldedOpc) {
1321 // The folded opcodes csinc, csinc and csneg apply the operation to
1322 // FalseReg, so we need to invert the condition.
1324 TrueReg = FalseReg;
1325 } else
1326 FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewReg);
1327
1328 // Fold the operation. Leave any dead instructions for DCE to clean up.
1329 if (FoldedOpc) {
1330 FalseReg = NewReg;
1331 Opc = FoldedOpc;
1332 // Extend the live range of NewReg.
1333 MRI.clearKillFlags(NewReg);
1334 }
1335 }
1336
1337 // Pull all virtual register into the appropriate class.
1338 MRI.constrainRegClass(TrueReg, RC);
1339 // FalseReg might be WZR or XZR if the folded operand is a literal 1.
1340 assert(
1341 (FalseReg.isVirtual() || FalseReg == AArch64::WZR ||
1342 FalseReg == AArch64::XZR) &&
1343 "FalseReg was folded into a non-virtual register other than WZR or XZR");
1344 if (FalseReg.isVirtual())
1345 MRI.constrainRegClass(FalseReg, RC);
1346
1347 // Insert the csel.
1348 BuildMI(MBB, I, DL, get(Opc), DstReg)
1349 .addReg(TrueReg)
1350 .addReg(FalseReg)
1351 .addImm(CC);
1352}
1353
1354// Return true if Imm can be loaded into a register by a "cheap" sequence of
1355// instructions. For now, "cheap" means at most two instructions.
1356static bool isCheapImmediate(const MachineInstr &MI, unsigned BitSize) {
1357 if (BitSize == 32)
1358 return true;
1359
1360 assert(BitSize == 64 && "Only bit sizes of 32 or 64 allowed");
1361 uint64_t Imm = static_cast<uint64_t>(MI.getOperand(1).getImm());
1363 AArch64_IMM::expandMOVImm(Imm, BitSize, Is);
1364
1365 return Is.size() <= 2;
1366}
1367
1368// Check if a COPY instruction is cheap.
1369static bool isCheapCopy(const MachineInstr &MI, const AArch64RegisterInfo &RI) {
1370 assert(MI.isCopy() && "Expected COPY instruction");
1371 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
1372
1373 // Cross-bank copies (e.g., between GPR and FPR) are expensive on AArch64,
1374 // typically requiring an FMOV instruction with a 2-6 cycle latency.
1375 auto GetRegClass = [&](Register Reg) -> const TargetRegisterClass * {
1376 if (Reg.isVirtual())
1377 return MRI.getRegClass(Reg);
1378 if (Reg.isPhysical())
1379 return RI.getMinimalPhysRegClass(Reg);
1380 return nullptr;
1381 };
1382 const TargetRegisterClass *DstRC = GetRegClass(MI.getOperand(0).getReg());
1383 const TargetRegisterClass *SrcRC = GetRegClass(MI.getOperand(1).getReg());
1384 if (DstRC && SrcRC && !RI.getCommonSubClass(DstRC, SrcRC))
1385 return false;
1386
1387 return MI.isAsCheapAsAMove();
1388}
1389
1390// FIXME: this implementation should be micro-architecture dependent, so a
1391// micro-architecture target hook should be introduced here in future.
1393 if (Subtarget.hasExynosCheapAsMoveHandling()) {
1394 if (isExynosCheapAsMove(MI))
1395 return true;
1396 return MI.isAsCheapAsAMove();
1397 }
1398
1399 switch (MI.getOpcode()) {
1400 default:
1401 return MI.isAsCheapAsAMove();
1402
1403 case TargetOpcode::COPY:
1404 return isCheapCopy(MI, RI);
1405
1406 case AArch64::ADDWrs:
1407 case AArch64::ADDXrs:
1408 case AArch64::SUBWrs:
1409 case AArch64::SUBXrs:
1410 return Subtarget.hasALULSLFast() && MI.getOperand(3).getImm() <= 4;
1411
1412 // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
1413 // ORRXri, it is as cheap as MOV.
1414 // Likewise if it can be expanded to MOVZ/MOVN/MOVK.
1415 case AArch64::MOVi32imm:
1416 return isCheapImmediate(MI, 32);
1417 case AArch64::MOVi64imm:
1418 return isCheapImmediate(MI, 64);
1419 }
1420}
1421
1422bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
1423 switch (MI.getOpcode()) {
1424 default:
1425 return false;
1426
1427 case AArch64::ADDWrs:
1428 case AArch64::ADDXrs:
1429 case AArch64::ADDSWrs:
1430 case AArch64::ADDSXrs: {
1431 unsigned Imm = MI.getOperand(3).getImm();
1432 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1433 if (ShiftVal == 0)
1434 return true;
1435 return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
1436 }
1437
1438 case AArch64::ADDWrx:
1439 case AArch64::ADDXrx:
1440 case AArch64::ADDXrx64:
1441 case AArch64::ADDSWrx:
1442 case AArch64::ADDSXrx:
1443 case AArch64::ADDSXrx64: {
1444 unsigned Imm = MI.getOperand(3).getImm();
1446 default:
1447 return false;
1448 case AArch64_AM::UXTB:
1449 case AArch64_AM::UXTH:
1450 case AArch64_AM::UXTW:
1451 case AArch64_AM::UXTX:
1453 }
1454 }
1455
1456 case AArch64::SUBWrs:
1457 case AArch64::SUBSWrs: {
1458 unsigned Imm = MI.getOperand(3).getImm();
1459 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1460 return ShiftVal == 0 ||
1461 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
1462 }
1463
1464 case AArch64::SUBXrs:
1465 case AArch64::SUBSXrs: {
1466 unsigned Imm = MI.getOperand(3).getImm();
1467 unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
1468 return ShiftVal == 0 ||
1469 (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
1470 }
1471
1472 case AArch64::SUBWrx:
1473 case AArch64::SUBXrx:
1474 case AArch64::SUBXrx64:
1475 case AArch64::SUBSWrx:
1476 case AArch64::SUBSXrx:
1477 case AArch64::SUBSXrx64: {
1478 unsigned Imm = MI.getOperand(3).getImm();
1480 default:
1481 return false;
1482 case AArch64_AM::UXTB:
1483 case AArch64_AM::UXTH:
1484 case AArch64_AM::UXTW:
1485 case AArch64_AM::UXTX:
1487 }
1488 }
1489
1490 case AArch64::LDRBBroW:
1491 case AArch64::LDRBBroX:
1492 case AArch64::LDRBroW:
1493 case AArch64::LDRBroX:
1494 case AArch64::LDRDroW:
1495 case AArch64::LDRDroX:
1496 case AArch64::LDRHHroW:
1497 case AArch64::LDRHHroX:
1498 case AArch64::LDRHroW:
1499 case AArch64::LDRHroX:
1500 case AArch64::LDRQroW:
1501 case AArch64::LDRQroX:
1502 case AArch64::LDRSBWroW:
1503 case AArch64::LDRSBWroX:
1504 case AArch64::LDRSBXroW:
1505 case AArch64::LDRSBXroX:
1506 case AArch64::LDRSHWroW:
1507 case AArch64::LDRSHWroX:
1508 case AArch64::LDRSHXroW:
1509 case AArch64::LDRSHXroX:
1510 case AArch64::LDRSWroW:
1511 case AArch64::LDRSWroX:
1512 case AArch64::LDRSroW:
1513 case AArch64::LDRSroX:
1514 case AArch64::LDRWroW:
1515 case AArch64::LDRWroX:
1516 case AArch64::LDRXroW:
1517 case AArch64::LDRXroX:
1518 case AArch64::PRFMroW:
1519 case AArch64::PRFMroX:
1520 case AArch64::STRBBroW:
1521 case AArch64::STRBBroX:
1522 case AArch64::STRBroW:
1523 case AArch64::STRBroX:
1524 case AArch64::STRDroW:
1525 case AArch64::STRDroX:
1526 case AArch64::STRHHroW:
1527 case AArch64::STRHHroX:
1528 case AArch64::STRHroW:
1529 case AArch64::STRHroX:
1530 case AArch64::STRQroW:
1531 case AArch64::STRQroX:
1532 case AArch64::STRSroW:
1533 case AArch64::STRSroX:
1534 case AArch64::STRWroW:
1535 case AArch64::STRWroX:
1536 case AArch64::STRXroW:
1537 case AArch64::STRXroX: {
1538 unsigned IsSigned = MI.getOperand(3).getImm();
1539 return !IsSigned;
1540 }
1541 }
1542}
1543
1544bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
1545 unsigned Opc = MI.getOpcode();
1546 switch (Opc) {
1547 default:
1548 return false;
1549 case AArch64::SEH_StackAlloc:
1550 case AArch64::SEH_SaveFPLR:
1551 case AArch64::SEH_SaveFPLR_X:
1552 case AArch64::SEH_SaveReg:
1553 case AArch64::SEH_SaveReg_X:
1554 case AArch64::SEH_SaveRegP:
1555 case AArch64::SEH_SaveRegP_X:
1556 case AArch64::SEH_SaveFReg:
1557 case AArch64::SEH_SaveFReg_X:
1558 case AArch64::SEH_SaveFRegP:
1559 case AArch64::SEH_SaveFRegP_X:
1560 case AArch64::SEH_SetFP:
1561 case AArch64::SEH_AddFP:
1562 case AArch64::SEH_Nop:
1563 case AArch64::SEH_PrologEnd:
1564 case AArch64::SEH_EpilogStart:
1565 case AArch64::SEH_EpilogEnd:
1566 case AArch64::SEH_PACSignLR:
1567 case AArch64::SEH_SaveAnyRegI:
1568 case AArch64::SEH_SaveAnyRegIP:
1569 case AArch64::SEH_SaveAnyRegQP:
1570 case AArch64::SEH_SaveAnyRegQPX:
1571 case AArch64::SEH_AllocZ:
1572 case AArch64::SEH_SaveZReg:
1573 case AArch64::SEH_SavePReg:
1574 return true;
1575 }
1576}
1577
1579 Register &SrcReg, Register &DstReg,
1580 unsigned &SubIdx) const {
1581 switch (MI.getOpcode()) {
1582 default:
1583 return false;
1584 case AArch64::SBFMXri: // aka sxtw
1585 case AArch64::UBFMXri: // aka uxtw
1586 // Check for the 32 -> 64 bit extension case, these instructions can do
1587 // much more.
1588 if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1589 return false;
1590 // This is a signed or unsigned 32 -> 64 bit extension.
1591 SrcReg = MI.getOperand(1).getReg();
1592 DstReg = MI.getOperand(0).getReg();
1593 SubIdx = AArch64::sub_32;
1594 return true;
1595 }
1596}
1597
1599 const MachineInstr &MIa, const MachineInstr &MIb) const {
1600 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1601 int64_t OffsetA = 0, OffsetB = 0;
1602 TypeSize WidthA(0, false), WidthB(0, false);
1603 bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1604
1605 assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1606 assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1607
1610 return false;
1611
1612 // Retrieve the base, offset from the base and width. Width
1613 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8). If
1614 // base are identical, and the offset of a lower memory access +
1615 // the width doesn't overlap the offset of a higher memory access,
1616 // then the memory accesses are different.
1617 // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1618 // are assumed to have the same scale (vscale).
1619 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1620 WidthA) &&
1621 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1622 WidthB)) {
1623 if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1624 OffsetAIsScalable == OffsetBIsScalable) {
1625 int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1626 int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1627 TypeSize LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1628 if (LowWidth.isScalable() == OffsetAIsScalable &&
1629 LowOffset + (int)LowWidth.getKnownMinValue() <= HighOffset)
1630 return true;
1631 }
1632 }
1633 return false;
1634}
1635
1637 const MachineBasicBlock *MBB,
1638 const MachineFunction &MF) const {
1640 return true;
1641
1642 // Do not move an instruction that can be recognized as a branch target.
1643 if (hasBTISemantics(MI))
1644 return true;
1645
1646 switch (MI.getOpcode()) {
1647 case AArch64::HINT:
1648 // CSDB hints are scheduling barriers.
1649 if (MI.getOperand(0).getImm() == 0x14)
1650 return true;
1651 break;
1652 case AArch64::DSB:
1653 case AArch64::ISB:
1654 // DSB and ISB also are scheduling barriers.
1655 return true;
1656 case AArch64::MSRpstatesvcrImm1:
1657 // SMSTART and SMSTOP are also scheduling barriers.
1658 return true;
1659 default:;
1660 }
1661 if (isSEHInstruction(MI))
1662 return true;
1663 auto Next = std::next(MI.getIterator());
1664 return Next != MBB->end() && Next->isCFIInstruction();
1665}
1666
1667/// analyzeCompare - For a comparison instruction, return the source registers
1668/// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1669/// Return true if the comparison instruction can be analyzed.
1671 Register &SrcReg2, int64_t &CmpMask,
1672 int64_t &CmpValue) const {
1673 // The first operand can be a frame index where we'd normally expect a
1674 // register.
1675 // FIXME: Pass subregisters out of analyzeCompare
1676 assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1677 if (!MI.getOperand(1).isReg() || MI.getOperand(1).getSubReg())
1678 return false;
1679
1680 switch (MI.getOpcode()) {
1681 default:
1682 break;
1683 case AArch64::PTEST_PP:
1684 case AArch64::PTEST_PP_ANY:
1685 case AArch64::PTEST_PP_FIRST:
1686 SrcReg = MI.getOperand(0).getReg();
1687 SrcReg2 = MI.getOperand(1).getReg();
1688 if (MI.getOperand(2).getSubReg())
1689 return false;
1690
1691 // Not sure about the mask and value for now...
1692 CmpMask = ~0;
1693 CmpValue = 0;
1694 return true;
1695 case AArch64::SUBSWrr:
1696 case AArch64::SUBSWrs:
1697 case AArch64::SUBSWrx:
1698 case AArch64::SUBSXrr:
1699 case AArch64::SUBSXrs:
1700 case AArch64::SUBSXrx:
1701 case AArch64::ADDSWrr:
1702 case AArch64::ADDSWrs:
1703 case AArch64::ADDSWrx:
1704 case AArch64::ADDSXrr:
1705 case AArch64::ADDSXrs:
1706 case AArch64::ADDSXrx:
1707 // Replace SUBSWrr with SUBWrr if NZCV is not used.
1708 SrcReg = MI.getOperand(1).getReg();
1709 SrcReg2 = MI.getOperand(2).getReg();
1710
1711 // FIXME: Pass subregisters out of analyzeCompare
1712 if (MI.getOperand(2).getSubReg())
1713 return false;
1714
1715 CmpMask = ~0;
1716 CmpValue = 0;
1717 return true;
1718 case AArch64::SUBSWri:
1719 case AArch64::ADDSWri:
1720 case AArch64::SUBSXri:
1721 case AArch64::ADDSXri:
1722 SrcReg = MI.getOperand(1).getReg();
1723 SrcReg2 = 0;
1724 CmpMask = ~0;
1725 CmpValue = MI.getOperand(2).getImm();
1726 return true;
1727 case AArch64::ANDSWri:
1728 case AArch64::ANDSXri:
1729 // ANDS does not use the same encoding scheme as the others xxxS
1730 // instructions.
1731 SrcReg = MI.getOperand(1).getReg();
1732 SrcReg2 = 0;
1733 CmpMask = ~0;
1735 MI.getOperand(2).getImm(),
1736 MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1737 return true;
1738 }
1739
1740 return false;
1741}
1742
1744 MachineBasicBlock *MBB = Instr.getParent();
1745 assert(MBB && "Can't get MachineBasicBlock here");
1746 MachineFunction *MF = MBB->getParent();
1747 assert(MF && "Can't get MachineFunction here");
1750 MachineRegisterInfo *MRI = &MF->getRegInfo();
1751
1752 for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx;
1753 ++OpIdx) {
1754 MachineOperand &MO = Instr.getOperand(OpIdx);
1755 const TargetRegisterClass *OpRegCstraints =
1756 Instr.getRegClassConstraint(OpIdx, TII, TRI);
1757
1758 // If there's no constraint, there's nothing to do.
1759 if (!OpRegCstraints)
1760 continue;
1761 // If the operand is a frame index, there's nothing to do here.
1762 // A frame index operand will resolve correctly during PEI.
1763 if (MO.isFI())
1764 continue;
1765
1766 assert(MO.isReg() &&
1767 "Operand has register constraints without being a register!");
1768
1769 Register Reg = MO.getReg();
1770 if (Reg.isPhysical()) {
1771 if (!OpRegCstraints->contains(Reg))
1772 return false;
1773 } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) &&
1774 !MRI->constrainRegClass(Reg, OpRegCstraints))
1775 return false;
1776 }
1777
1778 return true;
1779}
1780
1781/// Return the opcode that does not set flags when possible - otherwise
1782/// return the original opcode. The caller is responsible to do the actual
1783/// substitution and legality checking.
1785 // Don't convert all compare instructions, because for some the zero register
1786 // encoding becomes the sp register.
1787 bool MIDefinesZeroReg = false;
1788 if (MI.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
1789 MI.definesRegister(AArch64::XZR, /*TRI=*/nullptr))
1790 MIDefinesZeroReg = true;
1791
1792 switch (MI.getOpcode()) {
1793 default:
1794 return MI.getOpcode();
1795 case AArch64::ADDSWrr:
1796 return AArch64::ADDWrr;
1797 case AArch64::ADDSWri:
1798 return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1799 case AArch64::ADDSWrs:
1800 return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1801 case AArch64::ADDSWrx:
1802 return AArch64::ADDWrx;
1803 case AArch64::ADDSXrr:
1804 return AArch64::ADDXrr;
1805 case AArch64::ADDSXri:
1806 return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1807 case AArch64::ADDSXrs:
1808 return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1809 case AArch64::ADDSXrx:
1810 return AArch64::ADDXrx;
1811 case AArch64::SUBSWrr:
1812 return AArch64::SUBWrr;
1813 case AArch64::SUBSWri:
1814 return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1815 case AArch64::SUBSWrs:
1816 return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1817 case AArch64::SUBSWrx:
1818 return AArch64::SUBWrx;
1819 case AArch64::SUBSXrr:
1820 return AArch64::SUBXrr;
1821 case AArch64::SUBSXri:
1822 return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1823 case AArch64::SUBSXrs:
1824 return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1825 case AArch64::SUBSXrx:
1826 return AArch64::SUBXrx;
1827 }
1828}
1829
1830enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1831
1832/// True when condition flags are accessed (either by writing or reading)
1833/// on the instruction trace starting at From and ending at To.
1834///
1835/// Note: If From and To are from different blocks it's assumed CC are accessed
1836/// on the path.
1839 const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1840 // Early exit if To is at the beginning of the BB.
1841 if (To == To->getParent()->begin())
1842 return true;
1843
1844 // Check whether the instructions are in the same basic block
1845 // If not, assume the condition flags might get modified somewhere.
1846 if (To->getParent() != From->getParent())
1847 return true;
1848
1849 // From must be above To.
1850 assert(std::any_of(
1851 ++To.getReverse(), To->getParent()->rend(),
1852 [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1853
1854 // We iterate backward starting at \p To until we hit \p From.
1855 for (const MachineInstr &Instr :
1857 if (((AccessToCheck & AK_Write) &&
1858 Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1859 ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1860 return true;
1861 }
1862 return false;
1863}
1864
1865std::optional<unsigned>
1866AArch64InstrInfo::canRemovePTestInstr(MachineInstr *PTest, MachineInstr *Mask,
1867 MachineInstr *Pred,
1868 const MachineRegisterInfo *MRI) const {
1869 unsigned MaskOpcode = Mask->getOpcode();
1870 unsigned PredOpcode = Pred->getOpcode();
1871 bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1872 bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1873
1874 if (PredIsWhileLike) {
1875 // For PTEST(PG, PG), PTEST is redundant when PG is the result of a WHILEcc
1876 // instruction and the condition is "any" since WHILcc does an implicit
1877 // PTEST(ALL, PG) check and PG is always a subset of ALL.
1878 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1879 return PredOpcode;
1880
1881 // For PTEST(PTRUE_ALL, WHILE), if the element size matches, the PTEST is
1882 // redundant since WHILE performs an implicit PTEST with an all active
1883 // mask.
1884 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1885 getElementSizeForOpcode(MaskOpcode) ==
1886 getElementSizeForOpcode(PredOpcode))
1887 return PredOpcode;
1888
1889 // For PTEST_FIRST(PTRUE_ALL, WHILE), the PTEST_FIRST is redundant since
1890 // WHILEcc performs an implicit PTEST with an all active mask, setting
1891 // the N flag as the PTEST_FIRST would.
1892 if (PTest->getOpcode() == AArch64::PTEST_PP_FIRST &&
1893 isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31)
1894 return PredOpcode;
1895
1896 return {};
1897 }
1898
1899 if (PredIsPTestLike) {
1900 // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1901 // instruction that sets the flags as PTEST would and the condition is
1902 // "any" since PG is always a subset of the governing predicate of the
1903 // ptest-like instruction.
1904 if ((Mask == Pred) && PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1905 return PredOpcode;
1906
1907 auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1908
1909 // If the PTEST like instruction's general predicate is not `Mask`, attempt
1910 // to look through a copy and try again. This is because some instructions
1911 // take a predicate whose register class is a subset of its result class.
1912 if (Mask != PTestLikeMask && PTestLikeMask->isFullCopy() &&
1913 PTestLikeMask->getOperand(1).getReg().isVirtual())
1914 PTestLikeMask =
1915 MRI->getUniqueVRegDef(PTestLikeMask->getOperand(1).getReg());
1916
1917 // For PTEST(PTRUE_ALL, PTEST_LIKE), the PTEST is redundant if the
1918 // the element size matches and either the PTEST_LIKE instruction uses
1919 // the same all active mask or the condition is "any".
1920 if (isPTrueOpcode(MaskOpcode) && Mask->getOperand(1).getImm() == 31 &&
1921 getElementSizeForOpcode(MaskOpcode) ==
1922 getElementSizeForOpcode(PredOpcode)) {
1923 if (Mask == PTestLikeMask || PTest->getOpcode() == AArch64::PTEST_PP_ANY)
1924 return PredOpcode;
1925 }
1926
1927 // For PTEST(PG, PTEST_LIKE(PG, ...)), the PTEST is redundant since the
1928 // flags are set based on the same mask 'PG', but PTEST_LIKE must operate
1929 // on 8-bit predicates like the PTEST. Otherwise, for instructions like
1930 // compare that also support 16/32/64-bit predicates, the implicit PTEST
1931 // performed by the compare could consider fewer lanes for these element
1932 // sizes.
1933 //
1934 // For example, consider
1935 //
1936 // ptrue p0.b ; P0=1111-1111-1111-1111
1937 // index z0.s, #0, #1 ; Z0=<0,1,2,3>
1938 // index z1.s, #1, #1 ; Z1=<1,2,3,4>
1939 // cmphi p1.s, p0/z, z1.s, z0.s ; P1=0001-0001-0001-0001
1940 // ; ^ last active
1941 // ptest p0, p1.b ; P1=0001-0001-0001-0001
1942 // ; ^ last active
1943 //
1944 // where the compare generates a canonical all active 32-bit predicate
1945 // (equivalent to 'ptrue p1.s, all'). The implicit PTEST sets the last
1946 // active flag, whereas the PTEST instruction with the same mask doesn't.
1947 // For PTEST_ANY this doesn't apply as the flags in this case would be
1948 // identical regardless of element size.
1949 uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1950 if (Mask == PTestLikeMask && (PredElementSize == AArch64::ElementSizeB ||
1951 PTest->getOpcode() == AArch64::PTEST_PP_ANY))
1952 return PredOpcode;
1953
1954 return {};
1955 }
1956
1957 // If OP in PTEST(PG, OP(PG, ...)) has a flag-setting variant change the
1958 // opcode so the PTEST becomes redundant.
1959 switch (PredOpcode) {
1960 case AArch64::AND_PPzPP:
1961 case AArch64::BIC_PPzPP:
1962 case AArch64::EOR_PPzPP:
1963 case AArch64::NAND_PPzPP:
1964 case AArch64::NOR_PPzPP:
1965 case AArch64::ORN_PPzPP:
1966 case AArch64::ORR_PPzPP:
1967 case AArch64::BRKA_PPzP:
1968 case AArch64::BRKPA_PPzPP:
1969 case AArch64::BRKB_PPzP:
1970 case AArch64::BRKPB_PPzPP:
1971 case AArch64::RDFFR_PPz: {
1972 // Check to see if our mask is the same. If not the resulting flag bits
1973 // may be different and we can't remove the ptest.
1974 auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1975 if (Mask != PredMask)
1976 return {};
1977 break;
1978 }
1979 case AArch64::BRKN_PPzP: {
1980 // BRKN uses an all active implicit mask to set flags unlike the other
1981 // flag-setting instructions.
1982 // PTEST(PTRUE_B(31), BRKN(PG, A, B)) -> BRKNS(PG, A, B).
1983 if ((MaskOpcode != AArch64::PTRUE_B) ||
1984 (Mask->getOperand(1).getImm() != 31))
1985 return {};
1986 break;
1987 }
1988 case AArch64::PTRUE_B:
1989 // PTEST(OP=PTRUE_B(A), OP) -> PTRUES_B(A)
1990 break;
1991 default:
1992 // Bail out if we don't recognize the input
1993 return {};
1994 }
1995
1996 return convertToFlagSettingOpc(PredOpcode);
1997}
1998
1999/// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
2000/// operation which could set the flags in an identical manner
2001bool AArch64InstrInfo::optimizePTestInstr(
2002 MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
2003 const MachineRegisterInfo *MRI) const {
2004 auto *Mask = MRI->getUniqueVRegDef(MaskReg);
2005 auto *Pred = MRI->getUniqueVRegDef(PredReg);
2006
2007 if (Pred->isCopy() && PTest->getOpcode() == AArch64::PTEST_PP_FIRST) {
2008 // Instructions which return a multi-vector (e.g. WHILECC_x2) require copies
2009 // before the branch to extract each subregister.
2010 auto Op = Pred->getOperand(1);
2011 if (Op.isReg() && Op.getReg().isVirtual() &&
2012 Op.getSubReg() == AArch64::psub0)
2013 Pred = MRI->getUniqueVRegDef(Op.getReg());
2014 }
2015
2016 unsigned PredOpcode = Pred->getOpcode();
2017 auto NewOp = canRemovePTestInstr(PTest, Mask, Pred, MRI);
2018 if (!NewOp)
2019 return false;
2020
2021 const TargetRegisterInfo *TRI = &getRegisterInfo();
2022
2023 // If another instruction between Pred and PTest accesses flags, don't remove
2024 // the ptest or update the earlier instruction to modify them.
2025 if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI))
2026 return false;
2027
2028 // If we pass all the checks, it's safe to remove the PTEST and use the flags
2029 // as they are prior to PTEST. Sometimes this requires the tested PTEST
2030 // operand to be replaced with an equivalent instruction that also sets the
2031 // flags.
2032 PTest->eraseFromParent();
2033 if (*NewOp != PredOpcode) {
2034 Pred->setDesc(get(*NewOp));
2035 bool succeeded = UpdateOperandRegClass(*Pred);
2036 (void)succeeded;
2037 assert(succeeded && "Operands have incompatible register classes!");
2038 Pred->addRegisterDefined(AArch64::NZCV, TRI);
2039 }
2040
2041 // Ensure that the flags def is live.
2042 if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
2043 unsigned i = 0, e = Pred->getNumOperands();
2044 for (; i != e; ++i) {
2045 MachineOperand &MO = Pred->getOperand(i);
2046 if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
2047 MO.setIsDead(false);
2048 break;
2049 }
2050 }
2051 }
2052 return true;
2053}
2054
2055/// Try to optimize a compare instruction. A compare instruction is an
2056/// instruction which produces AArch64::NZCV. It can be truly compare
2057/// instruction
2058/// when there are no uses of its destination register.
2059///
2060/// The following steps are tried in order:
2061/// 1. Convert CmpInstr into an unconditional version.
2062/// 2. Remove CmpInstr if above there is an instruction producing a needed
2063/// condition code or an instruction which can be converted into such an
2064/// instruction.
2065/// Only comparison with zero is supported.
2067 MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
2068 int64_t CmpValue, const MachineRegisterInfo *MRI) const {
2069 assert(CmpInstr.getParent());
2070 assert(MRI);
2071
2072 // Replace SUBSWrr with SUBWrr if NZCV is not used.
2073 int DeadNZCVIdx =
2074 CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
2075 if (DeadNZCVIdx != -1) {
2076 if (CmpInstr.definesRegister(AArch64::WZR, /*TRI=*/nullptr) ||
2077 CmpInstr.definesRegister(AArch64::XZR, /*TRI=*/nullptr)) {
2078 CmpInstr.eraseFromParent();
2079 return true;
2080 }
2081 unsigned Opc = CmpInstr.getOpcode();
2082 unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
2083 if (NewOpc == Opc)
2084 return false;
2085 const MCInstrDesc &MCID = get(NewOpc);
2086 CmpInstr.setDesc(MCID);
2087 CmpInstr.removeOperand(DeadNZCVIdx);
2088 bool succeeded = UpdateOperandRegClass(CmpInstr);
2089 (void)succeeded;
2090 assert(succeeded && "Some operands reg class are incompatible!");
2091 return true;
2092 }
2093
2094 if (CmpInstr.getOpcode() == AArch64::PTEST_PP ||
2095 CmpInstr.getOpcode() == AArch64::PTEST_PP_ANY ||
2096 CmpInstr.getOpcode() == AArch64::PTEST_PP_FIRST)
2097 return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
2098
2099 if (SrcReg2 != 0)
2100 return false;
2101
2102 // CmpInstr is a Compare instruction if destination register is not used.
2103 if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
2104 return false;
2105
2106 if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
2107 return true;
2108 return (CmpValue == 0 || CmpValue == 1) &&
2109 removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
2110}
2111
2112/// Get opcode of S version of Instr.
2113/// If Instr is S version its opcode is returned.
2114/// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
2115/// or we are not interested in it.
2116static unsigned sForm(MachineInstr &Instr) {
2117 switch (Instr.getOpcode()) {
2118 default:
2119 return AArch64::INSTRUCTION_LIST_END;
2120
2121 case AArch64::ADDSWrr:
2122 case AArch64::ADDSWri:
2123 case AArch64::ADDSXrr:
2124 case AArch64::ADDSXri:
2125 case AArch64::ADDSWrx:
2126 case AArch64::ADDSXrx:
2127 case AArch64::ADDSWrs:
2128 case AArch64::ADDSXrs:
2129 case AArch64::SUBSWrr:
2130 case AArch64::SUBSWri:
2131 case AArch64::SUBSWrx:
2132 case AArch64::SUBSWrs:
2133 case AArch64::SUBSXrr:
2134 case AArch64::SUBSXri:
2135 case AArch64::SUBSXrx:
2136 case AArch64::SUBSXrs:
2137 case AArch64::ANDSWri:
2138 case AArch64::ANDSWrr:
2139 case AArch64::ANDSWrs:
2140 case AArch64::ANDSXri:
2141 case AArch64::ANDSXrr:
2142 case AArch64::ANDSXrs:
2143 case AArch64::BICSWrr:
2144 case AArch64::BICSXrr:
2145 case AArch64::BICSWrs:
2146 case AArch64::BICSXrs:
2147 case AArch64::ADCSWr:
2148 case AArch64::ADCSXr:
2149 case AArch64::SBCSWr:
2150 case AArch64::SBCSXr:
2151 return Instr.getOpcode();
2152
2153 case AArch64::ADDWrr:
2154 return AArch64::ADDSWrr;
2155 case AArch64::ADDWri:
2156 return AArch64::ADDSWri;
2157 case AArch64::ADDXrr:
2158 return AArch64::ADDSXrr;
2159 case AArch64::ADDXri:
2160 return AArch64::ADDSXri;
2161 case AArch64::ADDWrx:
2162 return AArch64::ADDSWrx;
2163 case AArch64::ADDXrx:
2164 return AArch64::ADDSXrx;
2165 case AArch64::ADDWrs:
2166 return AArch64::ADDSWrs;
2167 case AArch64::ADDXrs:
2168 return AArch64::ADDSXrs;
2169 case AArch64::ADCWr:
2170 return AArch64::ADCSWr;
2171 case AArch64::ADCXr:
2172 return AArch64::ADCSXr;
2173 case AArch64::SUBWrr:
2174 return AArch64::SUBSWrr;
2175 case AArch64::SUBWri:
2176 return AArch64::SUBSWri;
2177 case AArch64::SUBXrr:
2178 return AArch64::SUBSXrr;
2179 case AArch64::SUBXri:
2180 return AArch64::SUBSXri;
2181 case AArch64::SUBWrx:
2182 return AArch64::SUBSWrx;
2183 case AArch64::SUBXrx:
2184 return AArch64::SUBSXrx;
2185 case AArch64::SUBWrs:
2186 return AArch64::SUBSWrs;
2187 case AArch64::SUBXrs:
2188 return AArch64::SUBSXrs;
2189 case AArch64::SBCWr:
2190 return AArch64::SBCSWr;
2191 case AArch64::SBCXr:
2192 return AArch64::SBCSXr;
2193 case AArch64::ANDWri:
2194 return AArch64::ANDSWri;
2195 case AArch64::ANDXri:
2196 return AArch64::ANDSXri;
2197 case AArch64::ANDWrr:
2198 return AArch64::ANDSWrr;
2199 case AArch64::ANDWrs:
2200 return AArch64::ANDSWrs;
2201 case AArch64::ANDXrr:
2202 return AArch64::ANDSXrr;
2203 case AArch64::ANDXrs:
2204 return AArch64::ANDSXrs;
2205 case AArch64::BICWrr:
2206 return AArch64::BICSWrr;
2207 case AArch64::BICXrr:
2208 return AArch64::BICSXrr;
2209 case AArch64::BICWrs:
2210 return AArch64::BICSWrs;
2211 case AArch64::BICXrs:
2212 return AArch64::BICSXrs;
2213 }
2214}
2215
2216/// Check if AArch64::NZCV should be alive in successors of MBB.
2218 for (auto *BB : MBB->successors())
2219 if (BB->isLiveIn(AArch64::NZCV))
2220 return true;
2221 return false;
2222}
2223
2224/// \returns The condition code operand index for \p Instr if it is a branch
2225/// or select and -1 otherwise.
2226int AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(
2227 const MachineInstr &Instr) {
2228 switch (Instr.getOpcode()) {
2229 default:
2230 return -1;
2231
2232 case AArch64::Bcc: {
2233 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2234 assert(Idx >= 2);
2235 return Idx - 2;
2236 }
2237
2238 case AArch64::CSINVWr:
2239 case AArch64::CSINVXr:
2240 case AArch64::CSINCWr:
2241 case AArch64::CSINCXr:
2242 case AArch64::CSELWr:
2243 case AArch64::CSELXr:
2244 case AArch64::CSNEGWr:
2245 case AArch64::CSNEGXr:
2246 case AArch64::FCSELSrrr:
2247 case AArch64::FCSELDrrr: {
2248 int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV, /*TRI=*/nullptr);
2249 assert(Idx >= 1);
2250 return Idx - 1;
2251 }
2252 }
2253}
2254
2255/// Find a condition code used by the instruction.
2256/// Returns AArch64CC::Invalid if either the instruction does not use condition
2257/// codes or we don't optimize CmpInstr in the presence of such instructions.
2259 int CCIdx =
2260 AArch64InstrInfo::findCondCodeUseOperandIdxForBranchOrSelect(Instr);
2261 return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
2262 Instr.getOperand(CCIdx).getImm())
2264}
2265
2268 UsedNZCV UsedFlags;
2269 switch (CC) {
2270 default:
2271 break;
2272
2273 case AArch64CC::EQ: // Z set
2274 case AArch64CC::NE: // Z clear
2275 UsedFlags.Z = true;
2276 break;
2277
2278 case AArch64CC::HI: // Z clear and C set
2279 case AArch64CC::LS: // Z set or C clear
2280 UsedFlags.Z = true;
2281 [[fallthrough]];
2282 case AArch64CC::HS: // C set
2283 case AArch64CC::LO: // C clear
2284 UsedFlags.C = true;
2285 break;
2286
2287 case AArch64CC::MI: // N set
2288 case AArch64CC::PL: // N clear
2289 UsedFlags.N = true;
2290 break;
2291
2292 case AArch64CC::VS: // V set
2293 case AArch64CC::VC: // V clear
2294 UsedFlags.V = true;
2295 break;
2296
2297 case AArch64CC::GT: // Z clear, N and V the same
2298 case AArch64CC::LE: // Z set, N and V differ
2299 UsedFlags.Z = true;
2300 [[fallthrough]];
2301 case AArch64CC::GE: // N and V the same
2302 case AArch64CC::LT: // N and V differ
2303 UsedFlags.N = true;
2304 UsedFlags.V = true;
2305 break;
2306 }
2307 return UsedFlags;
2308}
2309
2310/// \returns Conditions flags used after \p CmpInstr in its MachineBB if NZCV
2311/// flags are not alive in successors of the same \p CmpInstr and \p MI parent.
2312/// \returns std::nullopt otherwise.
2313///
2314/// Collect instructions using that flags in \p CCUseInstrs if provided.
2315std::optional<UsedNZCV>
2317 const TargetRegisterInfo &TRI,
2318 SmallVectorImpl<MachineInstr *> *CCUseInstrs) {
2319 MachineBasicBlock *CmpParent = CmpInstr.getParent();
2320 if (MI.getParent() != CmpParent)
2321 return std::nullopt;
2322
2323 if (areCFlagsAliveInSuccessors(CmpParent))
2324 return std::nullopt;
2325
2326 UsedNZCV NZCVUsedAfterCmp;
2328 std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
2329 if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
2331 if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
2332 return std::nullopt;
2333 NZCVUsedAfterCmp |= getUsedNZCV(CC);
2334 if (CCUseInstrs)
2335 CCUseInstrs->push_back(&Instr);
2336 }
2337 if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
2338 break;
2339 }
2340 return NZCVUsedAfterCmp;
2341}
2342
2343static bool isADDSRegImm(unsigned Opcode) {
2344 return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
2345}
2346
2347static bool isSUBSRegImm(unsigned Opcode) {
2348 return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
2349}
2350
2352 unsigned Opc = sForm(MI);
2353 switch (Opc) {
2354 case AArch64::ANDSWri:
2355 case AArch64::ANDSWrr:
2356 case AArch64::ANDSWrs:
2357 case AArch64::ANDSXri:
2358 case AArch64::ANDSXrr:
2359 case AArch64::ANDSXrs:
2360 case AArch64::BICSWrr:
2361 case AArch64::BICSXrr:
2362 case AArch64::BICSWrs:
2363 case AArch64::BICSXrs:
2364 return true;
2365 default:
2366 return false;
2367 }
2368}
2369
2370/// Check if CmpInstr can be substituted by MI.
2371///
2372/// CmpInstr can be substituted:
2373/// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2374/// - and, MI and CmpInstr are from the same MachineBB
2375/// - and, condition flags are not alive in successors of the CmpInstr parent
2376/// - and, if MI opcode is the S form there must be no defs of flags between
2377/// MI and CmpInstr
2378/// or if MI opcode is not the S form there must be neither defs of flags
2379/// nor uses of flags between MI and CmpInstr.
2380/// - and, C is not used after CmpInstr; CmpInstr's C is from adds/subs #0 on
2381/// SrcReg and can differ from MI (e.g. carry out of ADCS/SBCS).
2382/// - and, V is not used after CmpInstr unless MI is AND/BIC (V cleared) or MI
2383/// has NoSWrap (overflow is poison and the fold is still safe).
2385 const TargetRegisterInfo &TRI) {
2386 // MI is an opcode sForm maps (add/sub/adc/sbc/and/bic and their S forms).
2387 assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
2388
2389 const unsigned CmpOpcode = CmpInstr.getOpcode();
2390 if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
2391 return false;
2392
2393 assert((CmpInstr.getOperand(2).isImm() &&
2394 CmpInstr.getOperand(2).getImm() == 0) &&
2395 "Caller guarantees that CmpInstr compares with constant 0");
2396
2397 std::optional<UsedNZCV> NZVCUsed = examineCFlagsUse(MI, CmpInstr, TRI);
2398 if (!NZVCUsed || NZVCUsed->C)
2399 return false;
2400
2401 // CmpInstr is ADDS/SUBS with immediate 0 on SrcReg (compare SrcReg to zero).
2402 // After the fold, users see NZCV from MI (or its S form), not from CmpInstr.
2403 // N/Z match CmpInstr for the value in SrcReg; C/V need not match in general
2404 // (e.g. ADCS vs adds #0), so we require C unused after CmpInstr and gate V
2405 // as below. NoSWrap makes signed overflow poison; AND/BIC clear V.
2406 if (NZVCUsed->V && !MI.getFlag(MachineInstr::NoSWrap) && !isANDOpcode(MI))
2407 return false;
2408
2409 AccessKind AccessToCheck = AK_Write;
2410 if (sForm(MI) != MI.getOpcode())
2411 AccessToCheck = AK_All;
2412 return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
2413}
2414
2415/// Substitute an instruction comparing to zero with another instruction
2416/// which produces needed condition flags.
2417///
2418/// Return true on success.
2419bool AArch64InstrInfo::substituteCmpToZero(
2420 MachineInstr &CmpInstr, unsigned SrcReg,
2421 const MachineRegisterInfo &MRI) const {
2422 // Get the unique definition of SrcReg.
2423 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2424 if (!MI)
2425 return false;
2426
2427 const TargetRegisterInfo &TRI = getRegisterInfo();
2428
2429 unsigned NewOpc = sForm(*MI);
2430 if (NewOpc == AArch64::INSTRUCTION_LIST_END)
2431 return false;
2432
2433 if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
2434 return false;
2435
2436 // Update the instruction to set NZCV.
2437 MI->setDesc(get(NewOpc));
2438 CmpInstr.eraseFromParent();
2440 (void)succeeded;
2441 assert(succeeded && "Some operands reg class are incompatible!");
2442 MI->addRegisterDefined(AArch64::NZCV, &TRI);
2443 return true;
2444}
2445
2446/// \returns True if \p CmpInstr can be removed.
2447///
2448/// \p IsInvertCC is true if, after removing \p CmpInstr, condition
2449/// codes used in \p CCUseInstrs must be inverted.
2451 int CmpValue, const TargetRegisterInfo &TRI,
2453 bool &IsInvertCC) {
2454 assert((CmpValue == 0 || CmpValue == 1) &&
2455 "Only comparisons to 0 or 1 considered for removal!");
2456
2457 // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
2458 unsigned MIOpc = MI.getOpcode();
2459 if (MIOpc == AArch64::CSINCWr) {
2460 if (MI.getOperand(1).getReg() != AArch64::WZR ||
2461 MI.getOperand(2).getReg() != AArch64::WZR)
2462 return false;
2463 } else if (MIOpc == AArch64::CSINCXr) {
2464 if (MI.getOperand(1).getReg() != AArch64::XZR ||
2465 MI.getOperand(2).getReg() != AArch64::XZR)
2466 return false;
2467 } else {
2468 return false;
2469 }
2471 if (MICC == AArch64CC::Invalid)
2472 return false;
2473
2474 // NZCV needs to be defined
2475 if (MI.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) != -1)
2476 return false;
2477
2478 // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
2479 const unsigned CmpOpcode = CmpInstr.getOpcode();
2480 bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
2481 if (CmpValue && !IsSubsRegImm)
2482 return false;
2483 if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
2484 return false;
2485
2486 // MI conditions allowed: eq, ne, mi, pl
2487 UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
2488 if (MIUsedNZCV.C || MIUsedNZCV.V)
2489 return false;
2490
2491 std::optional<UsedNZCV> NZCVUsedAfterCmp =
2492 examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
2493 // Condition flags are not used in CmpInstr basic block successors and only
2494 // Z or N flags allowed to be used after CmpInstr within its basic block
2495 if (!NZCVUsedAfterCmp || NZCVUsedAfterCmp->C || NZCVUsedAfterCmp->V)
2496 return false;
2497 // Z or N flag used after CmpInstr must correspond to the flag used in MI
2498 if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
2499 (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
2500 return false;
2501 // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
2502 if (MIUsedNZCV.N && !CmpValue)
2503 return false;
2504
2505 // There must be no defs of flags between MI and CmpInstr
2506 if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
2507 return false;
2508
2509 // Condition code is inverted in the following cases:
2510 // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
2511 // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
2512 IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
2513 (!CmpValue && MICC == AArch64CC::NE);
2514 return true;
2515}
2516
2517/// Remove comparison in csinc-cmp sequence
2518///
2519/// Examples:
2520/// 1. \code
2521/// csinc w9, wzr, wzr, ne
2522/// cmp w9, #0
2523/// b.eq
2524/// \endcode
2525/// to
2526/// \code
2527/// csinc w9, wzr, wzr, ne
2528/// b.ne
2529/// \endcode
2530///
2531/// 2. \code
2532/// csinc x2, xzr, xzr, mi
2533/// cmp x2, #1
2534/// b.pl
2535/// \endcode
2536/// to
2537/// \code
2538/// csinc x2, xzr, xzr, mi
2539/// b.pl
2540/// \endcode
2541///
2542/// \param CmpInstr comparison instruction
2543/// \return True when comparison removed
2544bool AArch64InstrInfo::removeCmpToZeroOrOne(
2545 MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
2546 const MachineRegisterInfo &MRI) const {
2547 MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
2548 if (!MI)
2549 return false;
2550 const TargetRegisterInfo &TRI = getRegisterInfo();
2551 SmallVector<MachineInstr *, 4> CCUseInstrs;
2552 bool IsInvertCC = false;
2553 if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
2554 IsInvertCC))
2555 return false;
2556 // Make transformation
2557 CmpInstr.eraseFromParent();
2558 if (IsInvertCC) {
2559 // Invert condition codes in CmpInstr CC users
2560 for (MachineInstr *CCUseInstr : CCUseInstrs) {
2561 int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
2562 assert(Idx >= 0 && "Unexpected instruction using CC.");
2563 MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
2565 static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
2566 CCOperand.setImm(CCUse);
2567 }
2568 }
2569 return true;
2570}
2571
2572bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
2573 if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
2574 MI.getOpcode() != AArch64::CATCHRET &&
2575 MI.getOpcode() != AArch64::STACK_GUARD_UNMIX)
2576 return false;
2577
2578 MachineBasicBlock &MBB = *MI.getParent();
2579 auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
2580 auto TRI = Subtarget.getRegisterInfo();
2581 DebugLoc DL = MI.getDebugLoc();
2582
2583 if (MI.getOpcode() == AArch64::STACK_GUARD_UNMIX) {
2584 // Expand STACK_GUARD_UNMIX to: sub Rd, fp, Rs
2585 // This computes FP - stored_mixed_value to unmix the cookie
2586 Register DstReg = MI.getOperand(0).getReg();
2587 Register SrcReg = MI.getOperand(1).getReg();
2588
2589 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), DstReg)
2590 .addReg(AArch64::FP)
2591 .addReg(SrcReg);
2592
2593 MBB.erase(MI);
2594 return true;
2595 }
2596
2597 if (MI.getOpcode() == AArch64::CATCHRET) {
2598 // Skip to the first instruction before the epilog.
2599 const TargetInstrInfo *TII =
2601 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
2603 MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
2604 while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
2605 FirstEpilogSEH != MBB.begin())
2606 FirstEpilogSEH = std::prev(FirstEpilogSEH);
2607 if (FirstEpilogSEH != MBB.begin())
2608 FirstEpilogSEH = std::next(FirstEpilogSEH);
2609 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
2610 .addReg(AArch64::X0, RegState::Define)
2611 .addMBB(TargetMBB, AArch64II::MO_PAGE);
2612 BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
2613 .addReg(AArch64::X0, RegState::Define)
2614 .addReg(AArch64::X0)
2616 .addImm(0);
2617 TargetMBB->setMachineBlockAddressTaken();
2618 return true;
2619 }
2620
2621 Register Reg = MI.getOperand(0).getReg();
2623 if (M.getStackProtectorGuard() == "sysreg") {
2624 const AArch64SysReg::SysReg *SrcReg =
2625 AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
2626 if (!SrcReg)
2627 report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
2628
2629 // mrs xN, sysreg
2630 BuildMI(MBB, MI, DL, get(AArch64::MRS))
2632 .addImm(SrcReg->Encoding);
2633 int Offset = M.getStackProtectorGuardOffset();
2634 if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
2635 // ldr xN, [xN, #offset]
2636 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2637 .addDef(Reg)
2639 .addImm(Offset / 8);
2640 } else if (Offset >= -256 && Offset <= 255) {
2641 // ldur xN, [xN, #offset]
2642 BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
2643 .addDef(Reg)
2645 .addImm(Offset);
2646 } else if (Offset >= -4095 && Offset <= 4095) {
2647 if (Offset > 0) {
2648 // add xN, xN, #offset
2649 BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
2650 .addDef(Reg)
2652 .addImm(Offset)
2653 .addImm(0);
2654 } else {
2655 // sub xN, xN, #offset
2656 BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
2657 .addDef(Reg)
2659 .addImm(-Offset)
2660 .addImm(0);
2661 }
2662 // ldr xN, [xN]
2663 BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
2664 .addDef(Reg)
2666 .addImm(0);
2667 } else {
2668 // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
2669 // than 23760.
2670 // It might be nice to use AArch64::MOVi32imm here, which would get
2671 // expanded in PreSched2 after PostRA, but our lone scratch Reg already
2672 // contains the MRS result. findScratchNonCalleeSaveRegister() in
2673 // AArch64FrameLowering might help us find such a scratch register
2674 // though. If we failed to find a scratch register, we could emit a
2675 // stream of add instructions to build up the immediate. Or, we could try
2676 // to insert a AArch64::MOVi32imm before register allocation so that we
2677 // didn't need to scavenge for a scratch register.
2678 report_fatal_error("Unable to encode Stack Protector Guard Offset");
2679 }
2680 MBB.erase(MI);
2681 return true;
2682 }
2683
2684 const GlobalValue *GV =
2685 cast<GlobalValue>((*MI.memoperands_begin())->getValue());
2686 const TargetMachine &TM = MBB.getParent()->getTarget();
2687 unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
2688 const unsigned char MO_NC = AArch64II::MO_NC;
2689
2690 unsigned GuardWidth = M.getStackProtectorGuardValueWidth().value_or(
2691 Subtarget.isTargetILP32() ? 4 : 8);
2692 if (GuardWidth != 4 && GuardWidth != 8)
2693 report_fatal_error("Unsupported stack protector value width");
2694 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2695 BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
2696 .addGlobalAddress(GV, 0, OpFlags);
2697 if (GuardWidth == 4) {
2698 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2699 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2700 .addDef(Reg32, RegState::Dead)
2702 .addImm(0)
2703 .addMemOperand(*MI.memoperands_begin())
2705 } else {
2706 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2708 .addImm(0)
2709 .addMemOperand(*MI.memoperands_begin());
2710 }
2711 } else if (TM.getCodeModel() == CodeModel::Large) {
2712 BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
2713 .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
2714 .addImm(0);
2715 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2717 .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
2718 .addImm(16);
2719 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2721 .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
2722 .addImm(32);
2723 BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
2726 .addImm(48);
2727 if (GuardWidth == 4) {
2728 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2729 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2730 .addDef(Reg32, RegState::Dead)
2732 .addImm(0)
2733 .addMemOperand(*MI.memoperands_begin())
2735 } else {
2736 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2738 .addImm(0)
2739 .addMemOperand(*MI.memoperands_begin());
2740 }
2741 } else {
2742 BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
2743 .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
2744 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2745 if (GuardWidth == 4) {
2746 unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2747 BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2748 .addDef(Reg32, RegState::Dead)
2750 .addGlobalAddress(GV, 0, LoFlags)
2751 .addMemOperand(*MI.memoperands_begin())
2753 } else {
2754 BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2756 .addGlobalAddress(GV, 0, LoFlags)
2757 .addMemOperand(*MI.memoperands_begin());
2758 }
2759 }
2760 // To match MSVC. Unlike x86_64 which uses xor instruction to mix the cookie,
2761 // we use sub instruction to mix the cookie on aarch64.
2762 // The mixing happens here in expandPostRAPseudo (after RA) to ensure we use
2763 // the final frame pointer value.
2764 if (Subtarget.getTargetTriple().isOSMSVCRT())
2765 BuildMI(MBB, MI, DL, get(AArch64::SUBXrr), Reg)
2766 .addReg(AArch64::FP)
2768
2769 MBB.erase(MI);
2770
2771 return true;
2772}
2773
2774// Return true if this instruction simply sets its single destination register
2775// to zero. This is equivalent to a register rename of the zero-register.
2777 switch (MI.getOpcode()) {
2778 default:
2779 break;
2780 case AArch64::MOVZWi:
2781 case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2782 if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2783 assert(MI.getDesc().getNumOperands() == 3 &&
2784 MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2785 return true;
2786 }
2787 break;
2788 case AArch64::ANDWri: // and Rd, Rzr, #imm
2789 return MI.getOperand(1).getReg() == AArch64::WZR;
2790 case AArch64::ANDXri:
2791 return MI.getOperand(1).getReg() == AArch64::XZR;
2792 case TargetOpcode::COPY:
2793 return MI.getOperand(1).getReg() == AArch64::WZR;
2794 }
2795 return false;
2796}
2797
2798// Return true if this instruction simply renames a general register without
2799// modifying bits.
2801 switch (MI.getOpcode()) {
2802 default:
2803 break;
2804 case TargetOpcode::COPY: {
2805 // GPR32 copies will by lowered to ORRXrs
2806 Register DstReg = MI.getOperand(0).getReg();
2807 return (AArch64::GPR32RegClass.contains(DstReg) ||
2808 AArch64::GPR64RegClass.contains(DstReg));
2809 }
2810 case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2811 if (MI.getOperand(1).getReg() == AArch64::XZR) {
2812 assert(MI.getDesc().getNumOperands() == 4 &&
2813 MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2814 return true;
2815 }
2816 break;
2817 case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2818 if (MI.getOperand(2).getImm() == 0) {
2819 assert(MI.getDesc().getNumOperands() == 4 &&
2820 MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2821 return true;
2822 }
2823 break;
2824 }
2825 return false;
2826}
2827
2828// Return true if this instruction simply renames a general register without
2829// modifying bits.
2831 switch (MI.getOpcode()) {
2832 default:
2833 break;
2834 case TargetOpcode::COPY: {
2835 Register DstReg = MI.getOperand(0).getReg();
2836 return AArch64::FPR128RegClass.contains(DstReg);
2837 }
2838 case AArch64::ORRv16i8:
2839 if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2840 assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2841 "invalid ORRv16i8 operands");
2842 return true;
2843 }
2844 break;
2845 }
2846 return false;
2847}
2848
2849static bool isFrameLoadOpcode(int Opcode) {
2850 switch (Opcode) {
2851 default:
2852 return false;
2853 case AArch64::LDRWui:
2854 case AArch64::LDRXui:
2855 case AArch64::LDRBui:
2856 case AArch64::LDRHui:
2857 case AArch64::LDRSui:
2858 case AArch64::LDRDui:
2859 case AArch64::LDRQui:
2860 case AArch64::LDR_PXI:
2861 return true;
2862 }
2863}
2864
2866 int &FrameIndex) const {
2867 if (!isFrameLoadOpcode(MI.getOpcode()))
2868 return Register();
2869
2870 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2871 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2872 FrameIndex = MI.getOperand(1).getIndex();
2873 return MI.getOperand(0).getReg();
2874 }
2875 return Register();
2876}
2877
2878static bool isFrameStoreOpcode(int Opcode) {
2879 switch (Opcode) {
2880 default:
2881 return false;
2882 case AArch64::STRWui:
2883 case AArch64::STRXui:
2884 case AArch64::STRBui:
2885 case AArch64::STRHui:
2886 case AArch64::STRSui:
2887 case AArch64::STRDui:
2888 case AArch64::STRQui:
2889 case AArch64::STR_PXI:
2890 return true;
2891 }
2892}
2893
2895 int &FrameIndex) const {
2896 if (!isFrameStoreOpcode(MI.getOpcode()))
2897 return Register();
2898
2899 if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2900 MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2901 FrameIndex = MI.getOperand(1).getIndex();
2902 return MI.getOperand(0).getReg();
2903 }
2904 return Register();
2905}
2906
2908 int &FrameIndex) const {
2909 if (!isFrameStoreOpcode(MI.getOpcode()))
2910 return Register();
2911
2912 if (Register Reg = isStoreToStackSlot(MI, FrameIndex))
2913 return Reg;
2914
2916 if (hasStoreToStackSlot(MI, Accesses)) {
2917 if (Accesses.size() > 1)
2918 return Register();
2919
2920 FrameIndex =
2921 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2922 ->getFrameIndex();
2923 return MI.getOperand(0).getReg();
2924 }
2925 return Register();
2926}
2927
2929 int &FrameIndex) const {
2930 if (!isFrameLoadOpcode(MI.getOpcode()))
2931 return Register();
2932
2933 if (Register Reg = isLoadFromStackSlot(MI, FrameIndex))
2934 return Reg;
2935
2937 if (hasLoadFromStackSlot(MI, Accesses)) {
2938 if (Accesses.size() > 1)
2939 return Register();
2940
2941 FrameIndex =
2942 cast<FixedStackPseudoSourceValue>(Accesses.front()->getPseudoValue())
2943 ->getFrameIndex();
2944 return MI.getOperand(0).getReg();
2945 }
2946 return Register();
2947}
2948
2949/// Check all MachineMemOperands for a hint to suppress pairing.
2951 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2952 return MMO->getFlags() & MOSuppressPair;
2953 });
2954}
2955
2956/// Set a flag on the first MachineMemOperand to suppress pairing.
2958 if (MI.memoperands_empty())
2959 return;
2960 (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2961}
2962
2963/// Check all MachineMemOperands for a hint that the load/store is strided.
2965 return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2966 return MMO->getFlags() & MOStridedAccess;
2967 });
2968}
2969
2971 switch (Opc) {
2972 default:
2973 return false;
2974 case AArch64::STURSi:
2975 case AArch64::STRSpre:
2976 case AArch64::STURDi:
2977 case AArch64::STRDpre:
2978 case AArch64::STURQi:
2979 case AArch64::STRQpre:
2980 case AArch64::STURBBi:
2981 case AArch64::STURHHi:
2982 case AArch64::STURWi:
2983 case AArch64::STRWpre:
2984 case AArch64::STURXi:
2985 case AArch64::STRXpre:
2986 case AArch64::LDURSi:
2987 case AArch64::LDRSpre:
2988 case AArch64::LDURDi:
2989 case AArch64::LDRDpre:
2990 case AArch64::LDURQi:
2991 case AArch64::LDRQpre:
2992 case AArch64::LDURWi:
2993 case AArch64::LDRWpre:
2994 case AArch64::LDURXi:
2995 case AArch64::LDRXpre:
2996 case AArch64::LDRSWpre:
2997 case AArch64::LDURSWi:
2998 case AArch64::LDURHHi:
2999 case AArch64::LDURBBi:
3000 case AArch64::LDURSBWi:
3001 case AArch64::LDURSHWi:
3002 return true;
3003 }
3004}
3005
3006std::optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
3007 switch (Opc) {
3008 default: return {};
3009 case AArch64::PRFMui: return AArch64::PRFUMi;
3010 case AArch64::LDRXui: return AArch64::LDURXi;
3011 case AArch64::LDRWui: return AArch64::LDURWi;
3012 case AArch64::LDRBui: return AArch64::LDURBi;
3013 case AArch64::LDRHui: return AArch64::LDURHi;
3014 case AArch64::LDRSui: return AArch64::LDURSi;
3015 case AArch64::LDRDui: return AArch64::LDURDi;
3016 case AArch64::LDRQui: return AArch64::LDURQi;
3017 case AArch64::LDRBBui: return AArch64::LDURBBi;
3018 case AArch64::LDRHHui: return AArch64::LDURHHi;
3019 case AArch64::LDRSBXui: return AArch64::LDURSBXi;
3020 case AArch64::LDRSBWui: return AArch64::LDURSBWi;
3021 case AArch64::LDRSHXui: return AArch64::LDURSHXi;
3022 case AArch64::LDRSHWui: return AArch64::LDURSHWi;
3023 case AArch64::LDRSWui: return AArch64::LDURSWi;
3024 case AArch64::STRXui: return AArch64::STURXi;
3025 case AArch64::STRWui: return AArch64::STURWi;
3026 case AArch64::STRBui: return AArch64::STURBi;
3027 case AArch64::STRHui: return AArch64::STURHi;
3028 case AArch64::STRSui: return AArch64::STURSi;
3029 case AArch64::STRDui: return AArch64::STURDi;
3030 case AArch64::STRQui: return AArch64::STURQi;
3031 case AArch64::STRBBui: return AArch64::STURBBi;
3032 case AArch64::STRHHui: return AArch64::STURHHi;
3033 }
3034}
3035
3037 switch (Opc) {
3038 default:
3039 llvm_unreachable("Unhandled Opcode in getLoadStoreImmIdx");
3040 case AArch64::ADDG:
3041 case AArch64::LDAPURBi:
3042 case AArch64::LDAPURHi:
3043 case AArch64::LDAPURi:
3044 case AArch64::LDAPURSBWi:
3045 case AArch64::LDAPURSBXi:
3046 case AArch64::LDAPURSHWi:
3047 case AArch64::LDAPURSHXi:
3048 case AArch64::LDAPURSWi:
3049 case AArch64::LDAPURXi:
3050 case AArch64::LDR_PPXI:
3051 case AArch64::LDR_PXI:
3052 case AArch64::LDR_ZXI:
3053 case AArch64::LDR_ZZXI:
3054 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
3055 case AArch64::LDR_ZZZXI:
3056 case AArch64::LDR_ZZZZXI:
3057 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
3058 case AArch64::LDRBBui:
3059 case AArch64::LDRBui:
3060 case AArch64::LDRDui:
3061 case AArch64::LDRHHui:
3062 case AArch64::LDRHui:
3063 case AArch64::LDRQui:
3064 case AArch64::LDRSBWui:
3065 case AArch64::LDRSBXui:
3066 case AArch64::LDRSHWui:
3067 case AArch64::LDRSHXui:
3068 case AArch64::LDRSui:
3069 case AArch64::LDRSWui:
3070 case AArch64::LDRWui:
3071 case AArch64::LDRXui:
3072 case AArch64::LDURBBi:
3073 case AArch64::LDURBi:
3074 case AArch64::LDURDi:
3075 case AArch64::LDURHHi:
3076 case AArch64::LDURHi:
3077 case AArch64::LDURQi:
3078 case AArch64::LDURSBWi:
3079 case AArch64::LDURSBXi:
3080 case AArch64::LDURSHWi:
3081 case AArch64::LDURSHXi:
3082 case AArch64::LDURSi:
3083 case AArch64::LDURSWi:
3084 case AArch64::LDURWi:
3085 case AArch64::LDURXi:
3086 case AArch64::PRFMui:
3087 case AArch64::PRFUMi:
3088 case AArch64::ST2Gi:
3089 case AArch64::STGi:
3090 case AArch64::STLURBi:
3091 case AArch64::STLURHi:
3092 case AArch64::STLURWi:
3093 case AArch64::STLURXi:
3094 case AArch64::StoreSwiftAsyncContext:
3095 case AArch64::STR_PPXI:
3096 case AArch64::STR_PXI:
3097 case AArch64::STR_ZXI:
3098 case AArch64::STR_ZZXI:
3099 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
3100 case AArch64::STR_ZZZXI:
3101 case AArch64::STR_ZZZZXI:
3102 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
3103 case AArch64::STRBBui:
3104 case AArch64::STRBui:
3105 case AArch64::STRDui:
3106 case AArch64::STRHHui:
3107 case AArch64::STRHui:
3108 case AArch64::STRQui:
3109 case AArch64::STRSui:
3110 case AArch64::STRWui:
3111 case AArch64::STRXui:
3112 case AArch64::STURBBi:
3113 case AArch64::STURBi:
3114 case AArch64::STURDi:
3115 case AArch64::STURHHi:
3116 case AArch64::STURHi:
3117 case AArch64::STURQi:
3118 case AArch64::STURSi:
3119 case AArch64::STURWi:
3120 case AArch64::STURXi:
3121 case AArch64::STZ2Gi:
3122 case AArch64::STZGi:
3123 case AArch64::TAGPstack:
3124 case AArch64::ATOMIC_STORE_HINT_Bi:
3125 case AArch64::ATOMIC_STORE_HINT_Hi:
3126 case AArch64::ATOMIC_STORE_HINT_Wi:
3127 case AArch64::ATOMIC_STORE_HINT_Si:
3128 case AArch64::ATOMIC_STORE_HINT_Xi:
3129 case AArch64::ATOMIC_STORE_HINT_Di:
3130 case AArch64::ATOMIC_STORE_HINT_Bui:
3131 case AArch64::ATOMIC_STORE_HINT_Hui:
3132 case AArch64::ATOMIC_STORE_HINT_Wui:
3133 case AArch64::ATOMIC_STORE_HINT_Sui:
3134 case AArch64::ATOMIC_STORE_HINT_Xui:
3135 case AArch64::ATOMIC_STORE_HINT_Dui:
3136 return 2;
3137 case AArch64::LD1B_D_IMM:
3138 case AArch64::LD1B_H_IMM:
3139 case AArch64::LD1B_IMM:
3140 case AArch64::LD1B_S_IMM:
3141 case AArch64::LD1D_IMM:
3142 case AArch64::LD1H_D_IMM:
3143 case AArch64::LD1H_IMM:
3144 case AArch64::LD1H_S_IMM:
3145 case AArch64::LD1RB_D_IMM:
3146 case AArch64::LD1RB_H_IMM:
3147 case AArch64::LD1RB_IMM:
3148 case AArch64::LD1RB_S_IMM:
3149 case AArch64::LD1RD_IMM:
3150 case AArch64::LD1RH_D_IMM:
3151 case AArch64::LD1RH_IMM:
3152 case AArch64::LD1RH_S_IMM:
3153 case AArch64::LD1RSB_D_IMM:
3154 case AArch64::LD1RSB_H_IMM:
3155 case AArch64::LD1RSB_S_IMM:
3156 case AArch64::LD1RSH_D_IMM:
3157 case AArch64::LD1RSH_S_IMM:
3158 case AArch64::LD1RSW_IMM:
3159 case AArch64::LD1RW_D_IMM:
3160 case AArch64::LD1RW_IMM:
3161 case AArch64::LD1SB_D_IMM:
3162 case AArch64::LD1SB_H_IMM:
3163 case AArch64::LD1SB_S_IMM:
3164 case AArch64::LD1SH_D_IMM:
3165 case AArch64::LD1SH_S_IMM:
3166 case AArch64::LD1SW_D_IMM:
3167 case AArch64::LD1W_D_IMM:
3168 case AArch64::LD1W_IMM:
3169 case AArch64::LD2B_IMM:
3170 case AArch64::LD2D_IMM:
3171 case AArch64::LD2H_IMM:
3172 case AArch64::LD2W_IMM:
3173 case AArch64::LD3B_IMM:
3174 case AArch64::LD3D_IMM:
3175 case AArch64::LD3H_IMM:
3176 case AArch64::LD3W_IMM:
3177 case AArch64::LD4B_IMM:
3178 case AArch64::LD4D_IMM:
3179 case AArch64::LD4H_IMM:
3180 case AArch64::LD4W_IMM:
3181 case AArch64::LDG:
3182 case AArch64::LDNF1B_D_IMM:
3183 case AArch64::LDNF1B_H_IMM:
3184 case AArch64::LDNF1B_IMM:
3185 case AArch64::LDNF1B_S_IMM:
3186 case AArch64::LDNF1D_IMM:
3187 case AArch64::LDNF1H_D_IMM:
3188 case AArch64::LDNF1H_IMM:
3189 case AArch64::LDNF1H_S_IMM:
3190 case AArch64::LDNF1SB_D_IMM:
3191 case AArch64::LDNF1SB_H_IMM:
3192 case AArch64::LDNF1SB_S_IMM:
3193 case AArch64::LDNF1SH_D_IMM:
3194 case AArch64::LDNF1SH_S_IMM:
3195 case AArch64::LDNF1SW_D_IMM:
3196 case AArch64::LDNF1W_D_IMM:
3197 case AArch64::LDNF1W_IMM:
3198 case AArch64::LDNPDi:
3199 case AArch64::LDNPQi:
3200 case AArch64::LDNPSi:
3201 case AArch64::LDNPWi:
3202 case AArch64::LDNPXi:
3203 case AArch64::LDNT1B_ZRI:
3204 case AArch64::LDNT1D_ZRI:
3205 case AArch64::LDNT1H_ZRI:
3206 case AArch64::LDNT1W_ZRI:
3207 case AArch64::LDPDi:
3208 case AArch64::LDPQi:
3209 case AArch64::LDPSi:
3210 case AArch64::LDPWi:
3211 case AArch64::LDPXi:
3212 case AArch64::LDRBBpost:
3213 case AArch64::LDRBBpre:
3214 case AArch64::LDRBpost:
3215 case AArch64::LDRBpre:
3216 case AArch64::LDRDpost:
3217 case AArch64::LDRDpre:
3218 case AArch64::LDRHHpost:
3219 case AArch64::LDRHHpre:
3220 case AArch64::LDRHpost:
3221 case AArch64::LDRHpre:
3222 case AArch64::LDRQpost:
3223 case AArch64::LDRQpre:
3224 case AArch64::LDRSpost:
3225 case AArch64::LDRSpre:
3226 case AArch64::LDRWpost:
3227 case AArch64::LDRWpre:
3228 case AArch64::LDRXpost:
3229 case AArch64::LDRXpre:
3230 case AArch64::ST1B_D_IMM:
3231 case AArch64::ST1B_H_IMM:
3232 case AArch64::ST1B_IMM:
3233 case AArch64::ST1B_S_IMM:
3234 case AArch64::ST1D_IMM:
3235 case AArch64::ST1H_D_IMM:
3236 case AArch64::ST1H_IMM:
3237 case AArch64::ST1H_S_IMM:
3238 case AArch64::ST1W_D_IMM:
3239 case AArch64::ST1W_IMM:
3240 case AArch64::ST2B_IMM:
3241 case AArch64::ST2D_IMM:
3242 case AArch64::ST2H_IMM:
3243 case AArch64::ST2W_IMM:
3244 case AArch64::ST3B_IMM:
3245 case AArch64::ST3D_IMM:
3246 case AArch64::ST3H_IMM:
3247 case AArch64::ST3W_IMM:
3248 case AArch64::ST4B_IMM:
3249 case AArch64::ST4D_IMM:
3250 case AArch64::ST4H_IMM:
3251 case AArch64::ST4W_IMM:
3252 case AArch64::STGPi:
3253 case AArch64::STGPreIndex:
3254 case AArch64::STZGPreIndex:
3255 case AArch64::ST2GPreIndex:
3256 case AArch64::STZ2GPreIndex:
3257 case AArch64::STGPostIndex:
3258 case AArch64::STZGPostIndex:
3259 case AArch64::ST2GPostIndex:
3260 case AArch64::STZ2GPostIndex:
3261 case AArch64::STNPDi:
3262 case AArch64::STNPQi:
3263 case AArch64::STNPSi:
3264 case AArch64::STNPWi:
3265 case AArch64::STNPXi:
3266 case AArch64::STNT1B_ZRI:
3267 case AArch64::STNT1D_ZRI:
3268 case AArch64::STNT1H_ZRI:
3269 case AArch64::STNT1W_ZRI:
3270 case AArch64::STPDi:
3271 case AArch64::STPQi:
3272 case AArch64::STPSi:
3273 case AArch64::STPWi:
3274 case AArch64::STPXi:
3275 case AArch64::STRBBpost:
3276 case AArch64::STRBBpre:
3277 case AArch64::STRBpost:
3278 case AArch64::STRBpre:
3279 case AArch64::STRDpost:
3280 case AArch64::STRDpre:
3281 case AArch64::STRHHpost:
3282 case AArch64::STRHHpre:
3283 case AArch64::STRHpost:
3284 case AArch64::STRHpre:
3285 case AArch64::STRQpost:
3286 case AArch64::STRQpre:
3287 case AArch64::STRSpost:
3288 case AArch64::STRSpre:
3289 case AArch64::STRWpost:
3290 case AArch64::STRWpre:
3291 case AArch64::STRXpost:
3292 case AArch64::STRXpre:
3293 case AArch64::LD1B_2Z_IMM:
3294 case AArch64::LD1B_2Z_STRIDED_IMM:
3295 case AArch64::LD1H_2Z_IMM:
3296 case AArch64::LD1H_2Z_STRIDED_IMM:
3297 case AArch64::LD1W_2Z_IMM:
3298 case AArch64::LD1W_2Z_STRIDED_IMM:
3299 case AArch64::LD1D_2Z_IMM:
3300 case AArch64::LD1D_2Z_STRIDED_IMM:
3301 case AArch64::LD1B_4Z_IMM:
3302 case AArch64::LD1B_4Z_STRIDED_IMM:
3303 case AArch64::LD1H_4Z_IMM:
3304 case AArch64::LD1H_4Z_STRIDED_IMM:
3305 case AArch64::LD1W_4Z_IMM:
3306 case AArch64::LD1W_4Z_STRIDED_IMM:
3307 case AArch64::LD1D_4Z_IMM:
3308 case AArch64::LD1D_4Z_STRIDED_IMM:
3309 case AArch64::LD1B_2Z_IMM_PSEUDO:
3310 case AArch64::LD1H_2Z_IMM_PSEUDO:
3311 case AArch64::LD1W_2Z_IMM_PSEUDO:
3312 case AArch64::LD1D_2Z_IMM_PSEUDO:
3313 case AArch64::LD1B_4Z_IMM_PSEUDO:
3314 case AArch64::LD1H_4Z_IMM_PSEUDO:
3315 case AArch64::LD1W_4Z_IMM_PSEUDO:
3316 case AArch64::LD1D_4Z_IMM_PSEUDO:
3317 case AArch64::ST1B_2Z_IMM:
3318 case AArch64::ST1B_2Z_STRIDED_IMM:
3319 case AArch64::ST1H_2Z_IMM:
3320 case AArch64::ST1H_2Z_STRIDED_IMM:
3321 case AArch64::ST1W_2Z_IMM:
3322 case AArch64::ST1W_2Z_STRIDED_IMM:
3323 case AArch64::ST1D_2Z_IMM:
3324 case AArch64::ST1D_2Z_STRIDED_IMM:
3325 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
3326 case AArch64::LDNT1B_2Z_IMM:
3327 case AArch64::LDNT1B_2Z_STRIDED_IMM:
3328 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
3329 case AArch64::LDNT1H_2Z_IMM:
3330 case AArch64::LDNT1H_2Z_STRIDED_IMM:
3331 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
3332 case AArch64::LDNT1W_2Z_IMM:
3333 case AArch64::LDNT1W_2Z_STRIDED_IMM:
3334 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
3335 case AArch64::LDNT1D_2Z_IMM:
3336 case AArch64::LDNT1D_2Z_STRIDED_IMM:
3337 case AArch64::STNT1B_2Z_IMM:
3338 case AArch64::STNT1B_2Z_STRIDED_IMM:
3339 case AArch64::STNT1H_2Z_IMM:
3340 case AArch64::STNT1H_2Z_STRIDED_IMM:
3341 case AArch64::STNT1W_2Z_IMM:
3342 case AArch64::STNT1W_2Z_STRIDED_IMM:
3343 case AArch64::STNT1D_2Z_IMM:
3344 case AArch64::STNT1D_2Z_STRIDED_IMM:
3345 case AArch64::ST1B_2Z_IMM_PSEUDO:
3346 case AArch64::ST1H_2Z_IMM_PSEUDO:
3347 case AArch64::ST1W_2Z_IMM_PSEUDO:
3348 case AArch64::ST1D_2Z_IMM_PSEUDO:
3349 case AArch64::STNT1B_2Z_IMM_PSEUDO:
3350 case AArch64::STNT1H_2Z_IMM_PSEUDO:
3351 case AArch64::STNT1W_2Z_IMM_PSEUDO:
3352 case AArch64::STNT1D_2Z_IMM_PSEUDO:
3353 case AArch64::ST1B_4Z_IMM:
3354 case AArch64::ST1B_4Z_STRIDED_IMM:
3355 case AArch64::ST1H_4Z_IMM:
3356 case AArch64::ST1H_4Z_STRIDED_IMM:
3357 case AArch64::ST1W_4Z_IMM:
3358 case AArch64::ST1W_4Z_STRIDED_IMM:
3359 case AArch64::ST1D_4Z_IMM:
3360 case AArch64::ST1D_4Z_STRIDED_IMM:
3361 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
3362 case AArch64::LDNT1B_4Z_IMM:
3363 case AArch64::LDNT1B_4Z_STRIDED_IMM:
3364 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
3365 case AArch64::LDNT1H_4Z_IMM:
3366 case AArch64::LDNT1H_4Z_STRIDED_IMM:
3367 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
3368 case AArch64::LDNT1W_4Z_IMM:
3369 case AArch64::LDNT1W_4Z_STRIDED_IMM:
3370 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
3371 case AArch64::LDNT1D_4Z_IMM:
3372 case AArch64::LDNT1D_4Z_STRIDED_IMM:
3373 case AArch64::STNT1B_4Z_IMM:
3374 case AArch64::STNT1B_4Z_STRIDED_IMM:
3375 case AArch64::STNT1H_4Z_IMM:
3376 case AArch64::STNT1H_4Z_STRIDED_IMM:
3377 case AArch64::STNT1W_4Z_IMM:
3378 case AArch64::STNT1W_4Z_STRIDED_IMM:
3379 case AArch64::STNT1D_4Z_IMM:
3380 case AArch64::STNT1D_4Z_STRIDED_IMM:
3381 case AArch64::ST1B_4Z_IMM_PSEUDO:
3382 case AArch64::ST1H_4Z_IMM_PSEUDO:
3383 case AArch64::ST1W_4Z_IMM_PSEUDO:
3384 case AArch64::ST1D_4Z_IMM_PSEUDO:
3385 case AArch64::STNT1B_4Z_IMM_PSEUDO:
3386 case AArch64::STNT1H_4Z_IMM_PSEUDO:
3387 case AArch64::STNT1W_4Z_IMM_PSEUDO:
3388 case AArch64::STNT1D_4Z_IMM_PSEUDO:
3389 return 3;
3390 case AArch64::LDPDpost:
3391 case AArch64::LDPDpre:
3392 case AArch64::LDPQpost:
3393 case AArch64::LDPQpre:
3394 case AArch64::LDPSpost:
3395 case AArch64::LDPSpre:
3396 case AArch64::LDPWpost:
3397 case AArch64::LDPWpre:
3398 case AArch64::LDPXpost:
3399 case AArch64::LDPXpre:
3400 case AArch64::STGPpre:
3401 case AArch64::STGPpost:
3402 case AArch64::STPDpost:
3403 case AArch64::STPDpre:
3404 case AArch64::STPQpost:
3405 case AArch64::STPQpre:
3406 case AArch64::STPSpost:
3407 case AArch64::STPSpre:
3408 case AArch64::STPWpost:
3409 case AArch64::STPWpre:
3410 case AArch64::STPXpost:
3411 case AArch64::STPXpre:
3412 return 4;
3413 }
3414}
3415
3417 switch (MI.getOpcode()) {
3418 default:
3419 return false;
3420 // Scaled instructions.
3421 case AArch64::STRSui:
3422 case AArch64::STRDui:
3423 case AArch64::STRQui:
3424 case AArch64::STRXui:
3425 case AArch64::STRWui:
3426 case AArch64::LDRSui:
3427 case AArch64::LDRDui:
3428 case AArch64::LDRQui:
3429 case AArch64::LDRXui:
3430 case AArch64::LDRWui:
3431 case AArch64::LDRSWui:
3432 // Unscaled instructions.
3433 case AArch64::STURSi:
3434 case AArch64::STRSpre:
3435 case AArch64::STURDi:
3436 case AArch64::STRDpre:
3437 case AArch64::STURQi:
3438 case AArch64::STRQpre:
3439 case AArch64::STURWi:
3440 case AArch64::STRWpre:
3441 case AArch64::STURXi:
3442 case AArch64::STRXpre:
3443 case AArch64::LDURSi:
3444 case AArch64::LDRSpre:
3445 case AArch64::LDURDi:
3446 case AArch64::LDRDpre:
3447 case AArch64::LDURQi:
3448 case AArch64::LDRQpre:
3449 case AArch64::LDURWi:
3450 case AArch64::LDRWpre:
3451 case AArch64::LDURXi:
3452 case AArch64::LDRXpre:
3453 case AArch64::LDURSWi:
3454 case AArch64::LDRSWpre:
3455 // SVE instructions.
3456 case AArch64::LDR_ZXI:
3457 case AArch64::STR_ZXI:
3458 return true;
3459 }
3460}
3461
3463 switch (MI.getOpcode()) {
3464 default:
3465 assert((!MI.isCall() || !MI.isReturn()) &&
3466 "Unexpected instruction - was a new tail call opcode introduced?");
3467 return false;
3468 case AArch64::TCRETURNdi:
3469 case AArch64::TCRETURNri:
3470 case AArch64::TCRETURNrix16x17:
3471 case AArch64::TCRETURNrix17:
3472 case AArch64::TCRETURNrinotx16:
3473 case AArch64::TCRETURNriALL:
3474 case AArch64::AUTH_TCRETURN:
3475 case AArch64::AUTH_TCRETURN_BTI:
3476 return true;
3477 }
3478}
3479
3481 switch (Opc) {
3482 default:
3483 llvm_unreachable("Opcode has no flag setting equivalent!");
3484 // 32-bit cases:
3485 case AArch64::ADDWri:
3486 return AArch64::ADDSWri;
3487 case AArch64::ADDWrr:
3488 return AArch64::ADDSWrr;
3489 case AArch64::ADDWrs:
3490 return AArch64::ADDSWrs;
3491 case AArch64::ADDWrx:
3492 return AArch64::ADDSWrx;
3493 case AArch64::ANDWri:
3494 return AArch64::ANDSWri;
3495 case AArch64::ANDWrr:
3496 return AArch64::ANDSWrr;
3497 case AArch64::ANDWrs:
3498 return AArch64::ANDSWrs;
3499 case AArch64::BICWrr:
3500 return AArch64::BICSWrr;
3501 case AArch64::BICWrs:
3502 return AArch64::BICSWrs;
3503 case AArch64::SUBWri:
3504 return AArch64::SUBSWri;
3505 case AArch64::SUBWrr:
3506 return AArch64::SUBSWrr;
3507 case AArch64::SUBWrs:
3508 return AArch64::SUBSWrs;
3509 case AArch64::SUBWrx:
3510 return AArch64::SUBSWrx;
3511 // 64-bit cases:
3512 case AArch64::ADDXri:
3513 return AArch64::ADDSXri;
3514 case AArch64::ADDXrr:
3515 return AArch64::ADDSXrr;
3516 case AArch64::ADDXrs:
3517 return AArch64::ADDSXrs;
3518 case AArch64::ADDXrx:
3519 return AArch64::ADDSXrx;
3520 case AArch64::ANDXri:
3521 return AArch64::ANDSXri;
3522 case AArch64::ANDXrr:
3523 return AArch64::ANDSXrr;
3524 case AArch64::ANDXrs:
3525 return AArch64::ANDSXrs;
3526 case AArch64::BICXrr:
3527 return AArch64::BICSXrr;
3528 case AArch64::BICXrs:
3529 return AArch64::BICSXrs;
3530 case AArch64::SUBXri:
3531 return AArch64::SUBSXri;
3532 case AArch64::SUBXrr:
3533 return AArch64::SUBSXrr;
3534 case AArch64::SUBXrs:
3535 return AArch64::SUBSXrs;
3536 case AArch64::SUBXrx:
3537 return AArch64::SUBSXrx;
3538 // SVE instructions:
3539 case AArch64::AND_PPzPP:
3540 return AArch64::ANDS_PPzPP;
3541 case AArch64::BIC_PPzPP:
3542 return AArch64::BICS_PPzPP;
3543 case AArch64::EOR_PPzPP:
3544 return AArch64::EORS_PPzPP;
3545 case AArch64::NAND_PPzPP:
3546 return AArch64::NANDS_PPzPP;
3547 case AArch64::NOR_PPzPP:
3548 return AArch64::NORS_PPzPP;
3549 case AArch64::ORN_PPzPP:
3550 return AArch64::ORNS_PPzPP;
3551 case AArch64::ORR_PPzPP:
3552 return AArch64::ORRS_PPzPP;
3553 case AArch64::BRKA_PPzP:
3554 return AArch64::BRKAS_PPzP;
3555 case AArch64::BRKPA_PPzPP:
3556 return AArch64::BRKPAS_PPzPP;
3557 case AArch64::BRKB_PPzP:
3558 return AArch64::BRKBS_PPzP;
3559 case AArch64::BRKPB_PPzPP:
3560 return AArch64::BRKPBS_PPzPP;
3561 case AArch64::BRKN_PPzP:
3562 return AArch64::BRKNS_PPzP;
3563 case AArch64::RDFFR_PPz:
3564 return AArch64::RDFFRS_PPz;
3565 case AArch64::PTRUE_B:
3566 return AArch64::PTRUES_B;
3567 }
3568}
3569
3570// Is this a candidate for ld/st merging or pairing? For example, we don't
3571// touch volatiles or load/stores that have a hint to avoid pair formation.
3573
3574 bool IsPreLdSt = isPreLdSt(MI);
3575
3576 // If this is a volatile load/store, don't mess with it.
3577 if (MI.hasOrderedMemoryRef())
3578 return false;
3579
3580 // Make sure this is a reg/fi+imm (as opposed to an address reloc).
3581 // For Pre-inc LD/ST, the operand is shifted by one.
3582 assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
3583 MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
3584 "Expected a reg or frame index operand.");
3585
3586 // For Pre-indexed addressing quadword instructions, the third operand is the
3587 // immediate value.
3588 bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
3589
3590 if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
3591 return false;
3592
3593 // Can't merge/pair if the instruction modifies the base register.
3594 // e.g., ldr x0, [x0]
3595 // This case will never occur with an FI base.
3596 // However, if the instruction is an LDR<S,D,Q,W,X,SW>pre or
3597 // STR<S,D,Q,W,X>pre, it can be merged.
3598 // For example:
3599 // ldr q0, [x11, #32]!
3600 // ldr q1, [x11, #16]
3601 // to
3602 // ldp q0, q1, [x11, #32]!
3603 if (MI.getOperand(1).isReg() && !IsPreLdSt) {
3604 Register BaseReg = MI.getOperand(1).getReg();
3606 if (MI.modifiesRegister(BaseReg, TRI))
3607 return false;
3608 }
3609
3610 // Pairing SVE fills/spills is only valid for little-endian targets that
3611 // implement VLS 128.
3612 switch (MI.getOpcode()) {
3613 default:
3614 break;
3615 case AArch64::LDR_ZXI:
3616 case AArch64::STR_ZXI:
3617 if (!Subtarget.isLittleEndian() ||
3618 Subtarget.getSVEVectorSizeInBits() != 128)
3619 return false;
3620 }
3621
3622 // Check if this load/store has a hint to avoid pair formation.
3623 // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
3625 return false;
3626
3627 // Do not pair any callee-save store/reload instructions in the
3628 // prologue/epilogue if the CFI information encoded the operations as separate
3629 // instructions, as that will cause the size of the actual prologue to mismatch
3630 // with the prologue size recorded in the Windows CFI.
3631 if ((MI.getFlag(MachineInstr::FrameSetup) ||
3632 MI.getFlag(MachineInstr::FrameDestroy)) &&
3633 MI.getMF()->needsWinCFI())
3634 return false;
3635
3636 // On some CPUs quad load/store pairs are slower than two single load/stores.
3637 if (Subtarget.isPaired128Slow()) {
3638 switch (MI.getOpcode()) {
3639 default:
3640 break;
3641 case AArch64::LDURQi:
3642 case AArch64::STURQi:
3643 case AArch64::LDRQui:
3644 case AArch64::STRQui:
3645 return false;
3646 }
3647 }
3648
3649 return true;
3650}
3651
3654 int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const {
3655 if (!LdSt.mayLoadOrStore())
3656 return false;
3657
3658 const MachineOperand *BaseOp;
3659 TypeSize WidthN(0, false);
3660 if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
3661 WidthN))
3662 return false;
3663 // The maximum vscale is 16 under AArch64, return the maximal extent for the
3664 // vector.
3665 Width = LocationSize::precise(WidthN);
3666 BaseOps.push_back(BaseOp);
3667 return true;
3668}
3669
3670std::optional<ExtAddrMode>
3672 const MachineOperand *Base; // Filled with the base operand of MI.
3673 int64_t Offset; // Filled with the offset of MI.
3674 bool OffsetIsScalable;
3675 if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable))
3676 return std::nullopt;
3677
3678 if (!Base->isReg())
3679 return std::nullopt;
3680 ExtAddrMode AM;
3681 AM.BaseReg = Base->getReg();
3682 AM.Displacement = Offset;
3683 AM.ScaledReg = 0;
3684 AM.Scale = 0;
3685 return AM;
3686}
3687
3689 Register Reg,
3690 const MachineInstr &AddrI,
3691 ExtAddrMode &AM) const {
3692 // Filter out instructions into which we cannot fold.
3693 unsigned NumBytes;
3694 int64_t OffsetScale = 1;
3695 switch (MemI.getOpcode()) {
3696 default:
3697 return false;
3698
3699 case AArch64::LDURQi:
3700 case AArch64::STURQi:
3701 NumBytes = 16;
3702 break;
3703
3704 case AArch64::LDURDi:
3705 case AArch64::STURDi:
3706 case AArch64::LDURXi:
3707 case AArch64::STURXi:
3708 NumBytes = 8;
3709 break;
3710
3711 case AArch64::LDURWi:
3712 case AArch64::LDURSWi:
3713 case AArch64::STURWi:
3714 NumBytes = 4;
3715 break;
3716
3717 case AArch64::LDURHi:
3718 case AArch64::STURHi:
3719 case AArch64::LDURHHi:
3720 case AArch64::STURHHi:
3721 case AArch64::LDURSHXi:
3722 case AArch64::LDURSHWi:
3723 NumBytes = 2;
3724 break;
3725
3726 case AArch64::LDRBroX:
3727 case AArch64::LDRBBroX:
3728 case AArch64::LDRSBXroX:
3729 case AArch64::LDRSBWroX:
3730 case AArch64::STRBroX:
3731 case AArch64::STRBBroX:
3732 case AArch64::LDURBi:
3733 case AArch64::LDURBBi:
3734 case AArch64::LDURSBXi:
3735 case AArch64::LDURSBWi:
3736 case AArch64::STURBi:
3737 case AArch64::STURBBi:
3738 case AArch64::LDRBui:
3739 case AArch64::LDRBBui:
3740 case AArch64::LDRSBXui:
3741 case AArch64::LDRSBWui:
3742 case AArch64::STRBui:
3743 case AArch64::STRBBui:
3744 NumBytes = 1;
3745 break;
3746
3747 case AArch64::LDRQroX:
3748 case AArch64::STRQroX:
3749 case AArch64::LDRQui:
3750 case AArch64::STRQui:
3751 NumBytes = 16;
3752 OffsetScale = 16;
3753 break;
3754
3755 case AArch64::LDRDroX:
3756 case AArch64::STRDroX:
3757 case AArch64::LDRXroX:
3758 case AArch64::STRXroX:
3759 case AArch64::LDRDui:
3760 case AArch64::STRDui:
3761 case AArch64::LDRXui:
3762 case AArch64::STRXui:
3763 NumBytes = 8;
3764 OffsetScale = 8;
3765 break;
3766
3767 case AArch64::LDRWroX:
3768 case AArch64::LDRSWroX:
3769 case AArch64::STRWroX:
3770 case AArch64::LDRWui:
3771 case AArch64::LDRSWui:
3772 case AArch64::STRWui:
3773 NumBytes = 4;
3774 OffsetScale = 4;
3775 break;
3776
3777 case AArch64::LDRHroX:
3778 case AArch64::STRHroX:
3779 case AArch64::LDRHHroX:
3780 case AArch64::STRHHroX:
3781 case AArch64::LDRSHXroX:
3782 case AArch64::LDRSHWroX:
3783 case AArch64::LDRHui:
3784 case AArch64::STRHui:
3785 case AArch64::LDRHHui:
3786 case AArch64::STRHHui:
3787 case AArch64::LDRSHXui:
3788 case AArch64::LDRSHWui:
3789 NumBytes = 2;
3790 OffsetScale = 2;
3791 break;
3792 }
3793
3794 // Check the fold operand is not the loaded/stored value.
3795 const MachineOperand &BaseRegOp = MemI.getOperand(0);
3796 if (BaseRegOp.isReg() && BaseRegOp.getReg() == Reg)
3797 return false;
3798
3799 // Handle memory instructions with a [Reg, Reg] addressing mode.
3800 if (MemI.getOperand(2).isReg()) {
3801 // Bail if the addressing mode already includes extension of the offset
3802 // register.
3803 if (MemI.getOperand(3).getImm())
3804 return false;
3805
3806 // Check if we actually have a scaled offset.
3807 if (MemI.getOperand(4).getImm() == 0)
3808 OffsetScale = 1;
3809
3810 // If the address instructions is folded into the base register, then the
3811 // addressing mode must not have a scale. Then we can swap the base and the
3812 // scaled registers.
3813 if (MemI.getOperand(1).getReg() == Reg && OffsetScale != 1)
3814 return false;
3815
3816 switch (AddrI.getOpcode()) {
3817 default:
3818 return false;
3819
3820 case AArch64::SBFMXri:
3821 // sxtw Xa, Wm
3822 // ldr Xd, [Xn, Xa, lsl #N]
3823 // ->
3824 // ldr Xd, [Xn, Wm, sxtw #N]
3825 if (AddrI.getOperand(2).getImm() != 0 ||
3826 AddrI.getOperand(3).getImm() != 31)
3827 return false;
3828
3829 AM.BaseReg = MemI.getOperand(1).getReg();
3830 if (AM.BaseReg == Reg)
3831 AM.BaseReg = MemI.getOperand(2).getReg();
3832 AM.ScaledReg = AddrI.getOperand(1).getReg();
3833 AM.Scale = OffsetScale;
3834 AM.Displacement = 0;
3836 return true;
3837
3838 case TargetOpcode::SUBREG_TO_REG: {
3839 // mov Wa, Wm
3840 // ldr Xd, [Xn, Xa, lsl #N]
3841 // ->
3842 // ldr Xd, [Xn, Wm, uxtw #N]
3843
3844 // Zero-extension looks like an ORRWrs followed by a SUBREG_TO_REG.
3845 if (AddrI.getOperand(2).getImm() != AArch64::sub_32)
3846 return false;
3847
3848 const MachineRegisterInfo &MRI = AddrI.getMF()->getRegInfo();
3849 Register OffsetReg = AddrI.getOperand(1).getReg();
3850 if (!OffsetReg.isVirtual() || !MRI.hasOneNonDBGUse(OffsetReg))
3851 return false;
3852
3853 const MachineInstr &DefMI = *MRI.getVRegDef(OffsetReg);
3854 if (DefMI.getOpcode() != AArch64::ORRWrs ||
3855 DefMI.getOperand(1).getReg() != AArch64::WZR ||
3856 DefMI.getOperand(3).getImm() != 0)
3857 return false;
3858
3859 AM.BaseReg = MemI.getOperand(1).getReg();
3860 if (AM.BaseReg == Reg)
3861 AM.BaseReg = MemI.getOperand(2).getReg();
3862 AM.ScaledReg = DefMI.getOperand(2).getReg();
3863 AM.Scale = OffsetScale;
3864 AM.Displacement = 0;
3866 return true;
3867 }
3868 }
3869 }
3870
3871 // Handle memory instructions with a [Reg, #Imm] addressing mode.
3872
3873 // Check we are not breaking a potential conversion to an LDP.
3874 auto validateOffsetForLDP = [](unsigned NumBytes, int64_t OldOffset,
3875 int64_t NewOffset) -> bool {
3876 int64_t MinOffset, MaxOffset;
3877 switch (NumBytes) {
3878 default:
3879 return true;
3880 case 4:
3881 MinOffset = -256;
3882 MaxOffset = 252;
3883 break;
3884 case 8:
3885 MinOffset = -512;
3886 MaxOffset = 504;
3887 break;
3888 case 16:
3889 MinOffset = -1024;
3890 MaxOffset = 1008;
3891 break;
3892 }
3893 return OldOffset < MinOffset || OldOffset > MaxOffset ||
3894 (NewOffset >= MinOffset && NewOffset <= MaxOffset);
3895 };
3896 auto canFoldAddSubImmIntoAddrMode = [&](int64_t Disp) -> bool {
3897 int64_t OldOffset = MemI.getOperand(2).getImm() * OffsetScale;
3898 int64_t NewOffset = OldOffset + Disp;
3899 if (!isLegalAddressingMode(NumBytes, NewOffset, /* Scale */ 0))
3900 return false;
3901 // If the old offset would fit into an LDP, but the new offset wouldn't,
3902 // bail out.
3903 if (!validateOffsetForLDP(NumBytes, OldOffset, NewOffset))
3904 return false;
3905 AM.BaseReg = AddrI.getOperand(1).getReg();
3906 AM.ScaledReg = 0;
3907 AM.Scale = 0;
3908 AM.Displacement = NewOffset;
3910 return true;
3911 };
3912
3913 auto canFoldAddRegIntoAddrMode =
3914 [&](int64_t Scale,
3916 if (MemI.getOperand(2).getImm() != 0)
3917 return false;
3918 if ((unsigned)Scale != Scale)
3919 return false;
3920 if (!isLegalAddressingMode(NumBytes, /* Offset */ 0, Scale))
3921 return false;
3922 AM.BaseReg = AddrI.getOperand(1).getReg();
3923 AM.ScaledReg = AddrI.getOperand(2).getReg();
3924 AM.Scale = Scale;
3925 AM.Displacement = 0;
3926 AM.Form = Form;
3927 return true;
3928 };
3929
3930 auto avoidSlowSTRQ = [&](const MachineInstr &MemI) {
3931 unsigned Opcode = MemI.getOpcode();
3932 return (Opcode == AArch64::STURQi || Opcode == AArch64::STRQui) &&
3933 Subtarget.isSTRQroSlow();
3934 };
3935
3936 int64_t Disp = 0;
3937 const bool OptSize = MemI.getMF()->getFunction().hasOptSize();
3938 switch (AddrI.getOpcode()) {
3939 default:
3940 return false;
3941
3942 case AArch64::ADDXri:
3943 // add Xa, Xn, #N
3944 // ldr Xd, [Xa, #M]
3945 // ->
3946 // ldr Xd, [Xn, #N'+M]
3947 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3948 return canFoldAddSubImmIntoAddrMode(Disp);
3949
3950 case AArch64::SUBXri:
3951 // sub Xa, Xn, #N
3952 // ldr Xd, [Xa, #M]
3953 // ->
3954 // ldr Xd, [Xn, #N'+M]
3955 Disp = AddrI.getOperand(2).getImm() << AddrI.getOperand(3).getImm();
3956 return canFoldAddSubImmIntoAddrMode(-Disp);
3957
3958 case AArch64::ADDXrs: {
3959 // add Xa, Xn, Xm, lsl #N
3960 // ldr Xd, [Xa]
3961 // ->
3962 // ldr Xd, [Xn, Xm, lsl #N]
3963
3964 // Don't fold the add if the result would be slower, unless optimising for
3965 // size.
3966 unsigned Shift = static_cast<unsigned>(AddrI.getOperand(3).getImm());
3968 return false;
3969 Shift = AArch64_AM::getShiftValue(Shift);
3970 if (!OptSize) {
3971 if (Shift != 2 && Shift != 3 && Subtarget.hasAddrLSLSlow14())
3972 return false;
3973 if (avoidSlowSTRQ(MemI))
3974 return false;
3975 }
3976 return canFoldAddRegIntoAddrMode(1ULL << Shift);
3977 }
3978
3979 case AArch64::ADDXrr:
3980 // add Xa, Xn, Xm
3981 // ldr Xd, [Xa]
3982 // ->
3983 // ldr Xd, [Xn, Xm, lsl #0]
3984
3985 // Don't fold the add if the result would be slower, unless optimising for
3986 // size.
3987 if (!OptSize && avoidSlowSTRQ(MemI))
3988 return false;
3989 return canFoldAddRegIntoAddrMode(1);
3990
3991 case AArch64::ADDXrx:
3992 // add Xa, Xn, Wm, {s,u}xtw #N
3993 // ldr Xd, [Xa]
3994 // ->
3995 // ldr Xd, [Xn, Wm, {s,u}xtw #N]
3996
3997 // Don't fold the add if the result would be slower, unless optimising for
3998 // size.
3999 if (!OptSize && avoidSlowSTRQ(MemI))
4000 return false;
4001
4002 // Can fold only sign-/zero-extend of a word.
4003 unsigned Imm = static_cast<unsigned>(AddrI.getOperand(3).getImm());
4005 if (Extend != AArch64_AM::UXTW && Extend != AArch64_AM::SXTW)
4006 return false;
4007
4008 return canFoldAddRegIntoAddrMode(
4012 }
4013}
4014
4015// Given an opcode for an instruction with a [Reg, #Imm] addressing mode,
4016// return the opcode of an instruction performing the same operation, but using
4017// the [Reg, Reg] addressing mode.
4018static unsigned regOffsetOpcode(unsigned Opcode) {
4019 switch (Opcode) {
4020 default:
4021 llvm_unreachable("Address folding not implemented for instruction");
4022
4023 case AArch64::LDURQi:
4024 case AArch64::LDRQui:
4025 return AArch64::LDRQroX;
4026 case AArch64::STURQi:
4027 case AArch64::STRQui:
4028 return AArch64::STRQroX;
4029 case AArch64::LDURDi:
4030 case AArch64::LDRDui:
4031 return AArch64::LDRDroX;
4032 case AArch64::STURDi:
4033 case AArch64::STRDui:
4034 return AArch64::STRDroX;
4035 case AArch64::LDURXi:
4036 case AArch64::LDRXui:
4037 return AArch64::LDRXroX;
4038 case AArch64::STURXi:
4039 case AArch64::STRXui:
4040 return AArch64::STRXroX;
4041 case AArch64::LDURWi:
4042 case AArch64::LDRWui:
4043 return AArch64::LDRWroX;
4044 case AArch64::LDURSWi:
4045 case AArch64::LDRSWui:
4046 return AArch64::LDRSWroX;
4047 case AArch64::STURWi:
4048 case AArch64::STRWui:
4049 return AArch64::STRWroX;
4050 case AArch64::LDURHi:
4051 case AArch64::LDRHui:
4052 return AArch64::LDRHroX;
4053 case AArch64::STURHi:
4054 case AArch64::STRHui:
4055 return AArch64::STRHroX;
4056 case AArch64::LDURHHi:
4057 case AArch64::LDRHHui:
4058 return AArch64::LDRHHroX;
4059 case AArch64::STURHHi:
4060 case AArch64::STRHHui:
4061 return AArch64::STRHHroX;
4062 case AArch64::LDURSHXi:
4063 case AArch64::LDRSHXui:
4064 return AArch64::LDRSHXroX;
4065 case AArch64::LDURSHWi:
4066 case AArch64::LDRSHWui:
4067 return AArch64::LDRSHWroX;
4068 case AArch64::LDURBi:
4069 case AArch64::LDRBui:
4070 return AArch64::LDRBroX;
4071 case AArch64::LDURBBi:
4072 case AArch64::LDRBBui:
4073 return AArch64::LDRBBroX;
4074 case AArch64::LDURSBXi:
4075 case AArch64::LDRSBXui:
4076 return AArch64::LDRSBXroX;
4077 case AArch64::LDURSBWi:
4078 case AArch64::LDRSBWui:
4079 return AArch64::LDRSBWroX;
4080 case AArch64::STURBi:
4081 case AArch64::STRBui:
4082 return AArch64::STRBroX;
4083 case AArch64::STURBBi:
4084 case AArch64::STRBBui:
4085 return AArch64::STRBBroX;
4086 }
4087}
4088
4089// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4090// the opcode of an instruction performing the same operation, but using the
4091// [Reg, #Imm] addressing mode with scaled offset.
4092unsigned scaledOffsetOpcode(unsigned Opcode, unsigned &Scale) {
4093 switch (Opcode) {
4094 default:
4095 llvm_unreachable("Address folding not implemented for instruction");
4096
4097 case AArch64::LDURQi:
4098 Scale = 16;
4099 return AArch64::LDRQui;
4100 case AArch64::STURQi:
4101 Scale = 16;
4102 return AArch64::STRQui;
4103 case AArch64::LDURDi:
4104 Scale = 8;
4105 return AArch64::LDRDui;
4106 case AArch64::STURDi:
4107 Scale = 8;
4108 return AArch64::STRDui;
4109 case AArch64::LDURXi:
4110 Scale = 8;
4111 return AArch64::LDRXui;
4112 case AArch64::STURXi:
4113 Scale = 8;
4114 return AArch64::STRXui;
4115 case AArch64::LDURWi:
4116 Scale = 4;
4117 return AArch64::LDRWui;
4118 case AArch64::LDURSWi:
4119 Scale = 4;
4120 return AArch64::LDRSWui;
4121 case AArch64::STURWi:
4122 Scale = 4;
4123 return AArch64::STRWui;
4124 case AArch64::LDURHi:
4125 Scale = 2;
4126 return AArch64::LDRHui;
4127 case AArch64::STURHi:
4128 Scale = 2;
4129 return AArch64::STRHui;
4130 case AArch64::LDURHHi:
4131 Scale = 2;
4132 return AArch64::LDRHHui;
4133 case AArch64::STURHHi:
4134 Scale = 2;
4135 return AArch64::STRHHui;
4136 case AArch64::LDURSHXi:
4137 Scale = 2;
4138 return AArch64::LDRSHXui;
4139 case AArch64::LDURSHWi:
4140 Scale = 2;
4141 return AArch64::LDRSHWui;
4142 case AArch64::LDURBi:
4143 Scale = 1;
4144 return AArch64::LDRBui;
4145 case AArch64::LDURBBi:
4146 Scale = 1;
4147 return AArch64::LDRBBui;
4148 case AArch64::LDURSBXi:
4149 Scale = 1;
4150 return AArch64::LDRSBXui;
4151 case AArch64::LDURSBWi:
4152 Scale = 1;
4153 return AArch64::LDRSBWui;
4154 case AArch64::STURBi:
4155 Scale = 1;
4156 return AArch64::STRBui;
4157 case AArch64::STURBBi:
4158 Scale = 1;
4159 return AArch64::STRBBui;
4160 case AArch64::LDRQui:
4161 case AArch64::STRQui:
4162 Scale = 16;
4163 return Opcode;
4164 case AArch64::LDRDui:
4165 case AArch64::STRDui:
4166 case AArch64::LDRXui:
4167 case AArch64::STRXui:
4168 Scale = 8;
4169 return Opcode;
4170 case AArch64::LDRWui:
4171 case AArch64::LDRSWui:
4172 case AArch64::STRWui:
4173 Scale = 4;
4174 return Opcode;
4175 case AArch64::LDRHui:
4176 case AArch64::STRHui:
4177 case AArch64::LDRHHui:
4178 case AArch64::STRHHui:
4179 case AArch64::LDRSHXui:
4180 case AArch64::LDRSHWui:
4181 Scale = 2;
4182 return Opcode;
4183 case AArch64::LDRBui:
4184 case AArch64::LDRBBui:
4185 case AArch64::LDRSBXui:
4186 case AArch64::LDRSBWui:
4187 case AArch64::STRBui:
4188 case AArch64::STRBBui:
4189 Scale = 1;
4190 return Opcode;
4191 }
4192}
4193
4194// Given an opcode for an instruction with a [Reg, #Imm] addressing mode, return
4195// the opcode of an instruction performing the same operation, but using the
4196// [Reg, #Imm] addressing mode with unscaled offset.
4197unsigned unscaledOffsetOpcode(unsigned Opcode) {
4198 switch (Opcode) {
4199 default:
4200 llvm_unreachable("Address folding not implemented for instruction");
4201
4202 case AArch64::LDURQi:
4203 case AArch64::STURQi:
4204 case AArch64::LDURDi:
4205 case AArch64::STURDi:
4206 case AArch64::LDURXi:
4207 case AArch64::STURXi:
4208 case AArch64::LDURWi:
4209 case AArch64::LDURSWi:
4210 case AArch64::STURWi:
4211 case AArch64::LDURHi:
4212 case AArch64::STURHi:
4213 case AArch64::LDURHHi:
4214 case AArch64::STURHHi:
4215 case AArch64::LDURSHXi:
4216 case AArch64::LDURSHWi:
4217 case AArch64::LDURBi:
4218 case AArch64::STURBi:
4219 case AArch64::LDURBBi:
4220 case AArch64::STURBBi:
4221 case AArch64::LDURSBWi:
4222 case AArch64::LDURSBXi:
4223 return Opcode;
4224 case AArch64::LDRQui:
4225 return AArch64::LDURQi;
4226 case AArch64::STRQui:
4227 return AArch64::STURQi;
4228 case AArch64::LDRDui:
4229 return AArch64::LDURDi;
4230 case AArch64::STRDui:
4231 return AArch64::STURDi;
4232 case AArch64::LDRXui:
4233 return AArch64::LDURXi;
4234 case AArch64::STRXui:
4235 return AArch64::STURXi;
4236 case AArch64::LDRWui:
4237 return AArch64::LDURWi;
4238 case AArch64::LDRSWui:
4239 return AArch64::LDURSWi;
4240 case AArch64::STRWui:
4241 return AArch64::STURWi;
4242 case AArch64::LDRHui:
4243 return AArch64::LDURHi;
4244 case AArch64::STRHui:
4245 return AArch64::STURHi;
4246 case AArch64::LDRHHui:
4247 return AArch64::LDURHHi;
4248 case AArch64::STRHHui:
4249 return AArch64::STURHHi;
4250 case AArch64::LDRSHXui:
4251 return AArch64::LDURSHXi;
4252 case AArch64::LDRSHWui:
4253 return AArch64::LDURSHWi;
4254 case AArch64::LDRBBui:
4255 return AArch64::LDURBBi;
4256 case AArch64::LDRBui:
4257 return AArch64::LDURBi;
4258 case AArch64::STRBBui:
4259 return AArch64::STURBBi;
4260 case AArch64::STRBui:
4261 return AArch64::STURBi;
4262 case AArch64::LDRSBWui:
4263 return AArch64::LDURSBWi;
4264 case AArch64::LDRSBXui:
4265 return AArch64::LDURSBXi;
4266 }
4267}
4268
4269// Given the opcode of a memory load/store instruction, return the opcode of an
4270// instruction performing the same operation, but using
4271// the [Reg, Reg, {s,u}xtw #N] addressing mode with sign-/zero-extend of the
4272// offset register.
4273static unsigned offsetExtendOpcode(unsigned Opcode) {
4274 switch (Opcode) {
4275 default:
4276 llvm_unreachable("Address folding not implemented for instruction");
4277
4278 case AArch64::LDRQroX:
4279 case AArch64::LDURQi:
4280 case AArch64::LDRQui:
4281 return AArch64::LDRQroW;
4282 case AArch64::STRQroX:
4283 case AArch64::STURQi:
4284 case AArch64::STRQui:
4285 return AArch64::STRQroW;
4286 case AArch64::LDRDroX:
4287 case AArch64::LDURDi:
4288 case AArch64::LDRDui:
4289 return AArch64::LDRDroW;
4290 case AArch64::STRDroX:
4291 case AArch64::STURDi:
4292 case AArch64::STRDui:
4293 return AArch64::STRDroW;
4294 case AArch64::LDRXroX:
4295 case AArch64::LDURXi:
4296 case AArch64::LDRXui:
4297 return AArch64::LDRXroW;
4298 case AArch64::STRXroX:
4299 case AArch64::STURXi:
4300 case AArch64::STRXui:
4301 return AArch64::STRXroW;
4302 case AArch64::LDRWroX:
4303 case AArch64::LDURWi:
4304 case AArch64::LDRWui:
4305 return AArch64::LDRWroW;
4306 case AArch64::LDRSWroX:
4307 case AArch64::LDURSWi:
4308 case AArch64::LDRSWui:
4309 return AArch64::LDRSWroW;
4310 case AArch64::STRWroX:
4311 case AArch64::STURWi:
4312 case AArch64::STRWui:
4313 return AArch64::STRWroW;
4314 case AArch64::LDRHroX:
4315 case AArch64::LDURHi:
4316 case AArch64::LDRHui:
4317 return AArch64::LDRHroW;
4318 case AArch64::STRHroX:
4319 case AArch64::STURHi:
4320 case AArch64::STRHui:
4321 return AArch64::STRHroW;
4322 case AArch64::LDRHHroX:
4323 case AArch64::LDURHHi:
4324 case AArch64::LDRHHui:
4325 return AArch64::LDRHHroW;
4326 case AArch64::STRHHroX:
4327 case AArch64::STURHHi:
4328 case AArch64::STRHHui:
4329 return AArch64::STRHHroW;
4330 case AArch64::LDRSHXroX:
4331 case AArch64::LDURSHXi:
4332 case AArch64::LDRSHXui:
4333 return AArch64::LDRSHXroW;
4334 case AArch64::LDRSHWroX:
4335 case AArch64::LDURSHWi:
4336 case AArch64::LDRSHWui:
4337 return AArch64::LDRSHWroW;
4338 case AArch64::LDRBroX:
4339 case AArch64::LDURBi:
4340 case AArch64::LDRBui:
4341 return AArch64::LDRBroW;
4342 case AArch64::LDRBBroX:
4343 case AArch64::LDURBBi:
4344 case AArch64::LDRBBui:
4345 return AArch64::LDRBBroW;
4346 case AArch64::LDRSBXroX:
4347 case AArch64::LDURSBXi:
4348 case AArch64::LDRSBXui:
4349 return AArch64::LDRSBXroW;
4350 case AArch64::LDRSBWroX:
4351 case AArch64::LDURSBWi:
4352 case AArch64::LDRSBWui:
4353 return AArch64::LDRSBWroW;
4354 case AArch64::STRBroX:
4355 case AArch64::STURBi:
4356 case AArch64::STRBui:
4357 return AArch64::STRBroW;
4358 case AArch64::STRBBroX:
4359 case AArch64::STURBBi:
4360 case AArch64::STRBBui:
4361 return AArch64::STRBBroW;
4362 }
4363}
4364
4366 const ExtAddrMode &AM) const {
4367
4368 const DebugLoc &DL = MemI.getDebugLoc();
4369 MachineBasicBlock &MBB = *MemI.getParent();
4370 MachineRegisterInfo &MRI = MemI.getMF()->getRegInfo();
4371
4373 if (AM.ScaledReg) {
4374 // The new instruction will be in the form `ldr Rt, [Xn, Xm, lsl #imm]`.
4375 unsigned Opcode = regOffsetOpcode(MemI.getOpcode());
4376 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4377 auto B = BuildMI(MBB, MemI, DL, get(Opcode))
4378 .addReg(MemI.getOperand(0).getReg(),
4379 getDefRegState(MemI.mayLoad()))
4380 .addReg(AM.BaseReg)
4381 .addReg(AM.ScaledReg)
4382 .addImm(0)
4383 .addImm(AM.Scale > 1)
4384 .setMemRefs(MemI.memoperands())
4385 .setMIFlags(MemI.getFlags());
4386 return B.getInstr();
4387 }
4388
4389 assert(AM.ScaledReg == 0 && AM.Scale == 0 &&
4390 "Addressing mode not supported for folding");
4391
4392 // The new instruction will be in the form `ld[u]r Rt, [Xn, #imm]`.
4393 unsigned Scale = 1;
4394 unsigned Opcode = MemI.getOpcode();
4395 if (isInt<9>(AM.Displacement))
4396 Opcode = unscaledOffsetOpcode(Opcode);
4397 else
4398 Opcode = scaledOffsetOpcode(Opcode, Scale);
4399
4400 auto B =
4401 BuildMI(MBB, MemI, DL, get(Opcode))
4402 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4403 .addReg(AM.BaseReg)
4404 .addImm(AM.Displacement / Scale)
4405 .setMemRefs(MemI.memoperands())
4406 .setMIFlags(MemI.getFlags());
4407 return B.getInstr();
4408 }
4409
4412 // The new instruction will be in the form `ldr Rt, [Xn, Wm, {s,u}xtw #N]`.
4413 assert(AM.ScaledReg && !AM.Displacement &&
4414 "Address offset can be a register or an immediate, but not both");
4415 unsigned Opcode = offsetExtendOpcode(MemI.getOpcode());
4416 MRI.constrainRegClass(AM.BaseReg, &AArch64::GPR64spRegClass);
4417 // Make sure the offset register is in the correct register class.
4418 Register OffsetReg = AM.ScaledReg;
4419 const TargetRegisterClass *RC = MRI.getRegClass(OffsetReg);
4420 if (RC->hasSuperClassEq(&AArch64::GPR64RegClass)) {
4421 OffsetReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
4422 BuildMI(MBB, MemI, DL, get(TargetOpcode::COPY), OffsetReg)
4423 .addReg(AM.ScaledReg, {}, AArch64::sub_32);
4424 }
4425 auto B =
4426 BuildMI(MBB, MemI, DL, get(Opcode))
4427 .addReg(MemI.getOperand(0).getReg(), getDefRegState(MemI.mayLoad()))
4428 .addReg(AM.BaseReg)
4429 .addReg(OffsetReg)
4431 .addImm(AM.Scale != 1)
4432 .setMemRefs(MemI.memoperands())
4433 .setMIFlags(MemI.getFlags());
4434
4435 return B.getInstr();
4436 }
4437
4439 "Function must not be called with an addressing mode it can't handle");
4440}
4441
4442/// Return true if the opcode is a post-index ld/st instruction, which really
4443/// loads from base+0.
4444static bool isPostIndexLdStOpcode(unsigned Opcode) {
4445 switch (Opcode) {
4446 default:
4447 return false;
4448 case AArch64::LD1Fourv16b_POST:
4449 case AArch64::LD1Fourv1d_POST:
4450 case AArch64::LD1Fourv2d_POST:
4451 case AArch64::LD1Fourv2s_POST:
4452 case AArch64::LD1Fourv4h_POST:
4453 case AArch64::LD1Fourv4s_POST:
4454 case AArch64::LD1Fourv8b_POST:
4455 case AArch64::LD1Fourv8h_POST:
4456 case AArch64::LD1Onev16b_POST:
4457 case AArch64::LD1Onev1d_POST:
4458 case AArch64::LD1Onev2d_POST:
4459 case AArch64::LD1Onev2s_POST:
4460 case AArch64::LD1Onev4h_POST:
4461 case AArch64::LD1Onev4s_POST:
4462 case AArch64::LD1Onev8b_POST:
4463 case AArch64::LD1Onev8h_POST:
4464 case AArch64::LD1Rv16b_POST:
4465 case AArch64::LD1Rv1d_POST:
4466 case AArch64::LD1Rv2d_POST:
4467 case AArch64::LD1Rv2s_POST:
4468 case AArch64::LD1Rv4h_POST:
4469 case AArch64::LD1Rv4s_POST:
4470 case AArch64::LD1Rv8b_POST:
4471 case AArch64::LD1Rv8h_POST:
4472 case AArch64::LD1Threev16b_POST:
4473 case AArch64::LD1Threev1d_POST:
4474 case AArch64::LD1Threev2d_POST:
4475 case AArch64::LD1Threev2s_POST:
4476 case AArch64::LD1Threev4h_POST:
4477 case AArch64::LD1Threev4s_POST:
4478 case AArch64::LD1Threev8b_POST:
4479 case AArch64::LD1Threev8h_POST:
4480 case AArch64::LD1Twov16b_POST:
4481 case AArch64::LD1Twov1d_POST:
4482 case AArch64::LD1Twov2d_POST:
4483 case AArch64::LD1Twov2s_POST:
4484 case AArch64::LD1Twov4h_POST:
4485 case AArch64::LD1Twov4s_POST:
4486 case AArch64::LD1Twov8b_POST:
4487 case AArch64::LD1Twov8h_POST:
4488 case AArch64::LD1i16_POST:
4489 case AArch64::LD1i32_POST:
4490 case AArch64::LD1i64_POST:
4491 case AArch64::LD1i8_POST:
4492 case AArch64::LD2Rv16b_POST:
4493 case AArch64::LD2Rv1d_POST:
4494 case AArch64::LD2Rv2d_POST:
4495 case AArch64::LD2Rv2s_POST:
4496 case AArch64::LD2Rv4h_POST:
4497 case AArch64::LD2Rv4s_POST:
4498 case AArch64::LD2Rv8b_POST:
4499 case AArch64::LD2Rv8h_POST:
4500 case AArch64::LD2Twov16b_POST:
4501 case AArch64::LD2Twov2d_POST:
4502 case AArch64::LD2Twov2s_POST:
4503 case AArch64::LD2Twov4h_POST:
4504 case AArch64::LD2Twov4s_POST:
4505 case AArch64::LD2Twov8b_POST:
4506 case AArch64::LD2Twov8h_POST:
4507 case AArch64::LD2i16_POST:
4508 case AArch64::LD2i32_POST:
4509 case AArch64::LD2i64_POST:
4510 case AArch64::LD2i8_POST:
4511 case AArch64::LD3Rv16b_POST:
4512 case AArch64::LD3Rv1d_POST:
4513 case AArch64::LD3Rv2d_POST:
4514 case AArch64::LD3Rv2s_POST:
4515 case AArch64::LD3Rv4h_POST:
4516 case AArch64::LD3Rv4s_POST:
4517 case AArch64::LD3Rv8b_POST:
4518 case AArch64::LD3Rv8h_POST:
4519 case AArch64::LD3Threev16b_POST:
4520 case AArch64::LD3Threev2d_POST:
4521 case AArch64::LD3Threev2s_POST:
4522 case AArch64::LD3Threev4h_POST:
4523 case AArch64::LD3Threev4s_POST:
4524 case AArch64::LD3Threev8b_POST:
4525 case AArch64::LD3Threev8h_POST:
4526 case AArch64::LD3i16_POST:
4527 case AArch64::LD3i32_POST:
4528 case AArch64::LD3i64_POST:
4529 case AArch64::LD3i8_POST:
4530 case AArch64::LD4Fourv16b_POST:
4531 case AArch64::LD4Fourv2d_POST:
4532 case AArch64::LD4Fourv2s_POST:
4533 case AArch64::LD4Fourv4h_POST:
4534 case AArch64::LD4Fourv4s_POST:
4535 case AArch64::LD4Fourv8b_POST:
4536 case AArch64::LD4Fourv8h_POST:
4537 case AArch64::LD4Rv16b_POST:
4538 case AArch64::LD4Rv1d_POST:
4539 case AArch64::LD4Rv2d_POST:
4540 case AArch64::LD4Rv2s_POST:
4541 case AArch64::LD4Rv4h_POST:
4542 case AArch64::LD4Rv4s_POST:
4543 case AArch64::LD4Rv8b_POST:
4544 case AArch64::LD4Rv8h_POST:
4545 case AArch64::LD4i16_POST:
4546 case AArch64::LD4i32_POST:
4547 case AArch64::LD4i64_POST:
4548 case AArch64::LD4i8_POST:
4549 case AArch64::LDAPRWpost:
4550 case AArch64::LDAPRXpost:
4551 case AArch64::LDIAPPWpost:
4552 case AArch64::LDIAPPXpost:
4553 case AArch64::LDPDpost:
4554 case AArch64::LDPQpost:
4555 case AArch64::LDPSWpost:
4556 case AArch64::LDPSpost:
4557 case AArch64::LDPWpost:
4558 case AArch64::LDPXpost:
4559 case AArch64::LDRBBpost:
4560 case AArch64::LDRBpost:
4561 case AArch64::LDRDpost:
4562 case AArch64::LDRHHpost:
4563 case AArch64::LDRHpost:
4564 case AArch64::LDRQpost:
4565 case AArch64::LDRSBWpost:
4566 case AArch64::LDRSBXpost:
4567 case AArch64::LDRSHWpost:
4568 case AArch64::LDRSHXpost:
4569 case AArch64::LDRSWpost:
4570 case AArch64::LDRSpost:
4571 case AArch64::LDRWpost:
4572 case AArch64::LDRXpost:
4573 case AArch64::ST1Fourv16b_POST:
4574 case AArch64::ST1Fourv1d_POST:
4575 case AArch64::ST1Fourv2d_POST:
4576 case AArch64::ST1Fourv2s_POST:
4577 case AArch64::ST1Fourv4h_POST:
4578 case AArch64::ST1Fourv4s_POST:
4579 case AArch64::ST1Fourv8b_POST:
4580 case AArch64::ST1Fourv8h_POST:
4581 case AArch64::ST1Onev16b_POST:
4582 case AArch64::ST1Onev1d_POST:
4583 case AArch64::ST1Onev2d_POST:
4584 case AArch64::ST1Onev2s_POST:
4585 case AArch64::ST1Onev4h_POST:
4586 case AArch64::ST1Onev4s_POST:
4587 case AArch64::ST1Onev8b_POST:
4588 case AArch64::ST1Onev8h_POST:
4589 case AArch64::ST1Threev16b_POST:
4590 case AArch64::ST1Threev1d_POST:
4591 case AArch64::ST1Threev2d_POST:
4592 case AArch64::ST1Threev2s_POST:
4593 case AArch64::ST1Threev4h_POST:
4594 case AArch64::ST1Threev4s_POST:
4595 case AArch64::ST1Threev8b_POST:
4596 case AArch64::ST1Threev8h_POST:
4597 case AArch64::ST1Twov16b_POST:
4598 case AArch64::ST1Twov1d_POST:
4599 case AArch64::ST1Twov2d_POST:
4600 case AArch64::ST1Twov2s_POST:
4601 case AArch64::ST1Twov4h_POST:
4602 case AArch64::ST1Twov4s_POST:
4603 case AArch64::ST1Twov8b_POST:
4604 case AArch64::ST1Twov8h_POST:
4605 case AArch64::ST1i16_POST:
4606 case AArch64::ST1i32_POST:
4607 case AArch64::ST1i64_POST:
4608 case AArch64::ST1i8_POST:
4609 case AArch64::ST2GPostIndex:
4610 case AArch64::ST2Twov16b_POST:
4611 case AArch64::ST2Twov2d_POST:
4612 case AArch64::ST2Twov2s_POST:
4613 case AArch64::ST2Twov4h_POST:
4614 case AArch64::ST2Twov4s_POST:
4615 case AArch64::ST2Twov8b_POST:
4616 case AArch64::ST2Twov8h_POST:
4617 case AArch64::ST2i16_POST:
4618 case AArch64::ST2i32_POST:
4619 case AArch64::ST2i64_POST:
4620 case AArch64::ST2i8_POST:
4621 case AArch64::ST3Threev16b_POST:
4622 case AArch64::ST3Threev2d_POST:
4623 case AArch64::ST3Threev2s_POST:
4624 case AArch64::ST3Threev4h_POST:
4625 case AArch64::ST3Threev4s_POST:
4626 case AArch64::ST3Threev8b_POST:
4627 case AArch64::ST3Threev8h_POST:
4628 case AArch64::ST3i16_POST:
4629 case AArch64::ST3i32_POST:
4630 case AArch64::ST3i64_POST:
4631 case AArch64::ST3i8_POST:
4632 case AArch64::ST4Fourv16b_POST:
4633 case AArch64::ST4Fourv2d_POST:
4634 case AArch64::ST4Fourv2s_POST:
4635 case AArch64::ST4Fourv4h_POST:
4636 case AArch64::ST4Fourv4s_POST:
4637 case AArch64::ST4Fourv8b_POST:
4638 case AArch64::ST4Fourv8h_POST:
4639 case AArch64::ST4i16_POST:
4640 case AArch64::ST4i32_POST:
4641 case AArch64::ST4i64_POST:
4642 case AArch64::ST4i8_POST:
4643 case AArch64::STGPostIndex:
4644 case AArch64::STGPpost:
4645 case AArch64::STPDpost:
4646 case AArch64::STPQpost:
4647 case AArch64::STPSpost:
4648 case AArch64::STPWpost:
4649 case AArch64::STPXpost:
4650 case AArch64::STRBBpost:
4651 case AArch64::STRBpost:
4652 case AArch64::STRDpost:
4653 case AArch64::STRHHpost:
4654 case AArch64::STRHpost:
4655 case AArch64::STRQpost:
4656 case AArch64::STRSpost:
4657 case AArch64::STRWpost:
4658 case AArch64::STRXpost:
4659 case AArch64::STZ2GPostIndex:
4660 case AArch64::STZGPostIndex:
4661 return true;
4662 }
4663}
4664
4666 const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
4667 bool &OffsetIsScalable, TypeSize &Width) const {
4668 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4669 // Handle only loads/stores with base register followed by immediate offset.
4670 if (LdSt.getNumExplicitOperands() == 3) {
4671 // Non-paired instruction (e.g., ldr x1, [x0, #8]).
4672 if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
4673 !LdSt.getOperand(2).isImm())
4674 return false;
4675 } else if (LdSt.getNumExplicitOperands() == 4) {
4676 // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
4677 if (!LdSt.getOperand(1).isReg() ||
4678 (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
4679 !LdSt.getOperand(3).isImm())
4680 return false;
4681 } else
4682 return false;
4683
4684 // Get the scaling factor for the instruction and set the width for the
4685 // instruction.
4686 TypeSize Scale(0U, false);
4687 int64_t Dummy1, Dummy2;
4688
4689 // If this returns false, then it's an instruction we don't want to handle.
4690 if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
4691 return false;
4692
4693 // Compute the offset. Offset is calculated as the immediate operand
4694 // multiplied by the scaling factor. Unscaled instructions have scaling factor
4695 // set to 1. Postindex are a special case which have an offset of 0.
4696 if (isPostIndexLdStOpcode(LdSt.getOpcode())) {
4697 BaseOp = &LdSt.getOperand(2);
4698 Offset = 0;
4699 } else if (LdSt.getNumExplicitOperands() == 3) {
4700 BaseOp = &LdSt.getOperand(1);
4701 Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinValue();
4702 } else {
4703 assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
4704 BaseOp = &LdSt.getOperand(2);
4705 Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinValue();
4706 }
4707 OffsetIsScalable = Scale.isScalable();
4708
4709 return BaseOp->isReg() || BaseOp->isFI();
4710}
4711
4714 assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
4715 MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
4716 assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
4717 return OfsOp;
4718}
4719
4720bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
4721 TypeSize &Width, int64_t &MinOffset,
4722 int64_t &MaxOffset) {
4723 switch (Opcode) {
4724 // Not a memory operation or something we want to handle.
4725 default:
4726 Scale = Width = TypeSize::getFixed(0);
4727 MinOffset = MaxOffset = 0;
4728 return false;
4729 // LDR / STR
4730 case AArch64::LDRQui:
4731 case AArch64::STRQui:
4732 Scale = Width = TypeSize::getFixed(16);
4733 MinOffset = 0;
4734 MaxOffset = 4095;
4735 break;
4736 case AArch64::LDRXui:
4737 case AArch64::LDRDui:
4738 case AArch64::STRXui:
4739 case AArch64::STRDui:
4740 case AArch64::PRFMui:
4741 case AArch64::ATOMIC_STORE_HINT_Xui:
4742 case AArch64::ATOMIC_STORE_HINT_Dui:
4743 Scale = Width = TypeSize::getFixed(8);
4744 MinOffset = 0;
4745 MaxOffset = 4095;
4746 break;
4747 case AArch64::LDRWui:
4748 case AArch64::LDRSui:
4749 case AArch64::LDRSWui:
4750 case AArch64::STRWui:
4751 case AArch64::STRSui:
4752 case AArch64::ATOMIC_STORE_HINT_Wui:
4753 case AArch64::ATOMIC_STORE_HINT_Sui:
4754 Scale = Width = TypeSize::getFixed(4);
4755 MinOffset = 0;
4756 MaxOffset = 4095;
4757 break;
4758 case AArch64::LDRHui:
4759 case AArch64::LDRHHui:
4760 case AArch64::LDRSHWui:
4761 case AArch64::LDRSHXui:
4762 case AArch64::STRHui:
4763 case AArch64::STRHHui:
4764 case AArch64::ATOMIC_STORE_HINT_Hui:
4765 Scale = Width = TypeSize::getFixed(2);
4766 MinOffset = 0;
4767 MaxOffset = 4095;
4768 break;
4769 case AArch64::LDRBui:
4770 case AArch64::LDRBBui:
4771 case AArch64::LDRSBWui:
4772 case AArch64::LDRSBXui:
4773 case AArch64::STRBui:
4774 case AArch64::STRBBui:
4775 case AArch64::ATOMIC_STORE_HINT_Bui:
4776 Scale = Width = TypeSize::getFixed(1);
4777 MinOffset = 0;
4778 MaxOffset = 4095;
4779 break;
4780 // post/pre inc
4781 case AArch64::STRQpre:
4782 case AArch64::LDRQpost:
4783 Scale = TypeSize::getFixed(1);
4784 Width = TypeSize::getFixed(16);
4785 MinOffset = -256;
4786 MaxOffset = 255;
4787 break;
4788 case AArch64::LDRDpost:
4789 case AArch64::LDRDpre:
4790 case AArch64::LDRXpost:
4791 case AArch64::LDRXpre:
4792 case AArch64::STRDpost:
4793 case AArch64::STRDpre:
4794 case AArch64::STRXpost:
4795 case AArch64::STRXpre:
4796 Scale = TypeSize::getFixed(1);
4797 Width = TypeSize::getFixed(8);
4798 MinOffset = -256;
4799 MaxOffset = 255;
4800 break;
4801 case AArch64::STRWpost:
4802 case AArch64::STRWpre:
4803 case AArch64::LDRWpost:
4804 case AArch64::LDRWpre:
4805 case AArch64::STRSpost:
4806 case AArch64::STRSpre:
4807 case AArch64::LDRSpost:
4808 case AArch64::LDRSpre:
4809 Scale = TypeSize::getFixed(1);
4810 Width = TypeSize::getFixed(4);
4811 MinOffset = -256;
4812 MaxOffset = 255;
4813 break;
4814 case AArch64::LDRHpost:
4815 case AArch64::LDRHpre:
4816 case AArch64::STRHpost:
4817 case AArch64::STRHpre:
4818 case AArch64::LDRHHpost:
4819 case AArch64::LDRHHpre:
4820 case AArch64::STRHHpost:
4821 case AArch64::STRHHpre:
4822 Scale = TypeSize::getFixed(1);
4823 Width = TypeSize::getFixed(2);
4824 MinOffset = -256;
4825 MaxOffset = 255;
4826 break;
4827 case AArch64::LDRBpost:
4828 case AArch64::LDRBpre:
4829 case AArch64::STRBpost:
4830 case AArch64::STRBpre:
4831 case AArch64::LDRBBpost:
4832 case AArch64::LDRBBpre:
4833 case AArch64::STRBBpost:
4834 case AArch64::STRBBpre:
4835 Scale = Width = TypeSize::getFixed(1);
4836 MinOffset = -256;
4837 MaxOffset = 255;
4838 break;
4839 // Unscaled
4840 case AArch64::LDURQi:
4841 case AArch64::STURQi:
4842 Scale = TypeSize::getFixed(1);
4843 Width = TypeSize::getFixed(16);
4844 MinOffset = -256;
4845 MaxOffset = 255;
4846 break;
4847 case AArch64::LDURXi:
4848 case AArch64::LDURDi:
4849 case AArch64::LDAPURXi:
4850 case AArch64::STURXi:
4851 case AArch64::STURDi:
4852 case AArch64::STLURXi:
4853 case AArch64::PRFUMi:
4854 case AArch64::ATOMIC_STORE_HINT_Xi:
4855 case AArch64::ATOMIC_STORE_HINT_Di:
4856 Scale = TypeSize::getFixed(1);
4857 Width = TypeSize::getFixed(8);
4858 MinOffset = -256;
4859 MaxOffset = 255;
4860 break;
4861 case AArch64::LDURWi:
4862 case AArch64::LDURSi:
4863 case AArch64::LDURSWi:
4864 case AArch64::LDAPURi:
4865 case AArch64::LDAPURSWi:
4866 case AArch64::STURWi:
4867 case AArch64::STURSi:
4868 case AArch64::STLURWi:
4869 case AArch64::ATOMIC_STORE_HINT_Wi:
4870 case AArch64::ATOMIC_STORE_HINT_Si:
4871 Scale = TypeSize::getFixed(1);
4872 Width = TypeSize::getFixed(4);
4873 MinOffset = -256;
4874 MaxOffset = 255;
4875 break;
4876 case AArch64::LDURHi:
4877 case AArch64::LDURHHi:
4878 case AArch64::LDURSHXi:
4879 case AArch64::LDURSHWi:
4880 case AArch64::LDAPURHi:
4881 case AArch64::LDAPURSHWi:
4882 case AArch64::LDAPURSHXi:
4883 case AArch64::STURHi:
4884 case AArch64::STURHHi:
4885 case AArch64::STLURHi:
4886 case AArch64::ATOMIC_STORE_HINT_Hi:
4887 Scale = TypeSize::getFixed(1);
4888 Width = TypeSize::getFixed(2);
4889 MinOffset = -256;
4890 MaxOffset = 255;
4891 break;
4892 case AArch64::LDURBi:
4893 case AArch64::LDURBBi:
4894 case AArch64::LDURSBXi:
4895 case AArch64::LDURSBWi:
4896 case AArch64::LDAPURBi:
4897 case AArch64::LDAPURSBWi:
4898 case AArch64::LDAPURSBXi:
4899 case AArch64::STURBi:
4900 case AArch64::STURBBi:
4901 case AArch64::STLURBi:
4902 case AArch64::ATOMIC_STORE_HINT_Bi:
4903 Scale = Width = TypeSize::getFixed(1);
4904 MinOffset = -256;
4905 MaxOffset = 255;
4906 break;
4907 // LDP / STP (including pre/post inc)
4908 case AArch64::LDPQi:
4909 case AArch64::LDNPQi:
4910 case AArch64::STPQi:
4911 case AArch64::STNPQi:
4912 case AArch64::LDPQpost:
4913 case AArch64::LDPQpre:
4914 case AArch64::STPQpost:
4915 case AArch64::STPQpre:
4916 Scale = TypeSize::getFixed(16);
4917 Width = TypeSize::getFixed(16 * 2);
4918 MinOffset = -64;
4919 MaxOffset = 63;
4920 break;
4921 case AArch64::LDPXi:
4922 case AArch64::LDPDi:
4923 case AArch64::LDNPXi:
4924 case AArch64::LDNPDi:
4925 case AArch64::STPXi:
4926 case AArch64::STPDi:
4927 case AArch64::STNPXi:
4928 case AArch64::STNPDi:
4929 case AArch64::LDPDpost:
4930 case AArch64::LDPDpre:
4931 case AArch64::LDPXpost:
4932 case AArch64::LDPXpre:
4933 case AArch64::STPDpost:
4934 case AArch64::STPDpre:
4935 case AArch64::STPXpost:
4936 case AArch64::STPXpre:
4937 Scale = TypeSize::getFixed(8);
4938 Width = TypeSize::getFixed(8 * 2);
4939 MinOffset = -64;
4940 MaxOffset = 63;
4941 break;
4942 case AArch64::LDPWi:
4943 case AArch64::LDPSi:
4944 case AArch64::LDNPWi:
4945 case AArch64::LDNPSi:
4946 case AArch64::STPWi:
4947 case AArch64::STPSi:
4948 case AArch64::STNPWi:
4949 case AArch64::STNPSi:
4950 case AArch64::LDPSpost:
4951 case AArch64::LDPSpre:
4952 case AArch64::LDPWpost:
4953 case AArch64::LDPWpre:
4954 case AArch64::STPSpost:
4955 case AArch64::STPSpre:
4956 case AArch64::STPWpost:
4957 case AArch64::STPWpre:
4958 Scale = TypeSize::getFixed(4);
4959 Width = TypeSize::getFixed(4 * 2);
4960 MinOffset = -64;
4961 MaxOffset = 63;
4962 break;
4963 case AArch64::StoreSwiftAsyncContext:
4964 // Store is an STRXui, but there might be an ADDXri in the expansion too.
4965 Scale = TypeSize::getFixed(1);
4966 Width = TypeSize::getFixed(8);
4967 MinOffset = 0;
4968 MaxOffset = 4095;
4969 break;
4970 case AArch64::ADDG:
4971 Scale = TypeSize::getFixed(16);
4972 Width = TypeSize::getFixed(0);
4973 MinOffset = 0;
4974 MaxOffset = 63;
4975 break;
4976 case AArch64::TAGPstack:
4977 Scale = TypeSize::getFixed(16);
4978 Width = TypeSize::getFixed(0);
4979 // TAGP with a negative offset turns into SUBP, which has a maximum offset
4980 // of 63 (not 64!).
4981 MinOffset = -63;
4982 MaxOffset = 63;
4983 break;
4984 case AArch64::LDG:
4985 case AArch64::STGi:
4986 case AArch64::STGPreIndex:
4987 case AArch64::STGPostIndex:
4988 case AArch64::STZGi:
4989 case AArch64::STZGPreIndex:
4990 case AArch64::STZGPostIndex:
4991 Scale = Width = TypeSize::getFixed(16);
4992 MinOffset = -256;
4993 MaxOffset = 255;
4994 break;
4995 // SVE
4996 case AArch64::STR_ZZZZXI:
4997 case AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS:
4998 case AArch64::LDR_ZZZZXI:
4999 case AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS:
5000 Scale = TypeSize::getScalable(16);
5001 Width = TypeSize::getScalable(16 * 4);
5002 MinOffset = -256;
5003 MaxOffset = 252;
5004 break;
5005 case AArch64::STR_ZZZXI:
5006 case AArch64::LDR_ZZZXI:
5007 Scale = TypeSize::getScalable(16);
5008 Width = TypeSize::getScalable(16 * 3);
5009 MinOffset = -256;
5010 MaxOffset = 253;
5011 break;
5012 case AArch64::STR_ZZXI:
5013 case AArch64::STR_ZZXI_STRIDED_CONTIGUOUS:
5014 case AArch64::LDR_ZZXI:
5015 case AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS:
5016 Scale = TypeSize::getScalable(16);
5017 Width = TypeSize::getScalable(16 * 2);
5018 MinOffset = -256;
5019 MaxOffset = 254;
5020 break;
5021 case AArch64::LDR_PXI:
5022 case AArch64::STR_PXI:
5023 Scale = Width = TypeSize::getScalable(2);
5024 MinOffset = -256;
5025 MaxOffset = 255;
5026 break;
5027 case AArch64::LDR_PPXI:
5028 case AArch64::STR_PPXI:
5029 Scale = TypeSize::getScalable(2);
5030 Width = TypeSize::getScalable(2 * 2);
5031 MinOffset = -256;
5032 MaxOffset = 254;
5033 break;
5034 case AArch64::LDR_ZXI:
5035 case AArch64::STR_ZXI:
5036 Scale = Width = TypeSize::getScalable(16);
5037 MinOffset = -256;
5038 MaxOffset = 255;
5039 break;
5040 case AArch64::LD1B_IMM:
5041 case AArch64::LD1H_IMM:
5042 case AArch64::LD1W_IMM:
5043 case AArch64::LD1D_IMM:
5044 case AArch64::LDNT1B_ZRI:
5045 case AArch64::LDNT1H_ZRI:
5046 case AArch64::LDNT1W_ZRI:
5047 case AArch64::LDNT1D_ZRI:
5048 case AArch64::ST1B_IMM:
5049 case AArch64::ST1H_IMM:
5050 case AArch64::ST1W_IMM:
5051 case AArch64::ST1D_IMM:
5052 case AArch64::STNT1B_ZRI:
5053 case AArch64::STNT1H_ZRI:
5054 case AArch64::STNT1W_ZRI:
5055 case AArch64::STNT1D_ZRI:
5056 case AArch64::LDNF1B_IMM:
5057 case AArch64::LDNF1H_IMM:
5058 case AArch64::LDNF1W_IMM:
5059 case AArch64::LDNF1D_IMM:
5060 // A full vectors worth of data
5061 // Width = mbytes * elements
5062 Scale = Width = TypeSize::getScalable(16);
5063 MinOffset = -8;
5064 MaxOffset = 7;
5065 break;
5066 case AArch64::LD2B_IMM:
5067 case AArch64::LD2H_IMM:
5068 case AArch64::LD2W_IMM:
5069 case AArch64::LD2D_IMM:
5070 case AArch64::ST2B_IMM:
5071 case AArch64::ST2H_IMM:
5072 case AArch64::ST2W_IMM:
5073 case AArch64::ST2D_IMM:
5074 case AArch64::LD1B_2Z_IMM:
5075 case AArch64::LD1B_2Z_STRIDED_IMM:
5076 case AArch64::LD1H_2Z_IMM:
5077 case AArch64::LD1H_2Z_STRIDED_IMM:
5078 case AArch64::LD1W_2Z_IMM:
5079 case AArch64::LD1W_2Z_STRIDED_IMM:
5080 case AArch64::LD1D_2Z_IMM:
5081 case AArch64::LD1D_2Z_STRIDED_IMM:
5082 case AArch64::LD1B_2Z_IMM_PSEUDO:
5083 case AArch64::LD1H_2Z_IMM_PSEUDO:
5084 case AArch64::LD1W_2Z_IMM_PSEUDO:
5085 case AArch64::LD1D_2Z_IMM_PSEUDO:
5086 case AArch64::ST1B_2Z_IMM:
5087 case AArch64::ST1B_2Z_STRIDED_IMM:
5088 case AArch64::ST1H_2Z_IMM:
5089 case AArch64::ST1H_2Z_STRIDED_IMM:
5090 case AArch64::ST1W_2Z_IMM:
5091 case AArch64::ST1W_2Z_STRIDED_IMM:
5092 case AArch64::ST1D_2Z_IMM:
5093 case AArch64::ST1D_2Z_STRIDED_IMM:
5094 case AArch64::LDNT1B_2Z_IMM_PSEUDO:
5095 case AArch64::LDNT1B_2Z_IMM:
5096 case AArch64::LDNT1B_2Z_STRIDED_IMM:
5097 case AArch64::LDNT1H_2Z_IMM_PSEUDO:
5098 case AArch64::LDNT1H_2Z_IMM:
5099 case AArch64::LDNT1H_2Z_STRIDED_IMM:
5100 case AArch64::LDNT1W_2Z_IMM_PSEUDO:
5101 case AArch64::LDNT1W_2Z_IMM:
5102 case AArch64::LDNT1W_2Z_STRIDED_IMM:
5103 case AArch64::LDNT1D_2Z_IMM_PSEUDO:
5104 case AArch64::LDNT1D_2Z_IMM:
5105 case AArch64::LDNT1D_2Z_STRIDED_IMM:
5106 case AArch64::STNT1B_2Z_IMM:
5107 case AArch64::STNT1B_2Z_STRIDED_IMM:
5108 case AArch64::STNT1H_2Z_IMM:
5109 case AArch64::STNT1H_2Z_STRIDED_IMM:
5110 case AArch64::STNT1W_2Z_IMM:
5111 case AArch64::STNT1W_2Z_STRIDED_IMM:
5112 case AArch64::STNT1D_2Z_IMM:
5113 case AArch64::STNT1D_2Z_STRIDED_IMM:
5114 case AArch64::ST1B_2Z_IMM_PSEUDO:
5115 case AArch64::ST1H_2Z_IMM_PSEUDO:
5116 case AArch64::ST1W_2Z_IMM_PSEUDO:
5117 case AArch64::ST1D_2Z_IMM_PSEUDO:
5118 case AArch64::STNT1B_2Z_IMM_PSEUDO:
5119 case AArch64::STNT1H_2Z_IMM_PSEUDO:
5120 case AArch64::STNT1W_2Z_IMM_PSEUDO:
5121 case AArch64::STNT1D_2Z_IMM_PSEUDO:
5122 Scale = Width = TypeSize::getScalable(16 * 2);
5123 MinOffset = -8;
5124 MaxOffset = 7;
5125 break;
5126 case AArch64::LD3B_IMM:
5127 case AArch64::LD3H_IMM:
5128 case AArch64::LD3W_IMM:
5129 case AArch64::LD3D_IMM:
5130 case AArch64::ST3B_IMM:
5131 case AArch64::ST3H_IMM:
5132 case AArch64::ST3W_IMM:
5133 case AArch64::ST3D_IMM:
5134 Scale = Width = TypeSize::getScalable(16 * 3);
5135 MinOffset = -8;
5136 MaxOffset = 7;
5137 break;
5138 case AArch64::LD4B_IMM:
5139 case AArch64::LD4H_IMM:
5140 case AArch64::LD4W_IMM:
5141 case AArch64::LD4D_IMM:
5142 case AArch64::ST4B_IMM:
5143 case AArch64::ST4H_IMM:
5144 case AArch64::ST4W_IMM:
5145 case AArch64::ST4D_IMM:
5146 case AArch64::LD1B_4Z_IMM:
5147 case AArch64::LD1B_4Z_STRIDED_IMM:
5148 case AArch64::LD1H_4Z_IMM:
5149 case AArch64::LD1H_4Z_STRIDED_IMM:
5150 case AArch64::LD1W_4Z_IMM:
5151 case AArch64::LD1W_4Z_STRIDED_IMM:
5152 case AArch64::LD1D_4Z_IMM:
5153 case AArch64::LD1D_4Z_STRIDED_IMM:
5154 case AArch64::LD1B_4Z_IMM_PSEUDO:
5155 case AArch64::LD1H_4Z_IMM_PSEUDO:
5156 case AArch64::LD1W_4Z_IMM_PSEUDO:
5157 case AArch64::LD1D_4Z_IMM_PSEUDO:
5158 case AArch64::ST1B_4Z_IMM:
5159 case AArch64::ST1B_4Z_STRIDED_IMM:
5160 case AArch64::ST1H_4Z_IMM:
5161 case AArch64::ST1H_4Z_STRIDED_IMM:
5162 case AArch64::ST1W_4Z_IMM:
5163 case AArch64::ST1W_4Z_STRIDED_IMM:
5164 case AArch64::ST1D_4Z_IMM:
5165 case AArch64::ST1D_4Z_STRIDED_IMM:
5166 case AArch64::LDNT1B_4Z_IMM_PSEUDO:
5167 case AArch64::LDNT1B_4Z_IMM:
5168 case AArch64::LDNT1B_4Z_STRIDED_IMM:
5169 case AArch64::LDNT1H_4Z_IMM_PSEUDO:
5170 case AArch64::LDNT1H_4Z_IMM:
5171 case AArch64::LDNT1H_4Z_STRIDED_IMM:
5172 case AArch64::LDNT1W_4Z_IMM_PSEUDO:
5173 case AArch64::LDNT1W_4Z_IMM:
5174 case AArch64::LDNT1W_4Z_STRIDED_IMM:
5175 case AArch64::LDNT1D_4Z_IMM_PSEUDO:
5176 case AArch64::LDNT1D_4Z_IMM:
5177 case AArch64::LDNT1D_4Z_STRIDED_IMM:
5178 case AArch64::STNT1B_4Z_IMM:
5179 case AArch64::STNT1B_4Z_STRIDED_IMM:
5180 case AArch64::STNT1H_4Z_IMM:
5181 case AArch64::STNT1H_4Z_STRIDED_IMM:
5182 case AArch64::STNT1W_4Z_IMM:
5183 case AArch64::STNT1W_4Z_STRIDED_IMM:
5184 case AArch64::STNT1D_4Z_IMM:
5185 case AArch64::STNT1D_4Z_STRIDED_IMM:
5186 case AArch64::ST1B_4Z_IMM_PSEUDO:
5187 case AArch64::ST1H_4Z_IMM_PSEUDO:
5188 case AArch64::ST1W_4Z_IMM_PSEUDO:
5189 case AArch64::ST1D_4Z_IMM_PSEUDO:
5190 case AArch64::STNT1B_4Z_IMM_PSEUDO:
5191 case AArch64::STNT1H_4Z_IMM_PSEUDO:
5192 case AArch64::STNT1W_4Z_IMM_PSEUDO:
5193 case AArch64::STNT1D_4Z_IMM_PSEUDO:
5194 Scale = Width = TypeSize::getScalable(16 * 4);
5195 MinOffset = -8;
5196 MaxOffset = 7;
5197 break;
5198 case AArch64::LD1B_H_IMM:
5199 case AArch64::LD1SB_H_IMM:
5200 case AArch64::LD1H_S_IMM:
5201 case AArch64::LD1SH_S_IMM:
5202 case AArch64::LD1W_D_IMM:
5203 case AArch64::LD1SW_D_IMM:
5204 case AArch64::ST1B_H_IMM:
5205 case AArch64::ST1H_S_IMM:
5206 case AArch64::ST1W_D_IMM:
5207 case AArch64::LDNF1B_H_IMM:
5208 case AArch64::LDNF1SB_H_IMM:
5209 case AArch64::LDNF1H_S_IMM:
5210 case AArch64::LDNF1SH_S_IMM:
5211 case AArch64::LDNF1W_D_IMM:
5212 case AArch64::LDNF1SW_D_IMM:
5213 // A half vector worth of data
5214 // Width = mbytes * elements
5215 Scale = Width = TypeSize::getScalable(8);
5216 MinOffset = -8;
5217 MaxOffset = 7;
5218 break;
5219 case AArch64::LD1B_S_IMM:
5220 case AArch64::LD1SB_S_IMM:
5221 case AArch64::LD1H_D_IMM:
5222 case AArch64::LD1SH_D_IMM:
5223 case AArch64::ST1B_S_IMM:
5224 case AArch64::ST1H_D_IMM:
5225 case AArch64::LDNF1B_S_IMM:
5226 case AArch64::LDNF1SB_S_IMM:
5227 case AArch64::LDNF1H_D_IMM:
5228 case AArch64::LDNF1SH_D_IMM:
5229 // A quarter vector worth of data
5230 // Width = mbytes * elements
5231 Scale = Width = TypeSize::getScalable(4);
5232 MinOffset = -8;
5233 MaxOffset = 7;
5234 break;
5235 case AArch64::LD1B_D_IMM:
5236 case AArch64::LD1SB_D_IMM:
5237 case AArch64::ST1B_D_IMM:
5238 case AArch64::LDNF1B_D_IMM:
5239 case AArch64::LDNF1SB_D_IMM:
5240 // A eighth vector worth of data
5241 // Width = mbytes * elements
5242 Scale = Width = TypeSize::getScalable(2);
5243 MinOffset = -8;
5244 MaxOffset = 7;
5245 break;
5246 case AArch64::ST2Gi:
5247 case AArch64::ST2GPreIndex:
5248 case AArch64::ST2GPostIndex:
5249 case AArch64::STZ2Gi:
5250 case AArch64::STZ2GPreIndex:
5251 case AArch64::STZ2GPostIndex:
5252 Scale = TypeSize::getFixed(16);
5253 Width = TypeSize::getFixed(32);
5254 MinOffset = -256;
5255 MaxOffset = 255;
5256 break;
5257 case AArch64::STGPi:
5258 case AArch64::STGPpost:
5259 case AArch64::STGPpre:
5260 Scale = Width = TypeSize::getFixed(16);
5261 MinOffset = -64;
5262 MaxOffset = 63;
5263 break;
5264 case AArch64::LD1RB_IMM:
5265 case AArch64::LD1RB_H_IMM:
5266 case AArch64::LD1RB_S_IMM:
5267 case AArch64::LD1RB_D_IMM:
5268 case AArch64::LD1RSB_H_IMM:
5269 case AArch64::LD1RSB_S_IMM:
5270 case AArch64::LD1RSB_D_IMM:
5271 Scale = Width = TypeSize::getFixed(1);
5272 MinOffset = 0;
5273 MaxOffset = 63;
5274 break;
5275 case AArch64::LD1RH_IMM:
5276 case AArch64::LD1RH_S_IMM:
5277 case AArch64::LD1RH_D_IMM:
5278 case AArch64::LD1RSH_S_IMM:
5279 case AArch64::LD1RSH_D_IMM:
5280 Scale = Width = TypeSize::getFixed(2);
5281 MinOffset = 0;
5282 MaxOffset = 63;
5283 break;
5284 case AArch64::LD1RW_IMM:
5285 case AArch64::LD1RW_D_IMM:
5286 case AArch64::LD1RSW_IMM:
5287 Scale = Width = TypeSize::getFixed(4);
5288 MinOffset = 0;
5289 MaxOffset = 63;
5290 break;
5291 case AArch64::LD1RD_IMM:
5292 Scale = Width = TypeSize::getFixed(8);
5293 MinOffset = 0;
5294 MaxOffset = 63;
5295 break;
5296 }
5297
5298 return true;
5299}
5300
5301// Scaling factor for unscaled load or store.
5303 switch (Opc) {
5304 default:
5305 llvm_unreachable("Opcode has unknown scale!");
5306 case AArch64::LDRBui:
5307 case AArch64::LDRBBui:
5308 case AArch64::LDURBBi:
5309 case AArch64::LDRSBWui:
5310 case AArch64::LDURSBWi:
5311 case AArch64::STRBui:
5312 case AArch64::STRBBui:
5313 case AArch64::STURBBi:
5314 return 1;
5315 case AArch64::LDRHui:
5316 case AArch64::LDRHHui:
5317 case AArch64::LDURHHi:
5318 case AArch64::LDRSHWui:
5319 case AArch64::LDURSHWi:
5320 case AArch64::STRHui:
5321 case AArch64::STRHHui:
5322 case AArch64::STURHHi:
5323 return 2;
5324 case AArch64::LDRSui:
5325 case AArch64::LDURSi:
5326 case AArch64::LDRSpre:
5327 case AArch64::LDRSWui:
5328 case AArch64::LDURSWi:
5329 case AArch64::LDRSWpre:
5330 case AArch64::LDRWpre:
5331 case AArch64::LDRWui:
5332 case AArch64::LDURWi:
5333 case AArch64::STRSui:
5334 case AArch64::STURSi:
5335 case AArch64::STRSpre:
5336 case AArch64::STRWui:
5337 case AArch64::STURWi:
5338 case AArch64::STRWpre:
5339 case AArch64::LDPSi:
5340 case AArch64::LDPSWi:
5341 case AArch64::LDPWi:
5342 case AArch64::STPSi:
5343 case AArch64::STPWi:
5344 return 4;
5345 case AArch64::LDRDui:
5346 case AArch64::LDURDi:
5347 case AArch64::LDRDpre:
5348 case AArch64::LDRXui:
5349 case AArch64::LDURXi:
5350 case AArch64::LDRXpre:
5351 case AArch64::STRDui:
5352 case AArch64::STURDi:
5353 case AArch64::STRDpre:
5354 case AArch64::STRXui:
5355 case AArch64::STURXi:
5356 case AArch64::STRXpre:
5357 case AArch64::LDPDi:
5358 case AArch64::LDPXi:
5359 case AArch64::STPDi:
5360 case AArch64::STPXi:
5361 return 8;
5362 case AArch64::LDRQui:
5363 case AArch64::LDURQi:
5364 case AArch64::STRQui:
5365 case AArch64::STURQi:
5366 case AArch64::STRQpre:
5367 case AArch64::LDPQi:
5368 case AArch64::LDRQpre:
5369 case AArch64::STPQi:
5370 case AArch64::STGi:
5371 case AArch64::STZGi:
5372 case AArch64::ST2Gi:
5373 case AArch64::STZ2Gi:
5374 case AArch64::STGPi:
5375 return 16;
5376 }
5377}
5378
5380 switch (MI.getOpcode()) {
5381 default:
5382 return false;
5383 case AArch64::LDRWpre:
5384 case AArch64::LDRXpre:
5385 case AArch64::LDRSWpre:
5386 case AArch64::LDRSpre:
5387 case AArch64::LDRDpre:
5388 case AArch64::LDRQpre:
5389 return true;
5390 }
5391}
5392
5394 switch (MI.getOpcode()) {
5395 default:
5396 return false;
5397 case AArch64::STRWpre:
5398 case AArch64::STRXpre:
5399 case AArch64::STRSpre:
5400 case AArch64::STRDpre:
5401 case AArch64::STRQpre:
5402 return true;
5403 }
5404}
5405
5407 return isPreLd(MI) || isPreSt(MI);
5408}
5409
5411 switch (MI.getOpcode()) {
5412 default:
5413 return false;
5414 case AArch64::LDURBBi:
5415 case AArch64::LDURHHi:
5416 case AArch64::LDURWi:
5417 case AArch64::LDRBBui:
5418 case AArch64::LDRHHui:
5419 case AArch64::LDRWui:
5420 case AArch64::LDRBBroX:
5421 case AArch64::LDRHHroX:
5422 case AArch64::LDRWroX:
5423 case AArch64::LDRBBroW:
5424 case AArch64::LDRHHroW:
5425 case AArch64::LDRWroW:
5426 return true;
5427 }
5428}
5429
5431 switch (MI.getOpcode()) {
5432 default:
5433 return false;
5434 case AArch64::LDURSBWi:
5435 case AArch64::LDURSHWi:
5436 case AArch64::LDURSBXi:
5437 case AArch64::LDURSHXi:
5438 case AArch64::LDURSWi:
5439 case AArch64::LDRSBWui:
5440 case AArch64::LDRSHWui:
5441 case AArch64::LDRSBXui:
5442 case AArch64::LDRSHXui:
5443 case AArch64::LDRSWui:
5444 case AArch64::LDRSBWroX:
5445 case AArch64::LDRSHWroX:
5446 case AArch64::LDRSBXroX:
5447 case AArch64::LDRSHXroX:
5448 case AArch64::LDRSWroX:
5449 case AArch64::LDRSBWroW:
5450 case AArch64::LDRSHWroW:
5451 case AArch64::LDRSBXroW:
5452 case AArch64::LDRSHXroW:
5453 case AArch64::LDRSWroW:
5454 return true;
5455 }
5456}
5457
5459 switch (MI.getOpcode()) {
5460 default:
5461 return false;
5462 case AArch64::LDPSi:
5463 case AArch64::LDPSWi:
5464 case AArch64::LDPDi:
5465 case AArch64::LDPQi:
5466 case AArch64::LDPWi:
5467 case AArch64::LDPXi:
5468 case AArch64::STPSi:
5469 case AArch64::STPDi:
5470 case AArch64::STPQi:
5471 case AArch64::STPWi:
5472 case AArch64::STPXi:
5473 case AArch64::STGPi:
5474 return true;
5475 }
5476}
5477
5479 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5480 unsigned Idx =
5482 : 1;
5483 return MI.getOperand(Idx);
5484}
5485
5486const MachineOperand &
5488 assert(MI.mayLoadOrStore() && "Load or store instruction expected");
5489 unsigned Idx =
5491 : 2;
5492 return MI.getOperand(Idx);
5493}
5494
5495const MachineOperand &
5497 switch (MI.getOpcode()) {
5498 default:
5499 llvm_unreachable("Unexpected opcode");
5500 case AArch64::LDRBroX:
5501 case AArch64::LDRBBroX:
5502 case AArch64::LDRSBXroX:
5503 case AArch64::LDRSBWroX:
5504 case AArch64::LDRHroX:
5505 case AArch64::LDRHHroX:
5506 case AArch64::LDRSHXroX:
5507 case AArch64::LDRSHWroX:
5508 case AArch64::LDRWroX:
5509 case AArch64::LDRSroX:
5510 case AArch64::LDRSWroX:
5511 case AArch64::LDRDroX:
5512 case AArch64::LDRXroX:
5513 case AArch64::LDRQroX:
5514 return MI.getOperand(4);
5515 }
5516}
5517
5519 Register Reg) {
5520 if (MI.getParent() == nullptr)
5521 return nullptr;
5522 const MachineFunction *MF = MI.getParent()->getParent();
5523 return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
5524}
5525
5527 auto IsHFPR = [&](const MachineOperand &Op) {
5528 if (!Op.isReg())
5529 return false;
5530 auto Reg = Op.getReg();
5531 if (Reg.isPhysical())
5532 return AArch64::FPR16RegClass.contains(Reg);
5533 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5534 return TRC == &AArch64::FPR16RegClass ||
5535 TRC == &AArch64::FPR16_loRegClass;
5536 };
5537 return llvm::any_of(MI.operands(), IsHFPR);
5538}
5539
5541 auto IsQFPR = [&](const MachineOperand &Op) {
5542 if (!Op.isReg())
5543 return false;
5544 auto Reg = Op.getReg();
5545 if (Reg.isPhysical())
5546 return AArch64::FPR128RegClass.contains(Reg);
5547 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5548 return TRC == &AArch64::FPR128RegClass ||
5549 TRC == &AArch64::FPR128_loRegClass;
5550 };
5551 return llvm::any_of(MI.operands(), IsQFPR);
5552}
5553
5555 switch (MI.getOpcode()) {
5556 case AArch64::BRK:
5557 case AArch64::HLT:
5558 case AArch64::PACIASP:
5559 case AArch64::PACIBSP:
5560 // Implicit BTI behavior.
5561 return true;
5562 case AArch64::PAUTH_PROLOGUE:
5563 // PAUTH_PROLOGUE expands to PACI(A|B)SP.
5564 return true;
5565 case AArch64::HINT: {
5566 unsigned Imm = MI.getOperand(0).getImm();
5567 // Explicit BTI instruction.
5568 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
5569 return true;
5570 // PACI(A|B)SP instructions.
5571 if (Imm == 25 || Imm == 27)
5572 return true;
5573 return false;
5574 }
5575 default:
5576 return false;
5577 }
5578}
5579
5581 if (Reg == 0)
5582 return false;
5583 assert(Reg.isPhysical() && "Expected physical register in isFpOrNEON");
5584 return AArch64::FPR128RegClass.contains(Reg) ||
5585 AArch64::FPR64RegClass.contains(Reg) ||
5586 AArch64::FPR32RegClass.contains(Reg) ||
5587 AArch64::FPR16RegClass.contains(Reg) ||
5588 AArch64::FPR8RegClass.contains(Reg);
5589}
5590
5592 auto IsFPR = [&](const MachineOperand &Op) {
5593 if (!Op.isReg())
5594 return false;
5595 auto Reg = Op.getReg();
5596 if (Reg.isPhysical())
5597 return isFpOrNEON(Reg);
5598
5599 const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
5600 return TRC == &AArch64::FPR128RegClass ||
5601 TRC == &AArch64::FPR128_loRegClass ||
5602 TRC == &AArch64::FPR64RegClass ||
5603 TRC == &AArch64::FPR64_loRegClass ||
5604 TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
5605 TRC == &AArch64::FPR8RegClass;
5606 };
5607 return llvm::any_of(MI.operands(), IsFPR);
5608}
5609
5610// Scale the unscaled offsets. Returns false if the unscaled offset can't be
5611// scaled.
5612static bool scaleOffset(unsigned Opc, int64_t &Offset) {
5614
5615 // If the byte-offset isn't a multiple of the stride, we can't scale this
5616 // offset.
5617 if (Offset % Scale != 0)
5618 return false;
5619
5620 // Convert the byte-offset used by unscaled into an "element" offset used
5621 // by the scaled pair load/store instructions.
5622 Offset /= Scale;
5623 return true;
5624}
5625
5626static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
5627 if (FirstOpc == SecondOpc)
5628 return true;
5629 // We can also pair sign-ext and zero-ext instructions.
5630 switch (FirstOpc) {
5631 default:
5632 return false;
5633 case AArch64::STRSui:
5634 case AArch64::STURSi:
5635 return SecondOpc == AArch64::STRSui || SecondOpc == AArch64::STURSi;
5636 case AArch64::STRDui:
5637 case AArch64::STURDi:
5638 return SecondOpc == AArch64::STRDui || SecondOpc == AArch64::STURDi;
5639 case AArch64::STRQui:
5640 case AArch64::STURQi:
5641 return SecondOpc == AArch64::STRQui || SecondOpc == AArch64::STURQi;
5642 case AArch64::STRWui:
5643 case AArch64::STURWi:
5644 return SecondOpc == AArch64::STRWui || SecondOpc == AArch64::STURWi;
5645 case AArch64::STRXui:
5646 case AArch64::STURXi:
5647 return SecondOpc == AArch64::STRXui || SecondOpc == AArch64::STURXi;
5648 case AArch64::LDRSui:
5649 case AArch64::LDURSi:
5650 return SecondOpc == AArch64::LDRSui || SecondOpc == AArch64::LDURSi;
5651 case AArch64::LDRDui:
5652 case AArch64::LDURDi:
5653 return SecondOpc == AArch64::LDRDui || SecondOpc == AArch64::LDURDi;
5654 case AArch64::LDRQui:
5655 case AArch64::LDURQi:
5656 return SecondOpc == AArch64::LDRQui || SecondOpc == AArch64::LDURQi;
5657 case AArch64::LDRWui:
5658 case AArch64::LDURWi:
5659 return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
5660 case AArch64::LDRSWui:
5661 case AArch64::LDURSWi:
5662 return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
5663 case AArch64::LDRXui:
5664 case AArch64::LDURXi:
5665 return SecondOpc == AArch64::LDRXui || SecondOpc == AArch64::LDURXi;
5666 }
5667 // These instructions can't be paired based on their opcodes.
5668 return false;
5669}
5670
5671static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
5672 int64_t Offset1, unsigned Opcode1, int FI2,
5673 int64_t Offset2, unsigned Opcode2) {
5674 // Accesses through fixed stack object frame indices may access a different
5675 // fixed stack slot. Check that the object offsets + offsets match.
5676 if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
5677 int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
5678 int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
5679 assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
5680 // Convert to scaled object offsets.
5681 int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
5682 if (ObjectOffset1 % Scale1 != 0)
5683 return false;
5684 ObjectOffset1 /= Scale1;
5685 int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
5686 if (ObjectOffset2 % Scale2 != 0)
5687 return false;
5688 ObjectOffset2 /= Scale2;
5689 ObjectOffset1 += Offset1;
5690 ObjectOffset2 += Offset2;
5691 return ObjectOffset1 + 1 == ObjectOffset2;
5692 }
5693
5694 return FI1 == FI2;
5695}
5696
5697/// Detect opportunities for ldp/stp formation.
5698///
5699/// Only called for LdSt for which getMemOperandWithOffset returns true.
5701 ArrayRef<const MachineOperand *> BaseOps1, int64_t OpOffset1,
5702 bool OffsetIsScalable1, ArrayRef<const MachineOperand *> BaseOps2,
5703 int64_t OpOffset2, bool OffsetIsScalable2, unsigned ClusterSize,
5704 unsigned NumBytes) const {
5705 assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
5706 const MachineOperand &BaseOp1 = *BaseOps1.front();
5707 const MachineOperand &BaseOp2 = *BaseOps2.front();
5708 const MachineInstr &FirstLdSt = *BaseOp1.getParent();
5709 const MachineInstr &SecondLdSt = *BaseOp2.getParent();
5710 if (BaseOp1.getType() != BaseOp2.getType())
5711 return false;
5712
5713 assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
5714 "Only base registers and frame indices are supported.");
5715
5716 // Check for both base regs and base FI.
5717 if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
5718 return false;
5719
5720 // Only cluster up to a single pair.
5721 if (ClusterSize > 2)
5722 return false;
5723
5724 if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
5725 return false;
5726
5727 // Can we pair these instructions based on their opcodes?
5728 unsigned FirstOpc = FirstLdSt.getOpcode();
5729 unsigned SecondOpc = SecondLdSt.getOpcode();
5730 if (!canPairLdStOpc(FirstOpc, SecondOpc))
5731 return false;
5732
5733 // Can't merge volatiles or load/stores that have a hint to avoid pair
5734 // formation, for example.
5735 if (!isCandidateToMergeOrPair(FirstLdSt) ||
5736 !isCandidateToMergeOrPair(SecondLdSt))
5737 return false;
5738
5739 // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
5740 int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
5741 if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
5742 return false;
5743
5744 int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
5745 if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
5746 return false;
5747
5748 // Pairwise instructions have a 7-bit signed offset field.
5749 if (Offset1 > 63 || Offset1 < -64)
5750 return false;
5751
5752 // The caller should already have ordered First/SecondLdSt by offset.
5753 // Note: except for non-equal frame index bases
5754 if (BaseOp1.isFI()) {
5755 assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
5756 "Caller should have ordered offsets.");
5757
5758 const MachineFrameInfo &MFI =
5759 FirstLdSt.getParent()->getParent()->getFrameInfo();
5760 return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
5761 BaseOp2.getIndex(), Offset2, SecondOpc);
5762 }
5763
5764 assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
5765
5766 return Offset1 + 1 == Offset2;
5767}
5768
5770 MCRegister Reg, unsigned SubIdx,
5771 RegState State,
5772 const TargetRegisterInfo *TRI) {
5773 if (!SubIdx)
5774 return MIB.addReg(Reg, State);
5775
5776 if (Reg.isPhysical())
5777 return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
5778 return MIB.addReg(Reg, State, SubIdx);
5779}
5780
5783 const DebugLoc &DL, MCRegister DestReg,
5784 MCRegister SrcReg, bool KillSrc,
5785 ArrayRef<unsigned> Indices) const {
5786 assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
5788 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5789 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5790 unsigned NumRegs = Indices.size();
5791 MCRegister DestSubReg = TRI->getSubReg(DestReg, Indices[0]);
5792 assert(!AArch64::PNRRegClass.contains(DestSubReg) &&
5793 "Unexpected predicate tuple copy");
5794 unsigned MaxRegs = AArch64::PPRRegClass.contains(DestSubReg) ? 15 : 31;
5795
5796 int SubReg = 0, End = NumRegs, Incr = 1;
5797 // Copy in reverse if a forward copy will clobber the tuple
5798 if (((DestEncoding - SrcEncoding) & MaxRegs) < NumRegs) {
5799 SubReg = NumRegs - 1;
5800 End = -1;
5801 Incr = -1;
5802 }
5803
5804 for (; SubReg != End; SubReg += Incr) {
5805 DestSubReg = TRI->getSubReg(DestReg, Indices[SubReg]);
5806 MCRegister SrcSubReg = TRI->getSubReg(SrcReg, Indices[SubReg]);
5807 copyPhysRegImpl(MBB, I, DL, DestSubReg, SrcSubReg, KillSrc);
5808 }
5809}
5810
5813 const DebugLoc &DL, MCRegister DestReg,
5814 MCRegister SrcReg, bool KillSrc,
5815 unsigned Opcode, unsigned ZeroReg,
5816 llvm::ArrayRef<unsigned> Indices) const {
5818 unsigned NumRegs = Indices.size();
5819
5820#ifndef NDEBUG
5821 uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
5822 uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
5823 assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
5824 "GPR reg sequences should not be able to overlap");
5825#endif
5826
5827 for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
5828 const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
5829 AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
5830 MIB.addReg(ZeroReg);
5831 AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
5832 MIB.addImm(0);
5833 }
5834}
5835
5836/// Returns true if the instruction at I is in a streaming call site region,
5837/// within a single basic block.
5838/// A "call site streaming region" starts after smstart and ends at smstop
5839/// around a call to a streaming function. This walks backward from I.
5842 MachineFunction &MF = *MBB.getParent();
5844 if (!AFI->hasStreamingModeChanges())
5845 return false;
5846 // Walk backwards to find smstart/smstop
5847 for (MachineInstr &MI : reverse(make_range(MBB.begin(), I))) {
5848 unsigned Opc = MI.getOpcode();
5849 if (Opc == AArch64::MSRpstatesvcrImm1 || Opc == AArch64::MSRpstatePseudo) {
5850 // Check if this is SM change (not ZA)
5851 int64_t PState = MI.getOperand(0).getImm();
5852 if (PState == AArch64SVCR::SVCRSM || PState == AArch64SVCR::SVCRSMZA) {
5853 // Operand 1 is 1 for start, 0 for stop
5854 return MI.getOperand(1).getImm() == 1;
5855 }
5856 }
5857 }
5858 return false;
5859}
5860
5861/// Returns true if in a streaming call site region without SME-FA64.
5862static bool mustAvoidNeonAtMBBI(const AArch64Subtarget &Subtarget,
5865 return !Subtarget.hasSMEFA64() && isInStreamingCallSiteRegion(MBB, I);
5866}
5867
5870 const DebugLoc &DL, Register DestReg,
5871 Register SrcReg, bool KillSrc,
5872 bool RenamableDest,
5873 bool RenamableSrc) const {
5874 if (AArch64::GPR32spRegClass.contains(DestReg) &&
5875 AArch64::GPR32spRegClass.contains(SrcReg)) {
5876 if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
5877 // If either operand is WSP, expand to ADD #0.
5878 if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5879 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5880 // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
5881 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5882 &AArch64::GPR64spRegClass);
5883 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5884 &AArch64::GPR64spRegClass);
5885 // This instruction is reading and writing X registers. This may upset
5886 // the register scavenger and machine verifier, so we need to indicate
5887 // that we are reading an undefined value from SrcRegX, but a proper
5888 // value from SrcReg.
5889 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
5890 .addReg(SrcRegX, RegState::Undef)
5891 .addImm(0)
5893 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5894 ++NumZCRegMoveInstrsGPR;
5895 } else {
5896 BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
5897 .addReg(SrcReg, getKillRegState(KillSrc))
5898 .addImm(0)
5900 if (Subtarget.hasZeroCycleRegMoveGPR32())
5901 ++NumZCRegMoveInstrsGPR;
5902 }
5903 } else if (Subtarget.hasZeroCycleRegMoveGPR64() &&
5904 !Subtarget.hasZeroCycleRegMoveGPR32()) {
5905 // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
5906 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5907 &AArch64::GPR64spRegClass);
5908 assert(DestRegX.isValid() && "Destination super-reg not valid");
5909 MCRegister SrcRegX = RI.getMatchingSuperReg(SrcReg, AArch64::sub_32,
5910 &AArch64::GPR64spRegClass);
5911 assert(SrcRegX.isValid() && "Source super-reg not valid");
5912 // This instruction is reading and writing X registers. This may upset
5913 // the register scavenger and machine verifier, so we need to indicate
5914 // that we are reading an undefined value from SrcRegX, but a proper
5915 // value from SrcReg.
5916 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
5917 .addReg(AArch64::XZR)
5918 .addReg(SrcRegX, RegState::Undef)
5919 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
5920 ++NumZCRegMoveInstrsGPR;
5921 } else {
5922 // Otherwise, expand to ORR WZR.
5923 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5924 .addReg(AArch64::WZR)
5925 .addReg(SrcReg, getKillRegState(KillSrc));
5926 if (Subtarget.hasZeroCycleRegMoveGPR32())
5927 ++NumZCRegMoveInstrsGPR;
5928 }
5929 return;
5930 }
5931
5932 // GPR32 zeroing
5933 if (AArch64::GPR32spRegClass.contains(DestReg) && SrcReg == AArch64::WZR) {
5934 if (Subtarget.hasZeroCycleZeroingGPR64() &&
5935 !Subtarget.hasZeroCycleZeroingGPR32()) {
5936 MCRegister DestRegX = RI.getMatchingSuperReg(DestReg, AArch64::sub_32,
5937 &AArch64::GPR64spRegClass);
5938 assert(DestRegX.isValid() && "Destination super-reg not valid");
5939 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestRegX)
5940 .addImm(0)
5942 ++NumZCZeroingInstrsGPR;
5943 } else if (Subtarget.hasZeroCycleZeroingGPR32()) {
5944 BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
5945 .addImm(0)
5947 ++NumZCZeroingInstrsGPR;
5948 } else {
5949 BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
5950 .addReg(AArch64::WZR)
5951 .addReg(AArch64::WZR);
5952 }
5953 return;
5954 }
5955
5956 if (AArch64::GPR64spRegClass.contains(DestReg) &&
5957 AArch64::GPR64spRegClass.contains(SrcReg)) {
5958 if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
5959 // If either operand is SP, expand to ADD #0.
5960 BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
5961 .addReg(SrcReg, getKillRegState(KillSrc))
5962 .addImm(0)
5964 if (Subtarget.hasZeroCycleRegMoveGPR64())
5965 ++NumZCRegMoveInstrsGPR;
5966 } else {
5967 // Otherwise, expand to ORR XZR.
5968 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5969 .addReg(AArch64::XZR)
5970 .addReg(SrcReg, getKillRegState(KillSrc));
5971 if (Subtarget.hasZeroCycleRegMoveGPR64())
5972 ++NumZCRegMoveInstrsGPR;
5973 }
5974 return;
5975 }
5976
5977 // GPR64 zeroing
5978 if (AArch64::GPR64spRegClass.contains(DestReg) && SrcReg == AArch64::XZR) {
5979 if (Subtarget.hasZeroCycleZeroingGPR64()) {
5980 BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
5981 .addImm(0)
5983 ++NumZCZeroingInstrsGPR;
5984 } else {
5985 BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
5986 .addReg(AArch64::XZR)
5987 .addReg(AArch64::XZR);
5988 }
5989 return;
5990 }
5991
5992 // Copy a Predicate register by ORRing with itself.
5993 if (AArch64::PPRRegClass.contains(DestReg) &&
5994 AArch64::PPRRegClass.contains(SrcReg)) {
5995 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
5996 "Unexpected SVE register.");
5997 BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
5998 .addReg(SrcReg) // Pg
5999 .addReg(SrcReg)
6000 .addReg(SrcReg, getKillRegState(KillSrc));
6001 return;
6002 }
6003
6004 // Copy a predicate-as-counter register by ORRing with itself as if it
6005 // were a regular predicate (mask) register.
6006 bool DestIsPNR = AArch64::PNRRegClass.contains(DestReg);
6007 bool SrcIsPNR = AArch64::PNRRegClass.contains(SrcReg);
6008 if (DestIsPNR || SrcIsPNR) {
6009 auto ToPPR = [](MCRegister R) -> MCRegister {
6010 return (R - AArch64::PN0) + AArch64::P0;
6011 };
6012 MCRegister PPRSrcReg = SrcIsPNR ? ToPPR(SrcReg) : SrcReg.asMCReg();
6013 MCRegister PPRDestReg = DestIsPNR ? ToPPR(DestReg) : DestReg.asMCReg();
6014
6015 if (PPRSrcReg != PPRDestReg) {
6016 auto NewMI = BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), PPRDestReg)
6017 .addReg(PPRSrcReg) // Pg
6018 .addReg(PPRSrcReg)
6019 .addReg(PPRSrcReg, getKillRegState(KillSrc));
6020 if (DestIsPNR)
6021 NewMI.addDef(DestReg, RegState::Implicit);
6022 }
6023 return;
6024 }
6025
6026 // Copy a predicate register pair by copying the individual sub-registers.
6027 if (AArch64::PPR2RegClass.contains(DestReg) &&
6028 AArch64::PPR2RegClass.contains(SrcReg)) {
6029 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6030 "Unexpected SVE predicate register.");
6031 static const unsigned Indices[] = {AArch64::psub0, AArch64::psub1};
6032 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6033 return;
6034 }
6035
6036 // Copy a Z register by ORRing with itself.
6037 if (AArch64::ZPRRegClass.contains(DestReg) &&
6038 AArch64::ZPRRegClass.contains(SrcReg)) {
6039 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6040 "Unexpected SVE register.");
6041 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
6042 .addReg(SrcReg)
6043 .addReg(SrcReg, getKillRegState(KillSrc));
6044 return;
6045 }
6046
6047 // Copy a Z register pair by copying the individual sub-registers.
6048 if ((AArch64::ZPR2RegClass.contains(DestReg) ||
6049 AArch64::ZPR2StridedOrContiguousRegClass.contains(DestReg)) &&
6050 (AArch64::ZPR2RegClass.contains(SrcReg) ||
6051 AArch64::ZPR2StridedOrContiguousRegClass.contains(SrcReg))) {
6052 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6053 "Unexpected SVE register.");
6054 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
6055 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6056 return;
6057 }
6058
6059 // Copy a Z register triple by copying the individual sub-registers.
6060 if (AArch64::ZPR3RegClass.contains(DestReg) &&
6061 AArch64::ZPR3RegClass.contains(SrcReg)) {
6062 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6063 "Unexpected SVE register.");
6064 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6065 AArch64::zsub2};
6066 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6067 return;
6068 }
6069
6070 // Copy a Z register quad by copying the individual sub-registers.
6071 if ((AArch64::ZPR4RegClass.contains(DestReg) ||
6072 AArch64::ZPR4StridedOrContiguousRegClass.contains(DestReg)) &&
6073 (AArch64::ZPR4RegClass.contains(SrcReg) ||
6074 AArch64::ZPR4StridedOrContiguousRegClass.contains(SrcReg))) {
6075 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6076 "Unexpected SVE register.");
6077 static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
6078 AArch64::zsub2, AArch64::zsub3};
6079 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6080 return;
6081 }
6082
6083 // Copy a DDDD register quad by copying the individual sub-registers.
6084 if (AArch64::DDDDRegClass.contains(DestReg) &&
6085 AArch64::DDDDRegClass.contains(SrcReg)) {
6086 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6087 AArch64::dsub2, AArch64::dsub3};
6088 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6089 return;
6090 }
6091
6092 // Copy a DDD register triple by copying the individual sub-registers.
6093 if (AArch64::DDDRegClass.contains(DestReg) &&
6094 AArch64::DDDRegClass.contains(SrcReg)) {
6095 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
6096 AArch64::dsub2};
6097 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6098 return;
6099 }
6100
6101 // Copy a DD register pair by copying the individual sub-registers.
6102 if (AArch64::DDRegClass.contains(DestReg) &&
6103 AArch64::DDRegClass.contains(SrcReg)) {
6104 static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
6105 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6106 return;
6107 }
6108
6109 // Copy a QQQQ register quad by copying the individual sub-registers.
6110 if (AArch64::QQQQRegClass.contains(DestReg) &&
6111 AArch64::QQQQRegClass.contains(SrcReg)) {
6112 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6113 AArch64::qsub2, AArch64::qsub3};
6114 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6115 return;
6116 }
6117
6118 // Copy a QQQ register triple by copying the individual sub-registers.
6119 if (AArch64::QQQRegClass.contains(DestReg) &&
6120 AArch64::QQQRegClass.contains(SrcReg)) {
6121 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
6122 AArch64::qsub2};
6123 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6124 return;
6125 }
6126
6127 // Copy a QQ register pair by copying the individual sub-registers.
6128 if (AArch64::QQRegClass.contains(DestReg) &&
6129 AArch64::QQRegClass.contains(SrcReg)) {
6130 static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
6131 copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, Indices);
6132 return;
6133 }
6134
6135 if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
6136 AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
6137 static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
6138 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
6139 AArch64::XZR, Indices);
6140 return;
6141 }
6142
6143 if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
6144 AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
6145 static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
6146 copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
6147 AArch64::WZR, Indices);
6148 return;
6149 }
6150
6151 if (AArch64::FPR128RegClass.contains(DestReg) &&
6152 AArch64::FPR128RegClass.contains(SrcReg)) {
6153 // In streaming regions, NEON is illegal but streaming-SVE is available.
6154 // Use SVE for copies if we're in a streaming region and SME is available.
6155 // With +sme-fa64, NEON is legal in streaming mode so we can use it.
6156 if ((Subtarget.isSVEorStreamingSVEAvailable() &&
6157 !Subtarget.isNeonAvailable()) ||
6158 mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6159 BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ))
6160 .addReg(AArch64::Z0 + (DestReg - AArch64::Q0), RegState::Define)
6161 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0))
6162 .addReg(AArch64::Z0 + (SrcReg - AArch64::Q0));
6163 } else if (Subtarget.isNeonAvailable()) {
6164 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
6165 .addReg(SrcReg)
6166 .addReg(SrcReg, getKillRegState(KillSrc));
6167 if (Subtarget.hasZeroCycleRegMoveFPR128())
6168 ++NumZCRegMoveInstrsFPR;
6169 } else {
6170 BuildMI(MBB, I, DL, get(AArch64::STRQpre))
6171 .addReg(AArch64::SP, RegState::Define)
6172 .addReg(SrcReg, getKillRegState(KillSrc))
6173 .addReg(AArch64::SP)
6174 .addImm(-16);
6175 BuildMI(MBB, I, DL, get(AArch64::LDRQpost))
6176 .addReg(AArch64::SP, RegState::Define)
6177 .addReg(DestReg, RegState::Define)
6178 .addReg(AArch64::SP)
6179 .addImm(16);
6180 }
6181 return;
6182 }
6183
6184 if (AArch64::FPR64RegClass.contains(DestReg) &&
6185 AArch64::FPR64RegClass.contains(SrcReg)) {
6186 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6187 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6188 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6189 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6190 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::dsub,
6191 &AArch64::FPR128RegClass);
6192 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::dsub,
6193 &AArch64::FPR128RegClass);
6194 // This instruction is reading and writing Q registers. This may upset
6195 // the register scavenger and machine verifier, so we need to indicate
6196 // that we are reading an undefined value from SrcRegQ, but a proper
6197 // value from SrcReg.
6198 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6199 .addReg(SrcRegQ, RegState::Undef)
6200 .addReg(SrcRegQ, RegState::Undef)
6201 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6202 ++NumZCRegMoveInstrsFPR;
6203 } else {
6204 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
6205 .addReg(SrcReg, getKillRegState(KillSrc));
6206 if (Subtarget.hasZeroCycleRegMoveFPR64())
6207 ++NumZCRegMoveInstrsFPR;
6208 }
6209 return;
6210 }
6211
6212 if (AArch64::FPR32RegClass.contains(DestReg) &&
6213 AArch64::FPR32RegClass.contains(SrcReg)) {
6214 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6215 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6216 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6217 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6218 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6219 &AArch64::FPR128RegClass);
6220 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6221 &AArch64::FPR128RegClass);
6222 // This instruction is reading and writing Q registers. This may upset
6223 // the register scavenger and machine verifier, so we need to indicate
6224 // that we are reading an undefined value from SrcRegQ, but a proper
6225 // value from SrcReg.
6226 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6227 .addReg(SrcRegQ, RegState::Undef)
6228 .addReg(SrcRegQ, RegState::Undef)
6229 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6230 ++NumZCRegMoveInstrsFPR;
6231 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6232 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6233 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::ssub,
6234 &AArch64::FPR64RegClass);
6235 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::ssub,
6236 &AArch64::FPR64RegClass);
6237 // This instruction is reading and writing D registers. This may upset
6238 // the register scavenger and machine verifier, so we need to indicate
6239 // that we are reading an undefined value from SrcRegD, but a proper
6240 // value from SrcReg.
6241 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6242 .addReg(SrcRegD, RegState::Undef)
6243 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6244 ++NumZCRegMoveInstrsFPR;
6245 } else {
6246 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6247 .addReg(SrcReg, getKillRegState(KillSrc));
6248 if (Subtarget.hasZeroCycleRegMoveFPR32())
6249 ++NumZCRegMoveInstrsFPR;
6250 }
6251 return;
6252 }
6253
6254 if (AArch64::FPR16RegClass.contains(DestReg) &&
6255 AArch64::FPR16RegClass.contains(SrcReg)) {
6256 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6257 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6258 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6259 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6260 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6261 &AArch64::FPR128RegClass);
6262 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6263 &AArch64::FPR128RegClass);
6264 // This instruction is reading and writing Q registers. This may upset
6265 // the register scavenger and machine verifier, so we need to indicate
6266 // that we are reading an undefined value from SrcRegQ, but a proper
6267 // value from SrcReg.
6268 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6269 .addReg(SrcRegQ, RegState::Undef)
6270 .addReg(SrcRegQ, RegState::Undef)
6271 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6272 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6273 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6274 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6275 &AArch64::FPR64RegClass);
6276 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6277 &AArch64::FPR64RegClass);
6278 // This instruction is reading and writing D registers. This may upset
6279 // the register scavenger and machine verifier, so we need to indicate
6280 // that we are reading an undefined value from SrcRegD, but a proper
6281 // value from SrcReg.
6282 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6283 .addReg(SrcRegD, RegState::Undef)
6284 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6285 } else {
6286 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::hsub,
6287 &AArch64::FPR32RegClass);
6288 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::hsub,
6289 &AArch64::FPR32RegClass);
6290 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6291 .addReg(SrcReg, getKillRegState(KillSrc));
6292 }
6293 return;
6294 }
6295
6296 if (AArch64::FPR8RegClass.contains(DestReg) &&
6297 AArch64::FPR8RegClass.contains(SrcReg)) {
6298 if (Subtarget.hasZeroCycleRegMoveFPR128() &&
6299 !Subtarget.hasZeroCycleRegMoveFPR64() &&
6300 !Subtarget.hasZeroCycleRegMoveFPR32() && Subtarget.isNeonAvailable() &&
6301 !mustAvoidNeonAtMBBI(Subtarget, MBB, I)) {
6302 MCRegister DestRegQ = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6303 &AArch64::FPR128RegClass);
6304 MCRegister SrcRegQ = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6305 &AArch64::FPR128RegClass);
6306 // This instruction is reading and writing Q registers. This may upset
6307 // the register scavenger and machine verifier, so we need to indicate
6308 // that we are reading an undefined value from SrcRegQ, but a proper
6309 // value from SrcReg.
6310 BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestRegQ)
6311 .addReg(SrcRegQ, RegState::Undef)
6312 .addReg(SrcRegQ, RegState::Undef)
6313 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6314 } else if (Subtarget.hasZeroCycleRegMoveFPR64() &&
6315 !Subtarget.hasZeroCycleRegMoveFPR32()) {
6316 MCRegister DestRegD = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6317 &AArch64::FPR64RegClass);
6318 MCRegister SrcRegD = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6319 &AArch64::FPR64RegClass);
6320 // This instruction is reading and writing D registers. This may upset
6321 // the register scavenger and machine verifier, so we need to indicate
6322 // that we are reading an undefined value from SrcRegD, but a proper
6323 // value from SrcReg.
6324 BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestRegD)
6325 .addReg(SrcRegD, RegState::Undef)
6326 .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
6327 } else {
6328 DestReg = RI.getMatchingSuperReg(DestReg, AArch64::bsub,
6329 &AArch64::FPR32RegClass);
6330 SrcReg = RI.getMatchingSuperReg(SrcReg, AArch64::bsub,
6331 &AArch64::FPR32RegClass);
6332 BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
6333 .addReg(SrcReg, getKillRegState(KillSrc));
6334 }
6335 return;
6336 }
6337
6338 // Copies between GPR64 and FPR64.
6339 if (AArch64::FPR64RegClass.contains(DestReg) &&
6340 AArch64::GPR64RegClass.contains(SrcReg)) {
6341 if (AArch64::XZR == SrcReg) {
6342 BuildMI(MBB, I, DL, get(AArch64::FMOVD0), DestReg);
6343 } else {
6344 BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
6345 .addReg(SrcReg, getKillRegState(KillSrc));
6346 }
6347 return;
6348 }
6349 if (AArch64::GPR64RegClass.contains(DestReg) &&
6350 AArch64::FPR64RegClass.contains(SrcReg)) {
6351 BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
6352 .addReg(SrcReg, getKillRegState(KillSrc));
6353 return;
6354 }
6355 // Copies between GPR32 and FPR32.
6356 if (AArch64::FPR32RegClass.contains(DestReg) &&
6357 AArch64::GPR32RegClass.contains(SrcReg)) {
6358 if (AArch64::WZR == SrcReg) {
6359 BuildMI(MBB, I, DL, get(AArch64::FMOVS0), DestReg);
6360 } else {
6361 BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
6362 .addReg(SrcReg, getKillRegState(KillSrc));
6363 }
6364 return;
6365 }
6366 if (AArch64::GPR32RegClass.contains(DestReg) &&
6367 AArch64::FPR32RegClass.contains(SrcReg)) {
6368 BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
6369 .addReg(SrcReg, getKillRegState(KillSrc));
6370 return;
6371 }
6372
6373 if (DestReg == AArch64::NZCV) {
6374 assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
6375 BuildMI(MBB, I, DL, get(AArch64::MSR))
6376 .addImm(AArch64SysReg::NZCV)
6377 .addReg(SrcReg, getKillRegState(KillSrc))
6378 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
6379 return;
6380 }
6381
6382 if (SrcReg == AArch64::NZCV) {
6383 assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
6384 BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
6385 .addImm(AArch64SysReg::NZCV)
6386 .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
6387 return;
6388 }
6389
6390#ifndef NDEBUG
6391 errs() << RI.getRegAsmName(DestReg) << " = COPY " << RI.getRegAsmName(SrcReg)
6392 << "\n";
6393#endif
6394 llvm_unreachable("unimplemented reg-to-reg copy");
6395}
6396
6399 const DebugLoc &DL, Register DestReg,
6400 Register SrcReg, bool KillSrc,
6401 bool RenamableDest,
6402 bool RenamableSrc) const {
6403 ++NumCopyInstrs;
6404 copyPhysRegImpl(MBB, I, DL, DestReg, SrcReg, KillSrc, RenamableDest,
6405 RenamableSrc);
6406 return;
6407}
6408
6411 MachineBasicBlock::iterator InsertBefore,
6412 const MCInstrDesc &MCID,
6413 Register SrcReg, bool IsKill,
6414 unsigned SubIdx0, unsigned SubIdx1, int FI,
6415 MachineMemOperand *MMO) {
6416 Register SrcReg0 = SrcReg;
6417 Register SrcReg1 = SrcReg;
6418 if (SrcReg.isPhysical()) {
6419 SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
6420 SubIdx0 = 0;
6421 SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
6422 SubIdx1 = 0;
6423 }
6424 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6425 .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
6426 .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
6427 .addFrameIndex(FI)
6428 .addImm(0)
6429 .addMemOperand(MMO);
6430}
6431
6434 Register SrcReg, bool isKill, int FI,
6435 const TargetRegisterClass *RC,
6436 Register VReg,
6437 MachineInstr::MIFlag Flags) const {
6438 MachineFunction &MF = *MBB.getParent();
6439 MachineFrameInfo &MFI = MF.getFrameInfo();
6440
6442 MachineMemOperand *MMO =
6444 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6445 unsigned Opc = 0;
6446 bool Offset = true;
6448 unsigned StackID = TargetStackID::Default;
6449 switch (RI.getSpillSize(*RC)) {
6450 case 1:
6451 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6452 Opc = AArch64::STRBui;
6453 break;
6454 case 2: {
6455 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6456 Opc = AArch64::STRHui;
6457 else if (AArch64::PNRRegClass.hasSubClassEq(RC) ||
6458 AArch64::PPRRegClass.hasSubClassEq(RC)) {
6459 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6460 "Unexpected register store without SVE store instructions");
6461 Opc = AArch64::STR_PXI;
6463 }
6464 break;
6465 }
6466 case 4:
6467 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6468 Opc = AArch64::STRWui;
6469 if (SrcReg.isVirtual())
6470 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
6471 else
6472 assert(SrcReg != AArch64::WSP);
6473 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6474 Opc = AArch64::STRSui;
6475 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6476 Opc = AArch64::STR_PPXI;
6478 }
6479 break;
6480 case 8:
6481 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6482 Opc = AArch64::STRXui;
6483 if (SrcReg.isVirtual())
6484 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
6485 else
6486 assert(SrcReg != AArch64::SP);
6487 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6488 Opc = AArch64::STRDui;
6489 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6491 get(AArch64::STPWi), SrcReg, isKill,
6492 AArch64::sube32, AArch64::subo32, FI, MMO);
6493 return;
6494 }
6495 break;
6496 case 16:
6497 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6498 Opc = AArch64::STRQui;
6499 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6500 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6501 Opc = AArch64::ST1Twov1d;
6502 Offset = false;
6503 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6505 get(AArch64::STPXi), SrcReg, isKill,
6506 AArch64::sube64, AArch64::subo64, FI, MMO);
6507 return;
6508 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6509 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6510 "Unexpected register store without SVE store instructions");
6511 Opc = AArch64::STR_ZXI;
6513 }
6514 break;
6515 case 24:
6516 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6517 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6518 Opc = AArch64::ST1Threev1d;
6519 Offset = false;
6520 }
6521 break;
6522 case 32:
6523 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6524 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6525 Opc = AArch64::ST1Fourv1d;
6526 Offset = false;
6527 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6528 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6529 Opc = AArch64::ST1Twov2d;
6530 Offset = false;
6531 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6532 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6533 "Unexpected register store without SVE store instructions");
6534 Opc = AArch64::STR_ZZXI_STRIDED_CONTIGUOUS;
6536 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6537 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6538 "Unexpected register store without SVE store instructions");
6539 Opc = AArch64::STR_ZZXI;
6541 }
6542 break;
6543 case 48:
6544 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6545 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6546 Opc = AArch64::ST1Threev2d;
6547 Offset = false;
6548 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6549 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6550 "Unexpected register store without SVE store instructions");
6551 Opc = AArch64::STR_ZZZXI;
6553 }
6554 break;
6555 case 64:
6556 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6557 assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
6558 Opc = AArch64::ST1Fourv2d;
6559 Offset = false;
6560 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6561 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6562 "Unexpected register store without SVE store instructions");
6563 Opc = AArch64::STR_ZZZZXI_STRIDED_CONTIGUOUS;
6565 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6566 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6567 "Unexpected register store without SVE store instructions");
6568 Opc = AArch64::STR_ZZZZXI;
6570 }
6571 break;
6572 }
6573 assert(Opc && "Unknown register class");
6574 MFI.setStackID(FI, StackID);
6575
6577 .addReg(SrcReg, getKillRegState(isKill))
6578 .addFrameIndex(FI);
6579
6580 if (Offset)
6581 MI.addImm(0);
6582 if (PNRReg.isValid())
6583 MI.addDef(PNRReg, RegState::Implicit);
6584 MI.addMemOperand(MMO);
6585}
6586
6589 MachineBasicBlock::iterator InsertBefore,
6590 const MCInstrDesc &MCID,
6591 Register DestReg, unsigned SubIdx0,
6592 unsigned SubIdx1, int FI,
6593 MachineMemOperand *MMO) {
6594 Register DestReg0 = DestReg;
6595 Register DestReg1 = DestReg;
6596 bool IsUndef = true;
6597 if (DestReg.isPhysical()) {
6598 DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
6599 SubIdx0 = 0;
6600 DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
6601 SubIdx1 = 0;
6602 IsUndef = false;
6603 }
6604 BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
6605 .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
6606 .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
6607 .addFrameIndex(FI)
6608 .addImm(0)
6609 .addMemOperand(MMO);
6610}
6611
6614 Register DestReg, int FI,
6615 const TargetRegisterClass *RC,
6616 Register VReg, unsigned SubReg,
6617 MachineInstr::MIFlag Flags) const {
6618 MachineFunction &MF = *MBB.getParent();
6619 MachineFrameInfo &MFI = MF.getFrameInfo();
6621 MachineMemOperand *MMO =
6623 MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
6624
6625 unsigned Opc = 0;
6626 bool Offset = true;
6627 unsigned StackID = TargetStackID::Default;
6628 Register PNRReg;
6629 switch (TRI.getSpillSize(*RC)) {
6630 case 1:
6631 if (AArch64::FPR8RegClass.hasSubClassEq(RC))
6632 Opc = AArch64::LDRBui;
6633 break;
6634 case 2: {
6635 bool IsPNR = AArch64::PNRRegClass.hasSubClassEq(RC);
6636 if (AArch64::FPR16RegClass.hasSubClassEq(RC))
6637 Opc = AArch64::LDRHui;
6638 else if (IsPNR || AArch64::PPRRegClass.hasSubClassEq(RC)) {
6639 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6640 "Unexpected register load without SVE load instructions");
6641 if (IsPNR)
6642 PNRReg = DestReg;
6643 Opc = AArch64::LDR_PXI;
6645 }
6646 break;
6647 }
6648 case 4:
6649 if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
6650 Opc = AArch64::LDRWui;
6651 if (DestReg.isVirtual())
6652 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
6653 else
6654 assert(DestReg != AArch64::WSP);
6655 } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
6656 Opc = AArch64::LDRSui;
6657 else if (AArch64::PPR2RegClass.hasSubClassEq(RC)) {
6658 Opc = AArch64::LDR_PPXI;
6660 }
6661 break;
6662 case 8:
6663 if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
6664 Opc = AArch64::LDRXui;
6665 if (DestReg.isVirtual())
6666 MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
6667 else
6668 assert(DestReg != AArch64::SP);
6669 } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
6670 Opc = AArch64::LDRDui;
6671 } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
6673 get(AArch64::LDPWi), DestReg, AArch64::sube32,
6674 AArch64::subo32, FI, MMO);
6675 return;
6676 }
6677 break;
6678 case 16:
6679 if (AArch64::FPR128RegClass.hasSubClassEq(RC))
6680 Opc = AArch64::LDRQui;
6681 else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
6682 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6683 Opc = AArch64::LD1Twov1d;
6684 Offset = false;
6685 } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
6687 get(AArch64::LDPXi), DestReg, AArch64::sube64,
6688 AArch64::subo64, FI, MMO);
6689 return;
6690 } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
6691 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6692 "Unexpected register load without SVE load instructions");
6693 Opc = AArch64::LDR_ZXI;
6695 }
6696 break;
6697 case 24:
6698 if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
6699 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6700 Opc = AArch64::LD1Threev1d;
6701 Offset = false;
6702 }
6703 break;
6704 case 32:
6705 if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
6706 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6707 Opc = AArch64::LD1Fourv1d;
6708 Offset = false;
6709 } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
6710 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6711 Opc = AArch64::LD1Twov2d;
6712 Offset = false;
6713 } else if (AArch64::ZPR2StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6714 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6715 "Unexpected register load without SVE load instructions");
6716 Opc = AArch64::LDR_ZZXI_STRIDED_CONTIGUOUS;
6718 } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
6719 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6720 "Unexpected register load without SVE load instructions");
6721 Opc = AArch64::LDR_ZZXI;
6723 }
6724 break;
6725 case 48:
6726 if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
6727 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6728 Opc = AArch64::LD1Threev2d;
6729 Offset = false;
6730 } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
6731 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6732 "Unexpected register load without SVE load instructions");
6733 Opc = AArch64::LDR_ZZZXI;
6735 }
6736 break;
6737 case 64:
6738 if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
6739 assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
6740 Opc = AArch64::LD1Fourv2d;
6741 Offset = false;
6742 } else if (AArch64::ZPR4StridedOrContiguousRegClass.hasSubClassEq(RC)) {
6743 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6744 "Unexpected register load without SVE load instructions");
6745 Opc = AArch64::LDR_ZZZZXI_STRIDED_CONTIGUOUS;
6747 } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
6748 assert(Subtarget.isSVEorStreamingSVEAvailable() &&
6749 "Unexpected register load without SVE load instructions");
6750 Opc = AArch64::LDR_ZZZZXI;
6752 }
6753 break;
6754 }
6755
6756 assert(Opc && "Unknown register class");
6757 MFI.setStackID(FI, StackID);
6758
6760 .addReg(DestReg, getDefRegState(true))
6761 .addFrameIndex(FI);
6762 if (Offset)
6763 MI.addImm(0);
6764 if (PNRReg.isValid() && !PNRReg.isVirtual())
6765 MI.addDef(PNRReg, RegState::Implicit);
6766 MI.addMemOperand(MMO);
6767}
6768
6770 const MachineInstr &UseMI,
6771 const TargetRegisterInfo *TRI) {
6772 return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
6773 UseMI.getIterator()),
6774 [TRI](const MachineInstr &I) {
6775 return I.modifiesRegister(AArch64::NZCV, TRI) ||
6776 I.readsRegister(AArch64::NZCV, TRI);
6777 });
6778}
6779
6780void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6781 const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
6782 // The smallest scalable element supported by scaled SVE addressing
6783 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6784 // byte offset must always be a multiple of 2.
6785 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6786
6787 // VGSized offsets are divided by '2', because the VG register is the
6788 // the number of 64bit granules as opposed to 128bit vector chunks,
6789 // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
6790 // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
6791 // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
6792 ByteSized = Offset.getFixed();
6793 VGSized = Offset.getScalable() / 2;
6794}
6795
6796/// Returns the offset in parts to which this frame offset can be
6797/// decomposed for the purpose of describing a frame offset.
6798/// For non-scalable offsets this is simply its byte size.
6799void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
6800 const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
6801 int64_t &NumDataVectors) {
6802 // The smallest scalable element supported by scaled SVE addressing
6803 // modes are predicates, which are 2 scalable bytes in size. So the scalable
6804 // byte offset must always be a multiple of 2.
6805 assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
6806
6807 NumBytes = Offset.getFixed();
6808 NumDataVectors = 0;
6809 NumPredicateVectors = Offset.getScalable() / 2;
6810 // This method is used to get the offsets to adjust the frame offset.
6811 // If the function requires ADDPL to be used and needs more than two ADDPL
6812 // instructions, part of the offset is folded into NumDataVectors so that it
6813 // uses ADDVL for part of it, reducing the number of ADDPL instructions.
6814 if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
6815 NumPredicateVectors > 62) {
6816 NumDataVectors = NumPredicateVectors / 8;
6817 NumPredicateVectors -= NumDataVectors * 8;
6818 }
6819}
6820
6821// Convenience function to create a DWARF expression for: Constant `Operation`.
6822// This helper emits compact sequences for common cases. For example, for`-15
6823// DW_OP_plus`, this helper would create DW_OP_lit15 DW_OP_minus.
6826 if (Operation == dwarf::DW_OP_plus && Constant < 0 && -Constant <= 31) {
6827 // -Constant (1 to 31)
6828 Expr.push_back(dwarf::DW_OP_lit0 - Constant);
6829 Operation = dwarf::DW_OP_minus;
6830 } else if (Constant >= 0 && Constant <= 31) {
6831 // Literal value 0 to 31
6832 Expr.push_back(dwarf::DW_OP_lit0 + Constant);
6833 } else {
6834 // Signed constant
6835 Expr.push_back(dwarf::DW_OP_consts);
6837 }
6838 return Expr.push_back(Operation);
6839}
6840
6841// Convenience function to create a DWARF expression for a register.
6842static void appendReadRegExpr(SmallVectorImpl<char> &Expr, unsigned RegNum) {
6843 Expr.push_back((char)dwarf::DW_OP_bregx);
6845 Expr.push_back(0);
6846}
6847
6848// Convenience function to create a DWARF expression for loading a register from
6849// a CFA offset.
6851 int64_t OffsetFromDefCFA) {
6852 // This assumes the top of the DWARF stack contains the CFA.
6853 Expr.push_back(dwarf::DW_OP_dup);
6854 // Add the offset to the register.
6855 appendConstantExpr(Expr, OffsetFromDefCFA, dwarf::DW_OP_plus);
6856 // Dereference the address (loads a 64 bit value)..
6857 Expr.push_back(dwarf::DW_OP_deref);
6858}
6859
6860// Convenience function to create a comment for
6861// (+/-) NumBytes (* RegScale)?
6862static void appendOffsetComment(int NumBytes, llvm::raw_string_ostream &Comment,
6863 StringRef RegScale = {}) {
6864 if (NumBytes) {
6865 Comment << (NumBytes < 0 ? " - " : " + ") << std::abs(NumBytes);
6866 if (!RegScale.empty())
6867 Comment << ' ' << RegScale;
6868 }
6869}
6870
6871// Creates an MCCFIInstruction:
6872// { DW_CFA_def_cfa_expression, ULEB128 (sizeof expr), expr }
6874 unsigned Reg,
6875 const StackOffset &Offset) {
6876 int64_t NumBytes, NumVGScaledBytes;
6877 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(Offset, NumBytes,
6878 NumVGScaledBytes);
6879 std::string CommentBuffer;
6880 llvm::raw_string_ostream Comment(CommentBuffer);
6881
6882 if (Reg == AArch64::SP)
6883 Comment << "sp";
6884 else if (Reg == AArch64::FP)
6885 Comment << "fp";
6886 else
6887 Comment << printReg(Reg, &TRI);
6888
6889 // Build up the expression (Reg + NumBytes + VG * NumVGScaledBytes)
6890 SmallString<64> Expr;
6891 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6892 assert(DwarfReg <= 31 && "DwarfReg out of bounds (0..31)");
6893 // Reg + NumBytes
6894 Expr.push_back(dwarf::DW_OP_breg0 + DwarfReg);
6895 appendLEB128<LEB128Sign::Signed>(Expr, NumBytes);
6896 appendOffsetComment(NumBytes, Comment);
6897 if (NumVGScaledBytes) {
6898 // + VG * NumVGScaledBytes
6899 appendOffsetComment(NumVGScaledBytes, Comment, "* VG");
6900 appendReadRegExpr(Expr, TRI.getDwarfRegNum(AArch64::VG, true));
6901 appendConstantExpr(Expr, NumVGScaledBytes, dwarf::DW_OP_mul);
6902 Expr.push_back(dwarf::DW_OP_plus);
6903 }
6904
6905 // Wrap this into DW_CFA_def_cfa.
6906 SmallString<64> DefCfaExpr;
6907 DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
6908 appendLEB128<LEB128Sign::Unsigned>(DefCfaExpr, Expr.size());
6909 DefCfaExpr.append(Expr.str());
6910 return MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str(), SMLoc(),
6911 Comment.str());
6912}
6913
6915 unsigned FrameReg, unsigned Reg,
6916 const StackOffset &Offset,
6917 bool LastAdjustmentWasScalable) {
6918 if (Offset.getScalable())
6919 return createDefCFAExpression(TRI, Reg, Offset);
6920
6921 if (FrameReg == Reg && !LastAdjustmentWasScalable)
6922 return MCCFIInstruction::cfiDefCfaOffset(nullptr, int(Offset.getFixed()));
6923
6924 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6925 return MCCFIInstruction::cfiDefCfa(nullptr, DwarfReg, (int)Offset.getFixed());
6926}
6927
6930 const StackOffset &OffsetFromDefCFA,
6931 std::optional<int64_t> IncomingVGOffsetFromDefCFA) {
6932 int64_t NumBytes, NumVGScaledBytes;
6933 AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
6934 OffsetFromDefCFA, NumBytes, NumVGScaledBytes);
6935
6936 unsigned DwarfReg = TRI.getDwarfRegNum(Reg, true);
6937
6938 // Non-scalable offsets can use DW_CFA_offset directly.
6939 if (!NumVGScaledBytes)
6940 return MCCFIInstruction::createOffset(nullptr, DwarfReg, NumBytes);
6941
6942 std::string CommentBuffer;
6943 llvm::raw_string_ostream Comment(CommentBuffer);
6944 Comment << printReg(Reg, &TRI) << " @ cfa";
6945
6946 // Build up expression (CFA + VG * NumVGScaledBytes + NumBytes)
6947 assert(NumVGScaledBytes && "Expected scalable offset");
6948 SmallString<64> OffsetExpr;
6949 // + VG * NumVGScaledBytes
6950 StringRef VGRegScale;
6951 if (IncomingVGOffsetFromDefCFA) {
6952 appendLoadRegExpr(OffsetExpr, *IncomingVGOffsetFromDefCFA);
6953 VGRegScale = "* IncomingVG";
6954 } else {
6955 appendReadRegExpr(OffsetExpr, TRI.getDwarfRegNum(AArch64::VG, true));
6956 VGRegScale = "* VG";
6957 }
6958 appendConstantExpr(OffsetExpr, NumVGScaledBytes, dwarf::DW_OP_mul);
6959 appendOffsetComment(NumVGScaledBytes, Comment, VGRegScale);
6960 OffsetExpr.push_back(dwarf::DW_OP_plus);
6961 if (NumBytes) {
6962 // + NumBytes
6963 appendOffsetComment(NumBytes, Comment);
6964 appendConstantExpr(OffsetExpr, NumBytes, dwarf::DW_OP_plus);
6965 }
6966
6967 // Wrap this into DW_CFA_expression
6968 SmallString<64> CfaExpr;
6969 CfaExpr.push_back(dwarf::DW_CFA_expression);
6970 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, DwarfReg);
6971 appendLEB128<LEB128Sign::Unsigned>(CfaExpr, OffsetExpr.size());
6972 CfaExpr.append(OffsetExpr.str());
6973
6974 return MCCFIInstruction::createEscape(nullptr, CfaExpr.str(), SMLoc(),
6975 Comment.str());
6976}
6977
6978// Helper function to emit a frame offset adjustment from a given
6979// pointer (SrcReg), stored into DestReg. This function is explicit
6980// in that it requires the opcode.
6983 const DebugLoc &DL, unsigned DestReg,
6984 unsigned SrcReg, int64_t Offset, unsigned Opc,
6985 const TargetInstrInfo *TII,
6986 MachineInstr::MIFlag Flag, bool NeedsWinCFI,
6987 bool *HasWinCFI, bool EmitCFAOffset,
6988 StackOffset CFAOffset, unsigned FrameReg) {
6989 int Sign = 1;
6990 unsigned MaxEncoding, ShiftSize;
6991 switch (Opc) {
6992 case AArch64::ADDXri:
6993 case AArch64::ADDSXri:
6994 case AArch64::SUBXri:
6995 case AArch64::SUBSXri:
6996 MaxEncoding = 0xfff;
6997 ShiftSize = 12;
6998 break;
6999 case AArch64::ADDVL_XXI:
7000 case AArch64::ADDPL_XXI:
7001 case AArch64::ADDSVL_XXI:
7002 case AArch64::ADDSPL_XXI:
7003 MaxEncoding = 31;
7004 ShiftSize = 0;
7005 if (Offset < 0) {
7006 MaxEncoding = 32;
7007 Sign = -1;
7008 Offset = -Offset;
7009 }
7010 break;
7011 default:
7012 llvm_unreachable("Unsupported opcode");
7013 }
7014
7015 // `Offset` can be in bytes or in "scalable bytes".
7016 int VScale = 1;
7017 if (Opc == AArch64::ADDVL_XXI || Opc == AArch64::ADDSVL_XXI)
7018 VScale = 16;
7019 else if (Opc == AArch64::ADDPL_XXI || Opc == AArch64::ADDSPL_XXI)
7020 VScale = 2;
7021
7022 // FIXME: If the offset won't fit in 24-bits, compute the offset into a
7023 // scratch register. If DestReg is a virtual register, use it as the
7024 // scratch register; otherwise, create a new virtual register (to be
7025 // replaced by the scavenger at the end of PEI). That case can be optimized
7026 // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
7027 // register can be loaded with offset%8 and the add/sub can use an extending
7028 // instruction with LSL#3.
7029 // Currently the function handles any offsets but generates a poor sequence
7030 // of code.
7031 // assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
7032
7033 const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
7034 Register TmpReg = DestReg;
7035 if (TmpReg == AArch64::XZR)
7036 TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
7037 &AArch64::GPR64RegClass);
7038 do {
7039 uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
7040 unsigned LocalShiftSize = 0;
7041 if (ThisVal > MaxEncoding) {
7042 ThisVal = ThisVal >> ShiftSize;
7043 LocalShiftSize = ShiftSize;
7044 }
7045 assert((ThisVal >> ShiftSize) <= MaxEncoding &&
7046 "Encoding cannot handle value that big");
7047
7048 Offset -= ThisVal << LocalShiftSize;
7049 if (Offset == 0)
7050 TmpReg = DestReg;
7051 auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
7052 .addReg(SrcReg)
7053 .addImm(Sign * (int)ThisVal);
7054 if (ShiftSize)
7055 MBI = MBI.addImm(
7057 MBI = MBI.setMIFlag(Flag);
7058
7059 auto Change =
7060 VScale == 1
7061 ? StackOffset::getFixed(ThisVal << LocalShiftSize)
7062 : StackOffset::getScalable(VScale * (ThisVal << LocalShiftSize));
7063 if (Sign == -1 || Opc == AArch64::SUBXri || Opc == AArch64::SUBSXri)
7064 CFAOffset += Change;
7065 else
7066 CFAOffset -= Change;
7067 if (EmitCFAOffset && DestReg == TmpReg) {
7068 MachineFunction &MF = *MBB.getParent();
7069 const TargetSubtargetInfo &STI = MF.getSubtarget();
7070 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
7071
7072 unsigned CFIIndex = MF.addFrameInst(
7073 createDefCFA(TRI, FrameReg, DestReg, CFAOffset, VScale != 1));
7074 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
7075 .addCFIIndex(CFIIndex)
7076 .setMIFlags(Flag);
7077 }
7078
7079 if (NeedsWinCFI) {
7080 int Imm = (int)(ThisVal << LocalShiftSize);
7081 if (VScale != 1 && DestReg == AArch64::SP) {
7082 if (HasWinCFI)
7083 *HasWinCFI = true;
7084 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AllocZ))
7085 .addImm(ThisVal)
7086 .setMIFlag(Flag);
7087 } else if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
7088 (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
7089 assert(VScale == 1 && "Expected non-scalable operation");
7090 if (HasWinCFI)
7091 *HasWinCFI = true;
7092 if (Imm == 0)
7093 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
7094 else
7095 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
7096 .addImm(Imm)
7097 .setMIFlag(Flag);
7098 assert(Offset == 0 && "Expected remaining offset to be zero to "
7099 "emit a single SEH directive");
7100 } else if (DestReg == AArch64::SP) {
7101 assert(VScale == 1 && "Expected non-scalable operation");
7102 if (HasWinCFI)
7103 *HasWinCFI = true;
7104 assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
7105 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
7106 .addImm(Imm)
7107 .setMIFlag(Flag);
7108 }
7109 }
7110
7111 SrcReg = TmpReg;
7112 } while (Offset);
7113}
7114
7117 unsigned DestReg, unsigned SrcReg,
7119 MachineInstr::MIFlag Flag, bool SetNZCV,
7120 bool NeedsWinCFI, bool *HasWinCFI,
7121 bool EmitCFAOffset, StackOffset CFAOffset,
7122 unsigned FrameReg) {
7123 // If a function is marked as arm_locally_streaming, then the runtime value of
7124 // vscale in the prologue/epilogue is different the runtime value of vscale
7125 // in the function's body. To avoid having to consider multiple vscales,
7126 // we can use `addsvl` to allocate any scalable stack-slots, which under
7127 // most circumstances will be only locals, not callee-save slots.
7128 const Function &F = MBB.getParent()->getFunction();
7129 bool UseSVL = F.hasFnAttribute("aarch64_pstate_sm_body");
7130
7131 int64_t Bytes, NumPredicateVectors, NumDataVectors;
7132 AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
7133 Offset, Bytes, NumPredicateVectors, NumDataVectors);
7134
7135 // Insert ADDSXri for scalable offset at the end.
7136 bool NeedsFinalDefNZCV = SetNZCV && (NumPredicateVectors || NumDataVectors);
7137 if (NeedsFinalDefNZCV)
7138 SetNZCV = false;
7139
7140 // First emit non-scalable frame offsets, or a simple 'mov'.
7141 if (Bytes || (!Offset && SrcReg != DestReg)) {
7142 assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
7143 "SP increment/decrement not 8-byte aligned");
7144 unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
7145 if (Bytes < 0) {
7146 Bytes = -Bytes;
7147 Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
7148 }
7149 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
7150 NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7151 FrameReg);
7152 CFAOffset += (Opc == AArch64::ADDXri || Opc == AArch64::ADDSXri)
7153 ? StackOffset::getFixed(-Bytes)
7154 : StackOffset::getFixed(Bytes);
7155 SrcReg = DestReg;
7156 FrameReg = DestReg;
7157 }
7158
7159 assert(!(NeedsWinCFI && NumPredicateVectors) &&
7160 "WinCFI can't allocate fractions of an SVE data vector");
7161
7162 if (NumDataVectors) {
7163 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
7164 UseSVL ? AArch64::ADDSVL_XXI : AArch64::ADDVL_XXI, TII,
7165 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7166 FrameReg);
7167 CFAOffset += StackOffset::getScalable(-NumDataVectors * 16);
7168 SrcReg = DestReg;
7169 }
7170
7171 if (NumPredicateVectors) {
7172 assert(DestReg != AArch64::SP && "Unaligned access to SP");
7173 emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
7174 UseSVL ? AArch64::ADDSPL_XXI : AArch64::ADDPL_XXI, TII,
7175 Flag, NeedsWinCFI, HasWinCFI, EmitCFAOffset, CFAOffset,
7176 FrameReg);
7177 }
7178
7179 if (NeedsFinalDefNZCV)
7180 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ADDSXri), DestReg)
7181 .addReg(DestReg)
7182 .addImm(0)
7183 .addImm(0);
7184}
7185
7188 int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS,
7189 VirtRegMap *VRM) const {
7191 // This is a bit of a hack. Consider this instruction:
7192 //
7193 // %0 = COPY %sp; GPR64all:%0
7194 //
7195 // We explicitly chose GPR64all for the virtual register so such a copy might
7196 // be eliminated by RegisterCoalescer. However, that may not be possible, and
7197 // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
7198 // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
7199 //
7200 // To prevent that, we are going to constrain the %0 register class here.
7201 if (MI.isFullCopy()) {
7202 Register DstReg = MI.getOperand(0).getReg();
7203 Register SrcReg = MI.getOperand(1).getReg();
7204 if (SrcReg == AArch64::SP && DstReg.isVirtual()) {
7205 MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
7206 return nullptr;
7207 }
7208 if (DstReg == AArch64::SP && SrcReg.isVirtual()) {
7209 MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
7210 return nullptr;
7211 }
7212 // Nothing can folded with copy from/to NZCV.
7213 if (SrcReg == AArch64::NZCV || DstReg == AArch64::NZCV)
7214 return nullptr;
7215 }
7216
7217 // Handle the case where a copy is being spilled or filled but the source
7218 // and destination register class don't match. For example:
7219 //
7220 // %0 = COPY %xzr; GPR64common:%0
7221 //
7222 // In this case we can still safely fold away the COPY and generate the
7223 // following spill code:
7224 //
7225 // STRXui %xzr, %stack.0
7226 //
7227 // This also eliminates spilled cross register class COPYs (e.g. between x and
7228 // d regs) of the same size. For example:
7229 //
7230 // %0 = COPY %1; GPR64:%0, FPR64:%1
7231 //
7232 // will be filled as
7233 //
7234 // LDRDui %0, fi<#0>
7235 //
7236 // instead of
7237 //
7238 // LDRXui %Temp, fi<#0>
7239 // %0 = FMOV %Temp
7240 //
7241 if (MI.isCopy() && Ops.size() == 1 &&
7242 // Make sure we're only folding the explicit COPY defs/uses.
7243 (Ops[0] == 0 || Ops[0] == 1)) {
7244 bool IsSpill = Ops[0] == 0;
7245 bool IsFill = !IsSpill;
7247 const MachineRegisterInfo &MRI = MF.getRegInfo();
7248 MachineBasicBlock &MBB = *MI.getParent();
7249 const MachineOperand &DstMO = MI.getOperand(0);
7250 const MachineOperand &SrcMO = MI.getOperand(1);
7251 Register DstReg = DstMO.getReg();
7252 Register SrcReg = SrcMO.getReg();
7253 // This is slightly expensive to compute for physical regs since
7254 // getMinimalPhysRegClass is slow.
7255 auto getRegClass = [&](unsigned Reg) {
7256 return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
7257 : TRI.getMinimalPhysRegClass(Reg);
7258 };
7259
7260 if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
7261 assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
7262 TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
7263 "Mismatched register size in non subreg COPY");
7264 if (IsSpill)
7265 storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
7266 getRegClass(SrcReg), Register());
7267 else
7268 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
7269 getRegClass(DstReg), Register());
7270 return &*--InsertPt;
7271 }
7272
7273 // Handle cases like spilling def of:
7274 //
7275 // %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
7276 //
7277 // where the physical register source can be widened and stored to the full
7278 // virtual reg destination stack slot, in this case producing:
7279 //
7280 // STRXui %xzr, %stack.0
7281 //
7282 if (IsSpill && DstMO.isUndef() && SrcReg == AArch64::WZR &&
7283 TRI.getRegSizeInBits(*getRegClass(DstReg)) == 64) {
7284 assert(SrcMO.getSubReg() == 0 &&
7285 "Unexpected subreg on physical register");
7286 storeRegToStackSlot(MBB, InsertPt, AArch64::XZR, SrcMO.isKill(),
7287 FrameIndex, &AArch64::GPR64RegClass, Register());
7288 return &*--InsertPt;
7289 }
7290
7291 // Handle cases like filling use of:
7292 //
7293 // %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
7294 //
7295 // where we can load the full virtual reg source stack slot, into the subreg
7296 // destination, in this case producing:
7297 //
7298 // LDRWui %0:sub_32<def,read-undef>, %stack.0
7299 //
7300 if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
7301 const TargetRegisterClass *FillRC = nullptr;
7302 switch (DstMO.getSubReg()) {
7303 default:
7304 break;
7305 case AArch64::sub_32:
7306 if (AArch64::GPR64RegClass.hasSubClassEq(getRegClass(DstReg)))
7307 FillRC = &AArch64::GPR32RegClass;
7308 break;
7309 case AArch64::ssub:
7310 FillRC = &AArch64::FPR32RegClass;
7311 break;
7312 case AArch64::dsub:
7313 FillRC = &AArch64::FPR64RegClass;
7314 break;
7315 }
7316
7317 if (FillRC) {
7318 assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
7319 TRI.getRegSizeInBits(*FillRC) &&
7320 "Mismatched regclass size on folded subreg COPY");
7321 loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC,
7322 Register());
7323 MachineInstr &LoadMI = *--InsertPt;
7324 MachineOperand &LoadDst = LoadMI.getOperand(0);
7325 assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
7326 LoadDst.setSubReg(DstMO.getSubReg());
7327 LoadDst.setIsUndef();
7328 return &LoadMI;
7329 }
7330 }
7331 }
7332
7333 // Cannot fold.
7334 return nullptr;
7335}
7336
7338 StackOffset &SOffset,
7339 bool *OutUseUnscaledOp,
7340 unsigned *OutUnscaledOp,
7341 int64_t *EmittableOffset) {
7342 // Set output values in case of early exit.
7343 if (EmittableOffset)
7344 *EmittableOffset = 0;
7345 if (OutUseUnscaledOp)
7346 *OutUseUnscaledOp = false;
7347 if (OutUnscaledOp)
7348 *OutUnscaledOp = 0;
7349
7350 // Exit early for structured vector spills/fills as they can't take an
7351 // immediate offset.
7352 switch (MI.getOpcode()) {
7353 default:
7354 break;
7355 case AArch64::LD1Rv1d:
7356 case AArch64::LD1Rv2s:
7357 case AArch64::LD1Rv2d:
7358 case AArch64::LD1Rv4h:
7359 case AArch64::LD1Rv4s:
7360 case AArch64::LD1Rv8b:
7361 case AArch64::LD1Rv8h:
7362 case AArch64::LD1Rv16b:
7363 case AArch64::LD1Twov2d:
7364 case AArch64::LD1Threev2d:
7365 case AArch64::LD1Fourv2d:
7366 case AArch64::LD1Twov1d:
7367 case AArch64::LD1Threev1d:
7368 case AArch64::LD1Fourv1d:
7369 case AArch64::ST1Twov2d:
7370 case AArch64::ST1Threev2d:
7371 case AArch64::ST1Fourv2d:
7372 case AArch64::ST1Twov1d:
7373 case AArch64::ST1Threev1d:
7374 case AArch64::ST1Fourv1d:
7375 case AArch64::ST1i8:
7376 case AArch64::ST1i16:
7377 case AArch64::ST1i32:
7378 case AArch64::ST1i64:
7379 case AArch64::IRG:
7380 case AArch64::IRGstack:
7381 case AArch64::STGloop:
7382 case AArch64::STZGloop:
7384 }
7385
7386 // Get the min/max offset and the scale.
7387 TypeSize ScaleValue(0U, false), Width(0U, false);
7388 int64_t MinOff, MaxOff;
7389 if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
7390 MaxOff))
7391 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7392
7393 // Construct the complete offset.
7394 bool IsMulVL = ScaleValue.isScalable();
7395 unsigned Scale = ScaleValue.getKnownMinValue();
7396 int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
7397
7398 const MachineOperand &ImmOpnd =
7399 MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
7400 Offset += ImmOpnd.getImm() * Scale;
7401
7402 // If the offset doesn't match the scale, we rewrite the instruction to
7403 // use the unscaled instruction instead. Likewise, if we have a negative
7404 // offset and there is an unscaled op to use.
7405 std::optional<unsigned> UnscaledOp =
7407 bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
7408 if (useUnscaledOp &&
7409 !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
7410 MaxOff))
7411 llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
7412
7413 Scale = ScaleValue.getKnownMinValue();
7414 assert(IsMulVL == ScaleValue.isScalable() &&
7415 "Unscaled opcode has different value for scalable");
7416
7417 int64_t Remainder = Offset % Scale;
7418 assert(!(Remainder && useUnscaledOp) &&
7419 "Cannot have remainder when using unscaled op");
7420
7421 assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
7422 int64_t NewOffset = Offset / Scale;
7423 if (MinOff <= NewOffset && NewOffset <= MaxOff)
7424 Offset = Remainder;
7425 else {
7426 // Try to minimise the number of instructions required to materialise the
7427 // offset calculation. Specifically, for fixed offsets, if masking out the
7428 // low 12 bits leaves a legal add immediate, we can realise the offset
7429 // calculation with a single add instruction. Whenever this is possible,
7430 // prefer this split.
7431 int64_t HighPart = Offset & ~0xFFF;
7432 int64_t LowPart = Offset & 0xFFF;
7433 int64_t LowScaled = LowPart / Scale;
7434 if (!IsMulVL && NewOffset >= 0 && LowPart % Scale == 0 &&
7435 MinOff <= LowScaled && LowScaled <= MaxOff &&
7437 NewOffset = LowScaled;
7438 Offset = HighPart;
7439 } else {
7440 // Default to a greedy split: take the memop immediate to be maximum /
7441 // minimum expressible offset and materialise the remainder.
7442 NewOffset = NewOffset < 0 ? MinOff : MaxOff;
7443 Offset = Offset - (NewOffset * Scale);
7444 }
7445 }
7446
7447 if (EmittableOffset)
7448 *EmittableOffset = NewOffset;
7449 if (OutUseUnscaledOp)
7450 *OutUseUnscaledOp = useUnscaledOp;
7451 if (OutUnscaledOp && UnscaledOp)
7452 *OutUnscaledOp = *UnscaledOp;
7453
7454 if (IsMulVL)
7455 SOffset = StackOffset::get(SOffset.getFixed(), Offset);
7456 else
7457 SOffset = StackOffset::get(Offset, SOffset.getScalable());
7459 (SOffset ? 0 : AArch64FrameOffsetIsLegal);
7460}
7461
7463 unsigned FrameReg, StackOffset &Offset,
7464 const AArch64InstrInfo *TII) {
7465 unsigned Opcode = MI.getOpcode();
7466 unsigned ImmIdx = FrameRegIdx + 1;
7467
7468 if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
7469 Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
7470 emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
7471 MI.getOperand(0).getReg(), FrameReg, Offset, TII,
7472 MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
7473 MI.eraseFromParent();
7474 Offset = StackOffset();
7475 return true;
7476 }
7477
7478 int64_t NewOffset;
7479 unsigned UnscaledOp;
7480 bool UseUnscaledOp;
7481 int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
7482 &UnscaledOp, &NewOffset);
7485 // Replace the FrameIndex with FrameReg.
7486 MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
7487 if (UseUnscaledOp)
7488 MI.setDesc(TII->get(UnscaledOp));
7489
7490 MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
7491 return !Offset;
7492 }
7493
7494 return false;
7495}
7496
7502
7503MCInst AArch64InstrInfo::getNop() const { return MCInstBuilder(AArch64::NOP); }
7504
7505// AArch64 supports MachineCombiner.
7506bool AArch64InstrInfo::useMachineCombiner() const { return true; }
7507
7508// True when Opc sets flag
7509static bool isCombineInstrSettingFlag(unsigned Opc) {
7510 switch (Opc) {
7511 case AArch64::ADDSWrr:
7512 case AArch64::ADDSWri:
7513 case AArch64::ADDSXrr:
7514 case AArch64::ADDSXri:
7515 case AArch64::SUBSWrr:
7516 case AArch64::SUBSXrr:
7517 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7518 case AArch64::SUBSWri:
7519 case AArch64::SUBSXri:
7520 return true;
7521 default:
7522 break;
7523 }
7524 return false;
7525}
7526
7527// 32b Opcodes that can be combined with a MUL
7528static bool isCombineInstrCandidate32(unsigned Opc) {
7529 switch (Opc) {
7530 case AArch64::ADDWrr:
7531 case AArch64::ADDWri:
7532 case AArch64::SUBWrr:
7533 case AArch64::ADDSWrr:
7534 case AArch64::ADDSWri:
7535 case AArch64::SUBSWrr:
7536 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7537 case AArch64::SUBWri:
7538 case AArch64::SUBSWri:
7539 return true;
7540 default:
7541 break;
7542 }
7543 return false;
7544}
7545
7546// 64b Opcodes that can be combined with a MUL
7547static bool isCombineInstrCandidate64(unsigned Opc) {
7548 switch (Opc) {
7549 case AArch64::ADDXrr:
7550 case AArch64::ADDXri:
7551 case AArch64::SUBXrr:
7552 case AArch64::ADDSXrr:
7553 case AArch64::ADDSXri:
7554 case AArch64::SUBSXrr:
7555 // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
7556 case AArch64::SUBXri:
7557 case AArch64::SUBSXri:
7558 case AArch64::ADDv8i8:
7559 case AArch64::ADDv16i8:
7560 case AArch64::ADDv4i16:
7561 case AArch64::ADDv8i16:
7562 case AArch64::ADDv2i32:
7563 case AArch64::ADDv4i32:
7564 case AArch64::SUBv8i8:
7565 case AArch64::SUBv16i8:
7566 case AArch64::SUBv4i16:
7567 case AArch64::SUBv8i16:
7568 case AArch64::SUBv2i32:
7569 case AArch64::SUBv4i32:
7570 return true;
7571 default:
7572 break;
7573 }
7574 return false;
7575}
7576
7577// FP Opcodes that can be combined with a FMUL.
7578static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
7579 switch (Inst.getOpcode()) {
7580 default:
7581 break;
7582 case AArch64::FADDHrr:
7583 case AArch64::FADDSrr:
7584 case AArch64::FADDDrr:
7585 case AArch64::FADDv4f16:
7586 case AArch64::FADDv8f16:
7587 case AArch64::FADDv2f32:
7588 case AArch64::FADDv2f64:
7589 case AArch64::FADDv4f32:
7590 case AArch64::FSUBHrr:
7591 case AArch64::FSUBSrr:
7592 case AArch64::FSUBDrr:
7593 case AArch64::FSUBv4f16:
7594 case AArch64::FSUBv8f16:
7595 case AArch64::FSUBv2f32:
7596 case AArch64::FSUBv2f64:
7597 case AArch64::FSUBv4f32:
7598 // We can fuse FADD/FSUB with FMUL, if FADD/FSUB has the contract fast-math
7599 // flag.
7600 return Inst.getFlag(MachineInstr::FmContract);
7601 }
7602 return false;
7603}
7604
7605// Opcodes that can be combined with a MUL
7609
7610//
7611// Utility routine that checks if \param MO is defined by an
7612// \param CombineOpc instruction in the basic block \param MBB
7614 unsigned CombineOpc, unsigned ZeroReg = 0,
7615 bool CheckZeroReg = false) {
7616 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7617 MachineInstr *MI = nullptr;
7618
7619 if (MO.isReg() && MO.getReg().isVirtual())
7620 MI = MRI.getUniqueVRegDef(MO.getReg());
7621 // And it needs to be in the trace (otherwise, it won't have a depth).
7622 if (!MI || MI->getParent() != &MBB || MI->getOpcode() != CombineOpc)
7623 return false;
7624 // Must only used by the user we combine with.
7625 if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
7626 return false;
7627
7628 if (CheckZeroReg) {
7629 assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
7630 MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
7631 MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
7632 // The third input reg must be zero.
7633 if (MI->getOperand(3).getReg() != ZeroReg)
7634 return false;
7635 }
7636
7637 if (isCombineInstrSettingFlag(CombineOpc) &&
7638 MI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) == -1)
7639 return false;
7640
7641 return true;
7642}
7643
7644//
7645// Is \param MO defined by an integer multiply and can be combined?
7647 unsigned MulOpc, unsigned ZeroReg) {
7648 return canCombine(MBB, MO, MulOpc, ZeroReg, true);
7649}
7650
7651//
7652// Is \param MO defined by a floating-point multiply and can be combined?
7654 unsigned MulOpc) {
7655 return canCombine(MBB, MO, MulOpc);
7656}
7657
7658// TODO: There are many more machine instruction opcodes to match:
7659// 1. Other data types (integer, vectors)
7660// 2. Other math / logic operations (xor, or)
7661// 3. Other forms of the same operation (intrinsics and other variants)
7662bool AArch64InstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst,
7663 bool Invert) const {
7664 if (Invert)
7665 return false;
7666 switch (Inst.getOpcode()) {
7667 // == Floating-point types ==
7668 // -- Floating-point instructions --
7669 case AArch64::FADDHrr:
7670 case AArch64::FADDSrr:
7671 case AArch64::FADDDrr:
7672 case AArch64::FMULHrr:
7673 case AArch64::FMULSrr:
7674 case AArch64::FMULDrr:
7675 case AArch64::FMULX16:
7676 case AArch64::FMULX32:
7677 case AArch64::FMULX64:
7678 // -- Advanced SIMD instructions --
7679 case AArch64::FADDv4f16:
7680 case AArch64::FADDv8f16:
7681 case AArch64::FADDv2f32:
7682 case AArch64::FADDv4f32:
7683 case AArch64::FADDv2f64:
7684 case AArch64::FMULv4f16:
7685 case AArch64::FMULv8f16:
7686 case AArch64::FMULv2f32:
7687 case AArch64::FMULv4f32:
7688 case AArch64::FMULv2f64:
7689 case AArch64::FMULXv4f16:
7690 case AArch64::FMULXv8f16:
7691 case AArch64::FMULXv2f32:
7692 case AArch64::FMULXv4f32:
7693 case AArch64::FMULXv2f64:
7694 // -- SVE instructions --
7695 // Opcodes FMULX_ZZZ_? don't exist because there is no unpredicated FMULX
7696 // in the SVE instruction set (though there are predicated ones).
7697 case AArch64::FADD_ZZZ_H:
7698 case AArch64::FADD_ZZZ_S:
7699 case AArch64::FADD_ZZZ_D:
7700 case AArch64::FMUL_ZZZ_H:
7701 case AArch64::FMUL_ZZZ_S:
7702 case AArch64::FMUL_ZZZ_D:
7705
7706 // == Integer types ==
7707 // -- Base instructions --
7708 // Opcodes MULWrr and MULXrr don't exist because
7709 // `MUL <Wd>, <Wn>, <Wm>` and `MUL <Xd>, <Xn>, <Xm>` are aliases of
7710 // `MADD <Wd>, <Wn>, <Wm>, WZR` and `MADD <Xd>, <Xn>, <Xm>, XZR` respectively.
7711 // The machine-combiner does not support three-source-operands machine
7712 // instruction. So we cannot reassociate MULs.
7713 case AArch64::ADDWrr:
7714 case AArch64::ADDXrr:
7715 case AArch64::ANDWrr:
7716 case AArch64::ANDXrr:
7717 case AArch64::ORRWrr:
7718 case AArch64::ORRXrr:
7719 case AArch64::EORWrr:
7720 case AArch64::EORXrr:
7721 case AArch64::EONWrr:
7722 case AArch64::EONXrr:
7723 // -- Advanced SIMD instructions --
7724 // Opcodes MULv1i64 and MULv2i64 don't exist because there is no 64-bit MUL
7725 // in the Advanced SIMD instruction set.
7726 case AArch64::ADDv8i8:
7727 case AArch64::ADDv16i8:
7728 case AArch64::ADDv4i16:
7729 case AArch64::ADDv8i16:
7730 case AArch64::ADDv2i32:
7731 case AArch64::ADDv4i32:
7732 case AArch64::ADDv1i64:
7733 case AArch64::ADDv2i64:
7734 case AArch64::MULv8i8:
7735 case AArch64::MULv16i8:
7736 case AArch64::MULv4i16:
7737 case AArch64::MULv8i16:
7738 case AArch64::MULv2i32:
7739 case AArch64::MULv4i32:
7740 case AArch64::ANDv8i8:
7741 case AArch64::ANDv16i8:
7742 case AArch64::ORRv8i8:
7743 case AArch64::ORRv16i8:
7744 case AArch64::EORv8i8:
7745 case AArch64::EORv16i8:
7746 // -- SVE instructions --
7747 case AArch64::ADD_ZZZ_B:
7748 case AArch64::ADD_ZZZ_H:
7749 case AArch64::ADD_ZZZ_S:
7750 case AArch64::ADD_ZZZ_D:
7751 case AArch64::MUL_ZZZ_B:
7752 case AArch64::MUL_ZZZ_H:
7753 case AArch64::MUL_ZZZ_S:
7754 case AArch64::MUL_ZZZ_D:
7755 case AArch64::AND_ZZZ:
7756 case AArch64::ORR_ZZZ:
7757 case AArch64::EOR_ZZZ:
7758 return true;
7759
7760 default:
7761 return false;
7762 }
7763}
7764
7765/// Find instructions that can be turned into madd.
7767 SmallVectorImpl<unsigned> &Patterns) {
7768 unsigned Opc = Root.getOpcode();
7769 MachineBasicBlock &MBB = *Root.getParent();
7770 bool Found = false;
7771
7773 return false;
7775 int Cmp_NZCV =
7776 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true);
7777 // When NZCV is live bail out.
7778 if (Cmp_NZCV == -1)
7779 return false;
7780 unsigned NewOpc = convertToNonFlagSettingOpc(Root);
7781 // When opcode can't change bail out.
7782 // CHECKME: do we miss any cases for opcode conversion?
7783 if (NewOpc == Opc)
7784 return false;
7785 Opc = NewOpc;
7786 }
7787
7788 auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
7789 unsigned Pattern) {
7790 if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
7791 Patterns.push_back(Pattern);
7792 Found = true;
7793 }
7794 };
7795
7796 auto setVFound = [&](int Opcode, int Operand, unsigned Pattern) {
7797 if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
7798 Patterns.push_back(Pattern);
7799 Found = true;
7800 }
7801 };
7802
7804
7805 switch (Opc) {
7806 default:
7807 break;
7808 case AArch64::ADDWrr:
7809 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
7810 "ADDWrr does not have register operands");
7811 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
7812 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
7813 break;
7814 case AArch64::ADDXrr:
7815 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
7816 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
7817 break;
7818 case AArch64::SUBWrr:
7819 setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
7820 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
7821 break;
7822 case AArch64::SUBXrr:
7823 setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
7824 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
7825 break;
7826 case AArch64::ADDWri:
7827 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
7828 break;
7829 case AArch64::ADDXri:
7830 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
7831 break;
7832 case AArch64::SUBWri:
7833 setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
7834 break;
7835 case AArch64::SUBXri:
7836 setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
7837 break;
7838 case AArch64::ADDv8i8:
7839 setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
7840 setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
7841 break;
7842 case AArch64::ADDv16i8:
7843 setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
7844 setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
7845 break;
7846 case AArch64::ADDv4i16:
7847 setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
7848 setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
7849 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
7850 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
7851 break;
7852 case AArch64::ADDv8i16:
7853 setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
7854 setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
7855 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
7856 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
7857 break;
7858 case AArch64::ADDv2i32:
7859 setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
7860 setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
7861 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
7862 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
7863 break;
7864 case AArch64::ADDv4i32:
7865 setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
7866 setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
7867 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
7868 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
7869 break;
7870 case AArch64::SUBv8i8:
7871 setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
7872 setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
7873 break;
7874 case AArch64::SUBv16i8:
7875 setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
7876 setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
7877 break;
7878 case AArch64::SUBv4i16:
7879 setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
7880 setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
7881 setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
7882 setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
7883 break;
7884 case AArch64::SUBv8i16:
7885 setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
7886 setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
7887 setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
7888 setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
7889 break;
7890 case AArch64::SUBv2i32:
7891 setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
7892 setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
7893 setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
7894 setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
7895 break;
7896 case AArch64::SUBv4i32:
7897 setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
7898 setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
7899 setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
7900 setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
7901 break;
7902 }
7903 return Found;
7904}
7905
7906bool AArch64InstrInfo::isAccumulationOpcode(unsigned Opcode) const {
7907 switch (Opcode) {
7908 default:
7909 break;
7910 case AArch64::UABALB_ZZZ_D:
7911 case AArch64::UABALB_ZZZ_H:
7912 case AArch64::UABALB_ZZZ_S:
7913 case AArch64::UABALT_ZZZ_D:
7914 case AArch64::UABALT_ZZZ_H:
7915 case AArch64::UABALT_ZZZ_S:
7916 case AArch64::SABALB_ZZZ_D:
7917 case AArch64::SABALB_ZZZ_S:
7918 case AArch64::SABALB_ZZZ_H:
7919 case AArch64::SABALT_ZZZ_D:
7920 case AArch64::SABALT_ZZZ_S:
7921 case AArch64::SABALT_ZZZ_H:
7922 case AArch64::UABALv16i8_v8i16:
7923 case AArch64::UABALv2i32_v2i64:
7924 case AArch64::UABALv4i16_v4i32:
7925 case AArch64::UABALv4i32_v2i64:
7926 case AArch64::UABALv8i16_v4i32:
7927 case AArch64::UABALv8i8_v8i16:
7928 case AArch64::UABAv16i8:
7929 case AArch64::UABAv2i32:
7930 case AArch64::UABAv4i16:
7931 case AArch64::UABAv4i32:
7932 case AArch64::UABAv8i16:
7933 case AArch64::UABAv8i8:
7934 case AArch64::SABALv16i8_v8i16:
7935 case AArch64::SABALv2i32_v2i64:
7936 case AArch64::SABALv4i16_v4i32:
7937 case AArch64::SABALv4i32_v2i64:
7938 case AArch64::SABALv8i16_v4i32:
7939 case AArch64::SABALv8i8_v8i16:
7940 case AArch64::SABAv16i8:
7941 case AArch64::SABAv2i32:
7942 case AArch64::SABAv4i16:
7943 case AArch64::SABAv4i32:
7944 case AArch64::SABAv8i16:
7945 case AArch64::SABAv8i8:
7946 return true;
7947 }
7948
7949 return false;
7950}
7951
7952unsigned AArch64InstrInfo::getAccumulationStartOpcode(
7953 unsigned AccumulationOpcode) const {
7954 switch (AccumulationOpcode) {
7955 default:
7956 llvm_unreachable("Unsupported accumulation Opcode!");
7957 case AArch64::UABALB_ZZZ_D:
7958 return AArch64::UABDLB_ZZZ_D;
7959 case AArch64::UABALB_ZZZ_H:
7960 return AArch64::UABDLB_ZZZ_H;
7961 case AArch64::UABALB_ZZZ_S:
7962 return AArch64::UABDLB_ZZZ_S;
7963 case AArch64::UABALT_ZZZ_D:
7964 return AArch64::UABDLT_ZZZ_D;
7965 case AArch64::UABALT_ZZZ_H:
7966 return AArch64::UABDLT_ZZZ_H;
7967 case AArch64::UABALT_ZZZ_S:
7968 return AArch64::UABDLT_ZZZ_S;
7969 case AArch64::UABALv16i8_v8i16:
7970 return AArch64::UABDLv16i8_v8i16;
7971 case AArch64::UABALv2i32_v2i64:
7972 return AArch64::UABDLv2i32_v2i64;
7973 case AArch64::UABALv4i16_v4i32:
7974 return AArch64::UABDLv4i16_v4i32;
7975 case AArch64::UABALv4i32_v2i64:
7976 return AArch64::UABDLv4i32_v2i64;
7977 case AArch64::UABALv8i16_v4i32:
7978 return AArch64::UABDLv8i16_v4i32;
7979 case AArch64::UABALv8i8_v8i16:
7980 return AArch64::UABDLv8i8_v8i16;
7981 case AArch64::UABAv16i8:
7982 return AArch64::UABDv16i8;
7983 case AArch64::UABAv2i32:
7984 return AArch64::UABDv2i32;
7985 case AArch64::UABAv4i16:
7986 return AArch64::UABDv4i16;
7987 case AArch64::UABAv4i32:
7988 return AArch64::UABDv4i32;
7989 case AArch64::UABAv8i16:
7990 return AArch64::UABDv8i16;
7991 case AArch64::UABAv8i8:
7992 return AArch64::UABDv8i8;
7993 case AArch64::SABALB_ZZZ_D:
7994 return AArch64::SABDLB_ZZZ_D;
7995 case AArch64::SABALB_ZZZ_S:
7996 return AArch64::SABDLB_ZZZ_S;
7997 case AArch64::SABALB_ZZZ_H:
7998 return AArch64::SABDLB_ZZZ_H;
7999 case AArch64::SABALT_ZZZ_D:
8000 return AArch64::SABDLT_ZZZ_D;
8001 case AArch64::SABALT_ZZZ_S:
8002 return AArch64::SABDLT_ZZZ_S;
8003 case AArch64::SABALT_ZZZ_H:
8004 return AArch64::SABDLT_ZZZ_H;
8005 case AArch64::SABALv16i8_v8i16:
8006 return AArch64::SABDLv16i8_v8i16;
8007 case AArch64::SABALv2i32_v2i64:
8008 return AArch64::SABDLv2i32_v2i64;
8009 case AArch64::SABALv4i16_v4i32:
8010 return AArch64::SABDLv4i16_v4i32;
8011 case AArch64::SABALv4i32_v2i64:
8012 return AArch64::SABDLv4i32_v2i64;
8013 case AArch64::SABALv8i16_v4i32:
8014 return AArch64::SABDLv8i16_v4i32;
8015 case AArch64::SABALv8i8_v8i16:
8016 return AArch64::SABDLv8i8_v8i16;
8017 case AArch64::SABAv16i8:
8018 return AArch64::SABDv16i8;
8019 case AArch64::SABAv2i32:
8020 return AArch64::SABDv2i32;
8021 case AArch64::SABAv4i16:
8022 return AArch64::SABDv4i16;
8023 case AArch64::SABAv4i32:
8024 return AArch64::SABDv4i32;
8025 case AArch64::SABAv8i16:
8026 return AArch64::SABDv8i16;
8027 case AArch64::SABAv8i8:
8028 return AArch64::SABDv8i8;
8029 }
8030}
8031
8032/// Floating-Point Support
8033
8034/// Find instructions that can be turned into madd.
8036 SmallVectorImpl<unsigned> &Patterns) {
8037
8038 if (!isCombineInstrCandidateFP(Root))
8039 return false;
8040
8041 MachineBasicBlock &MBB = *Root.getParent();
8042 bool Found = false;
8043
8044 auto Match = [&](int Opcode, int Operand, unsigned Pattern) -> bool {
8045 if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
8046 Patterns.push_back(Pattern);
8047 return true;
8048 }
8049 return false;
8050 };
8051
8053
8054 switch (Root.getOpcode()) {
8055 default:
8056 assert(false && "Unsupported FP instruction in combiner\n");
8057 break;
8058 case AArch64::FADDHrr:
8059 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8060 "FADDHrr does not have register operands");
8061
8062 Found = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
8063 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
8064 break;
8065 case AArch64::FADDSrr:
8066 assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
8067 "FADDSrr does not have register operands");
8068
8069 Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
8070 Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
8071
8072 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
8073 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
8074 break;
8075 case AArch64::FADDDrr:
8076 Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
8077 Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
8078
8079 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
8080 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
8081 break;
8082 case AArch64::FADDv4f16:
8083 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
8084 Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
8085
8086 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
8087 Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
8088 break;
8089 case AArch64::FADDv8f16:
8090 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
8091 Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
8092
8093 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
8094 Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
8095 break;
8096 case AArch64::FADDv2f32:
8097 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
8098 Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
8099
8100 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
8101 Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
8102 break;
8103 case AArch64::FADDv2f64:
8104 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
8105 Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
8106
8107 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
8108 Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
8109 break;
8110 case AArch64::FADDv4f32:
8111 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
8112 Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
8113
8114 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
8115 Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
8116 break;
8117 case AArch64::FSUBHrr:
8118 Found = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
8119 Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
8120 Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
8121 break;
8122 case AArch64::FSUBSrr:
8123 Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
8124
8125 Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
8126 Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
8127
8128 Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
8129 break;
8130 case AArch64::FSUBDrr:
8131 Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
8132
8133 Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
8134 Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
8135
8136 Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
8137 break;
8138 case AArch64::FSUBv4f16:
8139 Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
8140 Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
8141
8142 Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
8143 Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
8144 break;
8145 case AArch64::FSUBv8f16:
8146 Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
8147 Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
8148
8149 Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
8150 Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
8151 break;
8152 case AArch64::FSUBv2f32:
8153 Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
8154 Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
8155
8156 Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
8157 Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
8158 break;
8159 case AArch64::FSUBv2f64:
8160 Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
8161 Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
8162
8163 Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
8164 Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
8165 break;
8166 case AArch64::FSUBv4f32:
8167 Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
8168 Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
8169
8170 Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
8171 Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
8172 break;
8173 }
8174 return Found;
8175}
8176
8178 SmallVectorImpl<unsigned> &Patterns) {
8179 MachineBasicBlock &MBB = *Root.getParent();
8180 bool Found = false;
8181
8182 auto Match = [&](unsigned Opcode, int Operand, unsigned Pattern) -> bool {
8183 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8184 MachineOperand &MO = Root.getOperand(Operand);
8185 MachineInstr *MI = nullptr;
8186 if (MO.isReg() && MO.getReg().isVirtual())
8187 MI = MRI.getUniqueVRegDef(MO.getReg());
8188 // Ignore No-op COPYs in FMUL(COPY(DUP(..)))
8189 if (MI && MI->getOpcode() == TargetOpcode::COPY &&
8190 MI->getOperand(1).getReg().isVirtual())
8191 MI = MRI.getUniqueVRegDef(MI->getOperand(1).getReg());
8192 if (MI && MI->getOpcode() == Opcode) {
8193 Patterns.push_back(Pattern);
8194 return true;
8195 }
8196 return false;
8197 };
8198
8200
8201 switch (Root.getOpcode()) {
8202 default:
8203 return false;
8204 case AArch64::FMULv2f32:
8205 Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
8206 Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
8207 break;
8208 case AArch64::FMULv2f64:
8209 Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
8210 Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
8211 break;
8212 case AArch64::FMULv4f16:
8213 Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
8214 Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
8215 break;
8216 case AArch64::FMULv4f32:
8217 Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
8218 Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
8219 break;
8220 case AArch64::FMULv8f16:
8221 Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
8222 Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
8223 break;
8224 }
8225
8226 return Found;
8227}
8228
8230 SmallVectorImpl<unsigned> &Patterns) {
8231 unsigned Opc = Root.getOpcode();
8232 MachineBasicBlock &MBB = *Root.getParent();
8233 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
8234
8235 auto Match = [&](unsigned Opcode, unsigned Pattern) -> bool {
8236 MachineOperand &MO = Root.getOperand(1);
8238 if (MI != nullptr && (MI->getOpcode() == Opcode) &&
8239 MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()) &&
8243 MI->getFlag(MachineInstr::MIFlag::FmNsz)) {
8244 Patterns.push_back(Pattern);
8245 return true;
8246 }
8247 return false;
8248 };
8249
8250 switch (Opc) {
8251 default:
8252 break;
8253 case AArch64::FNEGDr:
8254 return Match(AArch64::FMADDDrrr, AArch64MachineCombinerPattern::FNMADD);
8255 case AArch64::FNEGSr:
8256 return Match(AArch64::FMADDSrrr, AArch64MachineCombinerPattern::FNMADD);
8257 }
8258
8259 return false;
8260}
8261
8262/// Return true when a code sequence can improve throughput. It
8263/// should be called only for instructions in loops.
8264/// \param Pattern - combiner pattern
8266 switch (Pattern) {
8267 default:
8268 break;
8374 return true;
8375 } // end switch (Pattern)
8376 return false;
8377}
8378
8379/// Find other MI combine patterns.
8381 SmallVectorImpl<unsigned> &Patterns) {
8382 // A - (B + C) ==> (A - B) - C or (A - C) - B
8383 unsigned Opc = Root.getOpcode();
8384 MachineBasicBlock &MBB = *Root.getParent();
8385
8386 switch (Opc) {
8387 case AArch64::SUBWrr:
8388 case AArch64::SUBSWrr:
8389 case AArch64::SUBXrr:
8390 case AArch64::SUBSXrr:
8391 // Found candidate root.
8392 break;
8393 default:
8394 return false;
8395 }
8396
8398 Root.findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr, true) ==
8399 -1)
8400 return false;
8401
8402 if (canCombine(MBB, Root.getOperand(2), AArch64::ADDWrr) ||
8403 canCombine(MBB, Root.getOperand(2), AArch64::ADDSWrr) ||
8404 canCombine(MBB, Root.getOperand(2), AArch64::ADDXrr) ||
8405 canCombine(MBB, Root.getOperand(2), AArch64::ADDSXrr)) {
8408 return true;
8409 }
8410
8411 return false;
8412}
8413
8414/// Check if the given instruction forms a gather load pattern that can be
8415/// optimized for better Memory-Level Parallelism (MLP). This function
8416/// identifies chains of NEON lane load instructions that load data from
8417/// different memory addresses into individual lanes of a 128-bit vector
8418/// register, then attempts to split the pattern into parallel loads to break
8419/// the serial dependency between instructions.
8420///
8421/// Pattern Matched:
8422/// Initial scalar load -> SUBREG_TO_REG (lane 0) -> LD1i* (lane 1) ->
8423/// LD1i* (lane 2) -> ... -> LD1i* (lane N-1, Root)
8424///
8425/// Transformed Into:
8426/// Two parallel vector loads using fewer lanes each, followed by ZIP1v2i64
8427/// to combine the results, enabling better memory-level parallelism.
8428///
8429/// Supported Element Types:
8430/// - 32-bit elements (LD1i32, 4 lanes total)
8431/// - 16-bit elements (LD1i16, 8 lanes total)
8432/// - 8-bit elements (LD1i8, 16 lanes total)
8434 SmallVectorImpl<unsigned> &Patterns,
8435 unsigned LoadLaneOpCode, unsigned NumLanes) {
8436 const MachineFunction *MF = Root.getMF();
8437
8438 // Early exit if optimizing for size.
8439 if (MF->getFunction().hasMinSize())
8440 return false;
8441
8442 const MachineRegisterInfo &MRI = MF->getRegInfo();
8444
8445 // The root of the pattern must load into the last lane of the vector.
8446 if (Root.getOperand(2).getImm() != NumLanes - 1)
8447 return false;
8448
8449 // Check that we have load into all lanes except lane 0.
8450 // For each load we also want to check that:
8451 // 1. It has a single non-debug use (since we will be replacing the virtual
8452 // register)
8453 // 2. That the addressing mode only uses a single pointer operand
8454 auto *CurrInstr = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8455 auto Range = llvm::seq<unsigned>(1, NumLanes - 1);
8456 SmallSet<unsigned, 16> RemainingLanes(Range.begin(), Range.end());
8458 while (!RemainingLanes.empty() && CurrInstr &&
8459 CurrInstr->getOpcode() == LoadLaneOpCode &&
8460 MRI.hasOneNonDBGUse(CurrInstr->getOperand(0).getReg()) &&
8461 CurrInstr->getNumOperands() == 4) {
8462 RemainingLanes.erase(CurrInstr->getOperand(2).getImm());
8463 LoadInstrs.push_back(CurrInstr);
8464 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8465 }
8466
8467 // Check that we have found a match for lanes N-1.. 1.
8468 if (!RemainingLanes.empty())
8469 return false;
8470
8471 // Match the SUBREG_TO_REG sequence.
8472 if (CurrInstr->getOpcode() != TargetOpcode::SUBREG_TO_REG)
8473 return false;
8474
8475 // Verify that the subreg to reg loads an integer into the first lane.
8476 auto Lane0LoadReg = CurrInstr->getOperand(1).getReg();
8477 unsigned SingleLaneSizeInBits = 128 / NumLanes;
8478 if (TRI->getRegSizeInBits(Lane0LoadReg, MRI) != SingleLaneSizeInBits)
8479 return false;
8480
8481 // Verify that it also has a single non debug use.
8482 if (!MRI.hasOneNonDBGUse(Lane0LoadReg))
8483 return false;
8484
8485 LoadInstrs.push_back(MRI.getUniqueVRegDef(Lane0LoadReg));
8486
8487 // If there is any chance of aliasing, do not apply the pattern.
8488 // Walk backward through the MBB starting from Root.
8489 // Exit early if we've encountered all load instructions or hit the search
8490 // limit.
8491 auto MBBItr = Root.getIterator();
8492 unsigned RemainingSteps =
8493 MF->getSubtarget<AArch64Subtarget>().getCLOpts().search_limit;
8494 SmallPtrSet<const MachineInstr *, 16> RemainingLoadInstrs;
8495 RemainingLoadInstrs.insert(LoadInstrs.begin(), LoadInstrs.end());
8496 const MachineBasicBlock *MBB = Root.getParent();
8497
8498 for (; MBBItr != MBB->begin() && RemainingSteps > 0 &&
8499 !RemainingLoadInstrs.empty();
8500 --MBBItr, --RemainingSteps) {
8501 const MachineInstr &CurrInstr = *MBBItr;
8502
8503 // Remove this instruction from remaining loads if it's one we're tracking.
8504 RemainingLoadInstrs.erase(&CurrInstr);
8505
8506 // Check for potential aliasing with any of the load instructions to
8507 // optimize.
8508 if (CurrInstr.isLoadFoldBarrier())
8509 return false;
8510 }
8511
8512 // If we hit the search limit without finding all load instructions,
8513 // don't match the pattern.
8514 if (RemainingSteps == 0 && !RemainingLoadInstrs.empty())
8515 return false;
8516
8517 switch (NumLanes) {
8518 case 4:
8520 break;
8521 case 8:
8523 break;
8524 case 16:
8526 break;
8527 default:
8528 llvm_unreachable("Got bad number of lanes for gather pattern.");
8529 }
8530
8531 return true;
8532}
8533
8534/// Search for patterns of LD instructions we can optimize.
8536 SmallVectorImpl<unsigned> &Patterns) {
8537
8538 // The pattern searches for loads into single lanes.
8539 switch (Root.getOpcode()) {
8540 case AArch64::LD1i32:
8541 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 4);
8542 case AArch64::LD1i16:
8543 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 8);
8544 case AArch64::LD1i8:
8545 return getGatherLanePattern(Root, Patterns, Root.getOpcode(), 16);
8546 default:
8547 return false;
8548 }
8549}
8550
8551/// Generate optimized instruction sequence for gather load patterns to improve
8552/// Memory-Level Parallelism (MLP). This function transforms a chain of
8553/// sequential NEON lane loads into parallel vector loads that can execute
8554/// concurrently.
8555static void
8559 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8560 unsigned Pattern, unsigned NumLanes) {
8561 MachineFunction &MF = *Root.getParent()->getParent();
8562 MachineRegisterInfo &MRI = MF.getRegInfo();
8564
8565 // Gather the initial load instructions to build the pattern.
8566 SmallVector<MachineInstr *, 16> LoadToLaneInstrs;
8567 MachineInstr *CurrInstr = &Root;
8568 for (unsigned i = 0; i < NumLanes - 1; ++i) {
8569 LoadToLaneInstrs.push_back(CurrInstr);
8570 CurrInstr = MRI.getUniqueVRegDef(CurrInstr->getOperand(1).getReg());
8571 }
8572
8573 // Sort the load instructions according to the lane.
8574 llvm::sort(LoadToLaneInstrs,
8575 [](const MachineInstr *A, const MachineInstr *B) {
8576 return A->getOperand(2).getImm() > B->getOperand(2).getImm();
8577 });
8578
8579 MachineInstr *SubregToReg = CurrInstr;
8580 LoadToLaneInstrs.push_back(
8581 MRI.getUniqueVRegDef(SubregToReg->getOperand(1).getReg()));
8582 auto LoadToLaneInstrsAscending = llvm::reverse(LoadToLaneInstrs);
8583
8584 const TargetRegisterClass *FPR128RegClass =
8585 MRI.getRegClass(Root.getOperand(0).getReg());
8586
8587 // Helper lambda to create a LD1 instruction.
8588 auto CreateLD1Instruction = [&](MachineInstr *OriginalInstr,
8589 Register SrcRegister, unsigned Lane,
8590 Register OffsetRegister,
8591 bool OffsetRegisterKillState) {
8592 auto NewRegister = MRI.createVirtualRegister(FPR128RegClass);
8593 MachineInstrBuilder LoadIndexIntoRegister =
8594 BuildMI(MF, MIMetadata(*OriginalInstr), TII->get(Root.getOpcode()),
8595 NewRegister)
8596 .addReg(SrcRegister)
8597 .addImm(Lane)
8598 .addReg(OffsetRegister, getKillRegState(OffsetRegisterKillState))
8599 .setMemRefs(OriginalInstr->memoperands());
8600 InstrIdxForVirtReg.insert(std::make_pair(NewRegister, InsInstrs.size()));
8601 InsInstrs.push_back(LoadIndexIntoRegister);
8602 return NewRegister;
8603 };
8604
8605 // Helper to create load instruction based on the NumLanes in the NEON
8606 // register we are rewriting.
8607 auto CreateLDRInstruction =
8608 [&](unsigned NumLanes, Register DestReg, Register OffsetReg,
8610 unsigned Opcode;
8611 switch (NumLanes) {
8612 case 4:
8613 Opcode = AArch64::LDRSui;
8614 break;
8615 case 8:
8616 Opcode = AArch64::LDRHui;
8617 break;
8618 case 16:
8619 Opcode = AArch64::LDRBui;
8620 break;
8621 default:
8623 "Got unsupported number of lanes in machine-combiner gather pattern");
8624 }
8625 // Immediate offset load
8626 return BuildMI(MF, MIMetadata(Root), TII->get(Opcode), DestReg)
8627 .addReg(OffsetReg)
8628 .addImm(0)
8629 .setMemRefs(MMOs);
8630 };
8631
8632 // Load the remaining lanes into register 0.
8633 auto LanesToLoadToReg0 =
8634 llvm::make_range(LoadToLaneInstrsAscending.begin() + 1,
8635 LoadToLaneInstrsAscending.begin() + NumLanes / 2);
8636 Register PrevReg = SubregToReg->getOperand(0).getReg();
8637 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg0)) {
8638 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8639 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8640 OffsetRegOperand.getReg(),
8641 OffsetRegOperand.isKill());
8642 DelInstrs.push_back(LoadInstr);
8643 }
8644 Register LastLoadReg0 = PrevReg;
8645
8646 // First load into register 1. Perform an integer load to zero out the upper
8647 // lanes in a single instruction.
8648 MachineInstr *Lane0Load = *LoadToLaneInstrsAscending.begin();
8649 MachineInstr *OriginalSplitLoad =
8650 *std::next(LoadToLaneInstrsAscending.begin(), NumLanes / 2);
8651 Register DestRegForMiddleIndex = MRI.createVirtualRegister(
8652 MRI.getRegClass(Lane0Load->getOperand(0).getReg()));
8653
8654 const MachineOperand &OriginalSplitToLoadOffsetOperand =
8655 OriginalSplitLoad->getOperand(3);
8656 MachineInstrBuilder MiddleIndexLoadInstr =
8657 CreateLDRInstruction(NumLanes, DestRegForMiddleIndex,
8658 OriginalSplitToLoadOffsetOperand.getReg(),
8659 OriginalSplitLoad->memoperands());
8660
8661 InstrIdxForVirtReg.insert(
8662 std::make_pair(DestRegForMiddleIndex, InsInstrs.size()));
8663 InsInstrs.push_back(MiddleIndexLoadInstr);
8664 DelInstrs.push_back(OriginalSplitLoad);
8665
8666 // Subreg To Reg instruction for register 1.
8667 Register DestRegForSubregToReg = MRI.createVirtualRegister(FPR128RegClass);
8668 unsigned SubregType;
8669 switch (NumLanes) {
8670 case 4:
8671 SubregType = AArch64::ssub;
8672 break;
8673 case 8:
8674 SubregType = AArch64::hsub;
8675 break;
8676 case 16:
8677 SubregType = AArch64::bsub;
8678 break;
8679 default:
8681 "Got invalid NumLanes for machine-combiner gather pattern");
8682 }
8683
8684 auto SubRegToRegInstr =
8685 BuildMI(MF, MIMetadata(Root), TII->get(SubregToReg->getOpcode()),
8686 DestRegForSubregToReg)
8687 .addReg(DestRegForMiddleIndex, getKillRegState(true))
8688 .addImm(SubregType);
8689 InstrIdxForVirtReg.insert(
8690 std::make_pair(DestRegForSubregToReg, InsInstrs.size()));
8691 InsInstrs.push_back(SubRegToRegInstr);
8692
8693 // Load remaining lanes into register 1.
8694 auto LanesToLoadToReg1 =
8695 llvm::make_range(LoadToLaneInstrsAscending.begin() + NumLanes / 2 + 1,
8696 LoadToLaneInstrsAscending.end());
8697 PrevReg = SubRegToRegInstr->getOperand(0).getReg();
8698 for (auto [Index, LoadInstr] : llvm::enumerate(LanesToLoadToReg1)) {
8699 const MachineOperand &OffsetRegOperand = LoadInstr->getOperand(3);
8700 PrevReg = CreateLD1Instruction(LoadInstr, PrevReg, Index + 1,
8701 OffsetRegOperand.getReg(),
8702 OffsetRegOperand.isKill());
8703
8704 // Do not add the last reg to DelInstrs - it will be removed later.
8705 if (Index == NumLanes / 2 - 2) {
8706 break;
8707 }
8708 DelInstrs.push_back(LoadInstr);
8709 }
8710 Register LastLoadReg1 = PrevReg;
8711
8712 // Create the final zip instruction to combine the results.
8713 MachineInstrBuilder ZipInstr =
8714 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::ZIP1v2i64),
8715 Root.getOperand(0).getReg())
8716 .addReg(LastLoadReg0)
8717 .addReg(LastLoadReg1);
8718 InsInstrs.push_back(ZipInstr);
8719}
8720
8734
8735/// Return true when there is potentially a faster code sequence for an
8736/// instruction chain ending in \p Root. All potential patterns are listed in
8737/// the \p Pattern vector. Pattern should be sorted in priority order since the
8738/// pattern evaluator stops checking as soon as it finds a faster sequence.
8739
8740bool AArch64InstrInfo::getMachineCombinerPatterns(
8741 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
8742 bool DoRegPressureReduce) const {
8743 // Integer patterns
8744 if (getMaddPatterns(Root, Patterns))
8745 return true;
8746 // Floating point patterns
8747 if (getFMULPatterns(Root, Patterns))
8748 return true;
8749 if (getFMAPatterns(Root, Patterns))
8750 return true;
8751 if (getFNEGPatterns(Root, Patterns))
8752 return true;
8753
8754 // Other patterns
8755 if (getMiscPatterns(Root, Patterns))
8756 return true;
8757
8758 // Load patterns
8759 if (getLoadPatterns(Root, Patterns))
8760 return true;
8761
8762 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
8763 DoRegPressureReduce);
8764}
8765
8767/// genFusedMultiply - Generate fused multiply instructions.
8768/// This function supports both integer and floating point instructions.
8769/// A typical example:
8770/// F|MUL I=A,B,0
8771/// F|ADD R,I,C
8772/// ==> F|MADD R,A,B,C
8773/// \param MF Containing MachineFunction
8774/// \param MRI Register information
8775/// \param TII Target information
8776/// \param Root is the F|ADD instruction
8777/// \param [out] InsInstrs is a vector of machine instructions and will
8778/// contain the generated madd instruction
8779/// \param IdxMulOpd is index of operand in Root that is the result of
8780/// the F|MUL. In the example above IdxMulOpd is 1.
8781/// \param MaddOpc the opcode fo the f|madd instruction
8782/// \param RC Register class of operands
8783/// \param kind of fma instruction (addressing mode) to be generated
8784/// \param ReplacedAddend is the result register from the instruction
8785/// replacing the non-combined operand, if any.
8786static MachineInstr *
8788 const TargetInstrInfo *TII, MachineInstr &Root,
8789 SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
8790 unsigned MaddOpc, const TargetRegisterClass *RC,
8792 const Register *ReplacedAddend = nullptr) {
8793 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
8794
8795 unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
8796 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
8797 Register ResultReg = Root.getOperand(0).getReg();
8798 Register SrcReg0 = MUL->getOperand(1).getReg();
8799 bool Src0IsKill = MUL->getOperand(1).isKill();
8800 Register SrcReg1 = MUL->getOperand(2).getReg();
8801 bool Src1IsKill = MUL->getOperand(2).isKill();
8802
8803 Register SrcReg2;
8804 bool Src2IsKill;
8805 if (ReplacedAddend) {
8806 // If we just generated a new addend, we must be it's only use.
8807 SrcReg2 = *ReplacedAddend;
8808 Src2IsKill = true;
8809 } else {
8810 SrcReg2 = Root.getOperand(IdxOtherOpd).getReg();
8811 Src2IsKill = Root.getOperand(IdxOtherOpd).isKill();
8812 }
8813
8814 if (ResultReg.isVirtual())
8815 MRI.constrainRegClass(ResultReg, RC);
8816 if (SrcReg0.isVirtual())
8817 MRI.constrainRegClass(SrcReg0, RC);
8818 if (SrcReg1.isVirtual())
8819 MRI.constrainRegClass(SrcReg1, RC);
8820 if (SrcReg2.isVirtual())
8821 MRI.constrainRegClass(SrcReg2, RC);
8822
8824 if (kind == FMAInstKind::Default)
8825 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8826 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8827 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8828 .addReg(SrcReg2, getKillRegState(Src2IsKill));
8829 else if (kind == FMAInstKind::Indexed)
8830 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8831 .addReg(SrcReg2, getKillRegState(Src2IsKill))
8832 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8833 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8834 .addImm(MUL->getOperand(3).getImm());
8835 else if (kind == FMAInstKind::Accumulator)
8836 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
8837 .addReg(SrcReg2, getKillRegState(Src2IsKill))
8838 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8839 .addReg(SrcReg1, getKillRegState(Src1IsKill));
8840 else
8841 assert(false && "Invalid FMA instruction kind \n");
8842 // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
8843 InsInstrs.push_back(MIB);
8844 return MUL;
8845}
8846
8847static MachineInstr *
8849 const TargetInstrInfo *TII, MachineInstr &Root,
8851 MachineInstr *MAD = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
8852
8853 unsigned Opc = 0;
8854 const TargetRegisterClass *RC = MRI.getRegClass(MAD->getOperand(0).getReg());
8855 if (AArch64::FPR32RegClass.hasSubClassEq(RC))
8856 Opc = AArch64::FNMADDSrrr;
8857 else if (AArch64::FPR64RegClass.hasSubClassEq(RC))
8858 Opc = AArch64::FNMADDDrrr;
8859 else
8860 return nullptr;
8861
8862 Register ResultReg = Root.getOperand(0).getReg();
8863 Register SrcReg0 = MAD->getOperand(1).getReg();
8864 Register SrcReg1 = MAD->getOperand(2).getReg();
8865 Register SrcReg2 = MAD->getOperand(3).getReg();
8866 bool Src0IsKill = MAD->getOperand(1).isKill();
8867 bool Src1IsKill = MAD->getOperand(2).isKill();
8868 bool Src2IsKill = MAD->getOperand(3).isKill();
8869 if (ResultReg.isVirtual())
8870 MRI.constrainRegClass(ResultReg, RC);
8871 if (SrcReg0.isVirtual())
8872 MRI.constrainRegClass(SrcReg0, RC);
8873 if (SrcReg1.isVirtual())
8874 MRI.constrainRegClass(SrcReg1, RC);
8875 if (SrcReg2.isVirtual())
8876 MRI.constrainRegClass(SrcReg2, RC);
8877
8879 BuildMI(MF, MIMetadata(Root), TII->get(Opc), ResultReg)
8880 .addReg(SrcReg0, getKillRegState(Src0IsKill))
8881 .addReg(SrcReg1, getKillRegState(Src1IsKill))
8882 .addReg(SrcReg2, getKillRegState(Src2IsKill));
8883 InsInstrs.push_back(MIB);
8884
8885 return MAD;
8886}
8887
8888/// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
8889static MachineInstr *
8892 unsigned IdxDupOp, unsigned MulOpc,
8893 const TargetRegisterClass *RC, MachineRegisterInfo &MRI) {
8894 assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
8895 "Invalid index of FMUL operand");
8896
8897 MachineFunction &MF = *Root.getMF();
8899
8900 MachineInstr *Dup =
8901 MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
8902
8903 if (Dup->getOpcode() == TargetOpcode::COPY)
8904 Dup = MRI.getUniqueVRegDef(Dup->getOperand(1).getReg());
8905
8906 Register DupSrcReg = Dup->getOperand(1).getReg();
8907 MRI.clearKillFlags(DupSrcReg);
8908 MRI.constrainRegClass(DupSrcReg, RC);
8909
8910 unsigned DupSrcLane = Dup->getOperand(2).getImm();
8911
8912 unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
8913 MachineOperand &MulOp = Root.getOperand(IdxMulOp);
8914
8915 Register ResultReg = Root.getOperand(0).getReg();
8916
8918 MIB = BuildMI(MF, MIMetadata(Root), TII->get(MulOpc), ResultReg)
8919 .add(MulOp)
8920 .addReg(DupSrcReg)
8921 .addImm(DupSrcLane);
8922
8923 InsInstrs.push_back(MIB);
8924 return &Root;
8925}
8926
8927/// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
8928/// instructions.
8929///
8930/// \see genFusedMultiply
8934 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
8935 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8937}
8938
8939/// genNeg - Helper to generate an intermediate negation of the second operand
8940/// of Root
8942 const TargetInstrInfo *TII, MachineInstr &Root,
8944 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
8945 unsigned MnegOpc, const TargetRegisterClass *RC) {
8946 Register NewVR = MRI.createVirtualRegister(RC);
8948 BuildMI(MF, MIMetadata(Root), TII->get(MnegOpc), NewVR)
8949 .add(Root.getOperand(2));
8950 InsInstrs.push_back(MIB);
8951
8952 assert(InstrIdxForVirtReg.empty());
8953 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
8954
8955 return NewVR;
8956}
8957
8958/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
8959/// instructions with an additional negation of the accumulator
8963 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
8964 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
8965 assert(IdxMulOpd == 1);
8966
8967 Register NewVR =
8968 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
8969 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8970 FMAInstKind::Accumulator, &NewVR);
8971}
8972
8973/// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
8974/// instructions.
8975///
8976/// \see genFusedMultiply
8980 unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
8981 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8983}
8984
8985/// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
8986/// instructions with an additional negation of the accumulator
8990 DenseMap<Register, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
8991 unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
8992 assert(IdxMulOpd == 1);
8993
8994 Register NewVR =
8995 genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
8996
8997 return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
8998 FMAInstKind::Indexed, &NewVR);
8999}
9000
9001/// genMaddR - Generate madd instruction and combine mul and add using
9002/// an extra virtual register
9003/// Example - an ADD intermediate needs to be stored in a register:
9004/// MUL I=A,B,0
9005/// ADD R,I,Imm
9006/// ==> ORR V, ZR, Imm
9007/// ==> MADD R,A,B,V
9008/// \param MF Containing MachineFunction
9009/// \param MRI Register information
9010/// \param TII Target information
9011/// \param Root is the ADD instruction
9012/// \param [out] InsInstrs is a vector of machine instructions and will
9013/// contain the generated madd instruction
9014/// \param IdxMulOpd is index of operand in Root that is the result of
9015/// the MUL. In the example above IdxMulOpd is 1.
9016/// \param MaddOpc the opcode fo the madd instruction
9017/// \param VR is a virtual register that holds the value of an ADD operand
9018/// (V in the example above).
9019/// \param RC Register class of operands
9021 const TargetInstrInfo *TII, MachineInstr &Root,
9023 unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
9024 const TargetRegisterClass *RC) {
9025 assert(IdxMulOpd == 1 || IdxMulOpd == 2);
9026
9027 MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
9028 Register ResultReg = Root.getOperand(0).getReg();
9029 Register SrcReg0 = MUL->getOperand(1).getReg();
9030 bool Src0IsKill = MUL->getOperand(1).isKill();
9031 Register SrcReg1 = MUL->getOperand(2).getReg();
9032 bool Src1IsKill = MUL->getOperand(2).isKill();
9033
9034 if (ResultReg.isVirtual())
9035 MRI.constrainRegClass(ResultReg, RC);
9036 if (SrcReg0.isVirtual())
9037 MRI.constrainRegClass(SrcReg0, RC);
9038 if (SrcReg1.isVirtual())
9039 MRI.constrainRegClass(SrcReg1, RC);
9041 MRI.constrainRegClass(VR, RC);
9042
9044 BuildMI(MF, MIMetadata(Root), TII->get(MaddOpc), ResultReg)
9045 .addReg(SrcReg0, getKillRegState(Src0IsKill))
9046 .addReg(SrcReg1, getKillRegState(Src1IsKill))
9047 .addReg(VR);
9048 // Insert the MADD
9049 InsInstrs.push_back(MIB);
9050 return MUL;
9051}
9052
9053/// Do the following transformation
9054/// A - (B + C) ==> (A - B) - C
9055/// A - (B + C) ==> (A - C) - B
9057 const TargetInstrInfo *TII, MachineInstr &Root,
9060 unsigned IdxOpd1,
9061 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
9062 assert(IdxOpd1 == 1 || IdxOpd1 == 2);
9063 unsigned IdxOtherOpd = IdxOpd1 == 1 ? 2 : 1;
9064 MachineInstr *AddMI = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
9065
9066 Register ResultReg = Root.getOperand(0).getReg();
9067 Register RegA = Root.getOperand(1).getReg();
9068 bool RegAIsKill = Root.getOperand(1).isKill();
9069 Register RegB = AddMI->getOperand(IdxOpd1).getReg();
9070 bool RegBIsKill = AddMI->getOperand(IdxOpd1).isKill();
9071 Register RegC = AddMI->getOperand(IdxOtherOpd).getReg();
9072 bool RegCIsKill = AddMI->getOperand(IdxOtherOpd).isKill();
9073 Register NewVR =
9075
9076 unsigned Opcode = Root.getOpcode();
9077 if (Opcode == AArch64::SUBSWrr)
9078 Opcode = AArch64::SUBWrr;
9079 else if (Opcode == AArch64::SUBSXrr)
9080 Opcode = AArch64::SUBXrr;
9081 else
9082 assert((Opcode == AArch64::SUBWrr || Opcode == AArch64::SUBXrr) &&
9083 "Unexpected instruction opcode.");
9084
9085 uint32_t Flags = Root.mergeFlagsWith(*AddMI);
9086 Flags &= ~MachineInstr::NoSWrap;
9087 Flags &= ~MachineInstr::NoUWrap;
9088
9089 MachineInstrBuilder MIB1 =
9090 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), NewVR)
9091 .addReg(RegA, getKillRegState(RegAIsKill))
9092 .addReg(RegB, getKillRegState(RegBIsKill))
9093 .setMIFlags(Flags);
9094 MachineInstrBuilder MIB2 =
9095 BuildMI(MF, MIMetadata(Root), TII->get(Opcode), ResultReg)
9096 .addReg(NewVR, getKillRegState(true))
9097 .addReg(RegC, getKillRegState(RegCIsKill))
9098 .setMIFlags(Flags);
9099
9100 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9101 InsInstrs.push_back(MIB1);
9102 InsInstrs.push_back(MIB2);
9103 DelInstrs.push_back(AddMI);
9104 DelInstrs.push_back(&Root);
9105}
9106
9107unsigned AArch64InstrInfo::getReduceOpcodeForAccumulator(
9108 unsigned int AccumulatorOpCode) const {
9109 switch (AccumulatorOpCode) {
9110 case AArch64::UABALB_ZZZ_D:
9111 case AArch64::SABALB_ZZZ_D:
9112 case AArch64::UABALT_ZZZ_D:
9113 case AArch64::SABALT_ZZZ_D:
9114 return AArch64::ADD_ZZZ_D;
9115 case AArch64::UABALB_ZZZ_H:
9116 case AArch64::SABALB_ZZZ_H:
9117 case AArch64::UABALT_ZZZ_H:
9118 case AArch64::SABALT_ZZZ_H:
9119 return AArch64::ADD_ZZZ_H;
9120 case AArch64::UABALB_ZZZ_S:
9121 case AArch64::SABALB_ZZZ_S:
9122 case AArch64::UABALT_ZZZ_S:
9123 case AArch64::SABALT_ZZZ_S:
9124 return AArch64::ADD_ZZZ_S;
9125 case AArch64::UABALv16i8_v8i16:
9126 case AArch64::SABALv8i8_v8i16:
9127 case AArch64::SABAv8i16:
9128 case AArch64::UABAv8i16:
9129 return AArch64::ADDv8i16;
9130 case AArch64::SABALv2i32_v2i64:
9131 case AArch64::UABALv2i32_v2i64:
9132 case AArch64::SABALv4i32_v2i64:
9133 return AArch64::ADDv2i64;
9134 case AArch64::UABALv4i16_v4i32:
9135 case AArch64::SABALv4i16_v4i32:
9136 case AArch64::SABALv8i16_v4i32:
9137 case AArch64::SABAv4i32:
9138 case AArch64::UABAv4i32:
9139 return AArch64::ADDv4i32;
9140 case AArch64::UABALv4i32_v2i64:
9141 return AArch64::ADDv2i64;
9142 case AArch64::UABALv8i16_v4i32:
9143 return AArch64::ADDv4i32;
9144 case AArch64::UABALv8i8_v8i16:
9145 case AArch64::SABALv16i8_v8i16:
9146 return AArch64::ADDv8i16;
9147 case AArch64::UABAv16i8:
9148 case AArch64::SABAv16i8:
9149 return AArch64::ADDv16i8;
9150 case AArch64::UABAv4i16:
9151 case AArch64::SABAv4i16:
9152 return AArch64::ADDv4i16;
9153 case AArch64::UABAv2i32:
9154 case AArch64::SABAv2i32:
9155 return AArch64::ADDv2i32;
9156 case AArch64::UABAv8i8:
9157 case AArch64::SABAv8i8:
9158 return AArch64::ADDv8i8;
9159 default:
9160 llvm_unreachable("Unknown accumulator opcode");
9161 }
9162}
9163
9164/// When getMachineCombinerPatterns() finds potential patterns,
9165/// this function generates the instructions that could replace the
9166/// original code sequence
9167void AArch64InstrInfo::genAlternativeCodeSequence(
9168 MachineInstr &Root, unsigned Pattern,
9171 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
9172 MachineBasicBlock &MBB = *Root.getParent();
9173 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
9174 MachineFunction &MF = *MBB.getParent();
9175 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9176
9177 MachineInstr *MUL = nullptr;
9178 const TargetRegisterClass *RC;
9179 unsigned Opc;
9180 switch (Pattern) {
9181 default:
9182 // Reassociate instructions.
9183 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
9184 DelInstrs, InstrIdxForVirtReg);
9185 return;
9187 // A - (B + C)
9188 // ==> (A - B) - C
9189 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 1,
9190 InstrIdxForVirtReg);
9191 return;
9193 // A - (B + C)
9194 // ==> (A - C) - B
9195 genSubAdd2SubSub(MF, MRI, TII, Root, InsInstrs, DelInstrs, 2,
9196 InstrIdxForVirtReg);
9197 return;
9200 // MUL I=A,B,0
9201 // ADD R,I,C
9202 // ==> MADD R,A,B,C
9203 // --- Create(MADD);
9205 Opc = AArch64::MADDWrrr;
9206 RC = &AArch64::GPR32RegClass;
9207 } else {
9208 Opc = AArch64::MADDXrrr;
9209 RC = &AArch64::GPR64RegClass;
9210 }
9211 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9212 break;
9215 // MUL I=A,B,0
9216 // ADD R,C,I
9217 // ==> MADD R,A,B,C
9218 // --- Create(MADD);
9220 Opc = AArch64::MADDWrrr;
9221 RC = &AArch64::GPR32RegClass;
9222 } else {
9223 Opc = AArch64::MADDXrrr;
9224 RC = &AArch64::GPR64RegClass;
9225 }
9226 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9227 break;
9232 // MUL I=A,B,0
9233 // ADD/SUB R,I,Imm
9234 // ==> MOV V, Imm/-Imm
9235 // ==> MADD R,A,B,V
9236 // --- Create(MADD);
9237 const TargetRegisterClass *RC;
9238 unsigned BitSize, MovImm;
9241 MovImm = AArch64::MOVi32imm;
9242 RC = &AArch64::GPR32spRegClass;
9243 BitSize = 32;
9244 Opc = AArch64::MADDWrrr;
9245 RC = &AArch64::GPR32RegClass;
9246 } else {
9247 MovImm = AArch64::MOVi64imm;
9248 RC = &AArch64::GPR64spRegClass;
9249 BitSize = 64;
9250 Opc = AArch64::MADDXrrr;
9251 RC = &AArch64::GPR64RegClass;
9252 }
9253 Register NewVR = MRI.createVirtualRegister(RC);
9254 uint64_t Imm = Root.getOperand(2).getImm();
9255
9256 if (Root.getOperand(3).isImm()) {
9257 unsigned Val = Root.getOperand(3).getImm();
9258 Imm = Imm << Val;
9259 }
9260 bool IsSub = Pattern == AArch64MachineCombinerPattern::MULSUBWI_OP1 ||
9262 uint64_t UImm = SignExtend64(IsSub ? -Imm : Imm, BitSize);
9263 // Check that the immediate can be composed via a single instruction.
9265 AArch64_IMM::expandMOVImm(UImm, BitSize, Insn);
9266 if (Insn.size() != 1)
9267 return;
9268 MachineInstrBuilder MIB1 =
9269 BuildMI(MF, MIMetadata(Root), TII->get(MovImm), NewVR)
9270 .addImm(IsSub ? -Imm : Imm);
9271 InsInstrs.push_back(MIB1);
9272 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9273 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9274 break;
9275 }
9278 // MUL I=A,B,0
9279 // SUB R,I, C
9280 // ==> SUB V, 0, C
9281 // ==> MADD R,A,B,V // = -C + A*B
9282 // --- Create(MADD);
9283 const TargetRegisterClass *SubRC;
9284 unsigned SubOpc, ZeroReg;
9286 SubOpc = AArch64::SUBWrr;
9287 SubRC = &AArch64::GPR32spRegClass;
9288 ZeroReg = AArch64::WZR;
9289 Opc = AArch64::MADDWrrr;
9290 RC = &AArch64::GPR32RegClass;
9291 } else {
9292 SubOpc = AArch64::SUBXrr;
9293 SubRC = &AArch64::GPR64spRegClass;
9294 ZeroReg = AArch64::XZR;
9295 Opc = AArch64::MADDXrrr;
9296 RC = &AArch64::GPR64RegClass;
9297 }
9298 Register NewVR = MRI.createVirtualRegister(SubRC);
9299 // SUB NewVR, 0, C
9300 MachineInstrBuilder MIB1 =
9301 BuildMI(MF, MIMetadata(Root), TII->get(SubOpc), NewVR)
9302 .addReg(ZeroReg)
9303 .add(Root.getOperand(2));
9304 InsInstrs.push_back(MIB1);
9305 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9306 MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
9307 break;
9308 }
9311 // MUL I=A,B,0
9312 // SUB R,C,I
9313 // ==> MSUB R,A,B,C (computes C - A*B)
9314 // --- Create(MSUB);
9316 Opc = AArch64::MSUBWrrr;
9317 RC = &AArch64::GPR32RegClass;
9318 } else {
9319 Opc = AArch64::MSUBXrrr;
9320 RC = &AArch64::GPR64RegClass;
9321 }
9322 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9323 break;
9325 Opc = AArch64::MLAv8i8;
9326 RC = &AArch64::FPR64RegClass;
9327 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9328 break;
9330 Opc = AArch64::MLAv8i8;
9331 RC = &AArch64::FPR64RegClass;
9332 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9333 break;
9335 Opc = AArch64::MLAv16i8;
9336 RC = &AArch64::FPR128RegClass;
9337 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9338 break;
9340 Opc = AArch64::MLAv16i8;
9341 RC = &AArch64::FPR128RegClass;
9342 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9343 break;
9345 Opc = AArch64::MLAv4i16;
9346 RC = &AArch64::FPR64RegClass;
9347 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9348 break;
9350 Opc = AArch64::MLAv4i16;
9351 RC = &AArch64::FPR64RegClass;
9352 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9353 break;
9355 Opc = AArch64::MLAv8i16;
9356 RC = &AArch64::FPR128RegClass;
9357 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9358 break;
9360 Opc = AArch64::MLAv8i16;
9361 RC = &AArch64::FPR128RegClass;
9362 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9363 break;
9365 Opc = AArch64::MLAv2i32;
9366 RC = &AArch64::FPR64RegClass;
9367 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9368 break;
9370 Opc = AArch64::MLAv2i32;
9371 RC = &AArch64::FPR64RegClass;
9372 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9373 break;
9375 Opc = AArch64::MLAv4i32;
9376 RC = &AArch64::FPR128RegClass;
9377 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9378 break;
9380 Opc = AArch64::MLAv4i32;
9381 RC = &AArch64::FPR128RegClass;
9382 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9383 break;
9384
9386 Opc = AArch64::MLAv8i8;
9387 RC = &AArch64::FPR64RegClass;
9388 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9389 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
9390 RC);
9391 break;
9393 Opc = AArch64::MLSv8i8;
9394 RC = &AArch64::FPR64RegClass;
9395 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9396 break;
9398 Opc = AArch64::MLAv16i8;
9399 RC = &AArch64::FPR128RegClass;
9400 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9401 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
9402 RC);
9403 break;
9405 Opc = AArch64::MLSv16i8;
9406 RC = &AArch64::FPR128RegClass;
9407 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9408 break;
9410 Opc = AArch64::MLAv4i16;
9411 RC = &AArch64::FPR64RegClass;
9412 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9413 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9414 RC);
9415 break;
9417 Opc = AArch64::MLSv4i16;
9418 RC = &AArch64::FPR64RegClass;
9419 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9420 break;
9422 Opc = AArch64::MLAv8i16;
9423 RC = &AArch64::FPR128RegClass;
9424 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9425 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9426 RC);
9427 break;
9429 Opc = AArch64::MLSv8i16;
9430 RC = &AArch64::FPR128RegClass;
9431 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9432 break;
9434 Opc = AArch64::MLAv2i32;
9435 RC = &AArch64::FPR64RegClass;
9436 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9437 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9438 RC);
9439 break;
9441 Opc = AArch64::MLSv2i32;
9442 RC = &AArch64::FPR64RegClass;
9443 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9444 break;
9446 Opc = AArch64::MLAv4i32;
9447 RC = &AArch64::FPR128RegClass;
9448 MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
9449 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9450 RC);
9451 break;
9453 Opc = AArch64::MLSv4i32;
9454 RC = &AArch64::FPR128RegClass;
9455 MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9456 break;
9457
9459 Opc = AArch64::MLAv4i16_indexed;
9460 RC = &AArch64::FPR64RegClass;
9461 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9462 break;
9464 Opc = AArch64::MLAv4i16_indexed;
9465 RC = &AArch64::FPR64RegClass;
9466 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9467 break;
9469 Opc = AArch64::MLAv8i16_indexed;
9470 RC = &AArch64::FPR128RegClass;
9471 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9472 break;
9474 Opc = AArch64::MLAv8i16_indexed;
9475 RC = &AArch64::FPR128RegClass;
9476 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9477 break;
9479 Opc = AArch64::MLAv2i32_indexed;
9480 RC = &AArch64::FPR64RegClass;
9481 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9482 break;
9484 Opc = AArch64::MLAv2i32_indexed;
9485 RC = &AArch64::FPR64RegClass;
9486 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9487 break;
9489 Opc = AArch64::MLAv4i32_indexed;
9490 RC = &AArch64::FPR128RegClass;
9491 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9492 break;
9494 Opc = AArch64::MLAv4i32_indexed;
9495 RC = &AArch64::FPR128RegClass;
9496 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9497 break;
9498
9500 Opc = AArch64::MLAv4i16_indexed;
9501 RC = &AArch64::FPR64RegClass;
9502 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9503 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
9504 RC);
9505 break;
9507 Opc = AArch64::MLSv4i16_indexed;
9508 RC = &AArch64::FPR64RegClass;
9509 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9510 break;
9512 Opc = AArch64::MLAv8i16_indexed;
9513 RC = &AArch64::FPR128RegClass;
9514 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9515 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
9516 RC);
9517 break;
9519 Opc = AArch64::MLSv8i16_indexed;
9520 RC = &AArch64::FPR128RegClass;
9521 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9522 break;
9524 Opc = AArch64::MLAv2i32_indexed;
9525 RC = &AArch64::FPR64RegClass;
9526 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9527 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
9528 RC);
9529 break;
9531 Opc = AArch64::MLSv2i32_indexed;
9532 RC = &AArch64::FPR64RegClass;
9533 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9534 break;
9536 Opc = AArch64::MLAv4i32_indexed;
9537 RC = &AArch64::FPR128RegClass;
9538 MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
9539 InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
9540 RC);
9541 break;
9543 Opc = AArch64::MLSv4i32_indexed;
9544 RC = &AArch64::FPR128RegClass;
9545 MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9546 break;
9547
9548 // Floating Point Support
9550 Opc = AArch64::FMADDHrrr;
9551 RC = &AArch64::FPR16RegClass;
9552 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9553 break;
9555 Opc = AArch64::FMADDSrrr;
9556 RC = &AArch64::FPR32RegClass;
9557 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9558 break;
9560 Opc = AArch64::FMADDDrrr;
9561 RC = &AArch64::FPR64RegClass;
9562 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9563 break;
9564
9566 Opc = AArch64::FMADDHrrr;
9567 RC = &AArch64::FPR16RegClass;
9568 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9569 break;
9571 Opc = AArch64::FMADDSrrr;
9572 RC = &AArch64::FPR32RegClass;
9573 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9574 break;
9576 Opc = AArch64::FMADDDrrr;
9577 RC = &AArch64::FPR64RegClass;
9578 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9579 break;
9580
9582 Opc = AArch64::FMLAv1i32_indexed;
9583 RC = &AArch64::FPR32RegClass;
9584 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9586 break;
9588 Opc = AArch64::FMLAv1i32_indexed;
9589 RC = &AArch64::FPR32RegClass;
9590 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9592 break;
9593
9595 Opc = AArch64::FMLAv1i64_indexed;
9596 RC = &AArch64::FPR64RegClass;
9597 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9599 break;
9601 Opc = AArch64::FMLAv1i64_indexed;
9602 RC = &AArch64::FPR64RegClass;
9603 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9605 break;
9606
9608 RC = &AArch64::FPR64RegClass;
9609 Opc = AArch64::FMLAv4i16_indexed;
9610 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9612 break;
9614 RC = &AArch64::FPR64RegClass;
9615 Opc = AArch64::FMLAv4f16;
9616 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9618 break;
9620 RC = &AArch64::FPR64RegClass;
9621 Opc = AArch64::FMLAv4i16_indexed;
9622 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9624 break;
9626 RC = &AArch64::FPR64RegClass;
9627 Opc = AArch64::FMLAv4f16;
9628 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9630 break;
9631
9634 RC = &AArch64::FPR64RegClass;
9636 Opc = AArch64::FMLAv2i32_indexed;
9637 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9639 } else {
9640 Opc = AArch64::FMLAv2f32;
9641 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9643 }
9644 break;
9647 RC = &AArch64::FPR64RegClass;
9649 Opc = AArch64::FMLAv2i32_indexed;
9650 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9652 } else {
9653 Opc = AArch64::FMLAv2f32;
9654 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9656 }
9657 break;
9658
9660 RC = &AArch64::FPR128RegClass;
9661 Opc = AArch64::FMLAv8i16_indexed;
9662 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9664 break;
9666 RC = &AArch64::FPR128RegClass;
9667 Opc = AArch64::FMLAv8f16;
9668 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9670 break;
9672 RC = &AArch64::FPR128RegClass;
9673 Opc = AArch64::FMLAv8i16_indexed;
9674 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9676 break;
9678 RC = &AArch64::FPR128RegClass;
9679 Opc = AArch64::FMLAv8f16;
9680 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9682 break;
9683
9686 RC = &AArch64::FPR128RegClass;
9688 Opc = AArch64::FMLAv2i64_indexed;
9689 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9691 } else {
9692 Opc = AArch64::FMLAv2f64;
9693 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9695 }
9696 break;
9699 RC = &AArch64::FPR128RegClass;
9701 Opc = AArch64::FMLAv2i64_indexed;
9702 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9704 } else {
9705 Opc = AArch64::FMLAv2f64;
9706 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9708 }
9709 break;
9710
9713 RC = &AArch64::FPR128RegClass;
9715 Opc = AArch64::FMLAv4i32_indexed;
9716 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9718 } else {
9719 Opc = AArch64::FMLAv4f32;
9720 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9722 }
9723 break;
9724
9727 RC = &AArch64::FPR128RegClass;
9729 Opc = AArch64::FMLAv4i32_indexed;
9730 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9732 } else {
9733 Opc = AArch64::FMLAv4f32;
9734 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9736 }
9737 break;
9738
9740 Opc = AArch64::FNMSUBHrrr;
9741 RC = &AArch64::FPR16RegClass;
9742 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9743 break;
9745 Opc = AArch64::FNMSUBSrrr;
9746 RC = &AArch64::FPR32RegClass;
9747 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9748 break;
9750 Opc = AArch64::FNMSUBDrrr;
9751 RC = &AArch64::FPR64RegClass;
9752 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9753 break;
9754
9756 Opc = AArch64::FNMADDHrrr;
9757 RC = &AArch64::FPR16RegClass;
9758 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9759 break;
9761 Opc = AArch64::FNMADDSrrr;
9762 RC = &AArch64::FPR32RegClass;
9763 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9764 break;
9766 Opc = AArch64::FNMADDDrrr;
9767 RC = &AArch64::FPR64RegClass;
9768 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
9769 break;
9770
9772 Opc = AArch64::FMSUBHrrr;
9773 RC = &AArch64::FPR16RegClass;
9774 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9775 break;
9777 Opc = AArch64::FMSUBSrrr;
9778 RC = &AArch64::FPR32RegClass;
9779 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9780 break;
9782 Opc = AArch64::FMSUBDrrr;
9783 RC = &AArch64::FPR64RegClass;
9784 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
9785 break;
9786
9788 Opc = AArch64::FMLSv1i32_indexed;
9789 RC = &AArch64::FPR32RegClass;
9790 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9792 break;
9793
9795 Opc = AArch64::FMLSv1i64_indexed;
9796 RC = &AArch64::FPR64RegClass;
9797 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9799 break;
9800
9803 RC = &AArch64::FPR64RegClass;
9804 Register NewVR = MRI.createVirtualRegister(RC);
9805 MachineInstrBuilder MIB1 =
9806 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f16), NewVR)
9807 .add(Root.getOperand(2));
9808 InsInstrs.push_back(MIB1);
9809 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9811 Opc = AArch64::FMLAv4f16;
9812 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9813 FMAInstKind::Accumulator, &NewVR);
9814 } else {
9815 Opc = AArch64::FMLAv4i16_indexed;
9816 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9817 FMAInstKind::Indexed, &NewVR);
9818 }
9819 break;
9820 }
9822 RC = &AArch64::FPR64RegClass;
9823 Opc = AArch64::FMLSv4f16;
9824 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9826 break;
9828 RC = &AArch64::FPR64RegClass;
9829 Opc = AArch64::FMLSv4i16_indexed;
9830 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9832 break;
9833
9836 RC = &AArch64::FPR64RegClass;
9838 Opc = AArch64::FMLSv2i32_indexed;
9839 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9841 } else {
9842 Opc = AArch64::FMLSv2f32;
9843 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9845 }
9846 break;
9847
9850 RC = &AArch64::FPR128RegClass;
9851 Register NewVR = MRI.createVirtualRegister(RC);
9852 MachineInstrBuilder MIB1 =
9853 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv8f16), NewVR)
9854 .add(Root.getOperand(2));
9855 InsInstrs.push_back(MIB1);
9856 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9858 Opc = AArch64::FMLAv8f16;
9859 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9860 FMAInstKind::Accumulator, &NewVR);
9861 } else {
9862 Opc = AArch64::FMLAv8i16_indexed;
9863 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9864 FMAInstKind::Indexed, &NewVR);
9865 }
9866 break;
9867 }
9869 RC = &AArch64::FPR128RegClass;
9870 Opc = AArch64::FMLSv8f16;
9871 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9873 break;
9875 RC = &AArch64::FPR128RegClass;
9876 Opc = AArch64::FMLSv8i16_indexed;
9877 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9879 break;
9880
9883 RC = &AArch64::FPR128RegClass;
9885 Opc = AArch64::FMLSv2i64_indexed;
9886 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9888 } else {
9889 Opc = AArch64::FMLSv2f64;
9890 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9892 }
9893 break;
9894
9897 RC = &AArch64::FPR128RegClass;
9899 Opc = AArch64::FMLSv4i32_indexed;
9900 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9902 } else {
9903 Opc = AArch64::FMLSv4f32;
9904 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
9906 }
9907 break;
9910 RC = &AArch64::FPR64RegClass;
9911 Register NewVR = MRI.createVirtualRegister(RC);
9912 MachineInstrBuilder MIB1 =
9913 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f32), NewVR)
9914 .add(Root.getOperand(2));
9915 InsInstrs.push_back(MIB1);
9916 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9918 Opc = AArch64::FMLAv2i32_indexed;
9919 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9920 FMAInstKind::Indexed, &NewVR);
9921 } else {
9922 Opc = AArch64::FMLAv2f32;
9923 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9924 FMAInstKind::Accumulator, &NewVR);
9925 }
9926 break;
9927 }
9930 RC = &AArch64::FPR128RegClass;
9931 Register NewVR = MRI.createVirtualRegister(RC);
9932 MachineInstrBuilder MIB1 =
9933 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv4f32), NewVR)
9934 .add(Root.getOperand(2));
9935 InsInstrs.push_back(MIB1);
9936 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9938 Opc = AArch64::FMLAv4i32_indexed;
9939 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9940 FMAInstKind::Indexed, &NewVR);
9941 } else {
9942 Opc = AArch64::FMLAv4f32;
9943 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9944 FMAInstKind::Accumulator, &NewVR);
9945 }
9946 break;
9947 }
9950 RC = &AArch64::FPR128RegClass;
9951 Register NewVR = MRI.createVirtualRegister(RC);
9952 MachineInstrBuilder MIB1 =
9953 BuildMI(MF, MIMetadata(Root), TII->get(AArch64::FNEGv2f64), NewVR)
9954 .add(Root.getOperand(2));
9955 InsInstrs.push_back(MIB1);
9956 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
9958 Opc = AArch64::FMLAv2i64_indexed;
9959 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9960 FMAInstKind::Indexed, &NewVR);
9961 } else {
9962 Opc = AArch64::FMLAv2f64;
9963 MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
9964 FMAInstKind::Accumulator, &NewVR);
9965 }
9966 break;
9967 }
9970 unsigned IdxDupOp =
9972 : 2;
9973 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
9974 &AArch64::FPR128RegClass, MRI);
9975 break;
9976 }
9979 unsigned IdxDupOp =
9981 : 2;
9982 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
9983 &AArch64::FPR128RegClass, MRI);
9984 break;
9985 }
9988 unsigned IdxDupOp =
9990 : 2;
9991 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
9992 &AArch64::FPR128_loRegClass, MRI);
9993 break;
9994 }
9997 unsigned IdxDupOp =
9999 : 2;
10000 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
10001 &AArch64::FPR128RegClass, MRI);
10002 break;
10003 }
10006 unsigned IdxDupOp =
10008 : 2;
10009 genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
10010 &AArch64::FPR128_loRegClass, MRI);
10011 break;
10012 }
10014 MUL = genFNegatedMAD(MF, MRI, TII, Root, InsInstrs);
10015 break;
10016 }
10018 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10019 Pattern, 4);
10020 break;
10021 }
10023 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10024 Pattern, 8);
10025 break;
10026 }
10028 generateGatherLanePattern(Root, InsInstrs, DelInstrs, InstrIdxForVirtReg,
10029 Pattern, 16);
10030 break;
10031 }
10032
10033 } // end switch (Pattern)
10034 // Record MUL and ADD/SUB for deletion
10035 if (MUL)
10036 DelInstrs.push_back(MUL);
10037 DelInstrs.push_back(&Root);
10038
10039 // Set the flags on the inserted instructions to be the merged flags of the
10040 // instructions that we have combined.
10041 uint32_t Flags = Root.getFlags();
10042 if (MUL)
10043 Flags = Root.mergeFlagsWith(*MUL);
10044 for (auto *MI : InsInstrs)
10045 MI->setFlags(Flags);
10046}
10047
10048/// Replace csincr-branch sequence by simple conditional branch
10049///
10050/// Examples:
10051/// 1. \code
10052/// csinc w9, wzr, wzr, <condition code>
10053/// tbnz w9, #0, 0x44
10054/// \endcode
10055/// to
10056/// \code
10057/// b.<inverted condition code>
10058/// \endcode
10059///
10060/// 2. \code
10061/// csinc w9, wzr, wzr, <condition code>
10062/// tbz w9, #0, 0x44
10063/// \endcode
10064/// to
10065/// \code
10066/// b.<condition code>
10067/// \endcode
10068///
10069/// Replace compare and branch sequence by TBZ/TBNZ instruction when the
10070/// compare's constant operand is power of 2.
10071///
10072/// Examples:
10073/// \code
10074/// and w8, w8, #0x400
10075/// cbnz w8, L1
10076/// \endcode
10077/// to
10078/// \code
10079/// tbnz w8, #10, L1
10080/// \endcode
10081///
10082/// \param MI Conditional Branch
10083/// \return True when the simple conditional branch is generated
10084///
10086 bool IsNegativeBranch = false;
10087 bool IsTestAndBranch = false;
10088 unsigned TargetBBInMI = 0;
10089 switch (MI.getOpcode()) {
10090 default:
10091 llvm_unreachable("Unknown branch instruction?");
10092 case AArch64::Bcc:
10093 case AArch64::CBWPri:
10094 case AArch64::CBXPri:
10095 case AArch64::CBBAssertExt:
10096 case AArch64::CBHAssertExt:
10097 case AArch64::CBWPrr:
10098 case AArch64::CBXPrr:
10099 return false;
10100 case AArch64::CBZW:
10101 case AArch64::CBZX:
10102 TargetBBInMI = 1;
10103 break;
10104 case AArch64::CBNZW:
10105 case AArch64::CBNZX:
10106 TargetBBInMI = 1;
10107 IsNegativeBranch = true;
10108 break;
10109 case AArch64::TBZW:
10110 case AArch64::TBZX:
10111 TargetBBInMI = 2;
10112 IsTestAndBranch = true;
10113 break;
10114 case AArch64::TBNZW:
10115 case AArch64::TBNZX:
10116 TargetBBInMI = 2;
10117 IsNegativeBranch = true;
10118 IsTestAndBranch = true;
10119 break;
10120 }
10121 // So we increment a zero register and test for bits other
10122 // than bit 0? Conservatively bail out in case the verifier
10123 // missed this case.
10124 if (IsTestAndBranch && MI.getOperand(1).getImm())
10125 return false;
10126
10127 // Find Definition.
10128 assert(MI.getParent() && "Incomplete machine instruction\n");
10129 MachineBasicBlock *MBB = MI.getParent();
10130 MachineFunction *MF = MBB->getParent();
10131 MachineRegisterInfo *MRI = &MF->getRegInfo();
10132 Register VReg = MI.getOperand(0).getReg();
10133 if (!VReg.isVirtual())
10134 return false;
10135
10136 MachineInstr *DefMI = MRI->getVRegDef(VReg);
10137 if (!DefMI)
10138 return false;
10139
10140 // Look through COPY instructions to find definition.
10141 while (DefMI->isCopy()) {
10142 Register CopyVReg = DefMI->getOperand(1).getReg();
10143 if (!CopyVReg.isVirtual())
10144 return false;
10145 if (!MRI->hasOneNonDBGUse(CopyVReg))
10146 return false;
10147 DefMI = MRI->getVRegDef(CopyVReg);
10148 if (!DefMI)
10149 return false;
10150 }
10151
10152 switch (DefMI->getOpcode()) {
10153 default:
10154 return false;
10155 // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
10156 case AArch64::ANDWri:
10157 case AArch64::ANDXri: {
10158 if (IsTestAndBranch)
10159 return false;
10160 if (DefMI->getParent() != MBB)
10161 return false;
10162 if (!MRI->hasOneNonDBGUse(VReg))
10163 return false;
10164
10165 bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
10166 uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
10167 DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
10168 if (!isPowerOf2_64(Mask))
10169 return false;
10170
10171 MachineOperand &MO = DefMI->getOperand(1);
10172 Register NewReg = MO.getReg();
10173 if (!NewReg.isVirtual())
10174 return false;
10175
10176 if (!MRI->getVRegDef(NewReg))
10177 return false;
10178
10179 MachineBasicBlock &RefToMBB = *MBB;
10180 MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
10181 DebugLoc DL = MI.getDebugLoc();
10182 unsigned Imm = Log2_64(Mask);
10183 unsigned Opc = (Imm < 32)
10184 ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
10185 : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
10186 MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
10187 .addReg(NewReg)
10188 .addImm(Imm)
10189 .addMBB(TBB);
10190 // Register lives on to the CBZ now.
10191 MO.setIsKill(false);
10192
10193 // For immediate smaller than 32, we need to use the 32-bit
10194 // variant (W) in all cases. Indeed the 64-bit variant does not
10195 // allow to encode them.
10196 // Therefore, if the input register is 64-bit, we need to take the
10197 // 32-bit sub-part.
10198 if (!Is32Bit && Imm < 32)
10199 NewMI->getOperand(0).setSubReg(AArch64::sub_32);
10200 MI.eraseFromParent();
10201 return true;
10202 }
10203 // Look for CSINC
10204 case AArch64::CSINCWr:
10205 case AArch64::CSINCXr: {
10206 if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
10207 DefMI->getOperand(2).getReg() == AArch64::WZR) &&
10208 !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
10209 DefMI->getOperand(2).getReg() == AArch64::XZR))
10210 return false;
10211
10212 if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, /*TRI=*/nullptr,
10213 true) != -1)
10214 return false;
10215
10216 AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
10217 // Convert only when the condition code is not modified between
10218 // the CSINC and the branch. The CC may be used by other
10219 // instructions in between.
10221 return false;
10222 MachineBasicBlock &RefToMBB = *MBB;
10223 MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
10224 DebugLoc DL = MI.getDebugLoc();
10225 if (IsNegativeBranch)
10227 BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
10228 MI.eraseFromParent();
10229 return true;
10230 }
10231 }
10232}
10233
10234std::pair<unsigned, unsigned>
10235AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
10236 const unsigned Mask = AArch64II::MO_FRAGMENT;
10237 return std::make_pair(TF & Mask, TF & ~Mask);
10238}
10239
10241AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
10242 using namespace AArch64II;
10243
10244 static const std::pair<unsigned, const char *> TargetFlags[] = {
10245 {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
10246 {MO_G3, "aarch64-g3"}, {MO_G2, "aarch64-g2"},
10247 {MO_G1, "aarch64-g1"}, {MO_G0, "aarch64-g0"},
10248 {MO_HI12, "aarch64-hi12"}};
10249 return ArrayRef(TargetFlags);
10250}
10251
10253AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
10254 using namespace AArch64II;
10255
10256 static const std::pair<unsigned, const char *> TargetFlags[] = {
10257 {MO_COFFSTUB, "aarch64-coffstub"},
10258 {MO_GOT, "aarch64-got"},
10259 {MO_NC, "aarch64-nc"},
10260 {MO_S, "aarch64-s"},
10261 {MO_TLS, "aarch64-tls"},
10262 {MO_DLLIMPORT, "aarch64-dllimport"},
10263 {MO_PREL, "aarch64-prel"},
10264 {MO_TAGGED, "aarch64-tagged"},
10265 {MO_ARM64EC_CALLMANGLE, "aarch64-arm64ec-callmangle"},
10266 };
10267 return ArrayRef(TargetFlags);
10268}
10269
10271AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
10272 static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
10273 {{MOSuppressPair, "aarch64-suppress-pair"},
10274 {MOStridedAccess, "aarch64-strided-access"}};
10275 return ArrayRef(TargetFlags);
10276}
10277
10278/// Constants defining how certain sequences should be outlined.
10279/// This encompasses how an outlined function should be called, and what kind of
10280/// frame should be emitted for that outlined function.
10281///
10282/// \p MachineOutlinerDefault implies that the function should be called with
10283/// a save and restore of LR to the stack.
10284///
10285/// That is,
10286///
10287/// I1 Save LR OUTLINED_FUNCTION:
10288/// I2 --> BL OUTLINED_FUNCTION I1
10289/// I3 Restore LR I2
10290/// I3
10291/// RET
10292///
10293/// * Call construction overhead: 3 (save + BL + restore)
10294/// * Frame construction overhead: 1 (ret)
10295/// * Requires stack fixups? Yes
10296///
10297/// \p MachineOutlinerTailCall implies that the function is being created from
10298/// a sequence of instructions ending in a return.
10299///
10300/// That is,
10301///
10302/// I1 OUTLINED_FUNCTION:
10303/// I2 --> B OUTLINED_FUNCTION I1
10304/// RET I2
10305/// RET
10306///
10307/// * Call construction overhead: 1 (B)
10308/// * Frame construction overhead: 0 (Return included in sequence)
10309/// * Requires stack fixups? No
10310///
10311/// \p MachineOutlinerNoLRSave implies that the function should be called using
10312/// a BL instruction, but doesn't require LR to be saved and restored. This
10313/// happens when LR is known to be dead.
10314///
10315/// That is,
10316///
10317/// I1 OUTLINED_FUNCTION:
10318/// I2 --> BL OUTLINED_FUNCTION I1
10319/// I3 I2
10320/// I3
10321/// RET
10322///
10323/// * Call construction overhead: 1 (BL)
10324/// * Frame construction overhead: 1 (RET)
10325/// * Requires stack fixups? No
10326///
10327/// \p MachineOutlinerThunk implies that the function is being created from
10328/// a sequence of instructions ending in a call. The outlined function is
10329/// called with a BL instruction, and the outlined function tail-calls the
10330/// original call destination.
10331///
10332/// That is,
10333///
10334/// I1 OUTLINED_FUNCTION:
10335/// I2 --> BL OUTLINED_FUNCTION I1
10336/// BL f I2
10337/// B f
10338/// * Call construction overhead: 1 (BL)
10339/// * Frame construction overhead: 0
10340/// * Requires stack fixups? No
10341///
10342/// \p MachineOutlinerRegSave implies that the function should be called with a
10343/// save and restore of LR to an available register. This allows us to avoid
10344/// stack fixups. Note that this outlining variant is compatible with the
10345/// NoLRSave case.
10346///
10347/// That is,
10348///
10349/// I1 Save LR OUTLINED_FUNCTION:
10350/// I2 --> BL OUTLINED_FUNCTION I1
10351/// I3 Restore LR I2
10352/// I3
10353/// RET
10354///
10355/// * Call construction overhead: 3 (save + BL + restore)
10356/// * Frame construction overhead: 1 (ret)
10357/// * Requires stack fixups? No
10359 MachineOutlinerDefault, /// Emit a save, restore, call, and return.
10360 MachineOutlinerTailCall, /// Only emit a branch.
10361 MachineOutlinerNoLRSave, /// Emit a call and return.
10362 MachineOutlinerThunk, /// Emit a call and tail-call.
10363 MachineOutlinerRegSave /// Same as default, but save to a register.
10364};
10365
10371
10372/// Return true if the frame-record form of the outlined prologue is enabled for
10373/// the target of \p MF.
10374///
10375/// A non-leaf outlined function must save LR. On MachO, saving LR alone
10376/// (str x30) has no compact unwind encoding, so we get a large DWARF FDE
10377/// instead. Saving FP and LR as a frame record (stp x29, x30 ; mov x29, sp)
10378/// gets the small FRAME encoding, and costs one extra instruction.
10380 return MF.getSubtarget<AArch64Subtarget>()
10381 .getCLOpts()
10382 .outliner_compact_unwind_frame &&
10384}
10385
10386/// Return true if the outlined function in \p MBB should save FP and LR as a
10387/// frame record instead of saving LR alone.
10389 const MachineBasicBlock &MBB) {
10390 const MachineFunction &MF = *MBB.getParent();
10391
10392 // Only worth it if the function has unwind info to shrink.
10395 return false;
10396
10397 // Only safe if the outlined code never touches FP, since we overwrite it.
10399 for (const MachineInstr &MI : MBB.instrs())
10400 LRU.accumulate(MI);
10401 return LRU.available(AArch64::FP);
10402}
10403
10404/// Predict what the above will answer, for use while costing candidates. The
10405/// outlined function does not exist yet, so answer from \p RepeatedSequenceLocs
10406/// instead. This is only an estimate; buildOutlinedFrame() makes the call.
10408 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10409 const TargetRegisterInfo &TRI) {
10410 if (!isCompactUnwindFrameRecordEnabled(*RepeatedSequenceLocs.front().getMF()))
10411 return false;
10412
10413 // The outlined function is nounwind only if every candidate is, so it has
10414 // unwind info if any candidate does.
10415 if (llvm::none_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10416 const MachineFunction &MF = *C.getMF();
10417 return MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF);
10418 }))
10419 return false;
10420
10421 // FP is free in the outlined function only if it is free in every candidate.
10422 return llvm::all_of(RepeatedSequenceLocs, [&TRI](outliner::Candidate &C) {
10423 return C.isAvailableInsideSeq(AArch64::FP, TRI);
10424 });
10425}
10426
10428AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
10429 MachineFunction *MF = C.getMF();
10430 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
10431 const AArch64RegisterInfo *ARI =
10432 static_cast<const AArch64RegisterInfo *>(&TRI);
10433 // Check if there is an available register across the sequence that we can
10434 // use.
10435 for (unsigned Reg : AArch64::GPR64RegClass) {
10436 if (!ARI->isReservedReg(*MF, Reg) &&
10437 Reg != AArch64::LR && // LR is not reserved, but don't use it.
10438 Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
10439 Reg != AArch64::X17 && // Ditto for X17.
10440 C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
10441 C.isAvailableInsideSeq(Reg, TRI))
10442 return Reg;
10443 }
10444 return Register();
10445}
10446
10447static bool
10449 const outliner::Candidate &b) {
10450 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10451 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10452
10453 return MFIa->getSignReturnAddressCondition() ==
10455}
10456
10457static bool
10459 const outliner::Candidate &b) {
10460 const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
10461 const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
10462
10463 return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
10464}
10465
10467 const outliner::Candidate &b) {
10468 const AArch64Subtarget &SubtargetA =
10470 const AArch64Subtarget &SubtargetB =
10471 b.getMF()->getSubtarget<AArch64Subtarget>();
10472 return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
10473}
10474
10475std::optional<std::unique_ptr<outliner::OutlinedFunction>>
10476AArch64InstrInfo::getOutliningCandidateInfo(
10477 const MachineModuleInfo &MMI,
10478 std::vector<outliner::Candidate> &RepeatedSequenceLocs,
10479 unsigned MinRepeats) const {
10480 unsigned SequenceSize = 0;
10481 for (auto &MI : RepeatedSequenceLocs[0])
10482 SequenceSize += getInstSizeInBytes(MI);
10483
10484 unsigned NumBytesToCreateFrame = 0;
10485
10486 // Avoid splitting ADRP ADD/LDR pair into outlined functions.
10487 // These instructions are fused together by the scheduler.
10488 // Any candidate where ADRP is the last instruction should be rejected
10489 // as that will lead to splitting ADRP pair.
10490 MachineInstr &LastMI = RepeatedSequenceLocs[0].back();
10491 MachineInstr &FirstMI = RepeatedSequenceLocs[0].front();
10492 if (LastMI.getOpcode() == AArch64::ADRP &&
10493 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_PAGE) != 0 &&
10494 (LastMI.getOperand(1).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10495 return std::nullopt;
10496 }
10497
10498 // Similarly any candidate where the first instruction is ADD/LDR with a
10499 // page offset should be rejected to avoid ADRP splitting.
10500 if ((FirstMI.getOpcode() == AArch64::ADDXri ||
10501 FirstMI.getOpcode() == AArch64::LDRXui) &&
10502 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_PAGEOFF) != 0 &&
10503 (FirstMI.getOperand(2).getTargetFlags() & AArch64II::MO_GOT) != 0) {
10504 return std::nullopt;
10505 }
10506
10507 // We only allow outlining for functions having exactly matching return
10508 // address signing attributes, i.e., all share the same value for the
10509 // attribute "sign-return-address" and all share the same type of key they
10510 // are signed with.
10511 // Additionally we require all functions to simultaneously either support
10512 // v8.3a features or not. Otherwise an outlined function could get signed
10513 // using dedicated v8.3 instructions and a call from a function that doesn't
10514 // support v8.3 instructions would therefore be invalid.
10515 if (std::adjacent_find(
10516 RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
10517 [](const outliner::Candidate &a, const outliner::Candidate &b) {
10518 // Return true if a and b are non-equal w.r.t. return address
10519 // signing or support of v8.3a features
10520 if (outliningCandidatesSigningScopeConsensus(a, b) &&
10521 outliningCandidatesSigningKeyConsensus(a, b) &&
10522 outliningCandidatesV8_3OpsConsensus(a, b)) {
10523 return false;
10524 }
10525 return true;
10526 }) != RepeatedSequenceLocs.end()) {
10527 return std::nullopt;
10528 }
10529
10530 // Since at this point all candidates agree on their return address signing
10531 // picking just one is fine. If the candidate functions potentially sign their
10532 // return addresses, the outlined function should do the same. Note that in
10533 // the case of "sign-return-address"="non-leaf" this is an assumption: It is
10534 // not certainly true that the outlined function will have to sign its return
10535 // address but this decision is made later, when the decision to outline
10536 // has already been made.
10537 // The same holds for the number of additional instructions we need: On
10538 // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
10539 // necessary. However, at this point we don't know if the outlined function
10540 // will have a RET instruction so we assume the worst.
10541 const TargetRegisterInfo &TRI = getRegisterInfo();
10542 // Performing a tail call may require extra checks when PAuth is enabled.
10543 // If PAuth is disabled, set it to zero for uniformity.
10544 unsigned NumBytesToCheckLRInTCEpilogue = 0;
10545 const auto RASignCondition = RepeatedSequenceLocs[0]
10546 .getMF()
10547 ->getInfo<AArch64FunctionInfo>()
10548 ->getSignReturnAddressCondition();
10549 if (RASignCondition != SignReturnAddress::None) {
10550 // Candidates that have Return Address Authentication Hardening enabled are
10551 // discarded.
10552 //
10553 // In its current form, the machine outliner does not preserve X16/X17
10554 // across outlined function calls, even though it should as they are
10555 // caller-saved registers. And since the hardening based on load from the
10556 // return address may clobber one of these registers, if they are alive
10557 // across a call their value would be lost due to the hardening mechanism.
10558 llvm::erase_if(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10559 return C.getMF()
10560 ->getInfo<AArch64FunctionInfo>()
10561 ->shouldHardenSignReturnAddress();
10562 });
10563 // If the sequence doesn't have enough candidates left, then we're done.
10564 if (RepeatedSequenceLocs.size() < MinRepeats)
10565 return std::nullopt;
10566
10567 // One PAC and one AUT instructions
10568 NumBytesToCreateFrame += 8;
10569
10570 // PAuth is enabled - set extra tail call cost, if any.
10571 auto LRCheckMethod = Subtarget.getAuthenticatedLRCheckMethod(
10572 *RepeatedSequenceLocs[0].getMF());
10573 NumBytesToCheckLRInTCEpilogue =
10575 // Checking the authenticated LR value may significantly impact
10576 // SequenceSize, so account for it for more precise results.
10577 if (isTailCallReturnInst(RepeatedSequenceLocs[0].back()))
10578 SequenceSize += NumBytesToCheckLRInTCEpilogue;
10579
10580 // We have to check if sp modifying instructions would get outlined.
10581 // If so we only allow outlining if sp is unchanged overall, so matching
10582 // sub and add instructions are okay to outline, all other sp modifications
10583 // are not
10584 auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
10585 int SPValue = 0;
10586 for (auto &MI : C) {
10587 if (MI.modifiesRegister(AArch64::SP, &TRI)) {
10588 switch (MI.getOpcode()) {
10589 case AArch64::ADDXri:
10590 case AArch64::ADDWri:
10591 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10592 assert(MI.getOperand(2).isImm() &&
10593 "Expected operand to be immediate");
10594 assert(MI.getOperand(1).isReg() &&
10595 "Expected operand to be a register");
10596 // Check if the add just increments sp. If so, we search for
10597 // matching sub instructions that decrement sp. If not, the
10598 // modification is illegal
10599 if (MI.getOperand(1).getReg() == AArch64::SP)
10600 SPValue += MI.getOperand(2).getImm();
10601 else
10602 return true;
10603 break;
10604 case AArch64::SUBXri:
10605 case AArch64::SUBWri:
10606 assert(MI.getNumOperands() == 4 && "Wrong number of operands");
10607 assert(MI.getOperand(2).isImm() &&
10608 "Expected operand to be immediate");
10609 assert(MI.getOperand(1).isReg() &&
10610 "Expected operand to be a register");
10611 // Check if the sub just decrements sp. If so, we search for
10612 // matching add instructions that increment sp. If not, the
10613 // modification is illegal
10614 if (MI.getOperand(1).getReg() == AArch64::SP)
10615 SPValue -= MI.getOperand(2).getImm();
10616 else
10617 return true;
10618 break;
10619 default:
10620 return true;
10621 }
10622 }
10623 }
10624 if (SPValue)
10625 return true;
10626 return false;
10627 };
10628 // Remove candidates with illegal stack modifying instructions
10629 llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
10630
10631 // If the sequence doesn't have enough candidates left, then we're done.
10632 if (RepeatedSequenceLocs.size() < MinRepeats)
10633 return std::nullopt;
10634 }
10635
10636 // Properties about candidate MBBs that hold for all of them.
10637 unsigned FlagsSetInAll = 0xF;
10638
10639 // Compute liveness information for each candidate, and set FlagsSetInAll.
10640 for (outliner::Candidate &C : RepeatedSequenceLocs)
10641 FlagsSetInAll &= C.Flags;
10642
10643 unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back().getOpcode();
10644
10645 // Helper lambda which sets call information for every candidate.
10646 auto SetCandidateCallInfo =
10647 [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
10648 for (outliner::Candidate &C : RepeatedSequenceLocs)
10649 C.setCallInfo(CallID, NumBytesForCall);
10650 };
10651
10652 unsigned FrameID = MachineOutlinerDefault;
10653 NumBytesToCreateFrame += 4;
10654
10655 bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
10656 return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
10657 });
10658
10659 // We check to see if CFI Instructions are present, and if they are
10660 // we find the number of CFI Instructions in the candidates.
10661 unsigned CFICount = 0;
10662 for (auto &I : RepeatedSequenceLocs[0]) {
10663 if (I.isCFIInstruction())
10664 CFICount++;
10665 }
10666
10667 // We compare the number of found CFI Instructions to the number of CFI
10668 // instructions in the parent function for each candidate. We must check this
10669 // since if we outline one of the CFI instructions in a function, we have to
10670 // outline them all for correctness. If we do not, the address offsets will be
10671 // incorrect between the two sections of the program.
10672 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10673 std::vector<MCCFIInstruction> CFIInstructions =
10674 C.getMF()->getFrameInstructions();
10675
10676 if (CFICount > 0 && CFICount != CFIInstructions.size())
10677 return std::nullopt;
10678 }
10679
10680 // Returns true if an instructions is safe to fix up, false otherwise.
10681 auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
10682 if (MI.isCall())
10683 return true;
10684
10685 if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
10686 !MI.readsRegister(AArch64::SP, &TRI))
10687 return true;
10688
10689 // Any modification of SP will break our code to save/restore LR.
10690 // FIXME: We could handle some instructions which add a constant
10691 // offset to SP, with a bit more work.
10692 if (MI.modifiesRegister(AArch64::SP, &TRI))
10693 return false;
10694
10695 // At this point, we have a stack instruction that we might need to
10696 // fix up. We'll handle it if it's a load or store.
10697 if (MI.mayLoadOrStore()) {
10698 const MachineOperand *Base; // Filled with the base operand of MI.
10699 int64_t Offset; // Filled with the offset of MI.
10700 bool OffsetIsScalable;
10701
10702 // Does it allow us to offset the base operand and is the base the
10703 // register SP?
10704 if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable) ||
10705 !Base->isReg() || Base->getReg() != AArch64::SP)
10706 return false;
10707
10708 // Fixe-up code below assumes bytes.
10709 if (OffsetIsScalable)
10710 return false;
10711
10712 // Find the minimum/maximum offset for this instruction and check
10713 // if fixing it up would be in range.
10714 int64_t MinOffset,
10715 MaxOffset; // Unscaled offsets for the instruction.
10716 // The scale to multiply the offsets by.
10717 TypeSize Scale(0U, false), DummyWidth(0U, false);
10718 getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
10719
10720 Offset += 16; // Update the offset to what it would be if we outlined.
10721 if (Offset < MinOffset * (int64_t)Scale.getFixedValue() ||
10722 Offset > MaxOffset * (int64_t)Scale.getFixedValue())
10723 return false;
10724
10725 // It's in range, so we can outline it.
10726 return true;
10727 }
10728
10729 // FIXME: Add handling for instructions like "add x0, sp, #8".
10730
10731 // We can't fix it up, so don't outline it.
10732 return false;
10733 };
10734
10735 // True if it's possible to fix up each stack instruction in this sequence.
10736 // Important for frames/call variants that modify the stack.
10737 bool AllStackInstrsSafe =
10738 llvm::all_of(RepeatedSequenceLocs[0], IsSafeToFixup);
10739
10740 // If the last instruction in any candidate is a terminator, then we should
10741 // tail call all of the candidates.
10742 if (RepeatedSequenceLocs[0].back().isTerminator()) {
10743 FrameID = MachineOutlinerTailCall;
10744 NumBytesToCreateFrame = 0;
10745 unsigned NumBytesForCall = 4 + NumBytesToCheckLRInTCEpilogue;
10746 SetCandidateCallInfo(MachineOutlinerTailCall, NumBytesForCall);
10747 }
10748
10749 else if (LastInstrOpcode == AArch64::BL ||
10750 ((LastInstrOpcode == AArch64::BLR ||
10751 LastInstrOpcode == AArch64::BLRNoIP) &&
10752 !HasBTI)) {
10753 // FIXME: Do we need to check if the code after this uses the value of LR?
10754 FrameID = MachineOutlinerThunk;
10755 NumBytesToCreateFrame = NumBytesToCheckLRInTCEpilogue;
10756 SetCandidateCallInfo(MachineOutlinerThunk, 4);
10757 }
10758
10759 else {
10760 // We need to decide how to emit calls + frames. We can always emit the same
10761 // frame if we don't need to save to the stack. If we have to save to the
10762 // stack, then we need a different frame.
10763 unsigned NumBytesNoStackCalls = 0;
10764 std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
10765
10766 // Check if we have to save LR.
10767 for (outliner::Candidate &C : RepeatedSequenceLocs) {
10768 bool LRAvailable =
10770 ? C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI)
10771 : true;
10772 // If we have a noreturn caller, then we're going to be conservative and
10773 // say that we have to save LR. If we don't have a ret at the end of the
10774 // block, then we can't reason about liveness accurately.
10775 //
10776 // FIXME: We can probably do better than always disabling this in
10777 // noreturn functions by fixing up the liveness info.
10778 bool IsNoReturn =
10779 C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
10780
10781 // Is LR available? If so, we don't need a save.
10782 if (LRAvailable && !IsNoReturn) {
10783 NumBytesNoStackCalls += 4;
10784 C.setCallInfo(MachineOutlinerNoLRSave, 4);
10785 CandidatesWithoutStackFixups.push_back(C);
10786 }
10787
10788 // Is an unused register available? If so, we won't modify the stack, so
10789 // we can outline with the same frame type as those that don't save LR.
10790 else if (findRegisterToSaveLRTo(C)) {
10791 NumBytesNoStackCalls += 12;
10792 C.setCallInfo(MachineOutlinerRegSave, 12);
10793 CandidatesWithoutStackFixups.push_back(C);
10794 }
10795
10796 // Is SP used in the sequence at all? If not, we don't have to modify
10797 // the stack, so we are guaranteed to get the same frame.
10798 else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
10799 NumBytesNoStackCalls += 12;
10800 C.setCallInfo(MachineOutlinerDefault, 12);
10801 CandidatesWithoutStackFixups.push_back(C);
10802 }
10803
10804 // If we outline this, we need to modify the stack. Pretend we don't
10805 // outline this by saving all of its bytes.
10806 else {
10807 NumBytesNoStackCalls += SequenceSize;
10808 }
10809 }
10810
10811 // If there are no places where we have to save LR, then note that we
10812 // don't have to update the stack. Otherwise, give every candidate the
10813 // default call type, as long as it's safe to do so.
10814 if (!AllStackInstrsSafe ||
10815 NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
10816 RepeatedSequenceLocs = CandidatesWithoutStackFixups;
10817 FrameID = MachineOutlinerNoLRSave;
10818 if (RepeatedSequenceLocs.size() < MinRepeats)
10819 return std::nullopt;
10820 } else {
10821 SetCandidateCallInfo(MachineOutlinerDefault, 12);
10822
10823 // Bugzilla ID: 46767
10824 // TODO: Check if fixing up the stack more than once is safe so we can
10825 // outline these.
10826 //
10827 // An outline resulting in a caller that requires stack fixups at the
10828 // callsite to a callee that also requires stack fixups can happen when
10829 // there are no available registers at the candidate callsite for a
10830 // candidate that itself also has calls.
10831 //
10832 // In other words if function_containing_sequence in the following pseudo
10833 // assembly requires that we save LR at the point of the call, but there
10834 // are no available registers: in this case we save using SP and as a
10835 // result the SP offsets requires stack fixups by multiples of 16.
10836 //
10837 // function_containing_sequence:
10838 // ...
10839 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10840 // call OUTLINED_FUNCTION_N
10841 // restore LR from SP
10842 // ...
10843 //
10844 // OUTLINED_FUNCTION_N:
10845 // save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
10846 // ...
10847 // bl foo
10848 // restore LR from SP
10849 // ret
10850 //
10851 // Because the code to handle more than one stack fixup does not
10852 // currently have the proper checks for legality, these cases will assert
10853 // in the AArch64 MachineOutliner. This is because the code to do this
10854 // needs more hardening, testing, better checks that generated code is
10855 // legal, etc and because it is only verified to handle a single pass of
10856 // stack fixup.
10857 //
10858 // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
10859 // these cases until they are known to be handled. Bugzilla 46767 is
10860 // referenced in comments at the assert site.
10861 //
10862 // To avoid asserting (or generating non-legal code on noassert builds)
10863 // we remove all candidates which would need more than one stack fixup by
10864 // pruning the cases where the candidate has calls while also having no
10865 // available LR and having no available general purpose registers to copy
10866 // LR to (ie one extra stack save/restore).
10867 //
10868 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
10869 erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
10870 auto IsCall = [](const MachineInstr &MI) { return MI.isCall(); };
10871 return (llvm::any_of(C, IsCall)) &&
10872 (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
10873 !findRegisterToSaveLRTo(C));
10874 });
10875 }
10876 }
10877
10878 // If we dropped all of the candidates, bail out here.
10879 if (RepeatedSequenceLocs.size() < MinRepeats)
10880 return std::nullopt;
10881 }
10882
10883 // Does every candidate's MBB contain a call? If so, then we might have a call
10884 // in the range.
10885 if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
10886 // Check if the range contains a call. These require a save + restore of the
10887 // link register.
10888 outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
10889 bool ModStackToSaveLR = false;
10890 if (any_of(drop_end(FirstCand),
10891 [](const MachineInstr &MI) { return MI.isCall(); }))
10892 ModStackToSaveLR = true;
10893
10894 // Handle the last instruction separately. If this is a tail call, then the
10895 // last instruction is a call. We don't want to save + restore in this case.
10896 // However, it could be possible that the last instruction is a call without
10897 // it being valid to tail call this sequence. We should consider this as
10898 // well.
10899 else if (FrameID != MachineOutlinerThunk &&
10900 FrameID != MachineOutlinerTailCall && FirstCand.back().isCall())
10901 ModStackToSaveLR = true;
10902
10903 if (ModStackToSaveLR) {
10904 // We can't fix up the stack. Bail out.
10905 if (!AllStackInstrsSafe)
10906 return std::nullopt;
10907
10908 // Save + restore LR.
10909 NumBytesToCreateFrame += 8;
10910
10911 // Add the extra mov if we will save a frame record instead of just LR.
10913 RepeatedSequenceLocs, TRI))
10914 NumBytesToCreateFrame += 4;
10915 }
10916 }
10917
10918 // If we have CFI instructions, we can only outline if the outlined section
10919 // can be a tail call
10920 if (FrameID != MachineOutlinerTailCall && CFICount > 0)
10921 return std::nullopt;
10922
10923 return std::make_unique<outliner::OutlinedFunction>(
10924 RepeatedSequenceLocs, SequenceSize, NumBytesToCreateFrame, FrameID);
10925}
10926
10927void AArch64InstrInfo::mergeOutliningCandidateAttributes(
10928 Function &F, std::vector<outliner::Candidate> &Candidates) const {
10929 // If a bunch of candidates reach this point they must agree on their return
10930 // address signing. It is therefore enough to just consider the signing
10931 // behaviour of one of them
10932 const auto &CFn = Candidates.front().getMF()->getFunction();
10933
10934 if (CFn.hasFnAttribute("ptrauth-returns"))
10935 F.addFnAttr(CFn.getFnAttribute("ptrauth-returns"));
10936 if (CFn.hasFnAttribute("ptrauth-auth-traps"))
10937 F.addFnAttr(CFn.getFnAttribute("ptrauth-auth-traps"));
10938 // Since all candidates belong to the same module, just copy the
10939 // function-level attributes of an arbitrary function.
10940 if (CFn.hasFnAttribute("sign-return-address"))
10941 F.addFnAttr(CFn.getFnAttribute("sign-return-address"));
10942 if (CFn.hasFnAttribute("sign-return-address-key"))
10943 F.addFnAttr(CFn.getFnAttribute("sign-return-address-key"));
10944 // The "sign-return-address-harden" attribute is not included because no
10945 // candidate is supposed to have hardening enabled.
10946 assert(llvm::none_of(Candidates, [](const outliner::Candidate &C) {
10947 return C.getMF()
10948 ->getInfo<AArch64FunctionInfo>()
10949 ->shouldHardenSignReturnAddress();
10950 }));
10951
10952 AArch64GenInstrInfo::mergeOutliningCandidateAttributes(F, Candidates);
10953}
10954
10955bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
10956 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
10957 const Function &F = MF.getFunction();
10958
10959 // Can F be deduplicated by the linker? If it can, don't outline from it.
10960 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
10961 return false;
10962
10963 // Don't outline from functions with section markings; the program could
10964 // expect that all the code is in the named section.
10965 // FIXME: Allow outlining from multiple functions with the same section
10966 // marking.
10967 if (F.hasSection())
10968 return false;
10969
10970 // Outlining from functions with redzones is unsafe since the outliner may
10971 // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
10972 // outline from it.
10973 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
10974 if (!AFI || AFI->hasRedZone().value_or(true))
10975 return false;
10976
10977 // FIXME: Determine whether it is safe to outline from functions which contain
10978 // streaming-mode changes. We may need to ensure any smstart/smstop pairs are
10979 // outlined together and ensure it is safe to outline with async unwind info,
10980 // required for saving & restoring VG around calls.
10981 if (AFI->hasStreamingModeChanges())
10982 return false;
10983
10984 // FIXME: Teach the outliner to generate/handle Windows unwind info.
10985 if (MF.usesWindowsUnwindInfo())
10986 return false;
10987
10988 // It's safe to outline from MF.
10989 return true;
10990}
10991
10993AArch64InstrInfo::getOutlinableRanges(MachineBasicBlock &MBB,
10994 unsigned &Flags) const {
10996 "Must track liveness!");
10998 std::pair<MachineBasicBlock::iterator, MachineBasicBlock::iterator>>
10999 Ranges;
11000 // According to the AArch64 Procedure Call Standard, the following are
11001 // undefined on entry/exit from a function call:
11002 //
11003 // * Registers x16, x17, (and thus w16, w17)
11004 // * Condition codes (and thus the NZCV register)
11005 //
11006 // If any of these registers are used inside or live across an outlined
11007 // function, then they may be modified later, either by the compiler or
11008 // some other tool (like the linker).
11009 //
11010 // To avoid outlining in these situations, partition each block into ranges
11011 // where these registers are dead. We will only outline from those ranges.
11012 LiveRegUnits LRU(getRegisterInfo());
11013 auto AreAllUnsafeRegsDead = [&LRU]() {
11014 return LRU.available(AArch64::W16) && LRU.available(AArch64::W17) &&
11015 LRU.available(AArch64::NZCV);
11016 };
11017
11018 // We need to know if LR is live across an outlining boundary later on in
11019 // order to decide how we'll create the outlined call, frame, etc.
11020 //
11021 // It's pretty expensive to check this for *every candidate* within a block.
11022 // That's some potentially n^2 behaviour, since in the worst case, we'd need
11023 // to compute liveness from the end of the block for O(n) candidates within
11024 // the block.
11025 //
11026 // So, to improve the average case, let's keep track of liveness from the end
11027 // of the block to the beginning of *every outlinable range*. If we know that
11028 // LR is available in every range we could outline from, then we know that
11029 // we don't need to check liveness for any candidate within that range.
11030 bool LRAvailableEverywhere = true;
11031 // Compute liveness bottom-up.
11032 LRU.addLiveOuts(MBB);
11033 // Update flags that require info about the entire MBB.
11034 auto UpdateWholeMBBFlags = [&Flags](const MachineInstr &MI) {
11035 if (MI.isCall() && !MI.isTerminator())
11037 };
11038 // Range: [RangeBegin, RangeEnd)
11039 MachineBasicBlock::instr_iterator RangeBegin, RangeEnd;
11040 unsigned RangeLen;
11041 auto CreateNewRangeStartingAt =
11042 [&RangeBegin, &RangeEnd,
11043 &RangeLen](MachineBasicBlock::instr_iterator NewBegin) {
11044 RangeBegin = NewBegin;
11045 RangeEnd = std::next(RangeBegin);
11046 RangeLen = 0;
11047 };
11048 auto SaveRangeIfNonEmpty = [&RangeLen, &Ranges, &RangeBegin, &RangeEnd]() {
11049 // At least one unsafe register is not dead. We do not want to outline at
11050 // this point. If it is long enough to outline from and does not cross a
11051 // bundle boundary, save the range [RangeBegin, RangeEnd).
11052 if (RangeLen <= 1)
11053 return;
11054 if (!RangeBegin.isEnd() && RangeBegin->isBundledWithPred())
11055 return;
11056 if (!RangeEnd.isEnd() && RangeEnd->isBundledWithPred())
11057 return;
11058 Ranges.emplace_back(RangeBegin, RangeEnd);
11059 };
11060 // Find the first point where all unsafe registers are dead.
11061 // FIND: <safe instr> <-- end of first potential range
11062 // SKIP: <unsafe def>
11063 // SKIP: ... everything between ...
11064 // SKIP: <unsafe use>
11065 auto FirstPossibleEndPt = MBB.instr_rbegin();
11066 for (; FirstPossibleEndPt != MBB.instr_rend(); ++FirstPossibleEndPt) {
11067 if (!FirstPossibleEndPt->isDebugInstr())
11068 LRU.stepBackward(*FirstPossibleEndPt);
11069 // Update flags that impact how we outline across the entire block,
11070 // regardless of safety.
11071 UpdateWholeMBBFlags(*FirstPossibleEndPt);
11072 if (AreAllUnsafeRegsDead())
11073 break;
11074 }
11075 // If we exhausted the entire block, we have no safe ranges to outline.
11076 if (FirstPossibleEndPt == MBB.instr_rend())
11077 return Ranges;
11078 // Current range.
11079 CreateNewRangeStartingAt(FirstPossibleEndPt->getIterator());
11080 // StartPt points to the first place where all unsafe registers
11081 // are dead (if there is any such point). Begin partitioning the MBB into
11082 // ranges.
11083 // Pseudo probes are ordinary instructions to the mapper, so only skip debug
11084 // instructions here.
11085 for (auto &MI : instructionsWithoutDebug(FirstPossibleEndPt, MBB.instr_rend(),
11086 /*SkipPseudoOp=*/false)) {
11087 LRU.stepBackward(MI);
11088 UpdateWholeMBBFlags(MI);
11089 if (!AreAllUnsafeRegsDead()) {
11090 SaveRangeIfNonEmpty();
11091 CreateNewRangeStartingAt(MI.getIterator());
11092 continue;
11093 }
11094 LRAvailableEverywhere &= LRU.available(AArch64::LR);
11095 // Pseudo probes count because the mapper treats them as ordinary
11096 // instructions.
11097 RangeBegin = MI.getIterator();
11098 ++RangeLen;
11099 }
11100 // Above loop misses the last (or only) range. If we are still safe, then
11101 // let's save the range.
11102 if (AreAllUnsafeRegsDead())
11103 SaveRangeIfNonEmpty();
11104 if (Ranges.empty())
11105 return Ranges;
11106 // We found the ranges bottom-up. Mapping expects the top-down. Reverse
11107 // the order.
11108 std::reverse(Ranges.begin(), Ranges.end());
11109 // If there is at least one outlinable range where LR is unavailable
11110 // somewhere, remember that.
11111 if (!LRAvailableEverywhere)
11113 return Ranges;
11114}
11115
11117AArch64InstrInfo::getOutliningTypeImpl(const MachineModuleInfo &MMI,
11119 unsigned Flags) const {
11120 MachineInstr &MI = *MIT;
11121
11122 // Don't outline anything used for return address signing. The outlined
11123 // function will get signed later if needed
11124 switch (MI.getOpcode()) {
11125 case AArch64::PACM:
11126 case AArch64::PACIASP:
11127 case AArch64::PACIBSP:
11128 case AArch64::PACIASPPC:
11129 case AArch64::PACIBSPPC:
11130 case AArch64::AUTIASP:
11131 case AArch64::AUTIBSP:
11132 case AArch64::AUTIASPPCi:
11133 case AArch64::AUTIASPPCr:
11134 case AArch64::AUTIBSPPCi:
11135 case AArch64::AUTIBSPPCr:
11136 case AArch64::RETAA:
11137 case AArch64::RETAB:
11138 case AArch64::RETAASPPCi:
11139 case AArch64::RETAASPPCr:
11140 case AArch64::RETABSPPCi:
11141 case AArch64::RETABSPPCr:
11142 case AArch64::EMITBKEY:
11143 case AArch64::PAUTH_PROLOGUE:
11144 case AArch64::PAUTH_EPILOGUE:
11146 }
11147
11148 // We can only outline these if we will tail call the outlined function, or
11149 // fix up the CFI offsets. Currently, CFI instructions are outlined only if
11150 // in a tail call.
11151 //
11152 // FIXME: If the proper fixups for the offset are implemented, this should be
11153 // possible.
11154 if (MI.isCFIInstruction())
11156
11157 // Is this a terminator for a basic block?
11158 if (MI.isTerminator())
11159 // TargetInstrInfo::getOutliningType has already filtered out anything
11160 // that would break this, so we can allow it here.
11162
11163 // Make sure none of the operands are un-outlinable.
11164 for (const MachineOperand &MOP : MI.operands()) {
11165 // A check preventing CFI indices was here before, but only CFI
11166 // instructions should have those.
11167 assert(!MOP.isCFIIndex());
11168
11169 // If it uses LR or W30 explicitly, then don't touch it.
11170 if (MOP.isReg() && !MOP.isImplicit() &&
11171 (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
11173 }
11174
11175 // Special cases for instructions that can always be outlined, but will fail
11176 // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
11177 // be outlined because they don't require a *specific* value to be in LR.
11178 if (MI.getOpcode() == AArch64::ADRP)
11180
11181 // If MI is a call we might be able to outline it. We don't want to outline
11182 // any calls that rely on the position of items on the stack. When we outline
11183 // something containing a call, we have to emit a save and restore of LR in
11184 // the outlined function. Currently, this always happens by saving LR to the
11185 // stack. Thus, if we outline, say, half the parameters for a function call
11186 // plus the call, then we'll break the callee's expectations for the layout
11187 // of the stack.
11188 //
11189 // FIXME: Allow calls to functions which construct a stack frame, as long
11190 // as they don't access arguments on the stack.
11191 // FIXME: Figure out some way to analyze functions defined in other modules.
11192 // We should be able to compute the memory usage based on the IR calling
11193 // convention, even if we can't see the definition.
11194 if (MI.isCall()) {
11195 // Get the function associated with the call. Look at each operand and find
11196 // the one that represents the callee and get its name.
11197 const Function *Callee = nullptr;
11198 for (const MachineOperand &MOP : MI.operands()) {
11199 if (MOP.isGlobal()) {
11200 Callee = dyn_cast<Function>(MOP.getGlobal());
11201 break;
11202 }
11203 }
11204
11205 // Never outline calls to mcount. There isn't any rule that would require
11206 // this, but the Linux kernel's "ftrace" feature depends on it.
11207 if (Callee && Callee->getName() == "\01_mcount")
11209
11210 // If we don't know anything about the callee, assume it depends on the
11211 // stack layout of the caller. In that case, it's only legal to outline
11212 // as a tail-call. Explicitly list the call instructions we know about so we
11213 // don't get unexpected results with call pseudo-instructions.
11214 auto UnknownCallOutlineType = outliner::InstrType::Illegal;
11215 if (MI.getOpcode() == AArch64::BLR ||
11216 MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
11217 UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
11218
11219 if (!Callee)
11220 return UnknownCallOutlineType;
11221
11222 // We have a function we have information about. Check it if it's something
11223 // can safely outline.
11224 MachineFunction *CalleeMF = MMI.getMachineFunction(*Callee);
11225
11226 // We don't know what's going on with the callee at all. Don't touch it.
11227 if (!CalleeMF)
11228 return UnknownCallOutlineType;
11229
11230 // Check if we know anything about the callee saves on the function. If we
11231 // don't, then don't touch it, since that implies that we haven't
11232 // computed anything about its stack frame yet.
11233 MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
11234 if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
11235 MFI.getNumObjects() > 0)
11236 return UnknownCallOutlineType;
11237
11238 // At this point, we can say that CalleeMF ought to not pass anything on the
11239 // stack. Therefore, we can outline it.
11241 }
11242
11243 // Don't touch the link register or W30.
11244 if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
11245 MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
11247
11248 // Don't outline BTI instructions, because that will prevent the outlining
11249 // site from being indirectly callable.
11250 if (hasBTISemantics(MI))
11252
11254}
11255
11256void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
11257 for (MachineInstr &MI : MBB) {
11258 const MachineOperand *Base;
11259 TypeSize Width(0, false);
11260 int64_t Offset;
11261 bool OffsetIsScalable;
11262
11263 // Is this a load or store with an immediate offset with SP as the base?
11264 if (!MI.mayLoadOrStore() ||
11265 !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable,
11266 Width) ||
11267 (Base->isReg() && Base->getReg() != AArch64::SP))
11268 continue;
11269
11270 // It is, so we have to fix it up.
11271 TypeSize Scale(0U, false);
11272 int64_t Dummy1, Dummy2;
11273
11274 MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI);
11275 assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
11276 getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
11277 assert(Scale != 0 && "Unexpected opcode!");
11278 assert(!OffsetIsScalable && "Expected offset to be a byte offset");
11279
11280 // We've pushed the return address to the stack, so add 16 to the offset.
11281 // This is safe, since we already checked if it would overflow when we
11282 // checked if this instruction was legal to outline.
11283 int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedValue();
11284 StackOffsetOperand.setImm(NewImm);
11285 }
11286}
11287
11289 const AArch64InstrInfo *TII,
11290 bool ShouldSignReturnAddr) {
11291 if (!ShouldSignReturnAddr)
11292 return;
11293
11294 BuildMI(MBB, MBB.begin(), DebugLoc(), TII->get(AArch64::PAUTH_PROLOGUE))
11296 TII->createPauthEpilogueInstr(MBB, DebugLoc());
11297}
11298
11299void AArch64InstrInfo::buildOutlinedFrame(
11301 const outliner::OutlinedFunction &OF) const {
11302
11303 AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
11304
11305 if (OF.FrameConstructionID == MachineOutlinerTailCall)
11306 FI->setOutliningStyle("Tail Call");
11307 else if (OF.FrameConstructionID == MachineOutlinerThunk) {
11308 // For thunk outlining, rewrite the last instruction from a call to a
11309 // tail-call.
11310 MachineInstr *Call = &*--MBB.instr_end();
11311 unsigned TailOpcode;
11312 if (Call->getOpcode() == AArch64::BL) {
11313 TailOpcode = AArch64::TCRETURNdi;
11314 } else {
11315 assert(Call->getOpcode() == AArch64::BLR ||
11316 Call->getOpcode() == AArch64::BLRNoIP);
11317 TailOpcode = AArch64::TCRETURNriALL;
11318 }
11319 MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
11320 .add(Call->getOperand(0))
11321 .addImm(0);
11322 MBB.insert(MBB.end(), TC);
11324
11325 FI->setOutliningStyle("Thunk");
11326 }
11327
11328 bool IsLeafFunction = true;
11329
11330 // Is there a call in the outlined range?
11331 auto IsNonTailCall = [](const MachineInstr &MI) {
11332 return MI.isCall() && !MI.isReturn();
11333 };
11334
11335 if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
11336 // Fix up the instructions in the range, since we're going to modify the
11337 // stack.
11338
11339 // Bugzilla ID: 46767
11340 // TODO: Check if fixing up twice is safe so we can outline these.
11341 assert(OF.FrameConstructionID != MachineOutlinerDefault &&
11342 "Can only fix up stack references once");
11343 fixupPostOutline(MBB);
11344
11345 IsLeafFunction = false;
11346
11347 // LR has to be a live in so that we can save it.
11348 if (!MBB.isLiveIn(AArch64::LR))
11349 MBB.addLiveIn(AArch64::LR);
11350
11353
11354 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11355 OF.FrameConstructionID == MachineOutlinerThunk)
11356 Et = std::prev(MBB.end());
11357
11358 // There is a call in the range, so we must save LR. Save it as part of a
11359 // frame record when that gives us a smaller compact unwind encoding.
11361 // FP is saved here, so it must be live-in.
11362 if (!MBB.isLiveIn(AArch64::FP))
11363 MBB.addLiveIn(AArch64::FP);
11364
11365 // stp x29, x30, [sp, #-16]! (the pre-index imm is scaled by 8: -2 * 8)
11366 MachineInstr *STPXpre = BuildMI(MF, DebugLoc(), get(AArch64::STPXpre))
11367 .addReg(AArch64::SP, RegState::Define)
11368 .addReg(AArch64::FP)
11369 .addReg(AArch64::LR)
11370 .addReg(AArch64::SP)
11371 .addImm(-2);
11372 It = MBB.insert(It, STPXpre);
11373
11374 // mov x29, sp (add x29, sp, #0), so x29 points at the frame record.
11375 MachineInstr *SetFP = BuildMI(MF, DebugLoc(), get(AArch64::ADDXri))
11376 .addReg(AArch64::FP, RegState::Define)
11377 .addReg(AArch64::SP)
11378 .addImm(0)
11379 .addImm(0);
11380 MBB.insertAfter(It, SetFP);
11381
11382 // Describe the frame record with FP as the CFA. The encoder needs all
11383 // three to pick FRAME. No need to check for unwind info here: we only
11384 // get here if the function has it.
11385 CFIInstBuilder CFIBuilder(MBB, std::next(SetFP->getIterator()),
11387 CFIBuilder.buildDefCFA(AArch64::FP, 16);
11388 CFIBuilder.buildOffset(AArch64::LR, -8);
11389 CFIBuilder.buildOffset(AArch64::FP, -16);
11390
11391 // ldp x29, x30, [sp], #16
11392 MachineInstr *LDPXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDPXpost))
11393 .addReg(AArch64::SP, RegState::Define)
11394 .addReg(AArch64::FP, RegState::Define)
11395 .addReg(AArch64::LR, RegState::Define)
11396 .addReg(AArch64::SP)
11397 .addImm(2);
11398 Et = MBB.insert(Et, LDPXpost);
11399 } else {
11400 // Insert a save before the outlined region
11401 MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11402 .addReg(AArch64::SP, RegState::Define)
11403 .addReg(AArch64::LR)
11404 .addReg(AArch64::SP)
11405 .addImm(-16);
11406 It = MBB.insert(It, STRXpre);
11407
11408 if (MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF)) {
11409 CFIInstBuilder CFIBuilder(MBB, It, MachineInstr::FrameSetup);
11410
11411 // Add a CFI saying the stack was moved 16 B down.
11412 CFIBuilder.buildDefCFAOffset(16);
11413
11414 // Add a CFI saying that the LR that we want to find is now 16 B higher
11415 // than before.
11416 CFIBuilder.buildOffset(AArch64::LR, -16);
11417 }
11418
11419 // Insert a restore before the terminator for the function.
11420 MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11421 .addReg(AArch64::SP, RegState::Define)
11422 .addReg(AArch64::LR, RegState::Define)
11423 .addReg(AArch64::SP)
11424 .addImm(16);
11425 Et = MBB.insert(Et, LDRXpost);
11426 }
11427 }
11428
11429 auto RASignCondition = FI->getSignReturnAddressCondition();
11430 bool ShouldSignReturnAddr = AArch64FunctionInfo::shouldSignReturnAddress(
11431 RASignCondition, !IsLeafFunction);
11432
11433 // If this is a tail call outlined function, then there's already a return.
11434 if (OF.FrameConstructionID == MachineOutlinerTailCall ||
11435 OF.FrameConstructionID == MachineOutlinerThunk) {
11436 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11437 return;
11438 }
11439
11440 // It's not a tail call, so we have to insert the return ourselves.
11441
11442 // LR has to be a live in so that we can return to it.
11443 if (!MBB.isLiveIn(AArch64::LR))
11444 MBB.addLiveIn(AArch64::LR);
11445
11446 MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
11447 .addReg(AArch64::LR);
11448 MBB.insert(MBB.end(), ret);
11449
11450 signOutlinedFunction(MF, MBB, this, ShouldSignReturnAddr);
11451
11452 FI->setOutliningStyle("Function");
11453
11454 // Did we have to modify the stack by saving the link register?
11455 if (OF.FrameConstructionID != MachineOutlinerDefault)
11456 return;
11457
11458 // We modified the stack.
11459 // Walk over the basic block and fix up all the stack accesses.
11460 fixupPostOutline(MBB);
11461}
11462
11463MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
11466
11467 // Are we tail calling?
11468 if (C.CallConstructionID == MachineOutlinerTailCall) {
11469 // If yes, then we can just branch to the label.
11470 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
11471 .addGlobalAddress(M.getNamedValue(MF.getName()))
11472 .addImm(0));
11473 return It;
11474 }
11475
11476 // Are we saving the link register?
11477 if (C.CallConstructionID == MachineOutlinerNoLRSave ||
11478 C.CallConstructionID == MachineOutlinerThunk) {
11479 // No, so just insert the call.
11480 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11481 .addGlobalAddress(M.getNamedValue(MF.getName())));
11482 return It;
11483 }
11484
11485 // We want to return the spot where we inserted the call.
11487
11488 // Instructions for saving and restoring LR around the call instruction we're
11489 // going to insert.
11490 MachineInstr *Save;
11491 MachineInstr *Restore;
11492 // Can we save to a register?
11493 if (C.CallConstructionID == MachineOutlinerRegSave) {
11494 // FIXME: This logic should be sunk into a target-specific interface so that
11495 // we don't have to recompute the register.
11496 Register Reg = findRegisterToSaveLRTo(C);
11497 assert(Reg && "No callee-saved register available?");
11498
11499 // LR has to be a live in so that we can save it.
11500 if (!MBB.isLiveIn(AArch64::LR))
11501 MBB.addLiveIn(AArch64::LR);
11502
11503 // Save and restore LR from Reg.
11504 Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
11505 .addReg(AArch64::XZR)
11506 .addReg(AArch64::LR)
11507 .addImm(0);
11508 Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
11509 .addReg(AArch64::XZR)
11510 .addReg(Reg)
11511 .addImm(0);
11512 } else {
11513 // We have the default case. Save and restore from SP.
11514 Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
11515 .addReg(AArch64::SP, RegState::Define)
11516 .addReg(AArch64::LR)
11517 .addReg(AArch64::SP)
11518 .addImm(-16);
11519 Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
11520 .addReg(AArch64::SP, RegState::Define)
11521 .addReg(AArch64::LR, RegState::Define)
11522 .addReg(AArch64::SP)
11523 .addImm(16);
11524 }
11525
11526 It = MBB.insert(It, Save);
11527 It++;
11528
11529 // Insert the call.
11530 It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
11531 .addGlobalAddress(M.getNamedValue(MF.getName())));
11532 CallPt = It;
11533 It++;
11534
11535 It = MBB.insert(It, Restore);
11536 return CallPt;
11537}
11538
11539bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
11540 MachineFunction &MF) const {
11541 return MF.getFunction().hasMinSize();
11542}
11543
11544void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock &MBB,
11546 DebugLoc &DL,
11547 bool AllowSideEffects) const {
11548 const MachineFunction &MF = *MBB.getParent();
11549 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
11550 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
11551
11552 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
11553 BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg).addImm(0).addImm(0);
11554 } else if (STI.isSVEorStreamingSVEAvailable()) {
11555 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
11556 .addImm(0)
11557 .addImm(0);
11558 } else if (STI.isNeonAvailable()) {
11559 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
11560 .addImm(0);
11561 } else {
11562 // No Advanced SIMD (streaming-compatible without SVE, or +nosimd), so use
11563 // `fmov d...` instead of `movi v...`; writing `d` also clears the upper
11564 // 64 bits.
11565 assert(STI.hasFPARMv8() && "Expected FP to be available.");
11566 Register Reg64 = TRI.getSubReg(Reg, AArch64::dsub);
11567 BuildMI(MBB, Iter, DL, get(AArch64::FMOVD0), Reg64);
11568 }
11569}
11570
11571std::optional<DestSourcePair>
11573
11574 // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
11575 // and zero immediate operands used as an alias for mov instruction.
11576 if ((MI.getOpcode() == AArch64::ORRWrs &&
11577 MI.getOperand(1).getReg() == AArch64::WZR &&
11578 MI.getOperand(3).getImm() == 0x0) ||
11579 (MI.getOpcode() == AArch64::ORRWrr &&
11580 MI.getOperand(1).getReg() == AArch64::WZR)) {
11581 // Check that the w->w move is not a zero-extending w->x mov.
11582 if ((MI.getOperand(0).getReg().isPhysical() &&
11583 MI.findRegisterDefOperandIdx(
11584 getXRegFromWReg(MI.getOperand(0).getReg()),
11585 /*TRI=*/nullptr) == -1) ||
11586 (MI.getOperand(0).getReg().isVirtual() &&
11587 !MI.getOperand(0).getSubReg()))
11588 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11589 }
11590
11591 if (MI.getOpcode() == AArch64::ORRXrs &&
11592 MI.getOperand(1).getReg() == AArch64::XZR &&
11593 MI.getOperand(3).getImm() == 0x0)
11594 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11595
11596 return std::nullopt;
11597}
11598
11599std::optional<DestSourcePair>
11601 if ((MI.getOpcode() == AArch64::ORRWrs &&
11602 MI.getOperand(1).getReg() == AArch64::WZR &&
11603 MI.getOperand(3).getImm() == 0x0) ||
11604 (MI.getOpcode() == AArch64::ORRWrr &&
11605 MI.getOperand(1).getReg() == AArch64::WZR))
11606 return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
11607 return std::nullopt;
11608}
11609
11610std::optional<RegImmPair>
11611AArch64InstrInfo::isAddImmediate(const MachineInstr &MI, Register Reg) const {
11612 int Sign = 1;
11613 int64_t Offset = 0;
11614
11615 // TODO: Handle cases where Reg is a super- or sub-register of the
11616 // destination register.
11617 const MachineOperand &Op0 = MI.getOperand(0);
11618 if (!Op0.isReg() || Reg != Op0.getReg())
11619 return std::nullopt;
11620
11621 switch (MI.getOpcode()) {
11622 default:
11623 return std::nullopt;
11624 case AArch64::SUBWri:
11625 case AArch64::SUBXri:
11626 case AArch64::SUBSWri:
11627 case AArch64::SUBSXri:
11628 Sign *= -1;
11629 [[fallthrough]];
11630 case AArch64::ADDSWri:
11631 case AArch64::ADDSXri:
11632 case AArch64::ADDWri:
11633 case AArch64::ADDXri: {
11634 // TODO: Third operand can be global address (usually some string).
11635 if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
11636 !MI.getOperand(2).isImm())
11637 return std::nullopt;
11638 int Shift = MI.getOperand(3).getImm();
11639 assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
11640 Offset = Sign * (MI.getOperand(2).getImm() << Shift);
11641 }
11642 }
11643 return RegImmPair{MI.getOperand(1).getReg(), Offset};
11644}
11645
11646/// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
11647/// the destination register then, if possible, describe the value in terms of
11648/// the source register.
11649static std::optional<ParamLoadedValue>
11651 const TargetInstrInfo *TII,
11652 const TargetRegisterInfo *TRI) {
11653 auto DestSrc = TII->isCopyLikeInstr(MI);
11654 if (!DestSrc)
11655 return std::nullopt;
11656
11657 Register DestReg = DestSrc->Destination->getReg();
11658 Register SrcReg = DestSrc->Source->getReg();
11659
11660 if (!DestReg.isValid() || !SrcReg.isValid())
11661 return std::nullopt;
11662
11663 auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
11664
11665 // If the described register is the destination, just return the source.
11666 if (DestReg == DescribedReg)
11667 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11668
11669 // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
11670 if (MI.getOpcode() == AArch64::ORRWrs &&
11671 TRI->isSuperRegister(DestReg, DescribedReg))
11672 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
11673
11674 // We may need to describe the lower part of a ORRXrs move.
11675 if (MI.getOpcode() == AArch64::ORRXrs &&
11676 TRI->isSubRegister(DestReg, DescribedReg)) {
11677 Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
11678 return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
11679 }
11680
11681 assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
11682 "Unhandled ORR[XW]rs copy case");
11683
11684 return std::nullopt;
11685}
11686
11687bool AArch64InstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
11688 // Functions cannot be split to different sections on AArch64 if they have
11689 // a red zone. This is because relaxing a cross-section branch may require
11690 // incrementing the stack pointer to spill a register, which would overwrite
11691 // the red zone.
11692 if (MF.getInfo<AArch64FunctionInfo>()->hasRedZone().value_or(true))
11693 return false;
11694
11696}
11697
11698bool AArch64InstrInfo::isMBBSafeToSplitToCold(
11699 const MachineBasicBlock &MBB) const {
11700 // Asm Goto blocks can contain conditional branches to goto labels, which can
11701 // get moved out of range of the branch instruction.
11702 auto isAsmGoto = [](const MachineInstr &MI) {
11703 return MI.getOpcode() == AArch64::INLINEASM_BR;
11704 };
11705 if (llvm::any_of(MBB, isAsmGoto) || MBB.isInlineAsmBrIndirectTarget())
11706 return false;
11707
11708 // Because jump tables are label-relative instead of table-relative, they all
11709 // must be in the same section or relocation fixup handling will fail.
11710
11711 // Check if MBB is a jump table target
11712 const MachineJumpTableInfo *MJTI = MBB.getParent()->getJumpTableInfo();
11713 auto containsMBB = [&MBB](const MachineJumpTableEntry &JTE) {
11714 return llvm::is_contained(JTE.MBBs, &MBB);
11715 };
11716 if (MJTI != nullptr && llvm::any_of(MJTI->getJumpTables(), containsMBB))
11717 return false;
11718
11719 // Check if MBB contains a jump table lookup
11720 for (const MachineInstr &MI : MBB) {
11721 switch (MI.getOpcode()) {
11722 case TargetOpcode::G_BRJT:
11723 case AArch64::JumpTableDest32:
11724 case AArch64::JumpTableDest16:
11725 case AArch64::JumpTableDest8:
11726 return false;
11727 default:
11728 continue;
11729 }
11730 }
11731
11732 // MBB isn't a special case, so it's safe to be split to the cold section.
11733 return true;
11734}
11735
11736std::optional<ParamLoadedValue>
11737AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
11738 Register Reg) const {
11739 const MachineFunction *MF = MI.getMF();
11740 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
11741 switch (MI.getOpcode()) {
11742 case AArch64::MOVZWi:
11743 case AArch64::MOVZXi: {
11744 // MOVZWi may be used for producing zero-extended 32-bit immediates in
11745 // 64-bit parameters, so we need to consider super-registers.
11746 if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
11747 return std::nullopt;
11748
11749 if (!MI.getOperand(1).isImm())
11750 return std::nullopt;
11751 int64_t Immediate = MI.getOperand(1).getImm();
11752 int Shift = MI.getOperand(2).getImm();
11753 return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
11754 nullptr);
11755 }
11756 case AArch64::ORRWrs:
11757 case AArch64::ORRXrs:
11758 return describeORRLoadedValue(MI, Reg, this, TRI);
11759 }
11760
11762}
11763
11764bool AArch64InstrInfo::isExtendLikelyToBeFolded(
11765 MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
11766 assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
11767 ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
11768 ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
11769
11770 // Anyexts are nops.
11771 if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
11772 return true;
11773
11774 Register DefReg = ExtMI.getOperand(0).getReg();
11775 if (!MRI.hasOneNonDBGUse(DefReg))
11776 return false;
11777
11778 // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
11779 // addressing mode.
11780 auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
11781 return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
11782}
11783
11784uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
11785 return get(Opc).TSFlags & AArch64::ElementSizeMask;
11786}
11787
11788bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
11789 return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
11790}
11791
11792bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
11793 return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
11794}
11795
11796unsigned int
11797AArch64InstrInfo::getTailDuplicateSize(CodeGenOptLevel OptLevel) const {
11798 return OptLevel >= CodeGenOptLevel::Aggressive ? 6 : 2;
11799}
11800
11801bool AArch64InstrInfo::isLegalAddressingMode(unsigned NumBytes, int64_t Offset,
11802 unsigned Scale) const {
11803 if (Offset && Scale)
11804 return false;
11805
11806 // Check Reg + Imm
11807 if (!Scale) {
11808 // 9-bit signed offset
11809 if (isInt<9>(Offset))
11810 return true;
11811
11812 // 12-bit unsigned offset
11813 unsigned Shift = Log2_64(NumBytes);
11814 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
11815 // Must be a multiple of NumBytes (NumBytes is a power of 2)
11816 (Offset >> Shift) << Shift == Offset)
11817 return true;
11818 return false;
11819 }
11820
11821 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
11822 return Scale == 1 || (Scale > 0 && Scale == NumBytes);
11823}
11824
11826 if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
11827 return AArch64::BLRNoIP;
11828 else
11829 return AArch64::BLR;
11830}
11831
11833 DebugLoc DL) const {
11834 MachineBasicBlock::iterator InsertPt = MBB.getFirstTerminator();
11835 auto Builder = BuildMI(MBB, InsertPt, DL, get(AArch64::PAUTH_EPILOGUE))
11837
11838 MachineFunction &MF = *MBB.getParent();
11839 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
11840 auto &AFL = *static_cast<const AArch64FrameLowering *>(
11841 MF.getSubtarget().getFrameLowering());
11842 if (AFL.getArgumentStackToRestore(MF, MBB)) {
11843 Builder.addReg(AArch64::X17, RegState::ImplicitDefine);
11844 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11845 if (AFI->branchProtectionPAuthLR())
11846 Builder.addReg(AArch64::X15, RegState::ImplicitDefine);
11847 return;
11848 }
11849
11850 if (AFI->branchProtectionPAuthLR() && !Subtarget.hasPAuthLR())
11851 Builder.addReg(AArch64::X16, RegState::ImplicitDefine);
11852}
11853
11855AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,
11856 Register TargetReg, bool FrameSetup) const {
11857 assert(TargetReg != AArch64::SP && "New top of stack cannot already be in SP");
11858
11859 MachineBasicBlock &MBB = *MBBI->getParent();
11860 MachineFunction &MF = *MBB.getParent();
11861 const AArch64InstrInfo *TII =
11862 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
11863 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
11864 DebugLoc DL = MBB.findDebugLoc(MBBI);
11865
11866 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
11867 MachineBasicBlock *LoopTestMBB =
11868 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11869 MF.insert(MBBInsertPoint, LoopTestMBB);
11870 MachineBasicBlock *LoopBodyMBB =
11871 MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11872 MF.insert(MBBInsertPoint, LoopBodyMBB);
11873 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
11874 MF.insert(MBBInsertPoint, ExitMBB);
11875 MachineInstr::MIFlag Flags =
11877
11878 // LoopTest:
11879 // SUB SP, SP, #ProbeSize
11880 emitFrameOffset(*LoopTestMBB, LoopTestMBB->end(), DL, AArch64::SP,
11881 AArch64::SP, StackOffset::getFixed(-ProbeSize), TII, Flags);
11882
11883 // CMP SP, TargetReg
11884 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
11885 AArch64::XZR)
11886 .addReg(AArch64::SP)
11887 .addReg(TargetReg)
11889 .setMIFlags(Flags);
11890
11891 // B.<Cond> LoopExit
11892 BuildMI(*LoopTestMBB, LoopTestMBB->end(), DL, TII->get(AArch64::Bcc))
11894 .addMBB(ExitMBB)
11895 .setMIFlags(Flags);
11896
11897 // LDR XZR, [SP]
11898 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::LDRXui))
11899 .addDef(AArch64::XZR)
11900 .addReg(AArch64::SP)
11901 .addImm(0)
11905 Align(8)))
11906 .setMIFlags(Flags);
11907
11908 // B loop
11909 BuildMI(*LoopBodyMBB, LoopBodyMBB->end(), DL, TII->get(AArch64::B))
11910 .addMBB(LoopTestMBB)
11911 .setMIFlags(Flags);
11912
11913 // LoopExit:
11914 // MOV SP, TargetReg
11915 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::ADDXri), AArch64::SP)
11916 .addReg(TargetReg)
11917 .addImm(0)
11919 .setMIFlags(Flags);
11920
11921 // LDR XZR, [SP]
11922 BuildMI(*ExitMBB, ExitMBB->end(), DL, TII->get(AArch64::LDRXui))
11923 .addReg(AArch64::XZR, RegState::Define)
11924 .addReg(AArch64::SP)
11925 .addImm(0)
11926 .setMIFlags(Flags);
11927
11928 ExitMBB->splice(ExitMBB->end(), &MBB, std::next(MBBI), MBB.end());
11930
11931 LoopTestMBB->addSuccessor(ExitMBB);
11932 LoopTestMBB->addSuccessor(LoopBodyMBB);
11933 LoopBodyMBB->addSuccessor(LoopTestMBB);
11934 MBB.addSuccessor(LoopTestMBB);
11935
11936 // Update liveins.
11937 if (MF.getRegInfo().reservedRegsFrozen())
11938 fullyRecomputeLiveIns({ExitMBB, LoopBodyMBB, LoopTestMBB});
11939
11940 return ExitMBB->begin();
11941}
11942
11943namespace {
11944class AArch64PipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo {
11945 MachineFunction *MF;
11946 const TargetInstrInfo *TII;
11947 const TargetRegisterInfo *TRI;
11948 MachineRegisterInfo &MRI;
11949
11950 /// The block of the loop
11951 MachineBasicBlock *LoopBB;
11952 /// The conditional branch of the loop
11953 MachineInstr *CondBranch;
11954 /// The compare instruction for loop control
11955 MachineInstr *Comp;
11956 /// The number of the operand of the loop counter value in Comp
11957 unsigned CompCounterOprNum;
11958 /// The instruction that updates the loop counter value
11959 MachineInstr *Update;
11960 /// The number of the operand of the loop counter value in Update
11961 unsigned UpdateCounterOprNum;
11962 /// The initial value of the loop counter
11963 Register Init;
11964 /// True iff Update is a predecessor of Comp
11965 bool IsUpdatePriorComp;
11966
11967 /// The normalized condition used by createTripCountGreaterCondition()
11968 SmallVector<MachineOperand, 4> Cond;
11969
11970public:
11971 AArch64PipelinerLoopInfo(MachineBasicBlock *LoopBB, MachineInstr *CondBranch,
11972 MachineInstr *Comp, unsigned CompCounterOprNum,
11973 MachineInstr *Update, unsigned UpdateCounterOprNum,
11974 Register Init, bool IsUpdatePriorComp,
11975 const SmallVectorImpl<MachineOperand> &Cond)
11976 : MF(Comp->getParent()->getParent()),
11977 TII(MF->getSubtarget().getInstrInfo()),
11978 TRI(MF->getSubtarget().getRegisterInfo()), MRI(MF->getRegInfo()),
11979 LoopBB(LoopBB), CondBranch(CondBranch), Comp(Comp),
11980 CompCounterOprNum(CompCounterOprNum), Update(Update),
11981 UpdateCounterOprNum(UpdateCounterOprNum), Init(Init),
11982 IsUpdatePriorComp(IsUpdatePriorComp), Cond(Cond.begin(), Cond.end()) {}
11983
11984 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override {
11985 // Make the instructions for loop control be placed in stage 0.
11986 // The predecessors of Comp are considered by the caller.
11987 return MI == Comp;
11988 }
11989
11990 std::optional<bool> createTripCountGreaterCondition(
11991 int TC, MachineBasicBlock &MBB,
11992 SmallVectorImpl<MachineOperand> &CondParam) override {
11993 // A branch instruction will be inserted as "if (Cond) goto epilogue".
11994 // Cond is normalized for such use.
11995 // The predecessors of the branch are assumed to have already been inserted.
11996 CondParam = Cond;
11997 return {};
11998 }
11999
12000 void createRemainingIterationsGreaterCondition(
12001 int TC, MachineBasicBlock &MBB, SmallVectorImpl<MachineOperand> &Cond,
12002 DenseMap<MachineInstr *, MachineInstr *> &LastStage0Insts) override;
12003
12004 void setPreheader(MachineBasicBlock *NewPreheader) override {}
12005
12006 void adjustTripCount(int TripCountAdjust) override {}
12007
12008 bool isMVEExpanderSupported() override { return true; }
12009};
12010} // namespace
12011
12012/// Clone an instruction from MI. The register of ReplaceOprNum-th operand
12013/// is replaced by ReplaceReg. The output register is newly created.
12014/// The other operands are unchanged from MI.
12015static Register cloneInstr(const MachineInstr *MI, unsigned ReplaceOprNum,
12016 Register ReplaceReg, MachineBasicBlock &MBB,
12017 MachineBasicBlock::iterator InsertTo) {
12018 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
12019 const TargetInstrInfo *TII = MBB.getParent()->getSubtarget().getInstrInfo();
12020 MachineInstr *NewMI = MBB.getParent()->CloneMachineInstr(MI);
12021 Register Result = 0;
12022 for (unsigned I = 0; I < NewMI->getNumOperands(); ++I) {
12023 if (I == 0 && NewMI->getOperand(0).getReg().isVirtual()) {
12024 Result = MRI.createVirtualRegister(
12025 MRI.getRegClass(NewMI->getOperand(0).getReg()));
12026 NewMI->getOperand(I).setReg(Result);
12027 } else if (I == ReplaceOprNum) {
12028 MRI.constrainRegClass(ReplaceReg, TII->getRegClass(NewMI->getDesc(), I));
12029 NewMI->getOperand(I).setReg(ReplaceReg);
12030 }
12031 }
12032 MBB.insert(InsertTo, NewMI);
12033 return Result;
12034}
12035
12036void AArch64PipelinerLoopInfo::createRemainingIterationsGreaterCondition(
12039 // Create and accumulate conditions for next TC iterations.
12040 // Example:
12041 // SUBSXrr N, counter, implicit-def $nzcv # compare instruction for the last
12042 // # iteration of the kernel
12043 //
12044 // # insert the following instructions
12045 // cond = CSINCXr 0, 0, C, implicit $nzcv
12046 // counter = ADDXri counter, 1 # clone from this->Update
12047 // SUBSXrr n, counter, implicit-def $nzcv # clone from this->Comp
12048 // cond = CSINCXr cond, cond, C, implicit $nzcv
12049 // ... (repeat TC times)
12050 // SUBSXri cond, 0, implicit-def $nzcv
12051
12052 assert(CondBranch->getOpcode() == AArch64::Bcc);
12053 // CondCode to exit the loop
12055 (AArch64CC::CondCode)CondBranch->getOperand(0).getImm();
12056 if (CondBranch->getOperand(1).getMBB() == LoopBB)
12058
12059 // Accumulate conditions to exit the loop
12060 Register AccCond = AArch64::XZR;
12061
12062 // If CC holds, CurCond+1 is returned; otherwise CurCond is returned.
12063 auto AccumulateCond = [&](Register CurCond,
12065 Register NewCond = MRI.createVirtualRegister(&AArch64::GPR64commonRegClass);
12066 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::CSINCXr))
12067 .addReg(NewCond, RegState::Define)
12068 .addReg(CurCond)
12069 .addReg(CurCond)
12071 return NewCond;
12072 };
12073
12074 if (!LastStage0Insts.empty() && LastStage0Insts[Comp]->getParent() == &MBB) {
12075 // Update and Comp for I==0 are already exists in MBB
12076 // (MBB is an unrolled kernel)
12077 Register Counter;
12078 for (int I = 0; I <= TC; ++I) {
12079 Register NextCounter;
12080 if (I != 0)
12081 NextCounter =
12082 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12083
12084 AccCond = AccumulateCond(AccCond, CC);
12085
12086 if (I != TC) {
12087 if (I == 0) {
12088 if (Update != Comp && IsUpdatePriorComp) {
12089 Counter =
12090 LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12091 NextCounter = cloneInstr(Update, UpdateCounterOprNum, Counter, MBB,
12092 MBB.end());
12093 } else {
12094 // can use already calculated value
12095 NextCounter = LastStage0Insts[Update]->getOperand(0).getReg();
12096 }
12097 } else if (Update != Comp) {
12098 NextCounter =
12099 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12100 }
12101 }
12102 Counter = NextCounter;
12103 }
12104 } else {
12105 Register Counter;
12106 if (LastStage0Insts.empty()) {
12107 // use initial counter value (testing if the trip count is sufficient to
12108 // be executed by pipelined code)
12109 Counter = Init;
12110 if (IsUpdatePriorComp)
12111 Counter =
12112 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12113 } else {
12114 // MBB is an epilogue block. LastStage0Insts[Comp] is in the kernel block.
12115 Counter = LastStage0Insts[Comp]->getOperand(CompCounterOprNum).getReg();
12116 }
12117
12118 for (int I = 0; I <= TC; ++I) {
12119 Register NextCounter;
12120 NextCounter =
12121 cloneInstr(Comp, CompCounterOprNum, Counter, MBB, MBB.end());
12122 AccCond = AccumulateCond(AccCond, CC);
12123 if (I != TC && Update != Comp)
12124 NextCounter =
12125 cloneInstr(Update, UpdateCounterOprNum, Counter, MBB, MBB.end());
12126 Counter = NextCounter;
12127 }
12128 }
12129
12130 // If AccCond == 0, the remainder is greater than TC.
12131 BuildMI(MBB, MBB.end(), Comp->getDebugLoc(), TII->get(AArch64::SUBSXri))
12132 .addReg(AArch64::XZR, RegState::Define | RegState::Dead)
12133 .addReg(AccCond)
12134 .addImm(0)
12135 .addImm(0);
12136 Cond.clear();
12138}
12139
12140static void extractPhiReg(const MachineInstr &Phi, const MachineBasicBlock *MBB,
12141 Register &RegMBB, Register &RegOther) {
12142 assert(Phi.getNumOperands() == 5);
12143 if (Phi.getOperand(2).getMBB() == MBB) {
12144 RegMBB = Phi.getOperand(1).getReg();
12145 RegOther = Phi.getOperand(3).getReg();
12146 } else {
12147 assert(Phi.getOperand(4).getMBB() == MBB);
12148 RegMBB = Phi.getOperand(3).getReg();
12149 RegOther = Phi.getOperand(1).getReg();
12150 }
12151}
12152
12154 if (!Reg.isVirtual())
12155 return false;
12156 const MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
12157 return MRI.getDefBlock(Reg) != BB;
12158}
12159
12160/// If Reg is an induction variable, return true and set some parameters
12161static bool getIndVarInfo(Register Reg, const MachineBasicBlock *LoopBB,
12162 MachineInstr *&UpdateInst,
12163 unsigned &UpdateCounterOprNum, Register &InitReg,
12164 bool &IsUpdatePriorComp) {
12165 // Example:
12166 //
12167 // Preheader:
12168 // InitReg = ...
12169 // LoopBB:
12170 // Reg0 = PHI (InitReg, Preheader), (Reg1, LoopBB)
12171 // Reg = COPY Reg0 ; COPY is ignored.
12172 // Reg1 = ADD Reg, #1; UpdateInst. Incremented by a loop invariant value.
12173 // ; Reg is the value calculated in the previous
12174 // ; iteration, so IsUpdatePriorComp == false.
12175
12176 if (LoopBB->pred_size() != 2)
12177 return false;
12178 if (!Reg.isVirtual())
12179 return false;
12180 const MachineRegisterInfo &MRI = LoopBB->getParent()->getRegInfo();
12181 UpdateInst = nullptr;
12182 UpdateCounterOprNum = 0;
12183 InitReg = 0;
12184 IsUpdatePriorComp = true;
12185 Register CurReg = Reg;
12186 while (true) {
12187 MachineInstr *Def = MRI.getVRegDef(CurReg);
12188 if (Def->getParent() != LoopBB)
12189 return false;
12190 if (Def->isCopy()) {
12191 // Ignore copy instructions unless they contain subregisters
12192 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
12193 return false;
12194 CurReg = Def->getOperand(1).getReg();
12195 } else if (Def->isPHI()) {
12196 if (InitReg != 0)
12197 return false;
12198 if (!UpdateInst)
12199 IsUpdatePriorComp = false;
12200 extractPhiReg(*Def, LoopBB, CurReg, InitReg);
12201 } else {
12202 if (UpdateInst)
12203 return false;
12204 switch (Def->getOpcode()) {
12205 case AArch64::ADDSXri:
12206 case AArch64::ADDSWri:
12207 case AArch64::SUBSXri:
12208 case AArch64::SUBSWri:
12209 case AArch64::ADDXri:
12210 case AArch64::ADDWri:
12211 case AArch64::SUBXri:
12212 case AArch64::SUBWri:
12213 UpdateInst = Def;
12214 UpdateCounterOprNum = 1;
12215 break;
12216 case AArch64::ADDSXrr:
12217 case AArch64::ADDSWrr:
12218 case AArch64::SUBSXrr:
12219 case AArch64::SUBSWrr:
12220 case AArch64::ADDXrr:
12221 case AArch64::ADDWrr:
12222 case AArch64::SUBXrr:
12223 case AArch64::SUBWrr:
12224 UpdateInst = Def;
12225 if (isDefinedOutside(Def->getOperand(2).getReg(), LoopBB))
12226 UpdateCounterOprNum = 1;
12227 else if (isDefinedOutside(Def->getOperand(1).getReg(), LoopBB))
12228 UpdateCounterOprNum = 2;
12229 else
12230 return false;
12231 break;
12232 default:
12233 return false;
12234 }
12235 CurReg = Def->getOperand(UpdateCounterOprNum).getReg();
12236 }
12237
12238 if (!CurReg.isVirtual())
12239 return false;
12240 if (Reg == CurReg)
12241 break;
12242 }
12243
12244 if (!UpdateInst)
12245 return false;
12246
12247 return true;
12248}
12249
12250std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo>
12252 // Accept loops that meet the following conditions
12253 // * The conditional branch is BCC
12254 // * The compare instruction is ADDS/SUBS/WHILEXX
12255 // * One operand of the compare is an induction variable and the other is a
12256 // loop invariant value
12257 // * The induction variable is incremented/decremented by a single instruction
12258 // * Does not contain CALL or instructions which have unmodeled side effects
12259
12260 for (MachineInstr &MI : *LoopBB)
12261 if (MI.isCall() || MI.hasUnmodeledSideEffects())
12262 // This instruction may use NZCV, which interferes with the instruction to
12263 // be inserted for loop control.
12264 return nullptr;
12265
12266 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
12268 if (analyzeBranch(*LoopBB, TBB, FBB, Cond))
12269 return nullptr;
12270
12271 // Infinite loops are not supported
12272 if (TBB == LoopBB && FBB == LoopBB)
12273 return nullptr;
12274
12275 // Must be conditional branch
12276 if (TBB != LoopBB && FBB == nullptr)
12277 return nullptr;
12278
12279 assert((TBB == LoopBB || FBB == LoopBB) &&
12280 "The Loop must be a single-basic-block loop");
12281
12282 MachineInstr *CondBranch = &*LoopBB->getFirstTerminator();
12284
12285 if (CondBranch->getOpcode() != AArch64::Bcc)
12286 return nullptr;
12287
12288 // Normalization for createTripCountGreaterCondition()
12289 if (TBB == LoopBB)
12291
12292 MachineInstr *Comp = nullptr;
12293 unsigned CompCounterOprNum = 0;
12294 for (MachineInstr &MI : reverse(*LoopBB)) {
12295 if (MI.modifiesRegister(AArch64::NZCV, &TRI)) {
12296 // Guarantee that the compare is SUBS/ADDS/WHILEXX and that one of the
12297 // operands is a loop invariant value
12298
12299 switch (MI.getOpcode()) {
12300 case AArch64::SUBSXri:
12301 case AArch64::SUBSWri:
12302 case AArch64::ADDSXri:
12303 case AArch64::ADDSWri:
12304 Comp = &MI;
12305 CompCounterOprNum = 1;
12306 break;
12307 case AArch64::ADDSWrr:
12308 case AArch64::ADDSXrr:
12309 case AArch64::SUBSWrr:
12310 case AArch64::SUBSXrr:
12311 Comp = &MI;
12312 break;
12313 default:
12314 if (isWhileOpcode(MI.getOpcode())) {
12315 Comp = &MI;
12316 break;
12317 }
12318 return nullptr;
12319 }
12320
12321 if (CompCounterOprNum == 0) {
12322 if (isDefinedOutside(Comp->getOperand(1).getReg(), LoopBB))
12323 CompCounterOprNum = 2;
12324 else if (isDefinedOutside(Comp->getOperand(2).getReg(), LoopBB))
12325 CompCounterOprNum = 1;
12326 else
12327 return nullptr;
12328 }
12329 break;
12330 }
12331 }
12332 if (!Comp)
12333 return nullptr;
12334
12335 MachineInstr *Update = nullptr;
12336 Register Init;
12337 bool IsUpdatePriorComp;
12338 unsigned UpdateCounterOprNum;
12339 if (!getIndVarInfo(Comp->getOperand(CompCounterOprNum).getReg(), LoopBB,
12340 Update, UpdateCounterOprNum, Init, IsUpdatePriorComp))
12341 return nullptr;
12342
12343 return std::make_unique<AArch64PipelinerLoopInfo>(
12344 LoopBB, CondBranch, Comp, CompCounterOprNum, Update, UpdateCounterOprNum,
12345 Init, IsUpdatePriorComp, Cond);
12346}
12347
12348/// verifyInstruction - Perform target specific instruction verification.
12349bool AArch64InstrInfo::verifyInstruction(const MachineInstr &MI,
12350 StringRef &ErrInfo) const {
12351 // Verify that immediate offsets on load/store instructions are within range.
12352 // Stack objects with an FI operand are excluded as they can be fixed up
12353 // during PEI.
12354 TypeSize Scale(0U, false), Width(0U, false);
12355 int64_t MinOffset, MaxOffset;
12356 if (getMemOpInfo(MI.getOpcode(), Scale, Width, MinOffset, MaxOffset)) {
12357 unsigned ImmIdx = getLoadStoreImmIdx(MI.getOpcode());
12358 if (MI.getOperand(ImmIdx).isImm() && !MI.getOperand(ImmIdx - 1).isFI()) {
12359 int64_t Imm = MI.getOperand(ImmIdx).getImm();
12360 if (Imm < MinOffset || Imm > MaxOffset) {
12361 ErrInfo = "Unexpected immediate on load/store instruction";
12362 return false;
12363 }
12364 }
12365 }
12366
12367 const MCInstrDesc &MCID = MI.getDesc();
12368 for (unsigned Op = 0; Op < MCID.getNumOperands(); Op++) {
12369 const MachineOperand &MO = MI.getOperand(Op);
12370 switch (MCID.operands()[Op].OperandType) {
12372 if (!MO.isImm() || MO.getImm() != 0) {
12373 ErrInfo = "OPERAND_IMPLICIT_IMM_0 should be 0";
12374 return false;
12375 }
12376 break;
12378 if (!MO.isImm() ||
12380 (AArch64_AM::getShiftValue(MO.getImm()) != 8 &&
12381 AArch64_AM::getShiftValue(MO.getImm()) != 16)) {
12382 ErrInfo = "OPERAND_SHIFT_MSL should be msl shift of 8 or 16";
12383 return false;
12384 }
12385 break;
12387 if (!MO.isImm() || (MO.getImm() != 0 && MO.getImm() != 1)) {
12388 ErrInfo = "OPERAND_IMM_UINT1 should be 0 or 1";
12389 return false;
12390 }
12391 break;
12393 if (!MO.isImm() || MO.getImm() <= 0 || MO.getImm() > 16) {
12394 ErrInfo = "OPERAND_IMM_UINT4plus1 should be in the range 1 to 16";
12395 return false;
12396 }
12397 break;
12399 if (!MO.isImm() || !isUInt<5>(MO.getImm())) {
12400 ErrInfo = "OPERAND_IMM_UINT5 should be in the range 0 to 31";
12401 return false;
12402 }
12403 break;
12405 if (!MO.isImm() || !isUInt<8>(MO.getImm())) {
12406 ErrInfo = "OPERAND_IMM_UINT8 should be in the range 0 to 255";
12407 return false;
12408 }
12409 break;
12410 default:
12411 break;
12412 }
12413 }
12414 return true;
12415}
12416
12417#define GET_INSTRINFO_HELPERS
12418#define GET_INSTRMAP_INFO
12419#include "AArch64GenInstrInfo.inc"
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
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 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 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 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 bool UpdateOperandRegClass(MachineInstr &Instr)
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 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)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
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
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
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:484
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
bool canInsertSelect(const MachineBasicBlock &, ArrayRef< MachineOperand > Cond, Register, Register, Register, int &, int &, int &) 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.
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,...
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:43
A debug info location.
Definition DebugLoc.h:126
bool empty() const
Definition DenseMap.h:717
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:828
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.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-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.
bool isCopy() const
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 registerDefIsDead(Register Reg, const TargetRegisterInfo *TRI) const
Returns true if the register is dead in this machine instruction.
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.
LLVM_ABI void addRegisterDefined(Register Reg, const TargetRegisterInfo *RegInfo=nullptr)
We have determined MI defines a register.
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.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
bool use_nodbg_empty(Register RegNo) const
use_nodbg_empty - Return true if there are no non-Debug instructions using the specified register.
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
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
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:30
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:46
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:49
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
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 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:339
static constexpr TypeSize getScalable(ScalarTy MinimumSize)
Definition TypeSize.h:342
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:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
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.
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.
bool succeeded(LogicalResult Result)
Utility function that returns true if the provided LogicalResult corresponds to a success value.
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:227
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:567
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:267
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.