LLVM 24.0.0git
AArch64FrameLowering.cpp
Go to the documentation of this file.
1//===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====//
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 TargetFrameLowering class.
10//
11// On AArch64, stack frames are structured as follows:
12//
13// The stack grows downward.
14//
15// All of the individual frame areas on the frame below are optional, i.e. it's
16// possible to create a function so that the particular area isn't present
17// in the frame.
18//
19// At function entry, the "frame" looks as follows:
20//
21// | | Higher address
22// |-----------------------------------|
23// | |
24// | arguments passed on the stack |
25// | |
26// |-----------------------------------| <- sp
27// | | Lower address
28//
29//
30// After the prologue has run, the frame has the following general structure.
31// Note that this doesn't depict the case where a red-zone is used. Also,
32// technically the last frame area (VLAs) doesn't get created until in the
33// main function body, after the prologue is run. However, it's depicted here
34// for completeness.
35//
36// | | Higher address
37// |-----------------------------------|
38// | |
39// | arguments passed on the stack |
40// | |
41// |-----------------------------------|
42// | |
43// | (Win64 only) varargs from reg |
44// | |
45// |-----------------------------------|
46// | |
47// | (Win64 only) callee-saved SVE reg |
48// | |
49// |-----------------------------------|
50// | |
51// | callee-saved gpr registers | <--.
52// | | | On Darwin platforms these
53// |- - - - - - - - - - - - - - - - - -| | callee saves are swapped,
54// | prev_lr | | (frame record first)
55// | prev_fp | <--'
56// | async context if needed |
57// | (a.k.a. "frame record") |
58// |-----------------------------------| <- fp(=x29)
59// Default SVE stack layout Split SVE objects
60// (aarch64-split-sve-objects=false) (aarch64-split-sve-objects=true)
61// |-----------------------------------| |-----------------------------------|
62// | <hazard padding> | | callee-saved PPR registers |
63// |-----------------------------------| |-----------------------------------|
64// | | | PPR stack objects |
65// | callee-saved fp/simd/SVE regs | |-----------------------------------|
66// | | | <hazard padding> |
67// |-----------------------------------| |-----------------------------------|
68// | | | callee-saved ZPR/FPR registers |
69// | SVE stack objects | |-----------------------------------|
70// | | | ZPR stack objects |
71// |-----------------------------------| |-----------------------------------|
72// ^ NB: FPR CSRs are promoted to ZPRs
73// |-----------------------------------|
74// |.empty.space.to.make.part.below....|
75// |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
76// |.the.standard.16-byte.alignment....| compile time; if present)
77// |-----------------------------------|
78// | local variables of fixed size |
79// | including spill slots |
80// | <FPR> |
81// | <hazard padding> |
82// | <GPR> |
83// |-----------------------------------| <- bp(not defined by ABI,
84// |.variable-sized.local.variables....| LLVM chooses X19)
85// |.(VLAs)............................| (size of this area is unknown at
86// |...................................| compile time)
87// |-----------------------------------| <- sp
88// | | Lower address
89//
90//
91// To access the data in a frame, at-compile time, a constant offset must be
92// computable from one of the pointers (fp, bp, sp) to access it. The size
93// of the areas with a dotted background cannot be computed at compile-time
94// if they are present, making it required to have all three of fp, bp and
95// sp to be set up to be able to access all contents in the frame areas,
96// assuming all of the frame areas are non-empty.
97//
98// For most functions, some of the frame areas are empty. For those functions,
99// it may not be necessary to set up fp or bp:
100// * A base pointer is definitely needed when there are both VLAs and local
101// variables with more-than-default alignment requirements.
102// * A frame pointer is definitely needed when there are local variables with
103// more-than-default alignment requirements.
104//
105// For Darwin platforms the frame-record (fp, lr) is stored at the top of the
106// callee-saved area, since the unwind encoding does not allow for encoding
107// this dynamically and existing tools depend on this layout. For other
108// platforms, the frame-record is stored at the bottom of the (gpr) callee-saved
109// area to allow SVE stack objects (allocated directly below the callee-saves,
110// if available) to be accessed directly from the framepointer.
111// The SVE spill/fill instructions have VL-scaled addressing modes such
112// as:
113// ldr z8, [fp, #-7 mul vl]
114// For SVE the size of the vector length (VL) is not known at compile-time, so
115// '#-7 mul vl' is an offset that can only be evaluated at runtime. With this
116// layout, we don't need to add an unscaled offset to the framepointer before
117// accessing the SVE object in the frame.
118//
119// In some cases when a base pointer is not strictly needed, it is generated
120// anyway when offsets from the frame pointer to access local variables become
121// so large that the offset can't be encoded in the immediate fields of loads
122// or stores.
123//
124// Outgoing function arguments must be at the bottom of the stack frame when
125// calling another function. If we do not have variable-sized stack objects, we
126// can allocate a "reserved call frame" area at the bottom of the local
127// variable area, large enough for all outgoing calls. If we do have VLAs, then
128// the stack pointer must be decremented and incremented around each call to
129// make space for the arguments below the VLAs.
130//
131// FIXME: also explain the redzone concept.
132//
133// About stack hazards: Under some SME contexts, a coprocessor with its own
134// separate cache can used for FP operations. This can create hazards if the CPU
135// and the SME unit try to access the same area of memory, including if the
136// access is to an area of the stack. To try to alleviate this we attempt to
137// introduce extra padding into the stack frame between FP and GPR accesses,
138// controlled by the aarch64-stack-hazard-size option. Without changing the
139// layout of the stack frame in the diagram above, a stack object of size
140// aarch64-stack-hazard-size is added between GPR and FPR CSRs. Another is added
141// to the stack objects section, and stack objects are sorted so that FPR >
142// Hazard padding slot > GPRs (where possible). Unfortunately some things are
143// not handled well (VLA area, arguments on the stack, objects with both GPR and
144// FPR accesses), but if those are controlled by the user then the entire stack
145// frame becomes GPR at the start/end with FPR in the middle, surrounded by
146// Hazard padding.
147//
148// An example of the prologue:
149//
150// .globl __foo
151// .align 2
152// __foo:
153// Ltmp0:
154// .cfi_startproc
155// .cfi_personality 155, ___gxx_personality_v0
156// Leh_func_begin:
157// .cfi_lsda 16, Lexception33
158//
159// stp xa,bx, [sp, -#offset]!
160// ...
161// stp x28, x27, [sp, #offset-32]
162// stp fp, lr, [sp, #offset-16]
163// add fp, sp, #offset - 16
164// sub sp, sp, #1360
165//
166// The Stack:
167// +-------------------------------------------+
168// 10000 | ........ | ........ | ........ | ........ |
169// 10004 | ........ | ........ | ........ | ........ |
170// +-------------------------------------------+
171// 10008 | ........ | ........ | ........ | ........ |
172// 1000c | ........ | ........ | ........ | ........ |
173// +===========================================+
174// 10010 | X28 Register |
175// 10014 | X28 Register |
176// +-------------------------------------------+
177// 10018 | X27 Register |
178// 1001c | X27 Register |
179// +===========================================+
180// 10020 | Frame Pointer |
181// 10024 | Frame Pointer |
182// +-------------------------------------------+
183// 10028 | Link Register |
184// 1002c | Link Register |
185// +===========================================+
186// 10030 | ........ | ........ | ........ | ........ |
187// 10034 | ........ | ........ | ........ | ........ |
188// +-------------------------------------------+
189// 10038 | ........ | ........ | ........ | ........ |
190// 1003c | ........ | ........ | ........ | ........ |
191// +-------------------------------------------+
192//
193// [sp] = 10030 :: >>initial value<<
194// sp = 10020 :: stp fp, lr, [sp, #-16]!
195// fp = sp == 10020 :: mov fp, sp
196// [sp] == 10020 :: stp x28, x27, [sp, #-16]!
197// sp == 10010 :: >>final value<<
198//
199// The frame pointer (w29) points to address 10020. If we use an offset of
200// '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24
201// for w27, and -32 for w28:
202//
203// Ltmp1:
204// .cfi_def_cfa w29, 16
205// Ltmp2:
206// .cfi_offset w30, -8
207// Ltmp3:
208// .cfi_offset w29, -16
209// Ltmp4:
210// .cfi_offset w27, -24
211// Ltmp5:
212// .cfi_offset w28, -32
213//
214//===----------------------------------------------------------------------===//
215
216#include "AArch64FrameLowering.h"
217#include "AArch64InstrInfo.h"
220#include "AArch64RegisterInfo.h"
221#include "AArch64SMEAttributes.h"
222#include "AArch64Subtarget.h"
225#include "llvm/ADT/ScopeExit.h"
226#include "llvm/ADT/SmallVector.h"
244#include "llvm/IR/Attributes.h"
245#include "llvm/IR/CallingConv.h"
246#include "llvm/IR/DataLayout.h"
247#include "llvm/IR/DebugLoc.h"
248#include "llvm/IR/Function.h"
249#include "llvm/IR/Module.h"
250#include "llvm/MC/MCAsmInfo.h"
251#include "llvm/MC/MCDwarf.h"
252#include "llvm/Support/Debug.h"
258#include <cassert>
259#include <cstdint>
260#include <iterator>
261#include <optional>
262#include <vector>
263
264using namespace llvm;
265
266#define DEBUG_TYPE "frame-info"
267
268int64_t
270 MachineBasicBlock &MBB) const {
271 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
273 bool IsTailCallReturn = (MBB.end() != MBBI)
275 : false;
276
277 int64_t ArgumentPopSize = 0;
278 if (IsTailCallReturn) {
279 MachineOperand &StackAdjust = MBBI->getOperand(1);
280
281 // For a tail-call in a callee-pops-arguments environment, some or all of
282 // the stack may actually be in use for the call's arguments, this is
283 // calculated during LowerCall and consumed here...
284 ArgumentPopSize = StackAdjust.getImm();
285 } else {
286 // ... otherwise the amount to pop is *all* of the argument space,
287 // conveniently stored in the MachineFunctionInfo by
288 // LowerFormalArguments. This will, of course, be zero for the C calling
289 // convention.
290 ArgumentPopSize = AFI->getArgumentStackToRestore();
291 }
292
293 return ArgumentPopSize;
294}
295
298 if (!MF.needsWinCFI() ||
300 return false;
301
302 // Funclets don't tail call, and are not what the unwind info is about.
303 MachineBasicBlock::iterator LastI = MBB.getLastNonDebugInstr();
304 if (LastI != MBB.end() && (LastI->getOpcode() == AArch64::CATCHRET ||
305 LastI->getOpcode() == AArch64::CLEANUPRET))
306 return false;
307
308 return getArgumentStackToRestore(MF, MBB) != 0;
309}
310
312 MachineFunction &MF);
313
314enum class AssignObjectOffsets { No, Yes };
315/// Process all the SVE stack objects and the SVE stack size and offsets for
316/// each object. If AssignOffsets is "Yes", the offsets get assigned (and SVE
317/// stack sizes set). Returns the size of the SVE stack.
319 AssignObjectOffsets AssignOffsets);
320
321static unsigned getStackHazardSize(const MachineFunction &MF) {
322 return MF.getSubtarget<AArch64Subtarget>().getStreamingHazardSize();
323}
324
330
333 // With split SVE objects, the hazard padding is added to the PPR region,
334 // which places it between the [GPR, PPR] area and the [ZPR, FPR] area. This
335 // avoids hazards between both GPRs and FPRs and ZPRs and PPRs.
338 : 0,
339 AFI->getStackSizePPR());
340}
341
342// Conservatively, returns true if the function is likely to have SVE vectors
343// on the stack. This function is safe to be called before callee-saves or
344// object offsets have been determined.
346 const MachineFunction &MF) {
347 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
348 if (AFI->isSVECC())
349 return true;
350
351 if (AFI->hasCalculatedStackSizeSVE())
352 return bool(AFL.getSVEStackSize(MF));
353
354 const MachineFrameInfo &MFI = MF.getFrameInfo();
355 for (int FI = MFI.getObjectIndexBegin(); FI < MFI.getObjectIndexEnd(); FI++) {
356 if (MFI.hasScalableStackID(FI))
357 return true;
358 }
359
360 return false;
361}
362
363static bool isTargetWindows(const MachineFunction &MF) {
364 // Note: UEFI follows the Windows ARM64 ABI and uses Windows CFI. The value
365 // returned here must align with the predicate used for returning the list of
366 // callee saved regs in AArch64RegisterInfo::getCalleeSavedRegs(), so that we
367 // use invalidateWindowsRegisterPairing() where appropriate.
368 return MF.getSubtarget<AArch64Subtarget>().isTargetWindowsOrUEFI();
369}
370
372 const MachineFunction &MF) const {
373 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
374 return isTargetWindows(MF) && AFI->getSVECalleeSavedStackSize();
375}
376
377/// Returns true if a homogeneous prolog or epilog code can be emitted
378/// for the size optimization. If possible, a frame helper call is injected.
379/// When Exit block is given, this check is for epilog.
380bool AArch64FrameLowering::homogeneousPrologEpilog(
381 MachineFunction &MF, MachineBasicBlock *Exit) const {
382 if (!MF.getFunction().hasMinSize())
383 return false;
384 const AArch64Options &CLOpts =
385 MF.getSubtarget<AArch64Subtarget>().getCLOpts();
386 if (!CLOpts.homogeneous_prolog_epilog)
387 return false;
388 if (CLOpts.redzone)
389 return false;
390
391 // TODO: Window is supported yet.
392 if (isTargetWindows(MF))
393 return false;
394
395 // TODO: SVE is not supported yet.
396 if (isLikelyToHaveSVEStack(*this, MF))
397 return false;
398
399 // Bail on stack adjustment needed on return for simplicity.
400 const MachineFrameInfo &MFI = MF.getFrameInfo();
401 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
402 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))
403 return false;
404 if (Exit && getArgumentStackToRestore(MF, *Exit))
405 return false;
406
407 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
408 if (AFI->hasSwiftAsyncContext() || AFI->hasStreamingModeChanges())
409 return false;
410
411 // If there are an odd number of GPRs before LR and FP in the CSRs list,
412 // they will not be paired into one RegGroupInfo, which is incompatible with
413 // the assumption made by the homogeneous prolog epilog pass.
414 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
415 unsigned NumGPRs = 0;
416 for (unsigned I = 0; CSRegs[I]; ++I) {
417 Register Reg = CSRegs[I];
418 if (Reg == AArch64::LR) {
419 assert(CSRegs[I + 1] == AArch64::FP);
420 if (NumGPRs % 2 != 0)
421 return false;
422 break;
423 }
424 if (AArch64::GPR64RegClass.contains(Reg))
425 ++NumGPRs;
426 }
427
428 return true;
429}
430
431/// Returns true if CSRs should be paired.
432bool AArch64FrameLowering::producePairRegisters(MachineFunction &MF) const {
433 return produceCompactUnwindFrame(*this, MF) || homogeneousPrologEpilog(MF);
434}
435
436/// This is the biggest offset to the stack pointer we can encode in aarch64
437/// instructions (without using a separate calculation and a temp register).
438/// Note that the exception here are vector stores/loads which cannot encode any
439/// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()).
440static const unsigned DefaultSafeSPDisplacement = 255;
441
442/// Look at each instruction that references stack frames and return the stack
443/// size limit beyond which some of these instructions will require a scratch
444/// register during their expansion later.
446 // FIXME: For now, just conservatively guesstimate based on unscaled indexing
447 // range. We'll end up allocating an unnecessary spill slot a lot, but
448 // realistically that's not a big deal at this stage of the game.
449 for (MachineBasicBlock &MBB : MF) {
450 for (MachineInstr &MI : MBB) {
451 if (MI.isDebugInstr() || MI.isPseudo() ||
452 MI.getOpcode() == AArch64::ADDXri ||
453 MI.getOpcode() == AArch64::ADDSXri)
454 continue;
455
456 for (const MachineOperand &MO : MI.operands()) {
457 if (!MO.isFI())
458 continue;
459
461 if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) ==
463 return 0;
464 }
465 }
466 }
468}
469
474
475unsigned
476AArch64FrameLowering::getFixedObjectSize(const MachineFunction &MF,
477 const AArch64FunctionInfo *AFI,
478 bool IsWin64, bool IsFunclet) const {
479 assert(AFI->getTailCallReservedStack() % 16 == 0 &&
480 "Tail call reserved stack must be aligned to 16 bytes");
481 if (!IsWin64) {
482 return AFI->getTailCallReservedStack();
483 } else if (IsFunclet) {
484 // A funclet has its own frame; the tail call reserve belongs to the parent
485 // function's incoming argument area.
486 return 0;
487 } else {
488 unsigned FixedObjectSize = AFI->getTailCallReservedStack();
489
490 // Var args are stored here in the primary function.
491 FixedObjectSize += AFI->getVarArgsGPRSize();
492
493 if (MF.hasEHFunclets()) {
494 // Catch objects are stored here in the primary function.
495 const MachineFrameInfo &MFI = MF.getFrameInfo();
496 const WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
497 SmallSetVector<int, 8> CatchObjFrameIndices;
498 for (const WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
499 for (const WinEHHandlerType &H : TBME.HandlerArray) {
500 int FrameIndex = H.CatchObj.FrameIndex;
501 if ((FrameIndex != INT_MAX) &&
502 CatchObjFrameIndices.insert(FrameIndex)) {
503 FixedObjectSize = alignTo(FixedObjectSize,
504 MFI.getObjectAlign(FrameIndex).value()) +
505 MFI.getObjectSize(FrameIndex);
506 }
507 }
508 }
509 // To support EH funclets we allocate an UnwindHelp object
510 FixedObjectSize += 8;
511 }
512 return alignTo(FixedObjectSize, 16);
513 }
514}
515
517 if (!MF.getSubtarget<AArch64Subtarget>().getCLOpts().redzone)
518 return false;
519
520 // Don't use the red zone if the function explicitly asks us not to.
521 // This is typically used for kernel code.
523 const unsigned RedZoneSize =
524 Subtarget.getTargetLowering()->getRedZoneSize(MF.getFunction());
525 if (!RedZoneSize)
526 return false;
527
528 const MachineFrameInfo &MFI = MF.getFrameInfo();
530 uint64_t NumBytes = AFI->getLocalStackSize();
531
532 // If neither NEON or SVE are available, a COPY from one Q-reg to
533 // another requires a spill -> reload sequence. We can do that
534 // using a pre-decrementing store/post-decrementing load, but
535 // if we do so, we can't use the Red Zone.
536 bool LowerQRegCopyThroughMem = Subtarget.hasFPARMv8() &&
537 !Subtarget.isNeonAvailable() &&
538 !Subtarget.hasSVE();
539
540 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > RedZoneSize ||
541 AFI->hasSVEStackSize() || LowerQRegCopyThroughMem);
542}
543
544/// hasFPImpl - Return true if the specified function should have a dedicated
545/// frame pointer register.
547 const MachineFrameInfo &MFI = MF.getFrameInfo();
548 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
550
551 // Win64 EH requires a frame pointer if funclets are present, as the locals
552 // are accessed off the frame pointer in both the parent function and the
553 // funclets.
554 if (MF.hasEHFunclets())
555 return true;
556
557 // Unwinding out of a callee that pops stack arguments we reserved in our
558 // prologue leaves SP higher than our unwind info expects, so on Windows we
559 // must be found via the frame pointer instead.
561 return true;
562
563 // When the stack guard is mixed with the frame pointer, a dedicated FP is
564 // required so the guard value remains stable in the presence of dynamic
565 // stack allocations (e.g. _alloca on MSVCRT).
566 if (MFI.hasStackProtectorIndex()) {
567 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
568 if (Subtarget.getTargetLowering()->useStackGuardMixFP())
569 return true;
570 }
571
572 // Retain behavior of always omitting the FP for leaf functions when possible.
574 return true;
575 if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
576 MFI.hasStackMap() || MFI.hasPatchPoint() ||
577 RegInfo->hasStackRealignment(MF))
578 return true;
579
580 // If we:
581 //
582 // 1. Have streaming mode changes
583 // OR:
584 // 2. Have a streaming body with SVE stack objects
585 //
586 // Then the value of VG restored when unwinding to this function may not match
587 // the value of VG used to set up the stack.
588 //
589 // This is a problem as the CFA can be described with an expression of the
590 // form: CFA = SP + NumBytes + VG * NumScalableBytes.
591 //
592 // If the value of VG used in that expression does not match the value used to
593 // set up the stack, an incorrect address for the CFA will be computed, and
594 // unwinding will fail.
595 //
596 // We work around this issue by ensuring the frame-pointer can describe the
597 // CFA in either of these cases.
598 if (AFI.needsDwarfUnwindInfo(MF) &&
601 return true;
602 // With large callframes around we may need to use FP to access the scavenging
603 // emergency spillslot.
604 //
605 // Unfortunately some calls to hasFP() like machine verifier ->
606 // getReservedReg() -> hasFP in the middle of global isel are too early
607 // to know the max call frame size. Hopefully conservatively returning "true"
608 // in those cases is fine.
609 // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs.
610 if (!MFI.isMaxCallFrameSizeComputed() ||
612 return true;
613
614 return false;
615}
616
617/// Should the Frame Pointer be reserved for the current function?
619 const Triple &TT = MF.getFunction().getParent()->getTargetTriple();
620
621 // These OSes require the frame chain is valid, even if the current frame does
622 // not use a frame pointer.
623 if (TT.isOSDarwin() || TT.isOSWindowsOrUEFI())
624 return true;
625
626 // If the function has a frame pointer, it is reserved.
627 if (hasFP(MF))
628 return true;
629
630 // Frontend has requested to preserve the frame pointer.
631 if (MF.framePointerIsReserved())
632 return true;
633
634 return false;
635}
636
637/// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
638/// not required, we reserve argument space for call sites in the function
639/// immediately on entry to the current function. This eliminates the need for
640/// add/sub sp brackets around call sites. Returns true if the call frame is
641/// included as part of the stack frame.
643 const MachineFunction &MF) const {
644 // The stack probing code for the dynamically allocated outgoing arguments
645 // area assumes that the stack is probed at the top - either by the prologue
646 // code, which issues a probe if `hasVarSizedObjects` return true, or by the
647 // most recent variable-sized object allocation. Changing the condition here
648 // may need to be followed up by changes to the probe issuing logic.
649 return !MF.getFrameInfo().hasVarSizedObjects();
650}
651
655
657 const AArch64InstrInfo *TII = Subtarget.getInstrInfo();
658 const AArch64TargetLowering *TLI = Subtarget.getTargetLowering();
659 [[maybe_unused]] MachineFrameInfo &MFI = MF.getFrameInfo();
660 DebugLoc DL = I->getDebugLoc();
661 unsigned Opc = I->getOpcode();
662 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
663 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
664
665 if (!hasReservedCallFrame(MF)) {
666 int64_t Amount = I->getOperand(0).getImm();
667 Amount = alignTo(Amount, getStackAlign());
668 if (!IsDestroy)
669 Amount = -Amount;
670
671 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it
672 // doesn't have to pop anything), then the first operand will be zero too so
673 // this adjustment is a no-op.
674 if (CalleePopAmount == 0) {
675 // FIXME: in-function stack adjustment for calls is limited to 24-bits
676 // because there's no guaranteed temporary register available.
677 //
678 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available.
679 // 1) For offset <= 12-bit, we use LSL #0
680 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses
681 // LSL #0, and the other uses LSL #12.
682 //
683 // Most call frames will be allocated at the start of a function so
684 // this is OK, but it is a limitation that needs dealing with.
685 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large");
686
687 if (TLI->hasInlineStackProbe(MF) &&
689 // When stack probing is enabled, the decrement of SP may need to be
690 // probed. We only need to do this if the call site needs 1024 bytes of
691 // space or more, because a region smaller than that is allowed to be
692 // unprobed at an ABI boundary. We rely on the fact that SP has been
693 // probed exactly at this point, either by the prologue or most recent
694 // dynamic allocation.
696 "non-reserved call frame without var sized objects?");
697 Register ScratchReg =
698 MF.getRegInfo().createVirtualRegister(&AArch64::GPR64RegClass);
699 inlineStackProbeFixed(I, ScratchReg, -Amount, StackOffset::get(0, 0));
700 } else {
701 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
702 StackOffset::getFixed(Amount), TII);
703 }
704 }
705 } else if (CalleePopAmount != 0) {
706 // If the calling convention demands that the callee pops arguments from the
707 // stack, we want to add it back if we have a reserved call frame.
708 assert(CalleePopAmount < 0xffffff && "call frame too large");
709 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP,
710 StackOffset::getFixed(-(int64_t)CalleePopAmount), TII);
711 }
712 return MBB.erase(I);
713}
714
716 MachineBasicBlock &MBB) const {
717
718 MachineFunction &MF = *MBB.getParent();
719 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
720 const auto &TRI = *Subtarget.getRegisterInfo();
721 const auto &MFI = *MF.getInfo<AArch64FunctionInfo>();
722
723 CFIInstBuilder CFIBuilder(MBB, MBB.begin(), MachineInstr::NoFlags);
724
725 // Reset the CFA to `SP + 0`.
726 CFIBuilder.buildDefCFA(AArch64::SP, 0);
727
728 // Flip the RA sign state.
729 if (MFI.shouldSignReturnAddress(MF)) {
730 if (MFI.branchProtectionPAuthLR()) {
731 CFIBuilder.buildNegateRAStateWithPC();
732 } else if (!MF.getTarget().getTargetTriple().isOSBinFormatMachO()) {
733 CFIBuilder.buildNegateRAState();
734 }
735 }
736
737 // Shadow call stack uses X18, reset it.
738 if (MFI.needsShadowCallStackPrologueEpilogue(MF))
739 CFIBuilder.buildSameValue(AArch64::X18);
740
741 // Emit .cfi_same_value for callee-saved registers.
742 const std::vector<CalleeSavedInfo> &CSI =
744 for (const auto &Info : CSI) {
745 MCRegister Reg = Info.getReg();
746 if (!TRI.regNeedsCFI(Reg, Reg))
747 continue;
748 CFIBuilder.buildSameValue(Reg);
749 }
750}
751
753 switch (Reg.id()) {
754 default:
755 // The called routine is expected to preserve r19-r28
756 // r29 and r30 are used as frame pointer and link register resp.
757 return 0;
758
759 // GPRs
760#define CASE(n) \
761 case AArch64::W##n: \
762 case AArch64::X##n: \
763 return AArch64::X##n
764 CASE(0);
765 CASE(1);
766 CASE(2);
767 CASE(3);
768 CASE(4);
769 CASE(5);
770 CASE(6);
771 CASE(7);
772 CASE(8);
773 CASE(9);
774 CASE(10);
775 CASE(11);
776 CASE(12);
777 CASE(13);
778 CASE(14);
779 CASE(15);
780 CASE(16);
781 CASE(17);
782 CASE(18);
783#undef CASE
784
785 // FPRs
786#define CASE(n) \
787 case AArch64::B##n: \
788 case AArch64::H##n: \
789 case AArch64::S##n: \
790 case AArch64::D##n: \
791 case AArch64::Q##n: \
792 return HasSVE ? AArch64::Z##n : AArch64::Q##n
793 CASE(0);
794 CASE(1);
795 CASE(2);
796 CASE(3);
797 CASE(4);
798 CASE(5);
799 CASE(6);
800 CASE(7);
801 CASE(8);
802 CASE(9);
803 CASE(10);
804 CASE(11);
805 CASE(12);
806 CASE(13);
807 CASE(14);
808 CASE(15);
809 CASE(16);
810 CASE(17);
811 CASE(18);
812 CASE(19);
813 CASE(20);
814 CASE(21);
815 CASE(22);
816 CASE(23);
817 CASE(24);
818 CASE(25);
819 CASE(26);
820 CASE(27);
821 CASE(28);
822 CASE(29);
823 CASE(30);
824 CASE(31);
825#undef CASE
826 }
827}
828
829void AArch64FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
831 RegScavenger *) const {
832 // Insertion point.
834
835 // Fake a debug loc.
836 DebugLoc DL;
837 if (MBBI != MBB.end())
838 DL = MBBI->getDebugLoc();
839
840 const MachineFunction &MF = *MBB.getParent();
841 const AArch64Subtarget &STI = MF.getSubtarget<AArch64Subtarget>();
842 const AArch64RegisterInfo &TRI = *STI.getRegisterInfo();
843
844 BitVector GPRsToZero(TRI.getNumRegs());
845 BitVector FPRsToZero(TRI.getNumRegs());
846 bool HasSVE = STI.isSVEorStreamingSVEAvailable();
847 // Without an FP unit (e.g. -mgeneral-regs-only) the FP/vector registers can't
848 // hold a value and there is no instruction to clear them, so leave them out.
849 bool HasFPR = STI.hasFPARMv8();
850 for (MCRegister Reg : RegsToZero.set_bits()) {
851 if (TRI.isGeneralPurposeRegister(MF, Reg)) {
852 // For GPRs, we only care to clear out the 64-bit register.
853 if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
854 GPRsToZero.set(XReg);
855 } else if (HasFPR && AArch64InstrInfo::isFpOrNEON(Reg)) {
856 // For FPRs,
857 if (MCRegister XReg = getRegisterOrZero(Reg, HasSVE))
858 FPRsToZero.set(XReg);
859 }
860 }
861
862 const AArch64InstrInfo &TII = *STI.getInstrInfo();
863
864 // Zero out GPRs.
865 for (MCRegister Reg : GPRsToZero.set_bits())
866 TII.buildClearRegister(Reg, MBB, MBBI, DL);
867
868 // Zero out FP/vector registers.
869 for (MCRegister Reg : FPRsToZero.set_bits())
870 TII.buildClearRegister(Reg, MBB, MBBI, DL);
871
872 if (HasSVE) {
873 for (MCRegister PReg :
874 {AArch64::P0, AArch64::P1, AArch64::P2, AArch64::P3, AArch64::P4,
875 AArch64::P5, AArch64::P6, AArch64::P7, AArch64::P8, AArch64::P9,
876 AArch64::P10, AArch64::P11, AArch64::P12, AArch64::P13, AArch64::P14,
877 AArch64::P15}) {
878 if (RegsToZero[PReg])
879 BuildMI(MBB, MBBI, DL, TII.get(AArch64::PFALSE), PReg);
880 }
881 }
882}
883
884bool AArch64FrameLowering::windowsRequiresStackProbe(
885 const MachineFunction &MF, uint64_t StackSizeInBytes) const {
886 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
887 const AArch64FunctionInfo &MFI = *MF.getInfo<AArch64FunctionInfo>();
888 // TODO: When implementing stack protectors, take that into account
889 // for the probe threshold.
890 return Subtarget.isTargetWindowsOrUEFI() && MFI.hasStackProbing() &&
891 StackSizeInBytes >= uint64_t(MFI.getStackProbeSize());
892}
893
895 const MachineBasicBlock &MBB) {
896 const MachineFunction *MF = MBB.getParent();
897 LiveRegs.addLiveIns(MBB);
898 // Mark callee saved registers as used so we will not choose them.
899 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs();
900 for (unsigned i = 0; CSRegs[i]; ++i)
901 LiveRegs.addReg(CSRegs[i]);
902}
903
905AArch64FrameLowering::findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB,
906 bool HasCall) const {
908
909 // If MBB is an entry block, use X9 as the scratch register
910 // preserve_none functions may be using X9 to pass arguments,
911 // so prefer to pick an available register below.
912 if (&MF->front() == MBB &&
914 return AArch64::X9;
915
916 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>();
917 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
918 LivePhysRegs LiveRegs(TRI);
919 getLiveRegsForEntryMBB(LiveRegs, *MBB);
920 if (HasCall) {
921 LiveRegs.addReg(AArch64::X16);
922 LiveRegs.addReg(AArch64::X17);
923 LiveRegs.addReg(AArch64::X18);
924 }
925
926 // Prefer X9 since it was historically used for the prologue scratch reg.
927 const MachineRegisterInfo &MRI = MF->getRegInfo();
928 if (LiveRegs.available(MRI, AArch64::X9))
929 return AArch64::X9;
930
931 for (unsigned Reg : AArch64::GPR64RegClass) {
932 if (LiveRegs.available(MRI, Reg))
933 return Reg;
934 }
935 return Register();
936}
937
939 const MachineBasicBlock &MBB) const {
940 const MachineFunction *MF = MBB.getParent();
941 if (!enableShrinkWrapping(*MF))
942 return false;
944 return false;
945
946 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB);
948 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
949 const AArch64TargetLowering *TLI = Subtarget.getTargetLowering();
951
952 if (AFI->hasSwiftAsyncContext()) {
953 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo();
954 const MachineRegisterInfo &MRI = MF->getRegInfo();
957 // The StoreSwiftAsyncContext clobbers X16 and X17. Make sure they are
958 // available.
959 if (!LiveRegs.available(MRI, AArch64::X16) ||
960 !LiveRegs.available(MRI, AArch64::X17))
961 return false;
962 }
963
964 // Certain stack probing sequences might clobber flags, then we can't use
965 // the block as a prologue if the flags register is a live-in.
967 MBB.isLiveIn(AArch64::NZCV))
968 return false;
969
970 if (RegInfo->hasStackRealignment(*MF) || TLI->hasInlineStackProbe(*MF))
971 if (!findScratchNonCalleeSaveRegister(TmpMBB).isValid())
972 return false;
973
974 // May need a scratch register (for return value) if require making a special
975 // call
976 if (requiresSaveVG(*MF) ||
977 windowsRequiresStackProbe(*MF, std::numeric_limits<uint64_t>::max()))
978 if (!findScratchNonCalleeSaveRegister(TmpMBB, true).isValid())
979 return false;
980
981 return true;
982}
983
985 const MachineFunction &MF) const {
986 // Returns that bypass the shrink-wrapped frame still need to pop incoming
987 // stack arguments, but they won't get an epilogue.
989}
990
992 const MachineFunction &MF) const {
993 const Function &F = MF.getFunction();
995
996 // The range-insertion pass currently runs only on Windows, not UEFI.
997 if (!Subtarget.isTargetWindows())
998 return false;
999
1000 // Range insertion relies on SEH pseudos, which are emitted only when the
1001 // function needs an unwind table entry.
1002 if (!F.needsUnwindTableEntry())
1003 return false;
1004
1005 // Splitting ranges does not yet preserve language-specific handler data.
1006 if (F.hasPersonalityFn())
1007 return false;
1008
1009 // Funclets have independent frames; range insertion assumes a single frame.
1010 if (MF.hasEHFunclets())
1011 return false;
1012
1013 // Naked functions do not have a compiler-generated prologue to shrink-wrap.
1014 if (F.hasFnAttribute(Attribute::Naked))
1015 return false;
1016
1017 // Signed return addresses need authentication-state handling across ranges
1018 // that is not yet implemented.
1021 return false;
1022
1023 return true;
1024}
1025
1026bool AArch64FrameLowering::shouldSignReturnAddressEverywhere(
1027 const MachineFunction &MF) const {
1028 // FIXME: With WinCFI, extra care should be taken to place SEH_PACSignLR
1029 // and SEH_EpilogEnd instructions in the correct order.
1030 if (MF.usesWindowsUnwindInfo())
1031 return false;
1034}
1035
1036// Given a load or a store instruction, generate an appropriate unwinding SEH
1037// code on Windows.
1039AArch64FrameLowering::insertSEH(MachineBasicBlock::iterator MBBI,
1040 const AArch64InstrInfo &TII,
1041 MachineInstr::MIFlag Flag) const {
1042 unsigned Opc = MBBI->getOpcode();
1043 MachineBasicBlock *MBB = MBBI->getParent();
1044 MachineFunction &MF = *MBB->getParent();
1045 DebugLoc DL = MBBI->getDebugLoc();
1046 unsigned ImmIdx = MBBI->getNumOperands() - 1;
1047 int Imm = MBBI->getOperand(ImmIdx).getImm();
1050 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1051
1052 switch (Opc) {
1053 default:
1054 report_fatal_error("No SEH Opcode for this instruction");
1055 case AArch64::STR_ZXI:
1056 case AArch64::LDR_ZXI: {
1057 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1058 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveZReg))
1059 .addImm(Reg0)
1060 .addImm(Imm)
1061 .setMIFlag(Flag);
1062 break;
1063 }
1064 case AArch64::STR_PXI:
1065 case AArch64::LDR_PXI: {
1066 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1067 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SavePReg))
1068 .addImm(Reg0)
1069 .addImm(Imm)
1070 .setMIFlag(Flag);
1071 break;
1072 }
1073 case AArch64::LDPDpost:
1074 Imm = -Imm;
1075 [[fallthrough]];
1076 case AArch64::STPDpre: {
1077 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1078 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
1079 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X))
1080 .addImm(Reg0)
1081 .addImm(Reg1)
1082 .addImm(Imm * 8)
1083 .setMIFlag(Flag);
1084 break;
1085 }
1086 case AArch64::LDPXpost:
1087 Imm = -Imm;
1088 [[fallthrough]];
1089 case AArch64::STPXpre: {
1090 Register Reg0 = MBBI->getOperand(1).getReg();
1091 Register Reg1 = MBBI->getOperand(2).getReg();
1092 if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1093 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X))
1094 .addImm(Imm * 8)
1095 .setMIFlag(Flag);
1096 else
1097 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X))
1098 .addImm(RegInfo->getSEHRegNum(Reg0))
1099 .addImm(RegInfo->getSEHRegNum(Reg1))
1100 .addImm(Imm * 8)
1101 .setMIFlag(Flag);
1102 break;
1103 }
1104 case AArch64::LDRDpost:
1105 Imm = -Imm;
1106 [[fallthrough]];
1107 case AArch64::STRDpre: {
1108 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1109 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X))
1110 .addImm(Reg)
1111 .addImm(Imm)
1112 .setMIFlag(Flag);
1113 break;
1114 }
1115 case AArch64::LDRXpost:
1116 Imm = -Imm;
1117 [[fallthrough]];
1118 case AArch64::STRXpre: {
1119 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1120 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X))
1121 .addImm(Reg)
1122 .addImm(Imm)
1123 .setMIFlag(Flag);
1124 break;
1125 }
1126 case AArch64::STPDi:
1127 case AArch64::LDPDi: {
1128 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1129 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1130 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP))
1131 .addImm(Reg0)
1132 .addImm(Reg1)
1133 .addImm(Imm * 8)
1134 .setMIFlag(Flag);
1135 break;
1136 }
1137 case AArch64::STPXi:
1138 case AArch64::LDPXi: {
1139 Register Reg0 = MBBI->getOperand(0).getReg();
1140 Register Reg1 = MBBI->getOperand(1).getReg();
1141
1142 int SEHReg0 = RegInfo->getSEHRegNum(Reg0);
1143 int SEHReg1 = RegInfo->getSEHRegNum(Reg1);
1144
1145 if (Reg0 == AArch64::FP && Reg1 == AArch64::LR)
1146 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR))
1147 .addImm(Imm * 8)
1148 .setMIFlag(Flag);
1149 else if (SEHReg0 >= 19 && SEHReg1 >= 19)
1150 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP))
1151 .addImm(SEHReg0)
1152 .addImm(SEHReg1)
1153 .addImm(Imm * 8)
1154 .setMIFlag(Flag);
1155 else
1156 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegIP))
1157 .addImm(SEHReg0)
1158 .addImm(SEHReg1)
1159 .addImm(Imm * 8)
1160 .setMIFlag(Flag);
1161 break;
1162 }
1163 case AArch64::STRXui:
1164 case AArch64::LDRXui: {
1165 int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1166 if (Reg >= 19)
1167 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg))
1168 .addImm(Reg)
1169 .addImm(Imm * 8)
1170 .setMIFlag(Flag);
1171 else
1172 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegI))
1173 .addImm(Reg)
1174 .addImm(Imm * 8)
1175 .setMIFlag(Flag);
1176 break;
1177 }
1178 case AArch64::STRDui:
1179 case AArch64::LDRDui: {
1180 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1181 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg))
1182 .addImm(Reg)
1183 .addImm(Imm * 8)
1184 .setMIFlag(Flag);
1185 break;
1186 }
1187 case AArch64::STRQui:
1188 case AArch64::LDRQui: {
1189 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1190 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQ))
1191 .addImm(Reg)
1192 .addImm(Imm * 16)
1193 .setMIFlag(Flag);
1194 break;
1195 }
1196 case AArch64::STPQi:
1197 case AArch64::LDPQi: {
1198 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg());
1199 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1200 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQP))
1201 .addImm(Reg0)
1202 .addImm(Reg1)
1203 .addImm(Imm * 16)
1204 .setMIFlag(Flag);
1205 break;
1206 }
1207 case AArch64::LDRQpost:
1208 Imm = -Imm;
1209 [[fallthrough]];
1210 case AArch64::STRQpre: {
1211 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1212 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQX))
1213 .addImm(Reg)
1214 .addImm(Imm)
1215 .setMIFlag(Flag);
1216 break;
1217 }
1218 case AArch64::LDPQpost:
1219 Imm = -Imm;
1220 [[fallthrough]];
1221 case AArch64::STPQpre: {
1222 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg());
1223 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg());
1224 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveAnyRegQPX))
1225 .addImm(Reg0)
1226 .addImm(Reg1)
1227 .addImm(Imm * 16)
1228 .setMIFlag(Flag);
1229 break;
1230 }
1231 }
1232 auto I = MBB->insertAfter(MBBI, MIB);
1233 return I;
1234}
1235
1238 if (!AFI->needsDwarfUnwindInfo(MF) || !AFI->hasStreamingModeChanges())
1239 return false;
1240 // For Darwin platforms we don't save VG for non-SVE functions, even if SME
1241 // is enabled with streaming mode changes.
1242 auto &ST = MF.getSubtarget<AArch64Subtarget>();
1243 if (ST.isTargetDarwin())
1244 return ST.hasSVE();
1245 return true;
1246}
1247
1249 MachineFunction &MF) const {
1251 const AArch64InstrInfo *TII = Subtarget.getInstrInfo();
1252
1253 auto EmitSignRA = [&](MachineBasicBlock &MBB) {
1254 DebugLoc DL; // Set debug location to unknown.
1256
1257 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PAUTH_PROLOGUE))
1259 };
1260
1261 auto EmitAuthRA = [&](MachineBasicBlock &MBB) {
1262 DebugLoc DL;
1263 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1264 if (MBBI != MBB.end())
1265 DL = MBBI->getDebugLoc();
1266
1267 TII->createPauthEpilogueInstr(MBB, DL);
1268 };
1269
1270 // This should be in sync with PEIImpl::calculateSaveRestoreBlocks.
1271 EmitSignRA(MF.front());
1272 for (MachineBasicBlock &MBB : MF) {
1273 if (MBB.isEHFuncletEntry())
1274 EmitSignRA(MBB);
1275 if (MBB.isReturnBlock())
1276 EmitAuthRA(MBB);
1277 }
1278}
1279
1281 MachineBasicBlock &MBB) const {
1282 AArch64PrologueEmitter PrologueEmitter(MF, MBB, *this);
1283 PrologueEmitter.emitPrologue();
1284}
1285
1287 MachineBasicBlock &MBB) const {
1288 AArch64EpilogueEmitter EpilogueEmitter(MF, MBB, *this);
1289 EpilogueEmitter.emitEpilogue();
1290}
1291
1294 MF.getInfo<AArch64FunctionInfo>()->needsDwarfUnwindInfo(MF);
1295}
1296
1298 return enableCFIFixup(MF) &&
1299 MF.getInfo<AArch64FunctionInfo>()->needsAsyncDwarfUnwindInfo(MF);
1300}
1301
1302/// getFrameIndexReference - Provide a base+offset reference to an FI slot for
1303/// debug info. It's the same as what we use for resolving the code-gen
1304/// references for now. FIXME: This can go wrong when references are
1305/// SP-relative and simple call frames aren't used.
1308 Register &FrameReg) const {
1310 MF, FI, FrameReg,
1311 /*PreferFP=*/
1312 MF.getFunction().hasFnAttribute(Attribute::SanitizeHWAddress) ||
1313 MF.getFunction().hasFnAttribute(Attribute::SanitizeMemTag),
1314 /*ForSimm=*/false);
1315}
1316
1319 int FI) const {
1320 // This function serves to provide a comparable offset from a single reference
1321 // point (the value of SP at function entry) that can be used for analysis,
1322 // e.g. the stack-frame-layout analysis pass. It is not guaranteed to be
1323 // correct for all objects in the presence of VLA-area objects or dynamic
1324 // stack re-alignment.
1325
1326 const auto &MFI = MF.getFrameInfo();
1327
1328 int64_t ObjectOffset = MFI.getObjectOffset(FI);
1329 StackOffset ZPRStackSize = getZPRStackSize(MF);
1330 StackOffset PPRStackSize = getPPRStackSize(MF);
1331 StackOffset SVEStackSize = ZPRStackSize + PPRStackSize;
1332
1333 // For VLA-area objects, just emit an offset at the end of the stack frame.
1334 // Whilst not quite correct, these objects do live at the end of the frame and
1335 // so it is more useful for analysis for the offset to reflect this.
1336 if (MFI.isVariableSizedObjectIndex(FI)) {
1337 return StackOffset::getFixed(-((int64_t)MFI.getStackSize())) - SVEStackSize;
1338 }
1339
1340 // This is correct in the absence of any SVE stack objects.
1341 if (!SVEStackSize)
1342 return StackOffset::getFixed(ObjectOffset - getOffsetOfLocalArea());
1343
1344 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1345 bool FPAfterSVECalleeSaves = hasSVECalleeSavesAboveFrameRecord(MF);
1346 if (MFI.hasScalableStackID(FI)) {
1347 if (FPAfterSVECalleeSaves &&
1348 -ObjectOffset <= (int64_t)AFI->getSVECalleeSavedStackSize()) {
1349 assert(!AFI->hasSplitSVEObjects() &&
1350 "split-sve-objects not supported with FPAfterSVECalleeSaves");
1351 return StackOffset::getScalable(ObjectOffset);
1352 }
1353 StackOffset AccessOffset{};
1354 // The scalable vectors are below (lower address) the scalable predicates
1355 // with split SVE objects, so we must subtract the size of the predicates.
1356 if (AFI->hasSplitSVEObjects() &&
1357 MFI.getStackID(FI) == TargetStackID::ScalableVector)
1358 AccessOffset = -PPRStackSize;
1359 return AccessOffset +
1360 StackOffset::get(-((int64_t)AFI->getCalleeSavedStackSize()),
1361 ObjectOffset);
1362 }
1363
1364 bool IsFixed = MFI.isFixedObjectIndex(FI);
1365 bool IsCSR =
1366 !IsFixed && ObjectOffset >= -((int)AFI->getCalleeSavedStackSize(MFI));
1367
1368 StackOffset ScalableOffset = {};
1369 if (!IsFixed && !IsCSR) {
1370 ScalableOffset = -SVEStackSize;
1371 } else if (FPAfterSVECalleeSaves && IsCSR) {
1372 ScalableOffset =
1374 }
1375
1376 return StackOffset::getFixed(ObjectOffset) + ScalableOffset;
1377}
1378
1384
1385StackOffset AArch64FrameLowering::getFPOffset(const MachineFunction &MF,
1386 int64_t ObjectOffset) const {
1387 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1388 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1389 const Function &F = MF.getFunction();
1390 bool IsWin64 = Subtarget.isCallingConvWin64(F.getCallingConv(), F.isVarArg());
1391 unsigned FixedObject =
1392 getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet=*/false);
1393 int64_t CalleeSaveSize = AFI->getCalleeSavedStackSize(MF.getFrameInfo());
1394 int64_t FPAdjust =
1395 CalleeSaveSize - AFI->getCalleeSaveBaseToFrameRecordOffset();
1396 return StackOffset::getFixed(ObjectOffset + FixedObject + FPAdjust);
1397}
1398
1399StackOffset AArch64FrameLowering::getStackOffset(const MachineFunction &MF,
1400 int64_t ObjectOffset) const {
1401 const auto &MFI = MF.getFrameInfo();
1402 return StackOffset::getFixed(ObjectOffset + (int64_t)MFI.getStackSize());
1403}
1404
1405// TODO: This function currently does not work for scalable vectors.
1407 int FI) const {
1408 const AArch64RegisterInfo *RegInfo =
1409 MF.getSubtarget<AArch64Subtarget>().getRegisterInfo();
1410 int ObjectOffset = MF.getFrameInfo().getObjectOffset(FI);
1411 return RegInfo->getLocalAddressRegister(MF) == AArch64::FP
1412 ? getFPOffset(MF, ObjectOffset).getFixed()
1413 : getStackOffset(MF, ObjectOffset).getFixed();
1414}
1415
1417 const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP,
1418 bool ForSimm) const {
1419 const auto &MFI = MF.getFrameInfo();
1420 int64_t ObjectOffset = MFI.getObjectOffset(FI);
1421 bool isFixed = MFI.isFixedObjectIndex(FI);
1422 auto StackID = static_cast<TargetStackID::Value>(MFI.getStackID(FI));
1423 return resolveFrameOffsetReference(MF, ObjectOffset, isFixed, StackID,
1424 FrameReg, PreferFP, ForSimm);
1425}
1426
1428 const MachineFunction &MF, int64_t ObjectOffset, bool isFixed,
1429 TargetStackID::Value StackID, Register &FrameReg, bool PreferFP,
1430 bool ForSimm) const {
1431 const auto &MFI = MF.getFrameInfo();
1432 const auto &Subtarget = MF.getSubtarget<AArch64Subtarget>();
1433 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1434 const auto *AFI = MF.getInfo<AArch64FunctionInfo>();
1435
1436 int64_t FPOffset = getFPOffset(MF, ObjectOffset).getFixed();
1437 int64_t Offset = getStackOffset(MF, ObjectOffset).getFixed();
1438
1439 // The fixed object area sits above the callee-saved area and can grow
1440 // large enough to displace it; account for that displacement here so CSR
1441 // objects aren't misclassified as locals and addressed via the base
1442 // pointer.
1443 bool IsWin64 = Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(),
1444 MF.getFunction().isVarArg());
1445 const int64_t FixedObjectSize =
1446 getFixedObjectSize(MF, AFI, IsWin64, /*IsFunclet*/ false);
1447 bool isCSR =
1448 !isFixed && ObjectOffset >= -((int64_t)AFI->getCalleeSavedStackSize(MFI) +
1449 FixedObjectSize);
1450 bool isSVE = MFI.isScalableStackID(StackID);
1451
1452 StackOffset ZPRStackSize = getZPRStackSize(MF);
1453 StackOffset PPRStackSize = getPPRStackSize(MF);
1454 StackOffset SVEStackSize = ZPRStackSize + PPRStackSize;
1455
1456 // Use frame pointer to reference fixed objects. Use it for locals if
1457 // there are VLAs or a dynamically realigned SP (and thus the SP isn't
1458 // reliable as a base). Make sure useFPForScavengingIndex() does the
1459 // right thing for the emergency spill slot.
1460 bool UseFP = false;
1461 if (AFI->hasStackFrame() && !isSVE) {
1462 // We shouldn't prefer using the FP to access fixed-sized stack objects when
1463 // there are scalable (SVE) objects in between the FP and the fixed-sized
1464 // objects.
1465 PreferFP &= !SVEStackSize;
1466
1467 // Note: Keeping the following as multiple 'if' statements rather than
1468 // merging to a single expression for readability.
1469 //
1470 // Argument access should always use the FP.
1471 if (isFixed) {
1472 UseFP = hasFP(MF);
1473 } else if (isCSR && RegInfo->hasStackRealignment(MF)) {
1474 // References to the CSR area must use FP if we're re-aligning the stack
1475 // since the dynamically-sized alignment padding is between the SP/BP and
1476 // the CSR area.
1477 assert(hasFP(MF) && "Re-aligned stack must have frame pointer");
1478 UseFP = true;
1479 } else if (hasFP(MF) && !RegInfo->hasStackRealignment(MF)) {
1480 // If the FPOffset is negative and we're producing a signed immediate, we
1481 // have to keep in mind that the available offset range for negative
1482 // offsets is smaller than for positive ones. If an offset is available
1483 // via the FP and the SP, use whichever is closest.
1484 bool FPOffsetFits = !ForSimm || FPOffset >= -256;
1485 PreferFP |= Offset > -FPOffset && !SVEStackSize;
1486
1487 if (FPOffset >= 0) {
1488 // If the FPOffset is positive, that'll always be best, as the SP/BP
1489 // will be even further away.
1490 UseFP = true;
1491 } else if (MFI.hasVarSizedObjects()) {
1492 // If we have variable sized objects, we can use either FP or BP, as the
1493 // SP offset is unknown. We can use the base pointer if we have one and
1494 // FP is not preferred. If not, we're stuck with using FP.
1495 bool CanUseBP = RegInfo->hasBasePointer(MF);
1496 if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best.
1497 UseFP = PreferFP;
1498 else if (!CanUseBP) // Can't use BP. Forced to use FP.
1499 UseFP = true;
1500 // else we can use BP and FP, but the offset from FP won't fit.
1501 // That will make us scavenge registers which we can probably avoid by
1502 // using BP. If it won't fit for BP either, we'll scavenge anyway.
1503 } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) {
1504 // Funclets access the locals contained in the parent's stack frame
1505 // via the frame pointer, so we have to use the FP in the parent
1506 // function.
1507 (void) Subtarget;
1508 assert(Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv(),
1509 MF.getFunction().isVarArg()) &&
1510 "Funclets should only be present on Win64");
1511 UseFP = true;
1512 } else {
1513 // We have the choice between FP and (SP or BP).
1514 if (FPOffsetFits && PreferFP) // If FP is the best fit, use it.
1515 UseFP = true;
1516 }
1517 }
1518 }
1519
1520 assert(
1521 ((isFixed || isCSR) || !RegInfo->hasStackRealignment(MF) || !UseFP) &&
1522 "In the presence of dynamic stack pointer realignment, "
1523 "non-argument/CSR objects cannot be accessed through the frame pointer");
1524
1525 bool FPAfterSVECalleeSaves = hasSVECalleeSavesAboveFrameRecord(MF);
1526
1527 if (isSVE) {
1528 StackOffset FPOffset = StackOffset::get(
1529 -AFI->getCalleeSaveBaseToFrameRecordOffset(), ObjectOffset);
1530 StackOffset SPOffset =
1531 SVEStackSize +
1532 StackOffset::get(MFI.getStackSize() - AFI->getCalleeSavedStackSize(),
1533 ObjectOffset);
1534
1535 // With split SVE objects the ObjectOffset is relative to the split area
1536 // (i.e. the PPR area or ZPR area respectively).
1537 if (AFI->hasSplitSVEObjects() && StackID == TargetStackID::ScalableVector) {
1538 // If we're accessing an SVE vector with split SVE objects...
1539 // - From the FP we need to move down past the PPR area:
1540 FPOffset -= PPRStackSize;
1541 // - From the SP we only need to move up to the ZPR area:
1542 SPOffset -= PPRStackSize;
1543 // Note: `SPOffset = SVEStackSize + ...`, so `-= PPRStackSize` results in
1544 // `SPOffset = ZPRStackSize + ...`.
1545 }
1546
1547 if (FPAfterSVECalleeSaves) {
1549 if (-ObjectOffset <= (int64_t)AFI->getSVECalleeSavedStackSize()) {
1552 }
1553 }
1554
1555 // Always use the FP for SVE spills if available and beneficial.
1556 if (hasFP(MF) && (SPOffset.getFixed() ||
1557 FPOffset.getScalable() < SPOffset.getScalable() ||
1558 RegInfo->hasStackRealignment(MF))) {
1559 FrameReg = RegInfo->getFrameRegister(MF);
1560 return FPOffset;
1561 }
1562 FrameReg = RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister()
1563 : MCRegister(AArch64::SP);
1564
1565 return SPOffset;
1566 }
1567
1568 StackOffset SVEAreaOffset = {};
1569 if (FPAfterSVECalleeSaves) {
1570 // In this stack layout, the FP is in between the callee saves and other
1571 // SVE allocations.
1572 StackOffset SVECalleeSavedStack =
1574 if (UseFP) {
1575 if (isFixed)
1576 SVEAreaOffset = SVECalleeSavedStack;
1577 else if (!isCSR)
1578 SVEAreaOffset = SVECalleeSavedStack - SVEStackSize;
1579 } else {
1580 if (isFixed)
1581 SVEAreaOffset = SVEStackSize;
1582 else if (isCSR)
1583 SVEAreaOffset = SVEStackSize - SVECalleeSavedStack;
1584 }
1585 } else {
1586 if (UseFP && !(isFixed || isCSR))
1587 SVEAreaOffset = -SVEStackSize;
1588 if (!UseFP && (isFixed || isCSR))
1589 SVEAreaOffset = SVEStackSize;
1590 }
1591
1592 if (UseFP) {
1593 FrameReg = RegInfo->getFrameRegister(MF);
1594 return StackOffset::getFixed(FPOffset) + SVEAreaOffset;
1595 }
1596
1597 // Use the base pointer if we have one.
1598 if (RegInfo->hasBasePointer(MF))
1599 FrameReg = RegInfo->getBaseRegister();
1600 else {
1601 assert(!MFI.hasVarSizedObjects() &&
1602 "Can't use SP when we have var sized objects.");
1603 FrameReg = AArch64::SP;
1604 // If we're using the red zone for this function, the SP won't actually
1605 // be adjusted, so the offsets will be negative. They're also all
1606 // within range of the signed 9-bit immediate instructions.
1607 if (canUseRedZone(MF))
1608 Offset -= AFI->getLocalStackSize();
1609 }
1610
1611 return StackOffset::getFixed(Offset) + SVEAreaOffset;
1612}
1613
1615 // Do not set a kill flag on values that are also marked as live-in. This
1616 // happens with the @llvm-returnaddress intrinsic and with arguments passed in
1617 // callee saved registers.
1618 // Omitting the kill flags is conservatively correct even if the live-in
1619 // is not used after all.
1620 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg);
1621 return getKillRegState(!IsLiveIn);
1622}
1623
1625 MachineFunction &MF) {
1629 return Subtarget.isTargetMachO() &&
1630 !(Subtarget.getTargetLowering()->supportSwiftError() &&
1631 Attrs.hasAttrSomewhere(Attribute::SwiftError)) &&
1633 !AFL.requiresSaveVG(MF) && !AFI->isSVECC();
1634}
1635
1636static bool invalidateWindowsRegisterPairing(bool SpillExtendedVolatile,
1637 int PairOffset, unsigned Reg1,
1638 unsigned Reg2, bool NeedsWinCFI,
1639 const TargetRegisterInfo *TRI) {
1640 // If we are generating register pairs for a Windows function that requires
1641 // EH support, then pair consecutive registers only. There are no unwind
1642 // opcodes for saves/restores of non-consecutive register pairs.
1643 // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x,
1644 // save_lrpair.
1645 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1646
1647 if (Reg2 == AArch64::FP)
1648 return true;
1649 if (!NeedsWinCFI)
1650 return false;
1651
1652 // ARM64EC introduced `save_any_regp`, which expects 16-byte alignment.
1653 // This is handled by only allowing paired spills for registers spilled at
1654 // even positions (which should be 16-byte aligned, as other GPRs/FPRs are
1655 // 8-bytes). We carve out an exception for {FP,LR}, which does not require
1656 // 16-byte alignment in the uop representation.
1657 if (TRI->getEncodingValue(Reg2) == TRI->getEncodingValue(Reg1) + 1)
1658 return SpillExtendedVolatile
1659 ? !((Reg1 == AArch64::FP && Reg2 == AArch64::LR) ||
1660 (PairOffset % 16) == 0)
1661 : false;
1662
1663 // If pairing a GPR with LR, the pair can be described by the save_lrpair
1664 // opcode. The save_lrpair opcode requires the first register to be odd.
1665 if (Reg1 >= AArch64::X19 && Reg1 <= AArch64::X27 &&
1666 (Reg1 - AArch64::X19) % 2 == 0 && Reg2 == AArch64::LR)
1667 return false;
1668 return true;
1669}
1670
1671/// Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
1672/// WindowsCFI requires that only consecutive registers can be paired.
1673/// LR and FP need to be allocated together when the frame needs to save
1674/// the frame-record. This means any other register pairing with LR is invalid.
1675static bool invalidateRegisterPairing(bool SpillExtendedVolatile,
1676 int PairOffset, unsigned Reg1,
1677 unsigned Reg2, bool UsesWinAAPCS,
1678 bool NeedsWinCFI, bool NeedsFrameRecord,
1679 const TargetRegisterInfo *TRI) {
1680 if (UsesWinAAPCS)
1681 return invalidateWindowsRegisterPairing(SpillExtendedVolatile, PairOffset,
1682 Reg1, Reg2, NeedsWinCFI, TRI);
1683
1684 // If we need to store the frame record, don't pair any register
1685 // with LR other than FP.
1686 if (NeedsFrameRecord)
1687 return Reg2 == AArch64::LR;
1688
1689 return false;
1690}
1691
1692// Returns true if Offset (in bytes) is aligned to the instruction's scale and
1693// the scaled immediate is within the instruction's valid range.
1694static bool isValidMemOpOffset(const AArch64InstrInfo *TII, unsigned Opcode,
1695 int Offset) {
1696 int64_t MinOff, MaxOff;
1697 TypeSize ScaleValue(0U, false), Width(0U, false);
1698 if (!TII->getMemOpInfo(Opcode, ScaleValue, Width, MinOff, MaxOff))
1699 return false;
1700
1701 if (Offset % ScaleValue.getKnownMinValue() != 0)
1702 return false;
1703
1704 Offset /= ScaleValue.getKnownMinValue();
1705 return Offset >= MinOff && Offset <= MaxOff;
1706}
1707
1708namespace {
1709
1710struct RegGroupInfo {
1711 Register Reg1;
1712 Register Reg2;
1713 int FrameIdx;
1714 int Offset;
1715 enum RegType { GPR, FPR64, FPR128, PPR, ZPR, VG } Type;
1716 const TargetRegisterClass *RC;
1717
1718 RegGroupInfo() = default;
1719
1720 bool isPaired() const { return getNumRegs() == 2; }
1721
1722 bool isQuad() const { return getNumRegs() == 4; }
1723
1724 bool isGrouped() const { return isPaired() || isQuad(); }
1725
1726 unsigned getNumRegs() const {
1727 if (!Reg2.isValid())
1728 return 1;
1729 if (Type != ZPR)
1730 return 2;
1731 // ZPR groups are contiguous with Reg2 holding the lower register.
1732 unsigned NumRegs = (Reg1 - Reg2) + 1;
1733 assert(NumRegs == 2 || NumRegs == 4);
1734 return NumRegs;
1735 }
1736
1737 bool isScalable() const { return Type == PPR || Type == ZPR; }
1738
1739 SmallVector<Register, 4> getRegisters() const {
1740 if (isPaired())
1741 return {Reg1, Reg2};
1742 if (isQuad()) {
1743 assert(Reg1 - 3 == Reg2 && "Quad not contiguous");
1744 return {Reg1, Reg1 - 1, Reg1 - 2, Reg1 - 3};
1745 }
1746 return {Reg1};
1747 }
1748
1749 auto getFrameIndexes() const {
1750 return seq(FrameIdx, FrameIdx + int(getNumRegs()));
1751 }
1752
1753 Register getAsMultiVectorRegister() const {
1754 assert(Type == ZPR && isGrouped() && "Expected ZPR register group");
1755 return (isQuad() ? AArch64::Z0_Z1_Z2_Z3 : AArch64::Z0_Z1) +
1756 (Reg2 - AArch64::Z0);
1757 }
1758
1759 void dump(const TargetRegisterInfo *TRI) const {
1760 dbgs() << "(";
1761 interleaveComma(getRegisters(), dbgs(),
1762 [&](Register Reg) { dbgs() << printReg(Reg, TRI); });
1763 dbgs() << ") -> fi#(";
1764 interleaveComma(getFrameIndexes(), dbgs(),
1765 [&](int FrameIdx) { dbgs() << FrameIdx; });
1766 dbgs() << ")\n";
1767 }
1768};
1769
1770} // end anonymous namespace
1771
1773 for (unsigned PReg = AArch64::P8; PReg <= AArch64::P15; ++PReg) {
1774 if (SavedRegs.test(PReg)) {
1775 unsigned PNReg = PReg - AArch64::P0 + AArch64::PN0;
1776 return MCRegister(PNReg);
1777 }
1778 }
1779 return MCRegister();
1780}
1781
1782// The multivector LD/ST are available only for SME or SVE2p1 targets
1784 MachineFunction &MF) {
1785 if (Subtarget.getCLOpts().disable_multivector_spill_fill)
1786 return false;
1787
1788 SMEAttrs FuncAttrs = MF.getInfo<AArch64FunctionInfo>()->getSMEFnAttrs();
1789 bool IsLocallyStreaming =
1790 FuncAttrs.hasStreamingBody() && !FuncAttrs.hasStreamingInterface();
1791
1792 // Only when in streaming mode SME2 instructions can be safely used.
1793 // It is not safe to use SME2 instructions when in streaming compatible or
1794 // locally streaming mode.
1795 return Subtarget.hasSVE2p1() ||
1796 (Subtarget.hasSME2() &&
1797 (!IsLocallyStreaming && Subtarget.isStreaming()));
1798}
1799
1801 MachineFunction &MF,
1803 const TargetRegisterInfo *TRI,
1805 bool NeedsFrameRecord) {
1806
1807 if (CSI.empty())
1808 return;
1809
1810 const AArch64InstrInfo *TII =
1811 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
1812 bool IsWindows = isTargetWindows(MF);
1813 bool NeedsWinCFI = MF.needsWinCFI();
1815 unsigned StackHazardSize = getStackHazardSize(MF);
1816 MachineFrameInfo &MFI = MF.getFrameInfo();
1818 unsigned Count = CSI.size();
1819 (void)CC;
1820 // MachO's compact unwind format relies on all registers being stored in
1821 // pairs.
1822 assert((!produceCompactUnwindFrame(AFL, MF) ||
1825 (Count & 1) == 0) &&
1826 "Odd number of callee-saved regs to spill!");
1827 int ByteOffset = AFI->getCalleeSavedStackSize();
1828 int StackFillDir = -1;
1829 int RegInc = 1;
1830 unsigned FirstReg = 0;
1831 if (IsWindows) {
1832 // For WinCFI, fill the stack from the bottom up.
1833 ByteOffset = 0;
1834 StackFillDir = 1;
1835 // As the CSI array is reversed to match PrologEpilogInserter, iterate
1836 // backwards, to pair up registers starting from lower numbered registers.
1837 RegInc = -1;
1838 FirstReg = Count - 1;
1839 }
1840
1841 bool FPAfterSVECalleeSaves = AFL.hasSVECalleeSavesAboveFrameRecord(MF);
1842 // Windows AAPCS has x9-x15 as volatile registers, x16-x17 as intra-procedural
1843 // scratch, x18 as platform reserved. However, clang has extended calling
1844 // convensions such as preserve_most and preserve_all which treat these as
1845 // CSR. As such, the ARM64 unwind uOPs bias registers by 19. We use ARM64EC
1846 // uOPs which have separate restrictions. We need to check for that.
1847 //
1848 // NOTE: we currently do not account for the D registers as LLVM does not
1849 // support non-ABI compliant D register spills.
1850 bool SpillExtendedVolatile =
1851 IsWindows && llvm::any_of(CSI, [](const CalleeSavedInfo &CSI) {
1852 const auto &Reg = CSI.getReg();
1853 return Reg >= AArch64::X0 && Reg <= AArch64::X18;
1854 });
1855
1856 int ZPRByteOffset = 0;
1857 int PPRByteOffset = 0;
1858 bool SplitPPRs = AFI->hasSplitSVEObjects();
1859 if (SplitPPRs) {
1860 ZPRByteOffset = AFI->getZPRCalleeSavedStackSize();
1861 PPRByteOffset = AFI->getPPRCalleeSavedStackSize();
1862 } else if (!FPAfterSVECalleeSaves) {
1863 ZPRByteOffset =
1865 // Unused: Everything goes in ZPR space.
1866 PPRByteOffset = 0;
1867 }
1868
1869 bool NeedGapToAlignStack = AFI->hasCalleeSaveStackFreeSpace();
1870 Register LastReg = 0;
1871 bool HasCSHazardPadding = AFI->hasStackHazardSlotIndex() && !SplitPPRs;
1872
1873 auto AlignOffset = [StackFillDir](int Offset, int Align) {
1874 if (StackFillDir < 0)
1875 return alignDown(Offset, Align);
1876 return alignTo(Offset, Align);
1877 };
1878
1879 // When iterating backwards, the loop condition relies on unsigned wraparound.
1880 for (unsigned i = FirstReg; i < Count; i += RegInc) {
1881 RegGroupInfo RGI;
1882 RGI.Reg1 = CSI[i].getReg();
1883
1884 if (AArch64::GPR64RegClass.contains(RGI.Reg1)) {
1885 RGI.Type = RegGroupInfo::GPR;
1886 RGI.RC = &AArch64::GPR64RegClass;
1887 } else if (AArch64::FPR64RegClass.contains(RGI.Reg1)) {
1888 RGI.Type = RegGroupInfo::FPR64;
1889 RGI.RC = &AArch64::FPR64RegClass;
1890 } else if (AArch64::FPR128RegClass.contains(RGI.Reg1)) {
1891 RGI.Type = RegGroupInfo::FPR128;
1892 RGI.RC = &AArch64::FPR128RegClass;
1893 } else if (AArch64::ZPRRegClass.contains(RGI.Reg1)) {
1894 RGI.Type = RegGroupInfo::ZPR;
1895 RGI.RC = &AArch64::ZPRRegClass;
1896 } else if (AArch64::PPRRegClass.contains(RGI.Reg1)) {
1897 RGI.Type = RegGroupInfo::PPR;
1898 RGI.RC = &AArch64::PPRRegClass;
1899 } else if (RGI.Reg1 == AArch64::VG) {
1900 RGI.Type = RegGroupInfo::VG;
1901 RGI.RC = &AArch64::FIXED_REGSRegClass;
1902 } else {
1903 llvm_unreachable("Unsupported register class.");
1904 }
1905
1906 int &ScalableByteOffset = RGI.Type == RegGroupInfo::PPR && SplitPPRs
1907 ? PPRByteOffset
1908 : ZPRByteOffset;
1909
1910 // Add the stack hazard size as we transition from GPR->FPR CSRs.
1911 if (HasCSHazardPadding &&
1912 (!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) &&
1914 ByteOffset += StackFillDir * StackHazardSize;
1915 LastReg = RGI.Reg1;
1916
1917 int Scale = TRI->getSpillSize(*RGI.RC);
1918 // Add the next reg to the pair if it is in the same register class.
1919 if (unsigned(i + RegInc) < Count && !HasCSHazardPadding) {
1920 MCRegister NextReg = CSI[i + RegInc].getReg();
1921 int Aligned = AlignOffset(ByteOffset, Scale);
1922 int PairOffset = IsWindows ? Aligned : Aligned + StackFillDir * 2 * Scale;
1923 bool PairFitsImmRange =
1924 PairOffset / Scale >= -64 && PairOffset / Scale <= 63;
1925 switch (RGI.Type) {
1926 case RegGroupInfo::GPR:
1927 case RegGroupInfo::FPR64:
1928 case RegGroupInfo::FPR128: {
1929 const TargetRegisterClass &SpillRC =
1930 RGI.Type == RegGroupInfo::GPR ? AArch64::GPR64RegClass
1931 : RGI.Type == RegGroupInfo::FPR64 ? AArch64::FPR64RegClass
1932 : AArch64::FPR128RegClass;
1933
1934 if (SpillRC.contains(NextReg) && PairFitsImmRange &&
1935 !invalidateRegisterPairing(SpillExtendedVolatile, PairOffset,
1936 RGI.Reg1, NextReg, IsWindows,
1937 NeedsWinCFI, NeedsFrameRecord, TRI))
1938 RGI.Reg2 = NextReg;
1939 break;
1940 }
1941 case RegGroupInfo::PPR:
1942 break;
1943 case RegGroupInfo::ZPR: {
1944 // Windows support is possible but the order requirement is reversed.
1945 // Also, WinCFI has no support for group ZPR loads/stores yet.
1946 if (isTargetWindows(MF) || AFI->getPredicateRegForFillSpill() == 0)
1947 break;
1948
1949 // We expect to see pairs and quads in descending order (e.g. [z7, z6,
1950 // z5, z4]). We ensure this in `orderZPRCalleeSavesForGroups()`. This
1951 // is required as (for Linux) StackFillDir is negative (so we start at
1952 // higher addresses) and we need to ensure the lower register in the
1953 // pair has the lower address to store the registers in the correct
1954 // order.
1955 auto GetZPRTupleLowestReg =
1956 [&](unsigned NumRegs) -> std::optional<Register> {
1957 // Check Reg1 is the last register in a tuple.
1958 if (RGI.Reg1 % NumRegs != NumRegs - 1)
1959 return std::nullopt;
1960
1961 // Check there's enough registers for the tuple.
1962 if (i + RegInc * NumRegs > Count)
1963 return std::nullopt;
1964
1965 for (unsigned Idx = 1; Idx < NumRegs; ++Idx) {
1966 Register Reg = CSI[i + RegInc * Idx].getReg();
1967 Register ExpectedReg = RGI.Reg1 - Idx;
1968 if (Reg != ExpectedReg)
1969 return std::nullopt;
1970 }
1971
1972 return RGI.Reg1 - NumRegs + 1;
1973 };
1974
1975 for (unsigned TupleSize : {4, 2}) {
1976 if (auto LowReg = GetZPRTupleLowestReg(TupleSize)) {
1977 // Note: ST1B has the same offset constraints.
1978 unsigned Opcode =
1979 TupleSize == 4 ? AArch64::LD1B_4Z_IMM : AArch64::LD1B_2Z_IMM;
1980 const int Offset =
1981 (ScalableByteOffset + StackFillDir * TupleSize * Scale);
1982 if (isValidMemOpOffset(TII, Opcode, Offset)) {
1983 RGI.Reg2 = *LowReg;
1984 break;
1985 }
1986 }
1987 }
1988
1989 break;
1990 }
1991 case RegGroupInfo::VG:
1992 break;
1993 }
1994 }
1995
1996 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI
1997 // list to come in sorted by frame index so that we can issue the store
1998 // pair instructions directly. Assert if we see anything otherwise.
1999 //
2000 // The order of the registers in the list is controlled by
2001 // getCalleeSavedRegs(), so they will always be in-order, as well.
2002 [[maybe_unused]] bool RegsOrdered =
2003 all_of(seq(RGI.getNumRegs() - 1), [&](int RegOffset) {
2004 return CSI[i + RegInc * RegOffset].getFrameIdx() + RegInc ==
2005 CSI[i + RegInc * RegOffset + RegInc].getFrameIdx();
2006 });
2007 assert(RegsOrdered && "Out of order callee saved regs!");
2008
2009 assert((!RGI.isQuad() || RGI.Type == RegGroupInfo::ZPR) &&
2010 "Currently only ZPR's support four-register spills");
2011
2012 assert((!RGI.isPaired() || !NeedsFrameRecord || RGI.Reg2 != AArch64::FP ||
2013 RGI.Reg1 == AArch64::LR) &&
2014 "FrameRecord must be allocated together with LR");
2015
2016 // Windows AAPCS has FP and LR reversed.
2017 assert((!RGI.isPaired() || !NeedsFrameRecord || RGI.Reg1 != AArch64::FP ||
2018 RGI.Reg2 == AArch64::LR) &&
2019 "FrameRecord must be allocated together with LR");
2020
2021 // MachO's compact unwind format relies on all registers being stored in
2022 // adjacent register pairs.
2023 assert((!produceCompactUnwindFrame(AFL, MF) ||
2026 (RGI.isPaired() &&
2027 ((RGI.Reg1 == AArch64::LR && RGI.Reg2 == AArch64::FP) ||
2028 RGI.Reg1 + 1 == RGI.Reg2))) &&
2029 "Callee-save registers not saved as adjacent register pair!");
2030
2031 RGI.FrameIdx = CSI[i].getFrameIdx();
2032 if (IsWindows)
2033 // RGI.FrameIdx must be the lower index of the group
2034 RGI.FrameIdx = CSI[i + RegInc * (RGI.getNumRegs() - 1)].getFrameIdx();
2035
2036 // Realign the scalable offset if necessary. This is relevant when spilling
2037 // predicates on Windows.
2038 if (RGI.isScalable() && ScalableByteOffset % Scale != 0)
2039 ScalableByteOffset = AlignOffset(ScalableByteOffset, Scale);
2040
2041 // Realign the fixed offset if necessary. This is relevant when spilling Q
2042 // registers after spilling an odd amount of X registers.
2043 if (!RGI.isScalable() && ByteOffset % Scale != 0)
2044 ByteOffset = AlignOffset(ByteOffset, Scale);
2045
2046 int OffsetPre = RGI.isScalable() ? ScalableByteOffset : ByteOffset;
2047 assert(OffsetPre % Scale == 0);
2048
2049 if (RGI.isScalable())
2050 ScalableByteOffset += StackFillDir * RGI.getNumRegs() * Scale;
2051 else
2052 ByteOffset += StackFillDir * RGI.getNumRegs() * Scale;
2053
2054 // Swift's async context is directly before FP, so allocate an extra
2055 // 8 bytes for it.
2056 if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2057 ((!IsWindows && RGI.Reg2 == AArch64::FP) ||
2058 (IsWindows && RGI.Reg2 == AArch64::LR)))
2059 ByteOffset += StackFillDir * 8;
2060
2061 // Round up size of non-pair to pair size if we need to pad the
2062 // callee-save area to ensure 16-byte alignment.
2063 if (NeedGapToAlignStack && !IsWindows && !RGI.isScalable() &&
2064 RGI.Type != RegGroupInfo::FPR128 && !RGI.isPaired() &&
2065 ByteOffset % 16 != 0) {
2066 ByteOffset += 8 * StackFillDir;
2067 assert(MFI.getObjectAlign(RGI.FrameIdx) <= Align(16));
2068 // A stack frame with a gap looks like this, bottom up:
2069 // d9, d8. x21, gap, x20, x19.
2070 // Set extra alignment on the x21 object to create the gap above it.
2071 MFI.setObjectAlignment(RGI.FrameIdx, Align(16));
2072 NeedGapToAlignStack = false;
2073 }
2074
2075 int OffsetPost = RGI.isScalable() ? ScalableByteOffset : ByteOffset;
2076 assert(OffsetPost % Scale == 0);
2077 // If filling top down (default), we want the offset after incrementing it.
2078 // If filling bottom up (WinCFI) we need the original offset.
2079 int Offset = IsWindows ? OffsetPre : OffsetPost;
2080
2081 // The FP, LR pair goes 8 bytes into our expanded 24-byte slot so that the
2082 // Swift context can directly precede FP.
2083 if (NeedsFrameRecord && AFI->hasSwiftAsyncContext() &&
2084 ((!IsWindows && RGI.Reg2 == AArch64::FP) ||
2085 (IsWindows && RGI.Reg2 == AArch64::LR)))
2086 Offset += 8;
2087
2088 assert(
2089 (!RGI.isGrouped() || RGI.Type != RegGroupInfo::ZPR ||
2091 TII, (RGI.isQuad() ? AArch64::LD1B_4Z_IMM : AArch64::LD1B_2Z_IMM),
2092 Offset)) &&
2093 "Offset invalid for LD1B/ST1B pair/quad variant immediate");
2094
2095 RGI.Offset = Offset / Scale;
2096 assert((!RGI.isGrouped() || RGI.Type == RegGroupInfo::ZPR ||
2097 (!RGI.isScalable() && RGI.Offset >= -64 && RGI.Offset <= 63) ||
2098 (RGI.isScalable() && RGI.Offset >= -256 && RGI.Offset <= 255)) &&
2099 "Offset out of bounds for LDP/STP immediate");
2100
2101 auto isFrameRecord = [&] {
2102 if (RGI.isPaired())
2103 return IsWindows ? RGI.Reg1 == AArch64::FP && RGI.Reg2 == AArch64::LR
2104 : RGI.Reg1 == AArch64::LR && RGI.Reg2 == AArch64::FP;
2105 // Otherwise, look for the frame record as two unpaired registers. This is
2106 // needed for -aarch64-stack-hazard-size=<val>, which disables register
2107 // pairing (as the padding may be too large for the LDP/STP offset). Note:
2108 // On Windows, this check works out as current reg == FP, next reg == LR,
2109 // and on other platforms current reg == FP, previous reg == LR. This
2110 // works out as the correct pre-increment or post-increment offsets
2111 // respectively.
2112 return i > 0 && RGI.Reg1 == AArch64::FP &&
2113 CSI[i - 1].getReg() == AArch64::LR;
2114 };
2115
2116 // Save the offset to frame record so that the FP register can point to the
2117 // innermost frame record (spilled FP and LR registers).
2118 if (NeedsFrameRecord && isFrameRecord())
2120
2121 RegGroups.push_back(RGI);
2122 i += RegInc * (RGI.getNumRegs() - 1);
2123 }
2124 if (IsWindows) {
2125 // If we need an alignment gap in the stack, align the topmost stack
2126 // object. A stack frame with a gap looks like this, bottom up:
2127 // x19, d8. d9, gap.
2128 // Set extra alignment on the topmost stack object (the first element in
2129 // CSI, which goes top down), to create the gap above it.
2130 if (AFI->hasCalleeSaveStackFreeSpace())
2131 MFI.setObjectAlignment(CSI[0].getFrameIdx(), Align(16));
2132 // We iterated bottom up over the registers; flip RegGroups back to top
2133 // down order.
2134 std::reverse(RegGroups.begin(), RegGroups.end());
2135 }
2136}
2137
2141 MachineFunction &MF = *MBB.getParent();
2143 auto &TLI = *Subtarget.getTargetLowering();
2144 const AArch64InstrInfo &TII = *Subtarget.getInstrInfo();
2145 bool NeedsWinCFI = MF.needsWinCFI();
2146 DebugLoc DL;
2148
2149 computeCalleeSaveRegisterGroups(*this, MF, CSI, TRI, RegGroups, hasFP(MF));
2150
2152 // Refresh the reserved regs in case there are any potential changes since the
2153 // last freeze.
2154 MRI.freezeReservedRegs();
2155
2156 if (homogeneousPrologEpilog(MF)) {
2157 auto MIB = BuildMI(MBB, MI, DL, TII.get(AArch64::HOM_Prolog))
2159
2160 for (auto &RGI : RegGroups) {
2161 MIB.addReg(RGI.Reg1);
2162 MIB.addReg(RGI.Reg2);
2163
2164 // Update register live in.
2165 if (!MRI.isReserved(RGI.Reg1))
2166 MBB.addLiveIn(RGI.Reg1);
2167 if (RGI.isPaired() && !MRI.isReserved(RGI.Reg2))
2168 MBB.addLiveIn(RGI.Reg2);
2169 }
2170 return true;
2171 }
2172 bool PTrueCreated = false;
2173 for (const RegGroupInfo &RGI : llvm::reverse(RegGroups)) {
2174 Register Reg1 = RGI.Reg1;
2175 Register Reg2 = RGI.Reg2;
2176 unsigned StrOpc;
2177
2178 // Issue sequence of spills for cs regs. The first spill may be converted
2179 // to a pre-decrement store later by emitPrologue if the callee-save stack
2180 // area allocation can't be combined with the local stack area allocation.
2181 // For example:
2182 // stp x22, x21, [sp, #0] // addImm(+0)
2183 // stp x20, x19, [sp, #16] // addImm(+2)
2184 // stp fp, lr, [sp, #32] // addImm(+4)
2185 // Rationale: This sequence saves uop updates compared to a sequence of
2186 // pre-increment spills like stp xi,xj,[sp,#-16]!
2187 // Note: Similar rationale and sequence for restores in epilog.
2188 unsigned Size = TRI->getSpillSize(*RGI.RC);
2189 Align Alignment = TRI->getSpillAlign(*RGI.RC);
2190 switch (RGI.Type) {
2191 case RegGroupInfo::GPR:
2192 StrOpc = RGI.isPaired() ? AArch64::STPXi : AArch64::STRXui;
2193 break;
2194 case RegGroupInfo::FPR64:
2195 StrOpc = RGI.isPaired() ? AArch64::STPDi : AArch64::STRDui;
2196 break;
2197 case RegGroupInfo::FPR128:
2198 StrOpc = RGI.isPaired() ? AArch64::STPQi : AArch64::STRQui;
2199 break;
2200 case RegGroupInfo::ZPR:
2201 StrOpc = RGI.isQuad()
2202 ? AArch64::ST1B_4Z_IMM
2203 : (RGI.isPaired() ? AArch64::ST1B_2Z_IMM : AArch64::STR_ZXI);
2204 break;
2205 case RegGroupInfo::PPR:
2206 StrOpc = AArch64::STR_PXI;
2207 break;
2208 case RegGroupInfo::VG:
2209 StrOpc = AArch64::STRXui;
2210 break;
2211 }
2212
2213 Register X0Scratch;
2214 llvm::scope_exit RestoreX0([&] {
2215 if (X0Scratch.isValid())
2216 BuildMI(MBB, MI, DL, TII.get(TargetOpcode::COPY), AArch64::X0)
2217 .addReg(X0Scratch)
2219 });
2220
2221 if (Reg1 == AArch64::VG) {
2222 // Find an available register to store value of VG to.
2223 Reg1 = findScratchNonCalleeSaveRegister(&MBB, true);
2224 assert(Reg1.isValid());
2225 if (MF.getSubtarget<AArch64Subtarget>().hasSVE()) {
2226 BuildMI(MBB, MI, DL, TII.get(AArch64::CNTD_XPiI), Reg1)
2227 .addImm(31)
2228 .addImm(1)
2230 } else {
2232 if (any_of(MBB.liveins(),
2233 [&STI](const MachineBasicBlock::RegisterMaskPair &LiveIn) {
2234 return STI.getRegisterInfo()->isSuperOrSubRegisterEq(
2235 AArch64::X0, LiveIn.PhysReg);
2236 })) {
2237 X0Scratch = Reg1;
2238 BuildMI(MBB, MI, DL, TII.get(TargetOpcode::COPY), X0Scratch)
2239 .addReg(AArch64::X0)
2241 }
2242
2243 RTLIB::Libcall LC = RTLIB::SMEABI_GET_CURRENT_VG;
2244 const uint32_t *RegMask =
2245 TRI->getCallPreservedMask(MF, TLI.getLibcallCallingConv(LC));
2246 BuildMI(MBB, MI, DL, TII.get(AArch64::BL))
2247 .addExternalSymbol(TLI.getLibcallName(LC))
2248 .addRegMask(RegMask)
2249 .addReg(AArch64::X0, RegState::ImplicitDefine)
2251 Reg1 = AArch64::X0;
2252 }
2253 }
2254
2255 LLVM_DEBUG(dbgs() << "CSR spill: ");
2256 LLVM_DEBUG(RGI.dump(TRI));
2257
2258 assert((!isTargetWindows(MF) ||
2259 !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) &&
2260 "Windows unwdinding requires a consecutive (FP,LR) pair");
2261
2263 unsigned PnReg = AFI->getPredicateRegForFillSpill();
2264
2265 if (!PTrueCreated && RGI.isGrouped() && RGI.isScalable()) {
2266 [[maybe_unused]] const AArch64Subtarget &Subtarget =
2268 assert((PnReg != 0 && enableMultiVectorSpillFill(Subtarget, MF)) &&
2269 "Expects SVE2.1 or SME2 target and a predicate register");
2270 PTrueCreated = true;
2271 BuildMI(MBB, MI, DL, TII.get(AArch64::PTRUE_C_B), PnReg)
2273 }
2274
2275 SmallVector<Register, 4> Registers = RGI.getRegisters();
2277 if (!MRI.isReserved(Reg))
2278 MBB.addLiveIn(Reg);
2279
2280 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc));
2281 if (RGI.isGrouped() && RGI.isScalable()) {
2282 assert(!isTargetWindows(MF) &&
2283 "Scalable register groups are not supported by Windows CFI yet");
2284#ifdef EXPENSIVE_CHECKS
2285 auto IsPPR = [](const RegGroupInfo &c) {
2286 return c.Type == RegGroupInfo::PPR;
2287 };
2288 auto PPRBegin = std::find_if(RegGroups.begin(), RegGroups.end(), IsPPR);
2289 auto IsZPR = [](const RegGroupInfo &c) {
2290 return c.Type == RegGroupInfo::ZPR;
2291 };
2292 auto ZPRBegin = std::find_if(RegGroups.begin(), RegGroups.end(), IsZPR);
2293 assert(!(PPRBegin < ZPRBegin) &&
2294 "Expected callee save predicate to be handled first");
2295#endif
2296
2297 assert(RGI.Reg2 < RGI.Reg1 && "Expected reversed ZPR group");
2298 MIB.addReg(RGI.getAsMultiVectorRegister());
2299
2300 MIB.addReg(PnReg);
2301 MIB.addReg(AArch64::SP)
2302 .addImm(RGI.Offset /
2303 RGI.getNumRegs()) // [sp, #imm*size*vscale],
2304 // where size*vscale is implicit
2306 } else { // The code when the pair of ZReg is not present
2307 // Windows unwind codes require consecutive registers if registers are
2308 // paired. Make the switch here, so that the code below will save (x,x+1)
2309 // and not (x+1,x).
2310 if (isTargetWindows(MF) && RGI.isPaired())
2311 std::swap(Reg1, Reg2);
2312 if (RGI.isPaired()) {
2313 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2));
2314 }
2315 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1))
2316 .addReg(AArch64::SP)
2317 .addImm(RGI.Offset) // [sp, #offset*vscale],
2318 // where factor*vscale is implicit
2320 if (NeedsWinCFI)
2321 insertSEH(MIB, TII, MachineInstr::FrameSetup);
2322 }
2323
2324 // Handle the StackIDs.
2325 MachineFrameInfo &MFI = MF.getFrameInfo();
2326 for (int FI :
2327 reverse_conditionally(RGI.getFrameIndexes(), !isTargetWindows(MF))) {
2328 MIB.addMemOperand(
2330 MachineMemOperand::MOStore, Size, Alignment));
2331 if (RGI.Type == RegGroupInfo::ZPR)
2333 else if (RGI.Type == RegGroupInfo::PPR)
2335 }
2336 }
2337 return true;
2338}
2339
2343 MachineFunction &MF = *MBB.getParent();
2344 const AArch64InstrInfo &TII =
2345 *MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
2346 DebugLoc DL;
2348 bool NeedsWinCFI = MF.needsWinCFI();
2349
2350 if (MBBI != MBB.end())
2351 DL = MBBI->getDebugLoc();
2352
2353 computeCalleeSaveRegisterGroups(*this, MF, CSI, TRI, RegGroups, hasFP(MF));
2354 if (homogeneousPrologEpilog(MF, &MBB)) {
2355 auto MIB = BuildMI(MBB, MBBI, DL, TII.get(AArch64::HOM_Epilog))
2357 for (auto &RGI : RegGroups) {
2358 MIB.addReg(RGI.Reg1, RegState::Define);
2359 MIB.addReg(RGI.Reg2, RegState::Define);
2360 }
2361 return true;
2362 }
2363
2364 // For performance reasons restore SVE register in increasing order
2365 auto IsPPR = [](const RegGroupInfo &c) {
2366 return c.Type == RegGroupInfo::PPR;
2367 };
2368 auto PPRBegin = llvm::find_if(RegGroups, IsPPR);
2369 auto PPREnd = std::find_if_not(PPRBegin, RegGroups.end(), IsPPR);
2370 std::reverse(PPRBegin, PPREnd);
2371 auto IsZPR = [](const RegGroupInfo &c) {
2372 return c.Type == RegGroupInfo::ZPR;
2373 };
2374 auto ZPRBegin = llvm::find_if(RegGroups, IsZPR);
2375 auto ZPREnd = std::find_if_not(ZPRBegin, RegGroups.end(), IsZPR);
2376 std::reverse(ZPRBegin, ZPREnd);
2377
2378 // If the return address is authenticated before the epilogue, it stays in LR
2379 // rather than being restored here, as that would replace it with the
2380 // unauthenticated value from the stack.
2381 bool KeepLR = authenticatesReturnAddressEarly(MF, MBB);
2382
2383 bool PTrueCreated = false;
2384 for (const RegGroupInfo &RGI : RegGroups) {
2385 Register Reg1 = RGI.Reg1;
2386 Register Reg2 = RGI.Reg2;
2387
2388 // Issue sequence of restores for cs regs. The last restore may be converted
2389 // to a post-increment load later by emitEpilogue if the callee-save stack
2390 // area allocation can't be combined with the local stack area allocation.
2391 // For example:
2392 // ldp fp, lr, [sp, #32] // addImm(+4)
2393 // ldp x20, x19, [sp, #16] // addImm(+2)
2394 // ldp x22, x21, [sp, #0] // addImm(+0)
2395 // Note: see comment in spillCalleeSavedRegisters()
2396 unsigned LdrOpc;
2397 unsigned Size = TRI->getSpillSize(*RGI.RC);
2398 Align Alignment = TRI->getSpillAlign(*RGI.RC);
2399 switch (RGI.Type) {
2400 case RegGroupInfo::GPR:
2401 LdrOpc = RGI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui;
2402 break;
2403 case RegGroupInfo::FPR64:
2404 LdrOpc = RGI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui;
2405 break;
2406 case RegGroupInfo::FPR128:
2407 LdrOpc = RGI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui;
2408 break;
2409 case RegGroupInfo::ZPR:
2410 LdrOpc = RGI.isQuad()
2411 ? AArch64::LD1B_4Z_IMM
2412 : (RGI.isPaired() ? AArch64::LD1B_2Z_IMM : AArch64::LDR_ZXI);
2413 break;
2414 case RegGroupInfo::PPR:
2415 LdrOpc = AArch64::LDR_PXI;
2416 break;
2417 case RegGroupInfo::VG:
2418 continue;
2419 }
2420
2421 LLVM_DEBUG(dbgs() << "CSR restore: ");
2422 LLVM_DEBUG(RGI.dump(TRI));
2423
2425 unsigned PnReg = AFI->getPredicateRegForFillSpill();
2426
2427 if (!PTrueCreated && RGI.isGrouped() && RGI.isScalable()) {
2428 [[maybe_unused]] const AArch64Subtarget &Subtarget =
2430 assert((PnReg != 0 && enableMultiVectorSpillFill(Subtarget, MF)) &&
2431 "Expects SVE2.1 or SME2 target and a predicate register");
2432 PTrueCreated = true;
2433 BuildMI(MBB, MBBI, DL, TII.get(AArch64::PTRUE_C_B), PnReg)
2435 }
2436
2437 if (KeepLR && RGI.Type == RegGroupInfo::GPR &&
2438 (Reg1 == AArch64::LR || Reg2 == AArch64::LR)) {
2439 // Windows pairs LR with the register before it, which is the one at the
2440 // lower address, so restore just that register. The pair has not been
2441 // swapped yet at this point, so that register is Reg1.
2442 if (!RGI.isPaired())
2443 continue;
2444 assert(Reg2 == AArch64::LR && "Expected LR to be the second of the pair");
2446 BuildMI(MBB, MBBI, DL, TII.get(AArch64::LDRXui));
2447 MIB.addReg(Reg1, getDefRegState(true));
2448 MIB.addReg(AArch64::SP)
2449 .addImm(RGI.Offset)
2452 MachinePointerInfo::getFixedStack(MF, RGI.FrameIdx),
2454 if (NeedsWinCFI)
2455 insertSEH(MIB, TII, MachineInstr::FrameDestroy);
2456 continue;
2457 }
2458
2459 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII.get(LdrOpc));
2460 if (RGI.isGrouped() && RGI.isScalable()) {
2461 assert(!isTargetWindows(MF) &&
2462 "Scalable register groups are not supported by Windows CFI yet");
2463#ifdef EXPENSIVE_CHECKS
2464 assert(!(PPRBegin < ZPRBegin) &&
2465 "Expected callee save predicate to be handled first");
2466#endif
2467 assert(RGI.Reg2 < RGI.Reg1 && "Expected reversed ZPR group");
2468 MIB.addReg(RGI.getAsMultiVectorRegister(), getDefRegState(true));
2469 MIB.addReg(PnReg);
2470 MIB.addReg(AArch64::SP)
2471 .addImm(RGI.Offset /
2472 RGI.getNumRegs()) // [sp, #imm*size*vscale]
2473 // where size*vscale is implicit
2475 } else {
2476 // Windows unwind codes require consecutive registers if registers are
2477 // paired. Make the switch here, so that the code below will save (x,x+1)
2478 // and not (x+1,x).
2479 if (isTargetWindows(MF) && RGI.isPaired())
2480 std::swap(Reg1, Reg2);
2481 if (RGI.isPaired())
2482 MIB.addReg(Reg2, getDefRegState(true));
2483 MIB.addReg(Reg1, getDefRegState(true));
2484 MIB.addReg(AArch64::SP)
2485 .addImm(RGI.Offset) // [sp, #offset*vscale]
2486 // where factor*vscale is implicit
2488 if (NeedsWinCFI)
2489 insertSEH(MIB, TII, MachineInstr::FrameDestroy);
2490 }
2491
2492 for (int FI :
2493 reverse_conditionally(RGI.getFrameIndexes(), !isTargetWindows(MF)))
2494 MIB.addMemOperand(
2496 MachineMemOperand::MOLoad, Size, Alignment));
2497 }
2498 return true;
2499}
2500
2501// Return the FrameID for a MMO.
2502static std::optional<int> getMMOFrameID(MachineMemOperand *MMO,
2503 const MachineFrameInfo &MFI) {
2504 auto *PSV =
2506 if (PSV)
2507 return std::optional<int>(PSV->getFrameIndex());
2508
2509 if (MMO->getValue()) {
2510 if (auto *Al = dyn_cast<AllocaInst>(getUnderlyingObject(MMO->getValue()))) {
2511 for (int FI = MFI.getObjectIndexBegin(); FI < MFI.getObjectIndexEnd();
2512 FI++)
2513 if (MFI.getObjectAllocation(FI) == Al)
2514 return FI;
2515 }
2516 }
2517
2518 return std::nullopt;
2519}
2520
2521// Return the FrameID for a Load/Store instruction by looking at the first MMO.
2522static std::optional<int> getLdStFrameID(const MachineInstr &MI,
2523 const MachineFrameInfo &MFI) {
2524 if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1)
2525 return std::nullopt;
2526
2527 return getMMOFrameID(*MI.memoperands_begin(), MFI);
2528}
2529
2530// Returns true if the LDST MachineInstr \p MI is a PPR access.
2531static bool isPPRAccess(const MachineInstr &MI) {
2532 return AArch64::PPRRegClass.contains(MI.getOperand(0).getReg());
2533}
2534
2535// Check if a Hazard slot is needed for the current function, and if so create
2536// one for it. The index is stored in AArch64FunctionInfo->StackHazardSlotIndex,
2537// which can be used to determine if any hazard padding is needed.
2538void AArch64FrameLowering::determineStackHazardSlot(
2539 MachineFunction &MF, BitVector &SavedRegs) const {
2540 unsigned StackHazardSize = getStackHazardSize(MF);
2541 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2542 if (StackHazardSize == 0 || StackHazardSize % 16 != 0 ||
2544 return;
2545
2546 // Stack hazards are only needed in streaming functions.
2547 SMEAttrs Attrs = AFI->getSMEFnAttrs();
2548 const AArch64Options &CLOpts =
2549 MF.getSubtarget<AArch64Subtarget>().getCLOpts();
2550 if (!CLOpts.stack_hazard_in_non_streaming &&
2551 Attrs.hasNonStreamingInterfaceAndBody())
2552 return;
2553
2554 MachineFrameInfo &MFI = MF.getFrameInfo();
2555
2556 // Add a hazard slot if there are any CSR FPR registers, or are any fp-only
2557 // stack objects.
2558 bool HasFPRCSRs = any_of(SavedRegs.set_bits(), [](unsigned Reg) {
2559 return AArch64::FPR64RegClass.contains(Reg) ||
2560 AArch64::FPR128RegClass.contains(Reg) ||
2561 AArch64::ZPRRegClass.contains(Reg);
2562 });
2563 bool HasPPRCSRs = any_of(SavedRegs.set_bits(), [](unsigned Reg) {
2564 return AArch64::PPRRegClass.contains(Reg);
2565 });
2566 bool HasFPRStackObjects = false;
2567 bool HasPPRStackObjects = false;
2568 if (!HasFPRCSRs || CLOpts.split_sve_objects) {
2569 enum SlotType : uint8_t {
2570 Unknown = 0,
2571 ZPRorFPR = 1 << 0,
2572 PPR = 1 << 1,
2573 GPR = 1 << 2,
2575 };
2576
2577 // Find stack slots solely used for one kind of register (ZPR, PPR, etc.),
2578 // based on the kinds of accesses used in the function.
2579 SmallVector<SlotType> SlotTypes(MFI.getObjectIndexEnd(), SlotType::Unknown);
2580 for (auto &MBB : MF) {
2581 for (auto &MI : MBB) {
2582 std::optional<int> FI = getLdStFrameID(MI, MFI);
2583 if (!FI || FI < 0 || FI > int(SlotTypes.size()))
2584 continue;
2585 if (MFI.hasScalableStackID(*FI)) {
2586 SlotTypes[*FI] |=
2587 isPPRAccess(MI) ? SlotType::PPR : SlotType::ZPRorFPR;
2588 } else {
2589 SlotTypes[*FI] |= AArch64InstrInfo::isFpOrNEON(MI)
2590 ? SlotType::ZPRorFPR
2591 : SlotType::GPR;
2592 }
2593 }
2594 }
2595
2596 for (int FI = 0; FI < int(SlotTypes.size()); ++FI) {
2597 HasFPRStackObjects |= SlotTypes[FI] == SlotType::ZPRorFPR;
2598 // For SplitSVEObjects remember that this stack slot is a predicate, this
2599 // will be needed later when determining the frame layout.
2600 if (SlotTypes[FI] == SlotType::PPR) {
2602 HasPPRStackObjects = true;
2603 }
2604 }
2605 }
2606
2607 if (HasFPRCSRs || HasFPRStackObjects) {
2608 int ID = MFI.CreateStackObject(StackHazardSize, Align(16), false);
2609 LLVM_DEBUG(dbgs() << "Created Hazard slot at " << ID << " size "
2610 << StackHazardSize << "\n");
2611 AFI->setStackHazardSlotIndex(ID);
2612 }
2613
2614 if (!AFI->hasStackHazardSlotIndex())
2615 return;
2616
2617 if (CLOpts.split_sve_objects) {
2618 CallingConv::ID CC = MF.getFunction().getCallingConv();
2620 AFI->setSplitSVEObjects(true);
2621 LLVM_DEBUG(dbgs() << "Using SplitSVEObjects for SVE CC function\n");
2622 return;
2623 }
2624
2625 // We only use SplitSVEObjects in non-SVE CC functions if there's a
2626 // possibility of a stack hazard between PPRs and ZPRs/FPRs.
2627 LLVM_DEBUG(dbgs() << "Determining if SplitSVEObjects should be used in "
2628 "non-SVE CC function...\n");
2629
2630 // If another calling convention is explicitly set FPRs can't be promoted to
2631 // ZPR callee-saves.
2633 LLVM_DEBUG(
2634 dbgs()
2635 << "Calling convention is not supported with SplitSVEObjects\n");
2636 return;
2637 }
2638
2639 if (!HasPPRCSRs && !HasPPRStackObjects) {
2640 LLVM_DEBUG(
2641 dbgs() << "Not using SplitSVEObjects as no PPRs are on the stack\n");
2642 return;
2643 }
2644
2645 if (!HasFPRCSRs && !HasFPRStackObjects) {
2646 LLVM_DEBUG(
2647 dbgs()
2648 << "Not using SplitSVEObjects as no FPRs or ZPRs are on the stack\n");
2649 return;
2650 }
2651
2652 [[maybe_unused]] const AArch64Subtarget &Subtarget =
2653 MF.getSubtarget<AArch64Subtarget>();
2655 "Expected SVE to be available for PPRs");
2656
2657 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
2658 // With SplitSVEObjects the CS hazard padding is placed between the
2659 // PPRs and ZPRs. If there are any FPR CS there would be a hazard between
2660 // them and the CS GRPs. Avoid this by promoting all FPR CS to ZPRs.
2661 BitVector FPRZRegs(SavedRegs.size());
2662 for (size_t Reg = 0, E = SavedRegs.size(); HasFPRCSRs && Reg < E; ++Reg) {
2663 BitVector::reference RegBit = SavedRegs[Reg];
2664 if (!RegBit)
2665 continue;
2666 unsigned SubRegIdx = 0;
2667 if (AArch64::FPR64RegClass.contains(Reg))
2668 SubRegIdx = AArch64::dsub;
2669 else if (AArch64::FPR128RegClass.contains(Reg))
2670 SubRegIdx = AArch64::zsub;
2671 else
2672 continue;
2673 // Clear the bit for the FPR save.
2674 RegBit = false;
2675 // Mark that we should save the corresponding ZPR.
2676 Register ZReg =
2677 TRI->getMatchingSuperReg(Reg, SubRegIdx, &AArch64::ZPRRegClass);
2678 FPRZRegs.set(ZReg);
2679 }
2680 SavedRegs |= FPRZRegs;
2681
2682 AFI->setSplitSVEObjects(true);
2683 LLVM_DEBUG(dbgs() << "SplitSVEObjects enabled!\n");
2684 }
2685}
2686
2688 BitVector &SavedRegs,
2689 RegScavenger *RS) const {
2691 // All calls are tail calls in GHC calling conv, and functions have no
2692 // prologue/epilogue.
2695 AFI->setSVECalleeSavedStackSize(/*ZPR=*/0, /*PPR=*/0);
2696 return;
2697 }
2698
2700
2702 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2703 Register UnspilledCSGPR;
2704 Register UnspilledCSGPRPaired;
2705
2706 MachineFrameInfo &MFI = MF.getFrameInfo();
2707 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
2708
2709 MCRegister BasePointerReg =
2710 RegInfo->hasBasePointer(MF) ? RegInfo->getBaseRegister() : MCRegister();
2711
2712 Register ExtraCSSpill;
2713 bool HasUnpairedGPR64 = false;
2714 bool HasPairZReg = false;
2715 BitVector UserReservedRegs = RegInfo->getUserReservedRegs(MF);
2716 BitVector ReservedRegs = RegInfo->getReservedRegs(MF);
2717
2718 // Figure out which callee-saved registers to save/restore.
2719 for (unsigned i = 0; CSRegs[i]; ++i) {
2720 const MCRegister Reg = CSRegs[i];
2721
2722 // Add the base pointer register to SavedRegs if it is callee-save.
2723 if (Reg == BasePointerReg)
2724 SavedRegs.set(Reg);
2725
2726 // Don't save manually reserved registers set through +reserve-x#i,
2727 // even for callee-saved registers, as per GCC's behavior.
2728 if (UserReservedRegs[Reg]) {
2729 SavedRegs.reset(Reg);
2730 continue;
2731 }
2732
2733 bool RegUsed = SavedRegs.test(Reg);
2734 MCRegister PairedReg;
2735 const bool RegIsGPR64 = AArch64::GPR64RegClass.contains(Reg);
2736 if (RegIsGPR64 || AArch64::FPR64RegClass.contains(Reg) ||
2737 AArch64::FPR128RegClass.contains(Reg)) {
2738 // Compensate for odd numbers of GP CSRs.
2739 // For now, all the known cases of odd number of CSRs are of GPRs.
2740 if (HasUnpairedGPR64)
2741 PairedReg = CSRegs[i % 2 == 0 ? i - 1 : i + 1];
2742 else
2743 PairedReg = CSRegs[i ^ 1];
2744 }
2745
2746 // If the function requires all the GP registers to save (SavedRegs),
2747 // and there are an odd number of GP CSRs at the same time (CSRegs),
2748 // PairedReg could be in a different register class from Reg, which would
2749 // lead to a FPR (usually D8) accidentally being marked saved.
2750 if (RegIsGPR64 && !AArch64::GPR64RegClass.contains(PairedReg)) {
2751 PairedReg = Register();
2752 HasUnpairedGPR64 = true;
2753 }
2754 assert(!PairedReg.isValid() ||
2755 AArch64::GPR64RegClass.contains(Reg, PairedReg) ||
2756 AArch64::FPR64RegClass.contains(Reg, PairedReg) ||
2757 AArch64::FPR128RegClass.contains(Reg, PairedReg));
2758
2759 if (!RegUsed) {
2760 if (AArch64::GPR64RegClass.contains(Reg) && !ReservedRegs[Reg]) {
2761 UnspilledCSGPR = Reg;
2762 UnspilledCSGPRPaired = PairedReg;
2763 }
2764 continue;
2765 }
2766
2767 // MachO's compact unwind format relies on all registers being stored in
2768 // pairs.
2769 // FIXME: the usual format is actually better if unwinding isn't needed.
2770 if (producePairRegisters(MF) && PairedReg.isValid() &&
2771 !SavedRegs.test(PairedReg)) {
2772 SavedRegs.set(PairedReg);
2773 if (AArch64::GPR64RegClass.contains(PairedReg) &&
2774 !ReservedRegs[PairedReg])
2775 ExtraCSSpill = PairedReg;
2776 }
2777 // Check if there is a pair of ZRegs, so it can select PReg for spill/fill
2778 HasPairZReg |= (AArch64::ZPRRegClass.contains(Reg, CSRegs[i ^ 1]) &&
2779 SavedRegs.test(CSRegs[i ^ 1]));
2780 }
2781
2782 if (HasPairZReg && enableMultiVectorSpillFill(Subtarget, MF)) {
2784 // Find a suitable predicate register for the multi-vector spill/fill
2785 // instructions.
2786 MCRegister PnReg = findFreePredicateReg(SavedRegs);
2787 if (PnReg.isValid())
2788 AFI->setPredicateRegForFillSpill(PnReg);
2789 // If no free callee-save has been found assign one.
2790 if (!AFI->getPredicateRegForFillSpill() &&
2791 MF.getFunction().getCallingConv() ==
2793 SavedRegs.set(AArch64::P8);
2794 AFI->setPredicateRegForFillSpill(AArch64::PN8);
2795 }
2796
2797 assert(!ReservedRegs[AFI->getPredicateRegForFillSpill()] &&
2798 "Predicate cannot be a reserved register");
2799 }
2800
2802 !Subtarget.isTargetWindowsOrUEFI()) {
2803 // For Windows calling convention on a non-windows OS, where X18 is treated
2804 // as reserved, back up X18 when entering non-windows code (marked with the
2805 // Windows calling convention) and restore when returning regardless of
2806 // whether the individual function uses it - it might call other functions
2807 // that clobber it.
2808 SavedRegs.set(AArch64::X18);
2809 }
2810
2811 // Determine if a Hazard slot should be used and where it should go.
2812 // If SplitSVEObjects is used, the hazard padding is placed between the PPRs
2813 // and ZPRs. Otherwise, it goes in the callee save area.
2814 determineStackHazardSlot(MF, SavedRegs);
2815
2816 // Calculates the callee saved stack size.
2817 unsigned CSStackSize = 0;
2818 unsigned ZPRCSStackSize = 0;
2819 unsigned PPRCSStackSize = 0;
2821 for (unsigned Reg : SavedRegs.set_bits()) {
2822 auto *RC = TRI->getMinimalPhysRegClass(MCRegister(Reg));
2823 assert(RC && "expected register class!");
2824 auto SpillSize = TRI->getSpillSize(*RC);
2825 bool IsZPR = AArch64::ZPRRegClass.contains(Reg);
2826 bool IsPPR = !IsZPR && AArch64::PPRRegClass.contains(Reg);
2827 if (IsZPR)
2828 ZPRCSStackSize += SpillSize;
2829 else if (IsPPR)
2830 PPRCSStackSize += SpillSize;
2831 else {
2832 // A register and its super-register can both appear in SavedRegs.
2833 // Only the widest register is actually spilled, so skip such
2834 // sub-registers here to avoid double-counting the overlap.
2835 bool SavedSuper = any_of(TRI->superregs(Reg), [&](MCPhysReg SuperReg) {
2836 return SavedRegs.test(SuperReg);
2837 });
2838 if (!SavedSuper)
2839 CSStackSize += SpillSize;
2840 }
2841 }
2842
2843 // Save number of saved regs, so we can easily update CSStackSize later to
2844 // account for any additional 64-bit GPR saves. Note: After this point
2845 // only 64-bit GPRs can be added to SavedRegs.
2846 unsigned NumSavedRegs = SavedRegs.count();
2847
2848 // If we have hazard padding in the CS area add that to the size.
2850 CSStackSize += getStackHazardSize(MF);
2851
2852 // Increase the callee-saved stack size if the function has streaming mode
2853 // changes, as we will need to spill the value of the VG register.
2854 if (requiresSaveVG(MF))
2855 CSStackSize += 8;
2856
2857 // If we must call __arm_get_current_vg in the prologue preserve the LR.
2858 if (requiresSaveVG(MF) && !Subtarget.hasSVE())
2859 SavedRegs.set(AArch64::LR);
2860
2861 // The frame record needs to be created by saving the appropriate registers
2862 uint64_t EstimatedStackSize = MFI.estimateStackSize(MF);
2863 if (hasFP(MF) ||
2864 windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) {
2865 SavedRegs.set(AArch64::FP);
2866 SavedRegs.set(AArch64::LR);
2867 }
2868
2869 LLVM_DEBUG({
2870 dbgs() << "*** determineCalleeSaves\nSaved CSRs:";
2871 for (unsigned Reg : SavedRegs.set_bits())
2872 dbgs() << ' ' << printReg(MCRegister(Reg), RegInfo);
2873 dbgs() << "\n";
2874 });
2875
2876 // If any callee-saved registers are used, the frame cannot be eliminated.
2877 auto [ZPRLocalStackSize, PPRLocalStackSize] =
2879 uint64_t SVELocals = ZPRLocalStackSize + PPRLocalStackSize;
2880 uint64_t SVEStackSize =
2881 alignTo(ZPRCSStackSize + PPRCSStackSize + SVELocals, 16);
2882 bool CanEliminateFrame = (SavedRegs.count() == 0) && !SVEStackSize;
2883
2884 // The CSR spill slots have not been allocated yet, so estimateStackSize
2885 // won't include them.
2886 unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF);
2887
2888 // We may address some of the stack above the canonical frame address, either
2889 // for our own arguments or during a call. Include that in calculating whether
2890 // we have complicated addressing concerns.
2891 int64_t CalleeStackUsed = 0;
2892 for (int I = MFI.getObjectIndexBegin(); I != 0; ++I) {
2893 int64_t FixedOff = MFI.getObjectOffset(I);
2894 if (FixedOff > CalleeStackUsed)
2895 CalleeStackUsed = FixedOff;
2896 }
2897
2898 // Conservatively always assume BigStack when there are SVE spills.
2899 bool BigStack = SVEStackSize || (EstimatedStackSize + CSStackSize +
2900 CalleeStackUsed) > EstimatedStackSizeLimit;
2901 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF))
2902 AFI->setHasStackFrame(true);
2903
2904 // Estimate if we might need to scavenge a register at some point in order
2905 // to materialize a stack offset. If so, either spill one additional
2906 // callee-saved register or reserve a special spill slot to facilitate
2907 // register scavenging. If we already spilled an extra callee-saved register
2908 // above to keep the number of spills even, we don't need to do anything else
2909 // here.
2910 if (BigStack) {
2911 if (!ExtraCSSpill.isValid() && UnspilledCSGPR.isValid()) {
2912 LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo)
2913 << " to get a scratch register.\n");
2914 SavedRegs.set(UnspilledCSGPR);
2915 ExtraCSSpill = UnspilledCSGPR;
2916
2917 // MachO's compact unwind format relies on all registers being stored in
2918 // pairs, so if we need to spill one extra for BigStack, then we need to
2919 // store the pair.
2920 if (producePairRegisters(MF)) {
2921 if (!UnspilledCSGPRPaired.isValid()) {
2922 // Failed to make a pair for compact unwind format, revert spilling.
2923 if (produceCompactUnwindFrame(*this, MF)) {
2924 SavedRegs.reset(UnspilledCSGPR);
2925 ExtraCSSpill = Register();
2926 }
2927 } else
2928 SavedRegs.set(UnspilledCSGPRPaired);
2929 }
2930 }
2931
2932 // If we didn't find an extra callee-saved register to spill, create
2933 // an emergency spill slot.
2934 if (!ExtraCSSpill.isValid() ||
2935 MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) {
2937 const TargetRegisterClass &RC = AArch64::GPR64RegClass;
2938 unsigned Size = TRI->getSpillSize(RC);
2939 Align Alignment = TRI->getSpillAlign(RC);
2940 int FI = MFI.CreateSpillStackObject(Size, Alignment);
2941 RS->addScavengingFrameIndex(FI);
2942 LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI
2943 << " as the emergency spill slot.\n");
2944 }
2945 }
2946
2947 // Adding the size of additional 64bit GPR saves.
2948 CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs);
2949
2950 // A Swift asynchronous context extends the frame record with a pointer
2951 // directly before FP.
2952 if (hasFP(MF) && AFI->hasSwiftAsyncContext())
2953 CSStackSize += 8;
2954
2955 uint64_t AlignedCSStackSize = alignTo(CSStackSize, 16);
2956 LLVM_DEBUG(dbgs() << "Estimated stack frame size: "
2957 << EstimatedStackSize + AlignedCSStackSize << " bytes.\n");
2958
2960 AFI->getCalleeSavedStackSize() == AlignedCSStackSize) &&
2961 "Should not invalidate callee saved info");
2962
2963 // Round up to register pair alignment to avoid additional SP adjustment
2964 // instructions.
2965 AFI->setCalleeSavedStackSize(AlignedCSStackSize);
2966 AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize);
2967 AFI->setSVECalleeSavedStackSize(ZPRCSStackSize, alignTo(PPRCSStackSize, 16));
2968}
2969
2970// Reorder ZPRs to maximize grouping, quads and pairs. The main condition we try
2971// to satisfy is the offset and the register number.
2972// Quads require a (scaled offset % 4 == 0) && (LowestRegister % 4 == 0),
2973// e.g: (z4, z5, z6, z7) where z4 is at offset 8 would be legal quad
2974// Pairs require a (scaled offset % 2 == 0) && (LowestRegister % 2 == 0).
2975// e.g: (z4, z5) where z4 is at offset 6 would be a legal pair
2978 std::vector<CalleeSavedInfo> &CSI) {
2979 assert(!isTargetWindows(MF) &&
2980 "ZPR callee-save reordering not supported on Windows");
2981
2982 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
2983 if (!AFI->getPredicateRegForFillSpill())
2984 return;
2985
2986 auto IsZPR = [](CalleeSavedInfo &CS) {
2987 return AArch64::ZPRRegClass.contains(CS.getReg());
2988 };
2989
2991 ZPRSaves = ZPRSaves.drop_until(IsZPR).take_while(IsZPR);
2992
2993 if (ZPRSaves.size() < 2)
2994 return;
2995
2996 int ZPRByteOffset = AFI->getZPRCalleeSavedStackSize();
2997 if (!AFI->hasSplitSVEObjects())
2998 ZPRByteOffset += AFI->getPPRCalleeSavedStackSize();
2999
3000 const int Scale = RegInfo->getSpillSize(AArch64::ZPRRegClass);
3001 const int LowestOffset =
3002 (ZPRByteOffset / Scale) - static_cast<int>(ZPRSaves.size());
3003
3004 int NumToAlign = alignTo(LowestOffset, 4) - LowestOffset;
3005 if (NumToAlign > int(ZPRSaves.size()))
3006 return;
3007
3008 sort(ZPRSaves,
3009 [](const auto &A, const auto &B) { return A.getReg() < B.getReg(); });
3010
3014
3015 int ZPRsNeededForAlignment = NumToAlign;
3016 for (size_t i = 0; i < ZPRSaves.size();) {
3017 int ZPRsRemaining = int(ZPRSaves.size()) - i;
3018 if (i + 3 < ZPRSaves.size() &&
3019 (ZPRSaves[i].getReg() - AArch64::Z0) % 4 == 0 &&
3020 ZPRSaves[i].getReg() + 3 == ZPRSaves[i + 3].getReg() &&
3021 ZPRsRemaining - 4 >= ZPRsNeededForAlignment) {
3022 Quads.push_back(
3023 {ZPRSaves[i], ZPRSaves[i + 1], ZPRSaves[i + 2], ZPRSaves[i + 3]});
3024 i += 4;
3025 continue;
3026 }
3027 // We only need to split a pair if there's no singles. If we have a single
3028 // ZPR then all required alignments (1, 2, or 3) can use that single and a
3029 // ZPR pair.
3030 bool MustSplitPairForSingle =
3031 ZPRsNeededForAlignment == 1 && Singles.empty() && ZPRsRemaining == 2;
3032
3033 if (i + 1 < ZPRSaves.size() &&
3034 (ZPRSaves[i].getReg() - AArch64::Z0) % 2 == 0 &&
3035 ZPRSaves[i].getReg() + 1 == ZPRSaves[i + 1].getReg() &&
3036 !MustSplitPairForSingle) {
3037 Pairs.push_back({ZPRSaves[i], ZPRSaves[i + 1]});
3038 // Don't decrement the ZPRs needed if we require one ZPR for alignment and
3039 // we've yet to find a single ZPR. We may still need to split a pair.
3040 if (ZPRsNeededForAlignment != 1 || !Singles.empty())
3041 ZPRsNeededForAlignment -= 2;
3042
3043 i += 2;
3044 continue;
3045 }
3046
3047 Singles.push_back(ZPRSaves[i++]);
3048 ZPRsNeededForAlignment--;
3049 }
3050
3051 if (Quads.empty() && Pairs.empty())
3052 return;
3053
3054 int NumUnassigned = ZPRSaves.size();
3055 auto Emit = [&](ArrayRef<CalleeSavedInfo> Saves) {
3056 // During pair/quad formation, we check for the register groups in reverse
3057 // order. This is to ensures that stack indexes remain consistent with the
3058 // instruction.
3059 for (const CalleeSavedInfo &CS : Saves)
3060 ZPRSaves[--NumUnassigned] = CS;
3061 };
3062
3063 // Align the offset to a multiple of 4 (to allow for the most quads/pairs).
3064 if (NumToAlign & 0b01)
3065 Emit(Singles.pop_back_val());
3066 if (NumToAlign & 0b10) {
3067 if (!Pairs.empty())
3068 Emit(Pairs.pop_back_val());
3069 else
3070 Emit({Singles.pop_back_val(), Singles.pop_back_val()});
3071 }
3072
3073 for (const auto &Quad : Quads)
3074 Emit(Quad);
3075
3076 for (const auto &Pair : Pairs)
3077 Emit(Pair);
3078
3079 for (const auto &Single : Singles)
3080 Emit(Single);
3081}
3082
3084 MachineFunction &MF, const TargetRegisterInfo *RegInfo,
3085 std::vector<CalleeSavedInfo> &CSI) const {
3086 bool IsWindows = isTargetWindows(MF);
3087 unsigned StackHazardSize = getStackHazardSize(MF);
3088 // To match the canonical windows frame layout, reverse the list of
3089 // callee saved registers to get them laid out by PrologEpilogInserter
3090 // in the right order. (PrologEpilogInserter allocates stack objects top
3091 // down. Windows canonical prologs store higher numbered registers at
3092 // the top, thus have the CSI array start from the highest registers.)
3093 if (IsWindows)
3094 std::reverse(CSI.begin(), CSI.end());
3095
3096 if (CSI.empty())
3097 return true; // Early exit if no callee saved registers are modified!
3098
3099 // Now that we know which registers need to be saved and restored, allocate
3100 // stack slots for them.
3101 MachineFrameInfo &MFI = MF.getFrameInfo();
3102 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
3103
3104 // Insert VG into the list of CSRs, immediately before LR if saved.
3105 if (requiresSaveVG(MF)) {
3106 CalleeSavedInfo VGInfo(AArch64::VG);
3107 auto It =
3108 find_if(CSI, [](auto &Info) { return Info.getReg() == AArch64::LR; });
3109 if (It != CSI.end())
3110 CSI.insert(It, VGInfo);
3111 else
3112 CSI.push_back(VGInfo);
3113 }
3114
3116 if (!IsWindows && enableMultiVectorSpillFill(Subtarget, MF))
3117 // The Windows stack layout is not supported by this reordering function
3118 // yet.
3119 orderZPRCalleeSavesForGroups(MF, RegInfo, CSI);
3120
3121 Register LastReg = 0;
3122 int HazardSlotIndex = std::numeric_limits<int>::max();
3123 for (auto &CS : CSI) {
3124 MCRegister Reg = CS.getReg();
3125 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
3126
3127 // Create a hazard slot as we switch between GPR and FPR CSRs.
3129 (!LastReg || !AArch64InstrInfo::isFpOrNEON(LastReg)) &&
3131 assert(HazardSlotIndex == std::numeric_limits<int>::max() &&
3132 "Unexpected register order for hazard slot");
3133 HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true);
3134 LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex
3135 << "\n");
3136 AFI->setStackHazardCSRSlotIndex(HazardSlotIndex);
3137 MFI.setIsCalleeSavedObjectIndex(HazardSlotIndex, true);
3138 }
3139
3140 unsigned Size = RegInfo->getSpillSize(*RC);
3141 Align Alignment(RegInfo->getSpillAlign(*RC));
3142 int FrameIdx = MFI.CreateStackObject(Size, Alignment, true);
3143 CS.setFrameIdx(FrameIdx);
3144 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
3145
3146 // Grab 8 bytes below FP for the extended asynchronous frame info.
3147 if (hasFP(MF) && AFI->hasSwiftAsyncContext() && Reg == AArch64::FP) {
3148 FrameIdx = MFI.CreateStackObject(8, Alignment, true);
3149 AFI->setSwiftAsyncContextFrameIdx(FrameIdx);
3150 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
3151 }
3152 LastReg = Reg;
3153 }
3154
3155 // Add hazard slot in the case where no FPR CSRs are present.
3157 HazardSlotIndex == std::numeric_limits<int>::max()) {
3158 HazardSlotIndex = MFI.CreateStackObject(StackHazardSize, Align(8), true);
3159 LLVM_DEBUG(dbgs() << "Created CSR Hazard at slot " << HazardSlotIndex
3160 << "\n");
3161 AFI->setStackHazardCSRSlotIndex(HazardSlotIndex);
3162 MFI.setIsCalleeSavedObjectIndex(HazardSlotIndex, true);
3163 }
3164
3165 return true;
3166}
3167
3169 const MachineFunction &MF) const {
3171 // If the function has streaming-mode changes, don't scavenge a
3172 // spillslot in the callee-save area, as that might require an
3173 // 'addvl' in the streaming-mode-changing call-sequence when the
3174 // function doesn't use a FP.
3175 if (AFI->hasStreamingModeChanges() && !hasFP(MF))
3176 return false;
3177 // Don't allow register salvaging with hazard slots, in case it moves objects
3178 // into the wrong place.
3179 if (AFI->hasStackHazardSlotIndex())
3180 return false;
3181 return AFI->hasCalleeSaveStackFreeSpace();
3182}
3183
3184/// returns true if there are any SVE callee saves.
3186 int &Min, int &Max) {
3187 Min = std::numeric_limits<int>::max();
3188 Max = std::numeric_limits<int>::min();
3189
3190 if (!MFI.isCalleeSavedInfoValid())
3191 return false;
3192
3193 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
3194 for (auto &CS : CSI) {
3195 if (AArch64::ZPRRegClass.contains(CS.getReg()) ||
3196 AArch64::PPRRegClass.contains(CS.getReg())) {
3197 assert((Max == std::numeric_limits<int>::min() ||
3198 Max + 1 == CS.getFrameIdx()) &&
3199 "SVE CalleeSaves are not consecutive");
3200 Min = std::min(Min, CS.getFrameIdx());
3201 Max = std::max(Max, CS.getFrameIdx());
3202 }
3203 }
3204 return Min != std::numeric_limits<int>::max();
3205}
3206
3208 AssignObjectOffsets AssignOffsets) {
3209 MachineFrameInfo &MFI = MF.getFrameInfo();
3210 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
3211
3212 SVEStackSizes SVEStack{};
3213
3214 // With SplitSVEObjects we maintain separate stack offsets for predicates
3215 // (PPRs) and SVE vectors (ZPRs). When SplitSVEObjects is disabled predicates
3216 // are included in the SVE vector area.
3217 uint64_t &ZPRStackTop = SVEStack.ZPRStackSize;
3218 uint64_t &PPRStackTop =
3219 AFI->hasSplitSVEObjects() ? SVEStack.PPRStackSize : SVEStack.ZPRStackSize;
3220
3221#ifndef NDEBUG
3222 // First process all fixed stack objects.
3223 for (int I = MFI.getObjectIndexBegin(); I != 0; ++I)
3224 assert(!MFI.hasScalableStackID(I) &&
3225 "SVE vectors should never be passed on the stack by value, only by "
3226 "reference.");
3227#endif
3228
3229 auto AllocateObject = [&](int FI) {
3231 ? ZPRStackTop
3232 : PPRStackTop;
3233
3234 // FIXME: Given that the length of SVE vectors is not necessarily a power of
3235 // two, we'd need to align every object dynamically at runtime if the
3236 // alignment is larger than 16. This is not yet supported.
3237 Align Alignment = MFI.getObjectAlign(FI);
3238 if (Alignment > Align(16))
3240 "Alignment of scalable vectors > 16 bytes is not yet supported");
3241
3242 StackTop += MFI.getObjectSize(FI);
3243 StackTop = alignTo(StackTop, Alignment);
3244
3245 assert(StackTop < (uint64_t)std::numeric_limits<int64_t>::max() &&
3246 "SVE StackTop far too large?!");
3247
3248 int64_t Offset = -int64_t(StackTop);
3249 if (AssignOffsets == AssignObjectOffsets::Yes)
3250 MFI.setObjectOffset(FI, Offset);
3251
3252 LLVM_DEBUG(dbgs() << "alloc FI(" << FI << ") at SP[" << Offset << "]\n");
3253 };
3254
3255 // Then process all callee saved slots.
3256 int MinCSFrameIndex, MaxCSFrameIndex;
3257 if (getSVECalleeSaveSlotRange(MFI, MinCSFrameIndex, MaxCSFrameIndex)) {
3258 for (int FI = MinCSFrameIndex; FI <= MaxCSFrameIndex; ++FI)
3259 AllocateObject(FI);
3260 }
3261
3262 // Ensure the CS area is 16-byte aligned.
3263 PPRStackTop = alignTo(PPRStackTop, Align(16U));
3264 ZPRStackTop = alignTo(ZPRStackTop, Align(16U));
3265
3266 // Create a buffer of SVE objects to allocate and sort it.
3267 SmallVector<int, 8> ObjectsToAllocate;
3268 // If we have a stack protector, and we've previously decided that we have SVE
3269 // objects on the stack and thus need it to go in the SVE stack area, then it
3270 // needs to go first.
3271 int StackProtectorFI = -1;
3272 if (MFI.hasStackProtectorIndex()) {
3273 StackProtectorFI = MFI.getStackProtectorIndex();
3274 if (MFI.getStackID(StackProtectorFI) == TargetStackID::ScalableVector)
3275 ObjectsToAllocate.push_back(StackProtectorFI);
3276 }
3277
3278 for (int FI = 0, E = MFI.getObjectIndexEnd(); FI != E; ++FI) {
3279 if (FI == StackProtectorFI || MFI.isDeadObjectIndex(FI) ||
3281 continue;
3282
3285 continue;
3286
3287 ObjectsToAllocate.push_back(FI);
3288 }
3289
3290 // Allocate all SVE locals and spills
3291 for (unsigned FI : ObjectsToAllocate)
3292 AllocateObject(FI);
3293
3294 PPRStackTop = alignTo(PPRStackTop, Align(16U));
3295 ZPRStackTop = alignTo(ZPRStackTop, Align(16U));
3296
3297 if (AssignOffsets == AssignObjectOffsets::Yes)
3298 AFI->setStackSizeSVE(SVEStack.ZPRStackSize, SVEStack.PPRStackSize);
3299
3300 return SVEStack;
3301}
3302
3304 MachineFunction &MF, RegScavenger *RS) const {
3306 "Upwards growing stack unsupported");
3307
3309
3310 // If this function isn't doing Win64-style C++ EH, we don't need to do
3311 // anything.
3312 if (!MF.hasEHFunclets())
3313 return;
3314
3315 MachineFrameInfo &MFI = MF.getFrameInfo();
3316 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
3317
3318 // Win64 C++ EH needs to allocate space for the catch objects in the fixed
3319 // object area right next to the UnwindHelp object.
3320 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
3321 int64_t CurrentOffset =
3323 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
3324 for (WinEHHandlerType &H : TBME.HandlerArray) {
3325 int FrameIndex = H.CatchObj.FrameIndex;
3326 if ((FrameIndex != INT_MAX) && MFI.getObjectOffset(FrameIndex) == 0) {
3327 CurrentOffset =
3328 alignTo(CurrentOffset, MFI.getObjectAlign(FrameIndex).value());
3329 CurrentOffset += MFI.getObjectSize(FrameIndex);
3330 MFI.setObjectOffset(FrameIndex, -CurrentOffset);
3331 }
3332 }
3333 }
3334
3335 // Create an UnwindHelp object.
3336 // The UnwindHelp object is allocated at the start of the fixed object area
3337 int64_t UnwindHelpOffset = alignTo(CurrentOffset + 8, Align(16));
3338 assert(UnwindHelpOffset == getFixedObjectSize(MF, AFI, /*IsWin64*/ true,
3339 /*IsFunclet*/ false) &&
3340 "UnwindHelpOffset must be at the start of the fixed object area");
3341 int UnwindHelpFI = MFI.CreateFixedObject(/*Size*/ 8, -UnwindHelpOffset,
3342 /*IsImmutable=*/false);
3343 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
3344
3345 MachineBasicBlock &MBB = MF.front();
3346 auto MBBI = MBB.begin();
3347 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
3348 ++MBBI;
3349
3350 // We need to store -2 into the UnwindHelp object at the start of the
3351 // function.
3352 DebugLoc DL;
3353 RS->enterBasicBlockEnd(MBB);
3354 RS->backward(MBBI);
3355 Register DstReg = RS->FindUnusedReg(&AArch64::GPR64commonRegClass);
3356 assert(DstReg && "There must be a free register after frame setup");
3357 const AArch64InstrInfo &TII =
3358 *MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
3359 BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2);
3360 BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi))
3361 .addReg(DstReg, getKillRegState(true))
3362 .addFrameIndex(UnwindHelpFI)
3363 .addImm(0);
3364}
3365
3366namespace {
3367struct TagStoreInstr {
3369 int64_t Offset, Size;
3370 explicit TagStoreInstr(MachineInstr *MI, int64_t Offset, int64_t Size)
3371 : MI(MI), Offset(Offset), Size(Size) {}
3372};
3373
3374class TagStoreEdit {
3375 MachineFunction *MF;
3376 MachineBasicBlock *MBB;
3377 MachineRegisterInfo *MRI;
3378 // Tag store instructions that are being replaced.
3380 // Combined memref arguments of the above instructions.
3382
3383 // Replace allocation tags in [FrameReg + FrameRegOffset, FrameReg +
3384 // FrameRegOffset + Size) with the address tag of SP.
3385 Register FrameReg;
3386 StackOffset FrameRegOffset;
3387 int64_t Size;
3388 // If not std::nullopt, move FrameReg to (FrameReg + FrameRegUpdate) at the
3389 // end.
3390 std::optional<int64_t> FrameRegUpdate;
3391 // MIFlags for any FrameReg updating instructions.
3392 unsigned FrameRegUpdateFlags;
3393
3394 // Use zeroing instruction variants.
3395 bool ZeroData;
3396 DebugLoc DL;
3397
3398 void emitUnrolled(MachineBasicBlock::iterator InsertI);
3399 void emitLoop(MachineBasicBlock::iterator InsertI);
3400
3401public:
3402 TagStoreEdit(MachineBasicBlock *MBB, bool ZeroData)
3403 : MBB(MBB), ZeroData(ZeroData) {
3404 MF = MBB->getParent();
3405 MRI = &MF->getRegInfo();
3406 }
3407 // Add an instruction to be replaced. Instructions must be added in the
3408 // ascending order of Offset, and have to be adjacent.
3409 void addInstruction(TagStoreInstr I) {
3410 assert((TagStores.empty() ||
3411 TagStores.back().Offset + TagStores.back().Size == I.Offset) &&
3412 "Non-adjacent tag store instructions.");
3413 TagStores.push_back(I);
3414 }
3415 void clear() { TagStores.clear(); }
3416 // Emit equivalent code at the given location, and erase the current set of
3417 // instructions. May skip if the replacement is not profitable. May invalidate
3418 // the input iterator and replace it with a valid one.
3419 void emitCode(MachineBasicBlock::iterator &InsertI,
3420 const AArch64FrameLowering *TFI, bool TryMergeSPUpdate);
3421};
3422
3423void TagStoreEdit::emitUnrolled(MachineBasicBlock::iterator InsertI) {
3424 const AArch64InstrInfo *TII =
3425 MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3426
3427 const int64_t kMinOffset = -256 * 16;
3428 const int64_t kMaxOffset = 255 * 16;
3429
3430 Register BaseReg = FrameReg;
3431 int64_t BaseRegOffsetBytes = FrameRegOffset.getFixed();
3432 if (BaseRegOffsetBytes < kMinOffset ||
3433 BaseRegOffsetBytes + (Size - Size % 32) > kMaxOffset ||
3434 // BaseReg can be FP, which is not necessarily aligned to 16-bytes. In
3435 // that case, BaseRegOffsetBytes will not be aligned to 16 bytes, which
3436 // is required for the offset of ST2G.
3437 BaseRegOffsetBytes % 16 != 0) {
3438 Register ScratchReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3439 emitFrameOffset(*MBB, InsertI, DL, ScratchReg, BaseReg,
3440 StackOffset::getFixed(BaseRegOffsetBytes), TII);
3441 BaseReg = ScratchReg;
3442 BaseRegOffsetBytes = 0;
3443 }
3444
3445 MachineInstr *LastI = nullptr;
3446 while (Size) {
3447 int64_t InstrSize = (Size > 16) ? 32 : 16;
3448 unsigned Opcode =
3449 InstrSize == 16
3450 ? (ZeroData ? AArch64::STZGi : AArch64::STGi)
3451 : (ZeroData ? AArch64::STZ2Gi : AArch64::ST2Gi);
3452 assert(BaseRegOffsetBytes % 16 == 0);
3453 MachineInstr *I = BuildMI(*MBB, InsertI, DL, TII->get(Opcode))
3454 .addReg(AArch64::SP)
3455 .addReg(BaseReg)
3456 .addImm(BaseRegOffsetBytes / 16)
3457 .setMemRefs(CombinedMemRefs);
3458 // A store to [BaseReg, #0] should go last for an opportunity to fold the
3459 // final SP adjustment in the epilogue.
3460 if (BaseRegOffsetBytes == 0)
3461 LastI = I;
3462 BaseRegOffsetBytes += InstrSize;
3463 Size -= InstrSize;
3464 }
3465
3466 if (LastI)
3467 MBB->splice(InsertI, MBB, LastI);
3468}
3469
3470void TagStoreEdit::emitLoop(MachineBasicBlock::iterator InsertI) {
3471 const AArch64InstrInfo *TII =
3472 MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
3473
3474 Register BaseReg = FrameRegUpdate
3475 ? FrameReg
3476 : MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3477 Register SizeReg = MRI->createVirtualRegister(&AArch64::GPR64RegClass);
3478
3479 emitFrameOffset(*MBB, InsertI, DL, BaseReg, FrameReg, FrameRegOffset, TII);
3480
3481 int64_t LoopSize = Size;
3482 // If the loop size is not a multiple of 32, split off one 16-byte store at
3483 // the end to fold BaseReg update into.
3484 if (FrameRegUpdate && *FrameRegUpdate)
3485 LoopSize -= LoopSize % 32;
3486 MachineInstr *LoopI = BuildMI(*MBB, InsertI, DL,
3487 TII->get(ZeroData ? AArch64::STZGloop_wback
3488 : AArch64::STGloop_wback))
3489 .addDef(SizeReg)
3490 .addDef(BaseReg)
3491 .addImm(LoopSize)
3492 .addReg(BaseReg)
3493 .setMemRefs(CombinedMemRefs);
3494 if (FrameRegUpdate)
3495 LoopI->setFlags(FrameRegUpdateFlags);
3496
3497 int64_t ExtraBaseRegUpdate =
3498 FrameRegUpdate ? (*FrameRegUpdate - FrameRegOffset.getFixed() - Size) : 0;
3499 LLVM_DEBUG(dbgs() << "TagStoreEdit::emitLoop: LoopSize=" << LoopSize
3500 << ", Size=" << Size
3501 << ", ExtraBaseRegUpdate=" << ExtraBaseRegUpdate
3502 << ", FrameRegUpdate=" << FrameRegUpdate
3503 << ", FrameRegOffset.getFixed()="
3504 << FrameRegOffset.getFixed() << "\n");
3505 if (LoopSize < Size) {
3506 assert(FrameRegUpdate);
3507 assert(Size - LoopSize == 16);
3508 // Tag 16 more bytes at BaseReg and update BaseReg.
3509 int64_t STGOffset = ExtraBaseRegUpdate + 16;
3510 assert(STGOffset % 16 == 0 && STGOffset >= -4096 && STGOffset <= 4080 &&
3511 "STG immediate out of range");
3512 BuildMI(*MBB, InsertI, DL,
3513 TII->get(ZeroData ? AArch64::STZGPostIndex : AArch64::STGPostIndex))
3514 .addDef(BaseReg)
3515 .addReg(BaseReg)
3516 .addReg(BaseReg)
3517 .addImm(STGOffset / 16)
3518 .setMemRefs(CombinedMemRefs)
3519 .setMIFlags(FrameRegUpdateFlags);
3520 } else if (ExtraBaseRegUpdate) {
3521 // Update BaseReg.
3522 int64_t AddSubOffset = std::abs(ExtraBaseRegUpdate);
3523 assert(AddSubOffset <= 4095 && "ADD/SUB immediate out of range");
3524 BuildMI(
3525 *MBB, InsertI, DL,
3526 TII->get(ExtraBaseRegUpdate > 0 ? AArch64::ADDXri : AArch64::SUBXri))
3527 .addDef(BaseReg)
3528 .addReg(BaseReg)
3529 .addImm(AddSubOffset)
3530 .addImm(0)
3531 .setMIFlags(FrameRegUpdateFlags);
3532 }
3533}
3534
3535// Check if *II is a register update that can be merged into STGloop that ends
3536// at (Reg + Size). RemainingOffset is the required adjustment to Reg after the
3537// end of the loop.
3538bool canMergeRegUpdate(MachineBasicBlock::iterator II, unsigned Reg,
3539 int64_t Size, int64_t *TotalOffset) {
3540 MachineInstr &MI = *II;
3541 if ((MI.getOpcode() == AArch64::ADDXri ||
3542 MI.getOpcode() == AArch64::SUBXri) &&
3543 MI.getOperand(0).getReg() == Reg && MI.getOperand(1).getReg() == Reg) {
3544 unsigned Shift = AArch64_AM::getShiftValue(MI.getOperand(3).getImm());
3545 int64_t Offset = MI.getOperand(2).getImm() << Shift;
3546 if (MI.getOpcode() == AArch64::SUBXri)
3547 Offset = -Offset;
3548 int64_t PostOffset = Offset - Size;
3549 // TagStoreEdit::emitLoop might emit either an ADD/SUB after the loop, or
3550 // an STGPostIndex which does the last 16 bytes of tag write. Which one is
3551 // chosen depends on the alignment of the loop size, but the difference
3552 // between the valid ranges for the two instructions is small, so we
3553 // conservatively assume that it could be either case here.
3554 //
3555 // Max offset of STGPostIndex, minus the 16 byte tag write folded into that
3556 // instruction.
3557 const int64_t kMaxOffset = 4080 - 16;
3558 // Max offset of SUBXri.
3559 const int64_t kMinOffset = -4095;
3560 if (PostOffset <= kMaxOffset && PostOffset >= kMinOffset &&
3561 PostOffset % 16 == 0) {
3562 *TotalOffset = Offset;
3563 return true;
3564 }
3565 }
3566 return false;
3567}
3568
3569void mergeMemRefs(const SmallVectorImpl<TagStoreInstr> &TSE,
3571 MemRefs.clear();
3572 for (auto &TS : TSE) {
3573 MachineInstr *MI = TS.MI;
3574 // An instruction without memory operands may access anything. Be
3575 // conservative and return an empty list.
3576 if (MI->memoperands_empty()) {
3577 MemRefs.clear();
3578 return;
3579 }
3580 MemRefs.append(MI->memoperands_begin(), MI->memoperands_end());
3581 }
3582}
3583
3584void TagStoreEdit::emitCode(MachineBasicBlock::iterator &InsertI,
3585 const AArch64FrameLowering *TFI,
3586 bool TryMergeSPUpdate) {
3587 if (TagStores.empty())
3588 return;
3589 TagStoreInstr &FirstTagStore = TagStores[0];
3590 TagStoreInstr &LastTagStore = TagStores[TagStores.size() - 1];
3591 Size = LastTagStore.Offset - FirstTagStore.Offset + LastTagStore.Size;
3592 DL = TagStores[0].MI->getDebugLoc();
3593
3594 Register Reg;
3595 FrameRegOffset = TFI->resolveFrameOffsetReference(
3596 *MF, FirstTagStore.Offset, false /*isFixed*/,
3597 TargetStackID::Default /*StackID*/, Reg,
3598 /*PreferFP=*/false, /*ForSimm=*/true);
3599 FrameReg = Reg;
3600 FrameRegUpdate = std::nullopt;
3601
3602 mergeMemRefs(TagStores, CombinedMemRefs);
3603
3604 LLVM_DEBUG({
3605 dbgs() << "Replacing adjacent STG instructions:\n";
3606 for (const auto &Instr : TagStores) {
3607 dbgs() << " " << *Instr.MI;
3608 }
3609 });
3610
3611 // Size threshold where a loop becomes shorter than a linear sequence of
3612 // tagging instructions.
3613 const int kSetTagLoopThreshold = 176;
3614 if (Size < kSetTagLoopThreshold) {
3615 if (TagStores.size() < 2)
3616 return;
3617 emitUnrolled(InsertI);
3618 } else {
3619 MachineInstr *UpdateInstr = nullptr;
3620 int64_t TotalOffset = 0;
3621 if (TryMergeSPUpdate) {
3622 // See if we can merge base register update into the STGloop.
3623 // This is done in AArch64LoadStoreOptimizer for "normal" stores,
3624 // but STGloop is way too unusual for that, and also it only
3625 // realistically happens in function epilogue. Also, STGloop is expanded
3626 // before that pass.
3627 auto UpdateI = skipDebugInstructionsForward(InsertI, MBB->end(),
3628 /*SkipPseudoOp=*/false);
3629 if (UpdateI != MBB->end() &&
3630 canMergeRegUpdate(UpdateI, FrameReg, FrameRegOffset.getFixed() + Size,
3631 &TotalOffset)) {
3632 // Keep skipped debug instructions before the loop so debug values see
3633 // the pre-update SP; only the tag stores move past them.
3634 UpdateInstr = &*UpdateI++;
3635 InsertI = UpdateI;
3636 LLVM_DEBUG(dbgs() << "Folding SP update into loop:\n "
3637 << *UpdateInstr);
3638 }
3639 }
3640
3641 if (!UpdateInstr && TagStores.size() < 2)
3642 return;
3643
3644 if (UpdateInstr) {
3645 FrameRegUpdate = TotalOffset;
3646 FrameRegUpdateFlags = UpdateInstr->getFlags();
3647 }
3648 emitLoop(InsertI);
3649 if (UpdateInstr)
3650 UpdateInstr->eraseFromParent();
3651 }
3652
3653 for (auto &TS : TagStores)
3654 TS.MI->eraseFromParent();
3655}
3656
3657bool isMergeableStackTaggingInstruction(MachineInstr &MI, int64_t &Offset,
3658 int64_t &Size, bool &ZeroData) {
3659 MachineFunction &MF = *MI.getParent()->getParent();
3660 const MachineFrameInfo &MFI = MF.getFrameInfo();
3661
3662 unsigned Opcode = MI.getOpcode();
3663 ZeroData = (Opcode == AArch64::STZGloop || Opcode == AArch64::STZGi ||
3664 Opcode == AArch64::STZ2Gi);
3665
3666 if (Opcode == AArch64::STGloop || Opcode == AArch64::STZGloop) {
3667 if (!MI.getOperand(0).isDead() || !MI.getOperand(1).isDead())
3668 return false;
3669 if (!MI.getOperand(2).isImm() || !MI.getOperand(3).isFI())
3670 return false;
3671 Offset = MFI.getObjectOffset(MI.getOperand(3).getIndex());
3672 Size = MI.getOperand(2).getImm();
3673 return true;
3674 }
3675
3676 if (Opcode == AArch64::STGi || Opcode == AArch64::STZGi)
3677 Size = 16;
3678 else if (Opcode == AArch64::ST2Gi || Opcode == AArch64::STZ2Gi)
3679 Size = 32;
3680 else
3681 return false;
3682
3683 if (MI.getOperand(0).getReg() != AArch64::SP || !MI.getOperand(1).isFI())
3684 return false;
3685
3686 Offset = MFI.getObjectOffset(MI.getOperand(1).getIndex()) +
3687 16 * MI.getOperand(2).getImm();
3688 return true;
3689}
3690
3691static size_t countAvailableScavengerSlots(LivePhysRegs &LiveRegs,
3693 RegScavenger *RS) {
3694 auto FreeGPRs =
3695 llvm::count_if(AArch64::GPR64RegClass, [&LiveRegs, &MRI](auto Reg) {
3696 return LiveRegs.available(MRI, Reg);
3697 });
3698
3699 size_t NumEmergencySlots = 0;
3700 if (RS)
3701 NumEmergencySlots = RS->getNumScavengingFrameIndices();
3702
3703 return FreeGPRs + NumEmergencySlots;
3704}
3705
3706// Detect a run of memory tagging instructions for adjacent stack frame slots,
3707// and replace them with a shorter instruction sequence:
3708// * replace STG + STG with ST2G
3709// * replace STGloop + STGloop with STGloop
3710// This code needs to run when stack slot offsets are already known, but before
3711// FrameIndex operands in STG instructions are eliminated.
3713 const AArch64FrameLowering *TFI,
3714 RegScavenger *RS) {
3715 bool FirstZeroData;
3716 int64_t Size, Offset;
3717 MachineInstr &MI = *II;
3720 if (&MI == &MBB->instr_back())
3721 return II;
3722 if (!isMergeableStackTaggingInstruction(MI, Offset, Size, FirstZeroData))
3723 return II;
3724
3726 Instrs.emplace_back(&MI, Offset, Size);
3727
3728 constexpr int kScanLimit = 10;
3729 int Count = 0;
3731 NextI != E && Count < kScanLimit; ++NextI) {
3732 MachineInstr &MI = *NextI;
3733 bool ZeroData;
3734 int64_t Size, Offset;
3735 // Collect instructions that update memory tags with a FrameIndex operand
3736 // and (when applicable) constant size, and whose output registers are dead
3737 // (the latter is almost always the case in practice). Since these
3738 // instructions effectively have no inputs or outputs, we are free to skip
3739 // any non-aliasing instructions in between without tracking used registers.
3740 if (isMergeableStackTaggingInstruction(MI, Offset, Size, ZeroData)) {
3741 if (ZeroData != FirstZeroData)
3742 break;
3743 Instrs.emplace_back(&MI, Offset, Size);
3744 continue;
3745 }
3746
3747 // Only count non-transient, non-tagging instructions toward the scan
3748 // limit.
3749 if (!MI.isTransient())
3750 ++Count;
3751
3752 // Just in case, stop before the epilogue code starts.
3753 if (MI.getFlag(MachineInstr::FrameSetup) ||
3755 break;
3756
3757 // Reject anything that may alias the collected instructions.
3758 if (MI.mayLoadOrStore() || MI.hasUnmodeledSideEffects() || MI.isCall())
3759 break;
3760 }
3761
3762 // New code will be inserted after the last tagging instruction we've found.
3763 MachineBasicBlock::iterator InsertI = Instrs.back().MI;
3764
3765 // All the gathered stack tag instructions are merged and placed after
3766 // last tag store in the list. The check should be made if the nzcv
3767 // flag is live at the point where we are trying to insert. Otherwise
3768 // the nzcv flag might get clobbered if any stg loops are present.
3769
3770 // FIXME : This approach of bailing out from merge is conservative in
3771 // some ways like even if stg loops are not present after merge the
3772 // insert list, this liveness check is done (which is not needed).
3774 LiveRegs.addLiveOuts(*MBB);
3775 for (auto I = MBB->rbegin();; ++I) {
3776 MachineInstr &MI = *I;
3777 if (MI == InsertI)
3778 break;
3779 LiveRegs.stepBackward(*I);
3780 }
3781 InsertI++;
3782 if (LiveRegs.contains(AArch64::NZCV))
3783 return InsertI;
3784
3785 // Emitting an MTE loop requires two physical registers (BaseReg and
3786 // SizeReg). If the function is under register pressure, the register
3787 // scavenger will crash trying to allocate them. If we don't have at least
3788 // two free slots (free registers + emergency slots), bail out and fall back
3789 // to the unrolled sequence.
3790 if (countAvailableScavengerSlots(LiveRegs, MBB->getParent()->getRegInfo(),
3791 RS) < 2) {
3792 LLVM_DEBUG(
3793 dbgs() << "Failed to merge MTE stack tagging instructions into loop "
3794 << "due to high register pressure.\n");
3795 return InsertI;
3796 }
3797
3798 llvm::stable_sort(Instrs,
3799 [](const TagStoreInstr &Left, const TagStoreInstr &Right) {
3800 return Left.Offset < Right.Offset;
3801 });
3802
3803 // Make sure that we don't have any overlapping stores.
3804 int64_t CurOffset = Instrs[0].Offset;
3805 for (auto &Instr : Instrs) {
3806 if (CurOffset > Instr.Offset)
3807 return NextI;
3808 CurOffset = Instr.Offset + Instr.Size;
3809 }
3810
3811 // Find contiguous runs of tagged memory and emit shorter instruction
3812 // sequences for them when possible.
3813 TagStoreEdit TSE(MBB, FirstZeroData);
3814 std::optional<int64_t> EndOffset;
3815 for (auto &Instr : Instrs) {
3816 if (EndOffset && *EndOffset != Instr.Offset) {
3817 // Found a gap.
3818 TSE.emitCode(InsertI, TFI, /*TryMergeSPUpdate = */ false);
3819 TSE.clear();
3820 }
3821
3822 TSE.addInstruction(Instr);
3823 EndOffset = Instr.Offset + Instr.Size;
3824 }
3825
3826 const MachineFunction *MF = MBB->getParent();
3827 // Multiple FP/SP updates in a loop cannot be described by CFI instructions.
3828 TSE.emitCode(
3829 InsertI, TFI, /*TryMergeSPUpdate = */
3831
3832 return InsertI;
3833}
3834} // namespace
3835
3837 MachineFunction &MF, RegScavenger *RS = nullptr) const {
3838 bool MergeSetTag = MF.getSubtarget<AArch64Subtarget>()
3839 .getCLOpts()
3840 .stack_tagging_merge_settag;
3841 for (auto &BB : MF)
3842 for (MachineBasicBlock::iterator II = BB.begin(); II != BB.end();) {
3843 if (MergeSetTag)
3844 II = tryMergeAdjacentSTG(II, this, RS);
3845 }
3846
3847 // By the time this method is called, most of the prologue/epilogue code is
3848 // already emitted, whether its location was affected by the shrink-wrapping
3849 // optimization or not.
3850 if (!MF.getFunction().hasFnAttribute(Attribute::Naked) &&
3851 shouldSignReturnAddressEverywhere(MF))
3853}
3854
3855/// For Win64 AArch64 EH, the offset to the Unwind object is from the SP
3856/// before the update. This is easily retrieved as it is exactly the offset
3857/// that is set in processFunctionBeforeFrameFinalized.
3859 const MachineFunction &MF, int FI, Register &FrameReg,
3860 bool IgnoreSPUpdates) const {
3861 const MachineFrameInfo &MFI = MF.getFrameInfo();
3862 if (IgnoreSPUpdates) {
3863 LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is "
3864 << MFI.getObjectOffset(FI) << "\n");
3865 FrameReg = AArch64::SP;
3866 return StackOffset::getFixed(MFI.getObjectOffset(FI));
3867 }
3868
3869 // Go to common code if we cannot provide sp + offset.
3870 if (MFI.hasVarSizedObjects() ||
3873 return getFrameIndexReference(MF, FI, FrameReg);
3874
3875 FrameReg = AArch64::SP;
3876 return getStackOffset(MF, MFI.getObjectOffset(FI));
3877}
3878
3879/// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve
3880/// the parent's frame pointer
3882 const MachineFunction &MF) const {
3883 return 0;
3884}
3885
3886/// Funclets only need to account for space for the callee saved registers,
3887/// as the locals are accounted for in the parent's stack frame.
3889 const MachineFunction &MF) const {
3890 // This is the size of the pushed CSRs.
3891 unsigned CSSize =
3892 MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize();
3893 // This is the amount of stack a funclet needs to allocate.
3894 return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(),
3895 getStackAlign());
3896}
3897
3898namespace {
3899struct FrameObject {
3900 bool IsValid = false;
3901 // Index of the object in MFI.
3902 int ObjectIndex = 0;
3903 // Group ID this object belongs to.
3904 int GroupIndex = -1;
3905 // This object should be placed first (closest to SP).
3906 bool ObjectFirst = false;
3907 // This object's group (which always contains the object with
3908 // ObjectFirst==true) should be placed first.
3909 bool GroupFirst = false;
3910
3911 // Used to distinguish between FP and GPR accesses. The values are decided so
3912 // that they sort FPR < Hazard < GPR and they can be or'd together.
3913 unsigned Accesses = 0;
3914 enum { AccessFPR = 1, AccessHazard = 2, AccessGPR = 4 };
3915};
3916
3917class GroupBuilder {
3918 SmallVector<int, 8> CurrentMembers;
3919 int NextGroupIndex = 0;
3920 std::vector<FrameObject> &Objects;
3921
3922public:
3923 GroupBuilder(std::vector<FrameObject> &Objects) : Objects(Objects) {}
3924 void AddMember(int Index) { CurrentMembers.push_back(Index); }
3925 void EndCurrentGroup() {
3926 if (CurrentMembers.size() > 1) {
3927 // Create a new group with the current member list. This might remove them
3928 // from their pre-existing groups. That's OK, dealing with overlapping
3929 // groups is too hard and unlikely to make a difference.
3930 LLVM_DEBUG(dbgs() << "group:");
3931 for (int Index : CurrentMembers) {
3932 Objects[Index].GroupIndex = NextGroupIndex;
3933 LLVM_DEBUG(dbgs() << " " << Index);
3934 }
3935 LLVM_DEBUG(dbgs() << "\n");
3936 NextGroupIndex++;
3937 }
3938 CurrentMembers.clear();
3939 }
3940};
3941
3942bool FrameObjectCompare(const FrameObject &A, const FrameObject &B) {
3943 // Objects at a lower index are closer to FP; objects at a higher index are
3944 // closer to SP.
3945 //
3946 // For consistency in our comparison, all invalid objects are placed
3947 // at the end. This also allows us to stop walking when we hit the
3948 // first invalid item after it's all sorted.
3949 //
3950 // If we want to include a stack hazard region, order FPR accesses < the
3951 // hazard object < GPRs accesses in order to create a separation between the
3952 // two. For the Accesses field 1 = FPR, 2 = Hazard Object, 4 = GPR.
3953 //
3954 // Otherwise the "first" object goes first (closest to SP), followed by the
3955 // members of the "first" group.
3956 //
3957 // The rest are sorted by the group index to keep the groups together.
3958 // Higher numbered groups are more likely to be around longer (i.e. untagged
3959 // in the function epilogue and not at some earlier point). Place them closer
3960 // to SP.
3961 //
3962 // If all else equal, sort by the object index to keep the objects in the
3963 // original order.
3964 return std::make_tuple(!A.IsValid, A.Accesses, A.ObjectFirst, A.GroupFirst,
3965 A.GroupIndex, A.ObjectIndex) <
3966 std::make_tuple(!B.IsValid, B.Accesses, B.ObjectFirst, B.GroupFirst,
3967 B.GroupIndex, B.ObjectIndex);
3968}
3969} // namespace
3970
3972 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3974
3975 if ((!MF.getSubtarget<AArch64Subtarget>().getCLOpts().order_frame_objects &&
3976 !AFI.hasSplitSVEObjects()) ||
3977 ObjectsToAllocate.empty())
3978 return;
3979
3980 const MachineFrameInfo &MFI = MF.getFrameInfo();
3981 std::vector<FrameObject> FrameObjects(MFI.getObjectIndexEnd());
3982 for (auto &Obj : ObjectsToAllocate) {
3983 FrameObjects[Obj].IsValid = true;
3984 FrameObjects[Obj].ObjectIndex = Obj;
3985 }
3986
3987 // Identify FPR vs GPR slots for hazards, and stack slots that are tagged at
3988 // the same time.
3989 GroupBuilder GB(FrameObjects);
3990 for (auto &MBB : MF) {
3991 for (auto &MI : MBB) {
3992 if (MI.isDebugInstr())
3993 continue;
3994
3995 if (AFI.hasStackHazardSlotIndex()) {
3996 std::optional<int> FI = getLdStFrameID(MI, MFI);
3997 if (FI && *FI >= 0 && *FI < (int)FrameObjects.size()) {
3998 if (MFI.getStackID(*FI) == TargetStackID::ScalableVector ||
4000 FrameObjects[*FI].Accesses |= FrameObject::AccessFPR;
4001 else
4002 FrameObjects[*FI].Accesses |= FrameObject::AccessGPR;
4003 }
4004 }
4005
4006 int OpIndex;
4007 switch (MI.getOpcode()) {
4008 case AArch64::STGloop:
4009 case AArch64::STZGloop:
4010 OpIndex = 3;
4011 break;
4012 case AArch64::STGi:
4013 case AArch64::STZGi:
4014 case AArch64::ST2Gi:
4015 case AArch64::STZ2Gi:
4016 OpIndex = 1;
4017 break;
4018 default:
4019 OpIndex = -1;
4020 }
4021
4022 int TaggedFI = -1;
4023 if (OpIndex >= 0) {
4024 const MachineOperand &MO = MI.getOperand(OpIndex);
4025 if (MO.isFI()) {
4026 int FI = MO.getIndex();
4027 if (FI >= 0 && FI < MFI.getObjectIndexEnd() &&
4028 FrameObjects[FI].IsValid)
4029 TaggedFI = FI;
4030 }
4031 }
4032
4033 // If this is a stack tagging instruction for a slot that is not part of a
4034 // group yet, either start a new group or add it to the current one.
4035 if (TaggedFI >= 0)
4036 GB.AddMember(TaggedFI);
4037 else
4038 GB.EndCurrentGroup();
4039 }
4040 // Groups should never span multiple basic blocks.
4041 GB.EndCurrentGroup();
4042 }
4043
4044 if (AFI.hasStackHazardSlotIndex()) {
4045 FrameObjects[AFI.getStackHazardSlotIndex()].Accesses =
4046 FrameObject::AccessHazard;
4047 // If a stack object is unknown or both GPR and FPR, sort it into GPR.
4048 for (auto &Obj : FrameObjects)
4049 if (!Obj.Accesses ||
4050 Obj.Accesses == (FrameObject::AccessGPR | FrameObject::AccessFPR))
4051 Obj.Accesses = FrameObject::AccessGPR;
4052 }
4053
4054 // If the function's tagged base pointer is pinned to a stack slot, we want to
4055 // put that slot first when possible. This will likely place it at SP + 0,
4056 // and save one instruction when generating the base pointer because IRG does
4057 // not allow an immediate offset.
4058 std::optional<int> TBPI = AFI.getTaggedBasePointerIndex();
4059 if (TBPI) {
4060 FrameObjects[*TBPI].ObjectFirst = true;
4061 FrameObjects[*TBPI].GroupFirst = true;
4062 int FirstGroupIndex = FrameObjects[*TBPI].GroupIndex;
4063 if (FirstGroupIndex >= 0)
4064 for (FrameObject &Object : FrameObjects)
4065 if (Object.GroupIndex == FirstGroupIndex)
4066 Object.GroupFirst = true;
4067 }
4068
4069 llvm::stable_sort(FrameObjects, FrameObjectCompare);
4070
4071 int i = 0;
4072 for (auto &Obj : FrameObjects) {
4073 // All invalid items are sorted at the end, so it's safe to stop.
4074 if (!Obj.IsValid)
4075 break;
4076 ObjectsToAllocate[i++] = Obj.ObjectIndex;
4077 }
4078
4079 LLVM_DEBUG({
4080 dbgs() << "Final frame order:\n";
4081 for (auto &Obj : FrameObjects) {
4082 if (!Obj.IsValid)
4083 break;
4084 dbgs() << " " << Obj.ObjectIndex << ": group " << Obj.GroupIndex;
4085 if (Obj.ObjectFirst)
4086 dbgs() << ", first";
4087 if (Obj.GroupFirst)
4088 dbgs() << ", group-first";
4089 dbgs() << "\n";
4090 }
4091 });
4092}
4093
4094/// Emit a loop to decrement SP until it is equal to TargetReg, with probes at
4095/// least every ProbeSize bytes. Returns an iterator of the first instruction
4096/// after the loop. The difference between SP and TargetReg must be an exact
4097/// multiple of ProbeSize.
4099AArch64FrameLowering::inlineStackProbeLoopExactMultiple(
4100 MachineBasicBlock::iterator MBBI, int64_t ProbeSize,
4101 Register TargetReg) const {
4102 MachineBasicBlock &MBB = *MBBI->getParent();
4103 MachineFunction &MF = *MBB.getParent();
4104 const AArch64InstrInfo *TII =
4105 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
4106 DebugLoc DL = MBB.findDebugLoc(MBBI);
4107
4108 MachineFunction::iterator MBBInsertPoint = std::next(MBB.getIterator());
4109 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
4110 MF.insert(MBBInsertPoint, LoopMBB);
4111 MachineBasicBlock *ExitMBB = MF.CreateMachineBasicBlock(MBB.getBasicBlock());
4112 MF.insert(MBBInsertPoint, ExitMBB);
4113
4114 // SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not encodable
4115 // in SUB).
4116 emitFrameOffset(*LoopMBB, LoopMBB->end(), DL, AArch64::SP, AArch64::SP,
4117 StackOffset::getFixed(-ProbeSize), TII,
4119 // LDR XZR, [SP]
4120 BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::LDRXui))
4121 .addDef(AArch64::XZR)
4122 .addReg(AArch64::SP)
4123 .addImm(0)
4127 Align(8)))
4129 // CMP SP, TargetReg
4130 BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::SUBSXrx64),
4131 AArch64::XZR)
4132 .addReg(AArch64::SP)
4133 .addReg(TargetReg)
4136 // B.CC Loop
4137 BuildMI(*LoopMBB, LoopMBB->end(), DL, TII->get(AArch64::Bcc))
4139 .addMBB(LoopMBB)
4141
4142 LoopMBB->addSuccessor(ExitMBB);
4143 LoopMBB->addSuccessor(LoopMBB);
4144 // Synthesize the exit MBB.
4145 ExitMBB->splice(ExitMBB->end(), &MBB, MBBI, MBB.end());
4147 MBB.addSuccessor(LoopMBB);
4148 // Update liveins.
4149 fullyRecomputeLiveIns({ExitMBB, LoopMBB});
4150
4151 return ExitMBB->begin();
4152}
4153
4154void AArch64FrameLowering::inlineStackProbeFixed(
4155 MachineBasicBlock::iterator MBBI, Register ScratchReg, int64_t FrameSize,
4156 StackOffset CFAOffset) const {
4157 MachineBasicBlock *MBB = MBBI->getParent();
4158 MachineFunction &MF = *MBB->getParent();
4159 const AArch64InstrInfo *TII =
4160 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
4161 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
4162 bool EmitAsyncCFI = AFI->needsAsyncDwarfUnwindInfo(MF);
4163 bool HasFP = hasFP(MF);
4164
4165 DebugLoc DL;
4166 int64_t ProbeSize = MF.getInfo<AArch64FunctionInfo>()->getStackProbeSize();
4167 int64_t NumBlocks = FrameSize / ProbeSize;
4168 int64_t ResidualSize = FrameSize % ProbeSize;
4169
4170 LLVM_DEBUG(dbgs() << "Stack probing: total " << FrameSize << " bytes, "
4171 << NumBlocks << " blocks of " << ProbeSize
4172 << " bytes, plus " << ResidualSize << " bytes\n");
4173
4174 // Decrement SP by NumBlock * ProbeSize bytes, with either unrolled or
4175 // ordinary loop.
4176 if (NumBlocks <= AArch64::StackProbeMaxLoopUnroll) {
4177 for (int i = 0; i < NumBlocks; ++i) {
4178 // SUB SP, SP, #ProbeSize (or equivalent if ProbeSize is not
4179 // encodable in a SUB).
4180 emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP,
4181 StackOffset::getFixed(-ProbeSize), TII,
4182 MachineInstr::FrameSetup, false, false, nullptr,
4183 EmitAsyncCFI && !HasFP, CFAOffset);
4184 CFAOffset += StackOffset::getFixed(ProbeSize);
4185 // LDR XZR, [SP]
4186 BuildMI(*MBB, MBBI, DL, TII->get(AArch64::LDRXui))
4187 .addDef(AArch64::XZR)
4188 .addReg(AArch64::SP)
4189 .addImm(0)
4193 Align(8)))
4195 }
4196 } else if (NumBlocks != 0) {
4197 // SUB ScratchReg, SP, #FrameSize (or equivalent if FrameSize is not
4198 // encodable in ADD). ScrathReg may temporarily become the CFA register.
4199 emitFrameOffset(*MBB, MBBI, DL, ScratchReg, AArch64::SP,
4200 StackOffset::getFixed(-ProbeSize * NumBlocks), TII,
4201 MachineInstr::FrameSetup, false, false, nullptr,
4202 EmitAsyncCFI && !HasFP, CFAOffset);
4203 CFAOffset += StackOffset::getFixed(ProbeSize * NumBlocks);
4204 MBBI = inlineStackProbeLoopExactMultiple(MBBI, ProbeSize, ScratchReg);
4205 MBB = MBBI->getParent();
4206 if (EmitAsyncCFI && !HasFP) {
4207 // Set the CFA register back to SP.
4208 CFIInstBuilder(*MBB, MBBI, MachineInstr::FrameSetup)
4209 .buildDefCFARegister(AArch64::SP);
4210 }
4211 }
4212
4213 if (ResidualSize != 0) {
4214 // SUB SP, SP, #ResidualSize (or equivalent if ResidualSize is not encodable
4215 // in SUB).
4216 emitFrameOffset(*MBB, MBBI, DL, AArch64::SP, AArch64::SP,
4217 StackOffset::getFixed(-ResidualSize), TII,
4218 MachineInstr::FrameSetup, false, false, nullptr,
4219 EmitAsyncCFI && !HasFP, CFAOffset);
4220 if (ResidualSize > AArch64::StackProbeMaxUnprobedStack) {
4221 // LDR XZR, [SP]
4222 BuildMI(*MBB, MBBI, DL, TII->get(AArch64::LDRXui))
4223 .addDef(AArch64::XZR)
4224 .addReg(AArch64::SP)
4225 .addImm(0)
4229 Align(8)))
4231 }
4232 }
4233}
4234
4235void AArch64FrameLowering::inlineStackProbe(MachineFunction &MF,
4236 MachineBasicBlock &MBB) const {
4237 // Get the instructions that need to be replaced. We emit at most two of
4238 // these. Remember them in order to avoid complications coming from the need
4239 // to traverse the block while potentially creating more blocks.
4240 SmallVector<MachineInstr *, 4> ToReplace;
4241 for (MachineInstr &MI : MBB)
4242 if (MI.getOpcode() == AArch64::PROBED_STACKALLOC ||
4243 MI.getOpcode() == AArch64::PROBED_STACKALLOC_VAR)
4244 ToReplace.push_back(&MI);
4245
4246 for (MachineInstr *MI : ToReplace) {
4247 if (MI->getOpcode() == AArch64::PROBED_STACKALLOC) {
4248 Register ScratchReg = MI->getOperand(0).getReg();
4249 int64_t FrameSize = MI->getOperand(1).getImm();
4250 StackOffset CFAOffset = StackOffset::get(MI->getOperand(2).getImm(),
4251 MI->getOperand(3).getImm());
4252 inlineStackProbeFixed(MI->getIterator(), ScratchReg, FrameSize,
4253 CFAOffset);
4254 } else {
4255 assert(MI->getOpcode() == AArch64::PROBED_STACKALLOC_VAR &&
4256 "Stack probe pseudo-instruction expected");
4257 const AArch64InstrInfo *TII =
4258 MI->getMF()->getSubtarget<AArch64Subtarget>().getInstrInfo();
4259 Register TargetReg = MI->getOperand(0).getReg();
4260 (void)TII->probedStackAlloc(MI->getIterator(), TargetReg, true);
4261 }
4262 MI->eraseFromParent();
4263 }
4264}
4265
4268 NotAccessed = 0, // Stack object not accessed by load/store instructions.
4269 GPR = 1 << 0, // A general purpose register.
4270 PPR = 1 << 1, // A predicate register.
4271 FPR = 1 << 2, // A floating point/Neon/SVE register.
4272 };
4273
4274 int Idx;
4276 int64_t Size;
4277 unsigned AccessTypes;
4278
4280
4281 bool operator<(const StackAccess &Rhs) const {
4282 return std::make_tuple(start(), Idx) <
4283 std::make_tuple(Rhs.start(), Rhs.Idx);
4284 }
4285
4286 bool isCPU() const {
4287 // Predicate register load and store instructions execute on the CPU.
4289 }
4290 bool isSME() const { return AccessTypes & AccessType::FPR; }
4291 bool isMixed() const { return isCPU() && isSME(); }
4292
4293 int64_t start() const { return Offset.getFixed() + Offset.getScalable(); }
4294 int64_t end() const { return start() + Size; }
4295
4296 std::string getTypeString() const {
4297 switch (AccessTypes) {
4298 case AccessType::FPR:
4299 return "FPR";
4300 case AccessType::PPR:
4301 return "PPR";
4302 case AccessType::GPR:
4303 return "GPR";
4305 return "NA";
4306 default:
4307 return "Mixed";
4308 }
4309 }
4310
4311 void print(raw_ostream &OS) const {
4312 OS << getTypeString() << " stack object at [SP"
4313 << (Offset.getFixed() < 0 ? "" : "+") << Offset.getFixed();
4314 if (Offset.getScalable())
4315 OS << (Offset.getScalable() < 0 ? "" : "+") << Offset.getScalable()
4316 << " * vscale";
4317 OS << "]";
4318 }
4319};
4320
4321static inline raw_ostream &operator<<(raw_ostream &OS, const StackAccess &SA) {
4322 SA.print(OS);
4323 return OS;
4324}
4325
4326void AArch64FrameLowering::emitRemarks(
4327 const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const {
4328
4329 auto *AFI = MF.getInfo<AArch64FunctionInfo>();
4331 return;
4332
4333 uint64_t HazardSize = getStackHazardSize(MF);
4334 if (!HazardSize)
4335 HazardSize = MF.getSubtarget<AArch64Subtarget>()
4336 .getCLOpts()
4337 .stack_hazard_remark_size;
4338
4339 if (HazardSize == 0)
4340 return;
4341
4342 const MachineFrameInfo &MFI = MF.getFrameInfo();
4343 // Bail if function has no stack objects.
4344 if (!MFI.hasStackObjects())
4345 return;
4346
4347 std::vector<StackAccess> StackAccesses(MFI.getNumObjects());
4348
4349 size_t NumFPLdSt = 0;
4350 size_t NumNonFPLdSt = 0;
4351
4352 // Collect stack accesses via Load/Store instructions.
4353 for (const MachineBasicBlock &MBB : MF) {
4354 for (const MachineInstr &MI : MBB) {
4355 if (!MI.mayLoadOrStore() || MI.getNumMemOperands() < 1)
4356 continue;
4357 for (MachineMemOperand *MMO : MI.memoperands()) {
4358 std::optional<int> FI = getMMOFrameID(MMO, MFI);
4359 if (FI && !MFI.isDeadObjectIndex(*FI)) {
4360 int FrameIdx = *FI;
4361
4362 size_t ArrIdx = FrameIdx + MFI.getNumFixedObjects();
4363 if (StackAccesses[ArrIdx].AccessTypes == StackAccess::NotAccessed) {
4364 StackAccesses[ArrIdx].Idx = FrameIdx;
4365 StackAccesses[ArrIdx].Offset =
4366 getFrameIndexReferenceFromSP(MF, FrameIdx);
4367 StackAccesses[ArrIdx].Size = MFI.getObjectSize(FrameIdx);
4368 }
4369
4370 unsigned RegTy = StackAccess::AccessType::GPR;
4371 if (MFI.hasScalableStackID(FrameIdx))
4374 RegTy = StackAccess::FPR;
4375
4376 StackAccesses[ArrIdx].AccessTypes |= RegTy;
4377
4378 if (RegTy == StackAccess::FPR)
4379 ++NumFPLdSt;
4380 else
4381 ++NumNonFPLdSt;
4382 }
4383 }
4384 }
4385 }
4386
4387 if (NumFPLdSt == 0 || NumNonFPLdSt == 0)
4388 return;
4389
4390 llvm::sort(StackAccesses);
4391 llvm::erase_if(StackAccesses, [](const StackAccess &S) {
4393 });
4394
4397
4398 if (StackAccesses.front().isMixed())
4399 MixedObjects.push_back(&StackAccesses.front());
4400
4401 for (auto It = StackAccesses.begin(), End = std::prev(StackAccesses.end());
4402 It != End; ++It) {
4403 const auto &First = *It;
4404 const auto &Second = *(It + 1);
4405
4406 if (Second.isMixed())
4407 MixedObjects.push_back(&Second);
4408
4409 if ((First.isSME() && Second.isCPU()) ||
4410 (First.isCPU() && Second.isSME())) {
4411 uint64_t Distance = static_cast<uint64_t>(Second.start() - First.end());
4412 if (Distance < HazardSize)
4413 HazardPairs.emplace_back(&First, &Second);
4414 }
4415 }
4416
4417 auto EmitRemark = [&](llvm::StringRef Str) {
4418 ORE->emit([&]() {
4419 auto R = MachineOptimizationRemarkAnalysis(
4420 "sme", "StackHazard", MF.getFunction().getSubprogram(), &MF.front());
4421 return R << formatv("stack hazard in '{0}': ", MF.getName()).str() << Str;
4422 });
4423 };
4424
4425 for (const auto &P : HazardPairs)
4426 EmitRemark(formatv("{0} is too close to {1}", *P.first, *P.second).str());
4427
4428 for (const auto *Obj : MixedObjects)
4429 EmitRemark(
4430 formatv("{0} accessed by both GP and FP instructions", *Obj).str());
4431}
static void getLiveRegsForEntryMBB(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB)
static const unsigned DefaultSafeSPDisplacement
This is the biggest offset to the stack pointer we can encode in aarch64 instructions (without using ...
static RegState getPrologueDeath(MachineFunction &MF, unsigned Reg)
static bool produceCompactUnwindFrame(const AArch64FrameLowering &, MachineFunction &MF)
static bool invalidateWindowsRegisterPairing(bool SpillExtendedVolatile, int PairOffset, unsigned Reg1, unsigned Reg2, bool NeedsWinCFI, const TargetRegisterInfo *TRI)
bool enableMultiVectorSpillFill(const AArch64Subtarget &Subtarget, MachineFunction &MF)
static std::optional< int > getLdStFrameID(const MachineInstr &MI, const MachineFrameInfo &MFI)
static void orderZPRCalleeSavesForGroups(MachineFunction &MF, const TargetRegisterInfo *RegInfo, std::vector< CalleeSavedInfo > &CSI)
void computeCalleeSaveRegisterGroups(const AArch64FrameLowering &AFL, MachineFunction &MF, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI, SmallVectorImpl< RegGroupInfo > &RegGroups, bool NeedsFrameRecord)
static bool invalidateRegisterPairing(bool SpillExtendedVolatile, int PairOffset, unsigned Reg1, unsigned Reg2, bool UsesWinAAPCS, bool NeedsWinCFI, bool NeedsFrameRecord, const TargetRegisterInfo *TRI)
Returns true if Reg1 and Reg2 cannot be paired using a ldp/stp instruction.
static bool isLikelyToHaveSVEStack(const AArch64FrameLowering &AFL, const MachineFunction &MF)
static SVEStackSizes determineSVEStackSizes(MachineFunction &MF, AssignObjectOffsets AssignOffsets)
Process all the SVE stack objects and the SVE stack size and offsets for each object.
static bool isTargetWindows(const MachineFunction &MF)
static unsigned estimateRSStackSizeLimit(MachineFunction &MF)
Look at each instruction that references stack frames and return the stack size limit beyond which so...
static bool getSVECalleeSaveSlotRange(const MachineFrameInfo &MFI, int &Min, int &Max)
returns true if there are any SVE callee saves.
static MCRegister getRegisterOrZero(MCRegister Reg, bool HasSVE)
static unsigned getStackHazardSize(const MachineFunction &MF)
static bool isValidMemOpOffset(const AArch64InstrInfo *TII, unsigned Opcode, int Offset)
MCRegister findFreePredicateReg(BitVector &SavedRegs)
static bool isPPRAccess(const MachineInstr &MI)
static std::optional< int > getMMOFrameID(MachineMemOperand *MMO, const MachineFrameInfo &MFI)
const AArch64Subtarget & Subtarget
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file contains the declaration of the AArch64PrologueEmitter and AArch64EpilogueEmitter classes,...
static const int kSetTagLoopThreshold
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
AMDGPU Reserve WWM Registers
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains the simple types necessary to represent the attributes associated with functions a...
#define CASE(ATTRNAME, AANAME,...)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Forward Handle Accesses
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
static std::string getTypeString(Type *T)
Definition LLParser.cpp:69
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
#define P(N)
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:479
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
StackOffset getSVEStackSize(const MachineFunction &MF) const
Returns the size of the entire SVE stackframe (PPRs + ZPRs).
StackOffset getZPRStackSize(const MachineFunction &MF) const
Returns the size of the entire ZPR stackframe (calleesaves + spills).
void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
bool enableShrinkWrapping(const MachineFunction &MF) const override
Returns true if the target will correctly handle shrink wrapping.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool canUseAsPrologue(const MachineBasicBlock &MBB) const override
Check whether or not the given MBB can be used as a prologue for the target.
bool enableStackSlotScavenging(const MachineFunction &MF) const override
Returns true if the stack slot holes in the fixed and callee-save stack area should be used when allo...
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
bool enableFullCFIFixup(const MachineFunction &MF) const override
enableFullCFIFixup - Returns true if we may need to fix the unwind information such that it is accura...
StackOffset getFrameIndexReferenceFromSP(const MachineFunction &MF, int FI) const override
getFrameIndexReferenceFromSP - This method returns the offset from the stack pointer to the slot of t...
bool enableCFIFixup(const MachineFunction &MF) const override
Returns true if we may need to fix the unwind information for the function.
StackOffset getNonLocalFrameIndexReference(const MachineFunction &MF, int FI) const override
getNonLocalFrameIndexReference - This method returns the offset used to reference a frame index locat...
TargetStackID::Value getStackIDForScalableVectors() const override
Returns the StackID that scalable vectors should be associated with.
bool hasFPImpl(const MachineFunction &MF) const override
hasFPImpl - Return true if the specified function should have a dedicated frame pointer register.
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
void resetCFIToInitialState(MachineBasicBlock &MBB) const override
Emit CFI instructions that recreate the state of the unwind information upon function entry.
bool hasReservedCallFrame(const MachineFunction &MF) const override
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
bool hasSVECalleeSavesAboveFrameRecord(const MachineFunction &MF) const
StackOffset resolveFrameOffsetReference(const MachineFunction &MF, int64_t ObjectOffset, bool isFixed, TargetStackID::Value StackID, Register &FrameReg, bool PreferFP, bool ForSimm) const
bool canUseRedZone(const MachineFunction &MF) const
Can this function use the red zone for local allocations.
bool isFPReserved(const MachineFunction &MF) const
Should the Frame Pointer be reserved for the current function?
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
int getSEHFrameIndexOffset(const MachineFunction &MF, int FI) const
unsigned getWinEHFuncletFrameSize(const MachineFunction &MF) const
Funclets only need to account for space for the callee saved registers, as the locals are accounted f...
void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &ObjectsToAllocate) const override
Order the symbols in the local stack frame.
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
StackOffset getPPRStackSize(const MachineFunction &MF) const
Returns the size of the entire PPR stackframe (calleesaves + spills + hazard padding).
int64_t getArgumentStackToRestore(MachineFunction &MF, MachineBasicBlock &MBB) const
Returns how much of the incoming argument stack area (in bytes) we should clean up in an epilogue.
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - Provide a base+offset reference to an FI slot for debug info.
bool authenticatesReturnAddressEarly(MachineFunction &MF, MachineBasicBlock &MBB) const
Whether the return address is authenticated before the epilogue starts, in the return block MBB,...
bool enableWindowsCFIShrinkWrapping(const MachineFunction &MF) const override
Returns true if Windows CFI shrink wrapping should be enabled by default.
StackOffset getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI, Register &FrameReg, bool IgnoreSPUpdates) const override
For Win64 AArch64 EH, the offset to the Unwind object is from the SP before the update.
StackOffset resolveFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg, bool PreferFP, bool ForSimm) const
unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const override
The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve the parent's frame pointer...
bool requiresSaveVG(const MachineFunction &MF) const
void emitPacRetPlusLeafHardening(MachineFunction &MF) const
Harden the entire function with pac-ret.
AArch64FunctionInfo - This class is derived from MachineFunctionInfo and contains private AArch64-spe...
unsigned getCalleeSavedStackSize(const MachineFrameInfo &MFI) const
void setCalleeSaveBaseToFrameRecordOffset(int Offset)
SignReturnAddress getSignReturnAddressCondition() const
void setStackSizeSVE(uint64_t ZPR, uint64_t PPR)
std::optional< int > getTaggedBasePointerIndex() const
bool needsDwarfUnwindInfo(const MachineFunction &MF) const
static bool shouldSignReturnAddress(SignReturnAddress Condition, bool IsLRSpilled)
void setSVECalleeSavedStackSize(unsigned ZPR, unsigned PPR)
bool needsAsyncDwarfUnwindInfo(const MachineFunction &MF) const
static bool isTailCallReturnInst(const MachineInstr &MI)
Returns true if MI is one of the TCRETURN* instructions.
static bool isFpOrNEON(Register Reg)
Returns whether the physical register is FP or NEON.
const AArch64RegisterInfo * getRegisterInfo() const override
const AArch64InstrInfo * getInstrInfo() const override
const AArch64Options & getCLOpts() const
bool isSVEorStreamingSVEAvailable() const
Returns true if the target has access to either the full range of SVE instructions,...
bool isTargetWindowsOrUEFI() const
UEFI follows the Windows ARM64 ABI and produces PE/COFF images, so most of the Windows specific ABI h...
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:179
Helper class for creating CFI instructions and inserting them into MIR.
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
A debug info location.
Definition DebugLoc.h:126
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
Module * getParent()
Get the module that this global value is contained inside of...
A set of physical registers with utility functions to track liveness when walking backward/forward th...
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
constexpr bool isValid() const
Definition MCRegister.h:87
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
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.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
reverse_iterator rbegin()
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
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
const AllocaInst * getObjectAllocation(int ObjectIdx) const
Return the underlying Alloca of the specified stack object if it exists.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
bool hasCalls() const
Return true if the current function has any function calls.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
bool isCalleeSavedObjectIndex(int ObjectIdx) const
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
bool hasPatchPoint() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool hasScalableStackID(int ObjectIdx) const
int getStackProtectorIndex() const
Return the index for the stack protector object.
LLVM_ABI uint64_t estimateStackSize(const MachineFunction &MF) const
Estimate and return the size of the stack frame.
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.
bool isMaxCallFrameSizeComputed() const
bool hasStackMap() const
This method may be called any time after instruction selection is complete to determine if there is a...
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
unsigned getNumObjects() const
Return the number of objects.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackProtectorIndex() const
bool hasStackObjects() const
Return true if there are any stack objects in this function.
uint8_t getStackID(int ObjectIdx) const
unsigned getNumFixedObjects() const
Return the number of fixed objects.
void setIsCalleeSavedObjectIndex(int ObjectIdx, bool IsCalleeSaved)
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
int getObjectIndexBegin() const
Return the minimum frame object index.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool framePointerIsReserved() const
Returns true if the frame pointer must always either point to a new frame record or be un-modified in...
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
bool needsWinCFI() const
True if this function uses SEH unwind opcodes and needs an unwind table entry.
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
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
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.
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 & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
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 & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) 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
Representation of each machine instruction.
void setFlags(unsigned flags)
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
A description of a memory reference used in the backend.
const PseudoSourceValue * getPseudoValue() const
@ MOVolatile
The memory access is volatile.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
const Value * getValue() const
Return the base address of the memory access.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
LLVM_ABI bool isLiveIn(Register Reg) const
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
LLVM_ABI bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest=false) const
Return true if the specified register is modified or read in this function.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
MutableArrayRef< T > drop_until(PredicateT Pred) const
Return a copy of *this with the first N elements not satisfying the given predicate removed.
Definition ArrayRef.h:403
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
SMEAttrs is a utility class to parse the SME ACLE attributes on functions.
bool hasStreamingInterface() const
bool hasNonStreamingInterfaceAndBody() const
bool hasStreamingBody() const
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
static StackOffset get(int64_t Fixed, int64_t Scalable)
Definition TypeSize.h:42
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
virtual bool enableCFIFixup(const MachineFunction &MF) const
Returns true if we may need to fix the unwind information for the function.
const Triple & getTargetTriple() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition Triple.h:879
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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...
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
const unsigned StackProbeMaxLoopUnroll
Maximum number of iterations to unroll for a constant size probing loop.
const unsigned StackProbeMaxUnprobedStack
Maximum allowed number of unprobed bytes above SP at an ABI boundary.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeAddr< InstrNode * > Instr
Definition RDFGraph.h:389
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
void stable_sort(R &&Range)
Definition STLExtras.h:2132
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
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
int isAArch64FrameOffsetLegal(const MachineInstr &MI, StackOffset &Offset, bool *OutUseUnscaledOp=nullptr, unsigned *OutUnscaledOp=nullptr, int64_t *EmittableOffset=nullptr)
Check if the Offset is a valid frame offset for MI.
@ Unknown
Not known to have no common set bits.
RegState
Flags to represent properties of register accesses.
@ Define
Register definition.
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
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2334
@ AArch64FrameOffsetCannotUpdate
Offset cannot apply.
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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 formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
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.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr RegState getDefRegState(bool B)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse)
Return a range that conditionally reverses C.
Definition STLExtras.h:1439
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
bool operator<(const StackAccess &Rhs) const
void print(raw_ostream &OS) const
int64_t start() const
std::string getTypeString() const
int64_t end() const
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Pair of physical register and lane mask.
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.
SmallVector< WinEHTryBlockMapEntry, 4 > TryBlockMap
SmallVector< WinEHHandlerType, 1 > HandlerArray