1 //===- AArch64FrameLowering.cpp - AArch64 Frame Lowering -------*- C++ -*-====// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains the AArch64 implementation of TargetFrameLowering class. 11 // 12 // On AArch64, stack frames are structured as follows: 13 // 14 // The stack grows downward. 15 // 16 // All of the individual frame areas on the frame below are optional, i.e. it's 17 // possible to create a function so that the particular area isn't present 18 // in the frame. 19 // 20 // At function entry, the "frame" looks as follows: 21 // 22 // | | Higher address 23 // |-----------------------------------| 24 // | | 25 // | arguments passed on the stack | 26 // | | 27 // |-----------------------------------| <- sp 28 // | | Lower address 29 // 30 // 31 // After the prologue has run, the frame has the following general structure. 32 // Note that this doesn't depict the case where a red-zone is used. Also, 33 // technically the last frame area (VLAs) doesn't get created until in the 34 // main function body, after the prologue is run. However, it's depicted here 35 // for completeness. 36 // 37 // | | Higher address 38 // |-----------------------------------| 39 // | | 40 // | arguments passed on the stack | 41 // | | 42 // |-----------------------------------| 43 // | | 44 // | (Win64 only) varargs from reg | 45 // | | 46 // |-----------------------------------| 47 // | | 48 // | prev_fp, prev_lr | 49 // | (a.k.a. "frame record") | 50 // |-----------------------------------| <- fp(=x29) 51 // | | 52 // | other callee-saved registers | 53 // | | 54 // |-----------------------------------| 55 // |.empty.space.to.make.part.below....| 56 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at 57 // |.the.standard.16-byte.alignment....| compile time; if present) 58 // |-----------------------------------| 59 // | | 60 // | local variables of fixed size | 61 // | including spill slots | 62 // |-----------------------------------| <- bp(not defined by ABI, 63 // |.variable-sized.local.variables....| LLVM chooses X19) 64 // |.(VLAs)............................| (size of this area is unknown at 65 // |...................................| compile time) 66 // |-----------------------------------| <- sp 67 // | | Lower address 68 // 69 // 70 // To access the data in a frame, at-compile time, a constant offset must be 71 // computable from one of the pointers (fp, bp, sp) to access it. The size 72 // of the areas with a dotted background cannot be computed at compile-time 73 // if they are present, making it required to have all three of fp, bp and 74 // sp to be set up to be able to access all contents in the frame areas, 75 // assuming all of the frame areas are non-empty. 76 // 77 // For most functions, some of the frame areas are empty. For those functions, 78 // it may not be necessary to set up fp or bp: 79 // * A base pointer is definitely needed when there are both VLAs and local 80 // variables with more-than-default alignment requirements. 81 // * A frame pointer is definitely needed when there are local variables with 82 // more-than-default alignment requirements. 83 // 84 // In some cases when a base pointer is not strictly needed, it is generated 85 // anyway when offsets from the frame pointer to access local variables become 86 // so large that the offset can't be encoded in the immediate fields of loads 87 // or stores. 88 // 89 // FIXME: also explain the redzone concept. 90 // FIXME: also explain the concept of reserved call frames. 91 // 92 //===----------------------------------------------------------------------===// 93 94 #include "AArch64FrameLowering.h" 95 #include "AArch64InstrInfo.h" 96 #include "AArch64MachineFunctionInfo.h" 97 #include "AArch64RegisterInfo.h" 98 #include "AArch64Subtarget.h" 99 #include "AArch64TargetMachine.h" 100 #include "MCTargetDesc/AArch64AddressingModes.h" 101 #include "llvm/ADT/ScopeExit.h" 102 #include "llvm/ADT/SmallVector.h" 103 #include "llvm/ADT/Statistic.h" 104 #include "llvm/CodeGen/LivePhysRegs.h" 105 #include "llvm/CodeGen/MachineBasicBlock.h" 106 #include "llvm/CodeGen/MachineFrameInfo.h" 107 #include "llvm/CodeGen/MachineFunction.h" 108 #include "llvm/CodeGen/MachineInstr.h" 109 #include "llvm/CodeGen/MachineInstrBuilder.h" 110 #include "llvm/CodeGen/MachineMemOperand.h" 111 #include "llvm/CodeGen/MachineModuleInfo.h" 112 #include "llvm/CodeGen/MachineOperand.h" 113 #include "llvm/CodeGen/MachineRegisterInfo.h" 114 #include "llvm/CodeGen/RegisterScavenging.h" 115 #include "llvm/CodeGen/TargetInstrInfo.h" 116 #include "llvm/CodeGen/TargetRegisterInfo.h" 117 #include "llvm/CodeGen/TargetSubtargetInfo.h" 118 #include "llvm/CodeGen/WinEHFuncInfo.h" 119 #include "llvm/IR/Attributes.h" 120 #include "llvm/IR/CallingConv.h" 121 #include "llvm/IR/DataLayout.h" 122 #include "llvm/IR/DebugLoc.h" 123 #include "llvm/IR/Function.h" 124 #include "llvm/MC/MCAsmInfo.h" 125 #include "llvm/MC/MCDwarf.h" 126 #include "llvm/Support/CommandLine.h" 127 #include "llvm/Support/Debug.h" 128 #include "llvm/Support/ErrorHandling.h" 129 #include "llvm/Support/MathExtras.h" 130 #include "llvm/Support/raw_ostream.h" 131 #include "llvm/Target/TargetMachine.h" 132 #include "llvm/Target/TargetOptions.h" 133 #include <cassert> 134 #include <cstdint> 135 #include <iterator> 136 #include <vector> 137 138 using namespace llvm; 139 140 #define DEBUG_TYPE "frame-info" 141 142 static cl::opt<bool> EnableRedZone("aarch64-redzone", 143 cl::desc("enable use of redzone on AArch64"), 144 cl::init(false), cl::Hidden); 145 146 static cl::opt<bool> 147 ReverseCSRRestoreSeq("reverse-csr-restore-seq", 148 cl::desc("reverse the CSR restore sequence"), 149 cl::init(false), cl::Hidden); 150 151 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone"); 152 153 /// This is the biggest offset to the stack pointer we can encode in aarch64 154 /// instructions (without using a separate calculation and a temp register). 155 /// Note that the exception here are vector stores/loads which cannot encode any 156 /// displacements (see estimateRSStackSizeLimit(), isAArch64FrameOffsetLegal()). 157 static const unsigned DefaultSafeSPDisplacement = 255; 158 159 /// Look at each instruction that references stack frames and return the stack 160 /// size limit beyond which some of these instructions will require a scratch 161 /// register during their expansion later. 162 static unsigned estimateRSStackSizeLimit(MachineFunction &MF) { 163 // FIXME: For now, just conservatively guestimate based on unscaled indexing 164 // range. We'll end up allocating an unnecessary spill slot a lot, but 165 // realistically that's not a big deal at this stage of the game. 166 for (MachineBasicBlock &MBB : MF) { 167 for (MachineInstr &MI : MBB) { 168 if (MI.isDebugInstr() || MI.isPseudo() || 169 MI.getOpcode() == AArch64::ADDXri || 170 MI.getOpcode() == AArch64::ADDSXri) 171 continue; 172 173 for (const MachineOperand &MO : MI.operands()) { 174 if (!MO.isFI()) 175 continue; 176 177 int Offset = 0; 178 if (isAArch64FrameOffsetLegal(MI, Offset, nullptr, nullptr, nullptr) == 179 AArch64FrameOffsetCannotUpdate) 180 return 0; 181 } 182 } 183 } 184 return DefaultSafeSPDisplacement; 185 } 186 187 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const { 188 if (!EnableRedZone) 189 return false; 190 // Don't use the red zone if the function explicitly asks us not to. 191 // This is typically used for kernel code. 192 if (MF.getFunction().hasFnAttribute(Attribute::NoRedZone)) 193 return false; 194 195 const MachineFrameInfo &MFI = MF.getFrameInfo(); 196 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 197 unsigned NumBytes = AFI->getLocalStackSize(); 198 199 return !(MFI.hasCalls() || hasFP(MF) || NumBytes > 128); 200 } 201 202 /// hasFP - Return true if the specified function should have a dedicated frame 203 /// pointer register. 204 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const { 205 const MachineFrameInfo &MFI = MF.getFrameInfo(); 206 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 207 // Win64 EH requires a frame pointer if funclets are present, as the locals 208 // are accessed off the frame pointer in both the parent function and the 209 // funclets. 210 if (MF.hasEHFunclets()) 211 return true; 212 // Retain behavior of always omitting the FP for leaf functions when possible. 213 if (MFI.hasCalls() && MF.getTarget().Options.DisableFramePointerElim(MF)) 214 return true; 215 if (MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() || 216 MFI.hasStackMap() || MFI.hasPatchPoint() || 217 RegInfo->needsStackRealignment(MF)) 218 return true; 219 // With large callframes around we may need to use FP to access the scavenging 220 // emergency spillslot. 221 // 222 // Unfortunately some calls to hasFP() like machine verifier -> 223 // getReservedReg() -> hasFP in the middle of global isel are too early 224 // to know the max call frame size. Hopefully conservatively returning "true" 225 // in those cases is fine. 226 // DefaultSafeSPDisplacement is fine as we only emergency spill GP regs. 227 if (!MFI.isMaxCallFrameSizeComputed() || 228 MFI.getMaxCallFrameSize() > DefaultSafeSPDisplacement) 229 return true; 230 231 return false; 232 } 233 234 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 235 /// not required, we reserve argument space for call sites in the function 236 /// immediately on entry to the current function. This eliminates the need for 237 /// add/sub sp brackets around call sites. Returns true if the call frame is 238 /// included as part of the stack frame. 239 bool 240 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 241 return !MF.getFrameInfo().hasVarSizedObjects(); 242 } 243 244 MachineBasicBlock::iterator AArch64FrameLowering::eliminateCallFramePseudoInstr( 245 MachineFunction &MF, MachineBasicBlock &MBB, 246 MachineBasicBlock::iterator I) const { 247 const AArch64InstrInfo *TII = 248 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo()); 249 DebugLoc DL = I->getDebugLoc(); 250 unsigned Opc = I->getOpcode(); 251 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode(); 252 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0; 253 254 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 255 if (!TFI->hasReservedCallFrame(MF)) { 256 unsigned Align = getStackAlignment(); 257 258 int64_t Amount = I->getOperand(0).getImm(); 259 Amount = alignTo(Amount, Align); 260 if (!IsDestroy) 261 Amount = -Amount; 262 263 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it 264 // doesn't have to pop anything), then the first operand will be zero too so 265 // this adjustment is a no-op. 266 if (CalleePopAmount == 0) { 267 // FIXME: in-function stack adjustment for calls is limited to 24-bits 268 // because there's no guaranteed temporary register available. 269 // 270 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available. 271 // 1) For offset <= 12-bit, we use LSL #0 272 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses 273 // LSL #0, and the other uses LSL #12. 274 // 275 // Most call frames will be allocated at the start of a function so 276 // this is OK, but it is a limitation that needs dealing with. 277 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large"); 278 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII); 279 } 280 } else if (CalleePopAmount != 0) { 281 // If the calling convention demands that the callee pops arguments from the 282 // stack, we want to add it back if we have a reserved call frame. 283 assert(CalleePopAmount < 0xffffff && "call frame too large"); 284 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount, 285 TII); 286 } 287 return MBB.erase(I); 288 } 289 290 static bool ShouldSignReturnAddress(MachineFunction &MF) { 291 // The function should be signed in the following situations: 292 // - sign-return-address=all 293 // - sign-return-address=non-leaf and the functions spills the LR 294 295 const Function &F = MF.getFunction(); 296 if (!F.hasFnAttribute("sign-return-address")) 297 return false; 298 299 StringRef Scope = F.getFnAttribute("sign-return-address").getValueAsString(); 300 if (Scope.equals("none")) 301 return false; 302 303 if (Scope.equals("all")) 304 return true; 305 306 assert(Scope.equals("non-leaf") && "Expected all, none or non-leaf"); 307 308 for (const auto &Info : MF.getFrameInfo().getCalleeSavedInfo()) 309 if (Info.getReg() == AArch64::LR) 310 return true; 311 312 return false; 313 } 314 315 void AArch64FrameLowering::emitCalleeSavedFrameMoves( 316 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 317 MachineFunction &MF = *MBB.getParent(); 318 MachineFrameInfo &MFI = MF.getFrameInfo(); 319 const TargetSubtargetInfo &STI = MF.getSubtarget(); 320 const MCRegisterInfo *MRI = STI.getRegisterInfo(); 321 const TargetInstrInfo *TII = STI.getInstrInfo(); 322 DebugLoc DL = MBB.findDebugLoc(MBBI); 323 324 // Add callee saved registers to move list. 325 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 326 if (CSI.empty()) 327 return; 328 329 for (const auto &Info : CSI) { 330 unsigned Reg = Info.getReg(); 331 int64_t Offset = 332 MFI.getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea(); 333 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 334 unsigned CFIIndex = MF.addFrameInst( 335 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 336 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 337 .addCFIIndex(CFIIndex) 338 .setMIFlags(MachineInstr::FrameSetup); 339 } 340 } 341 342 // Find a scratch register that we can use at the start of the prologue to 343 // re-align the stack pointer. We avoid using callee-save registers since they 344 // may appear to be free when this is called from canUseAsPrologue (during 345 // shrink wrapping), but then no longer be free when this is called from 346 // emitPrologue. 347 // 348 // FIXME: This is a bit conservative, since in the above case we could use one 349 // of the callee-save registers as a scratch temp to re-align the stack pointer, 350 // but we would then have to make sure that we were in fact saving at least one 351 // callee-save register in the prologue, which is additional complexity that 352 // doesn't seem worth the benefit. 353 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) { 354 MachineFunction *MF = MBB->getParent(); 355 356 // If MBB is an entry block, use X9 as the scratch register 357 if (&MF->front() == MBB) 358 return AArch64::X9; 359 360 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>(); 361 const AArch64RegisterInfo &TRI = *Subtarget.getRegisterInfo(); 362 LivePhysRegs LiveRegs(TRI); 363 LiveRegs.addLiveIns(*MBB); 364 365 // Mark callee saved registers as used so we will not choose them. 366 const MCPhysReg *CSRegs = MF->getRegInfo().getCalleeSavedRegs(); 367 for (unsigned i = 0; CSRegs[i]; ++i) 368 LiveRegs.addReg(CSRegs[i]); 369 370 // Prefer X9 since it was historically used for the prologue scratch reg. 371 const MachineRegisterInfo &MRI = MF->getRegInfo(); 372 if (LiveRegs.available(MRI, AArch64::X9)) 373 return AArch64::X9; 374 375 for (unsigned Reg : AArch64::GPR64RegClass) { 376 if (LiveRegs.available(MRI, Reg)) 377 return Reg; 378 } 379 return AArch64::NoRegister; 380 } 381 382 bool AArch64FrameLowering::canUseAsPrologue( 383 const MachineBasicBlock &MBB) const { 384 const MachineFunction *MF = MBB.getParent(); 385 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB); 386 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>(); 387 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 388 389 // Don't need a scratch register if we're not going to re-align the stack. 390 if (!RegInfo->needsStackRealignment(*MF)) 391 return true; 392 // Otherwise, we can use any block as long as it has a scratch register 393 // available. 394 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister; 395 } 396 397 static bool windowsRequiresStackProbe(MachineFunction &MF, 398 unsigned StackSizeInBytes) { 399 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 400 if (!Subtarget.isTargetWindows()) 401 return false; 402 const Function &F = MF.getFunction(); 403 // TODO: When implementing stack protectors, take that into account 404 // for the probe threshold. 405 unsigned StackProbeSize = 4096; 406 if (F.hasFnAttribute("stack-probe-size")) 407 F.getFnAttribute("stack-probe-size") 408 .getValueAsString() 409 .getAsInteger(0, StackProbeSize); 410 return (StackSizeInBytes >= StackProbeSize) && 411 !F.hasFnAttribute("no-stack-arg-probe"); 412 } 413 414 bool AArch64FrameLowering::shouldCombineCSRLocalStackBump( 415 MachineFunction &MF, unsigned StackBumpBytes) const { 416 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 417 const MachineFrameInfo &MFI = MF.getFrameInfo(); 418 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 419 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 420 421 if (AFI->getLocalStackSize() == 0) 422 return false; 423 424 // 512 is the maximum immediate for stp/ldp that will be used for 425 // callee-save save/restores 426 if (StackBumpBytes >= 512 || windowsRequiresStackProbe(MF, StackBumpBytes)) 427 return false; 428 429 if (MFI.hasVarSizedObjects()) 430 return false; 431 432 if (RegInfo->needsStackRealignment(MF)) 433 return false; 434 435 // This isn't strictly necessary, but it simplifies things a bit since the 436 // current RedZone handling code assumes the SP is adjusted by the 437 // callee-save save/restore code. 438 if (canUseRedZone(MF)) 439 return false; 440 441 return true; 442 } 443 444 // Given a load or a store instruction, generate an appropriate unwinding SEH 445 // code on Windows. 446 static MachineBasicBlock::iterator InsertSEH(MachineBasicBlock::iterator MBBI, 447 const TargetInstrInfo &TII, 448 MachineInstr::MIFlag Flag) { 449 unsigned Opc = MBBI->getOpcode(); 450 MachineBasicBlock *MBB = MBBI->getParent(); 451 MachineFunction &MF = *MBB->getParent(); 452 DebugLoc DL = MBBI->getDebugLoc(); 453 unsigned ImmIdx = MBBI->getNumOperands() - 1; 454 int Imm = MBBI->getOperand(ImmIdx).getImm(); 455 MachineInstrBuilder MIB; 456 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 457 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 458 459 switch (Opc) { 460 default: 461 llvm_unreachable("No SEH Opcode for this instruction"); 462 case AArch64::LDPDpost: 463 Imm = -Imm; 464 LLVM_FALLTHROUGH; 465 case AArch64::STPDpre: { 466 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 467 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(2).getReg()); 468 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP_X)) 469 .addImm(Reg0) 470 .addImm(Reg1) 471 .addImm(Imm * 8) 472 .setMIFlag(Flag); 473 break; 474 } 475 case AArch64::LDPXpost: 476 Imm = -Imm; 477 LLVM_FALLTHROUGH; 478 case AArch64::STPXpre: { 479 unsigned Reg0 = MBBI->getOperand(1).getReg(); 480 unsigned Reg1 = MBBI->getOperand(2).getReg(); 481 if (Reg0 == AArch64::FP && Reg1 == AArch64::LR) 482 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR_X)) 483 .addImm(Imm * 8) 484 .setMIFlag(Flag); 485 else 486 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP_X)) 487 .addImm(RegInfo->getSEHRegNum(Reg0)) 488 .addImm(RegInfo->getSEHRegNum(Reg1)) 489 .addImm(Imm * 8) 490 .setMIFlag(Flag); 491 break; 492 } 493 case AArch64::LDRDpost: 494 Imm = -Imm; 495 LLVM_FALLTHROUGH; 496 case AArch64::STRDpre: { 497 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 498 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg_X)) 499 .addImm(Reg) 500 .addImm(Imm) 501 .setMIFlag(Flag); 502 break; 503 } 504 case AArch64::LDRXpost: 505 Imm = -Imm; 506 LLVM_FALLTHROUGH; 507 case AArch64::STRXpre: { 508 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 509 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg_X)) 510 .addImm(Reg) 511 .addImm(Imm) 512 .setMIFlag(Flag); 513 break; 514 } 515 case AArch64::STPDi: 516 case AArch64::LDPDi: { 517 unsigned Reg0 = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 518 unsigned Reg1 = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 519 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFRegP)) 520 .addImm(Reg0) 521 .addImm(Reg1) 522 .addImm(Imm * 8) 523 .setMIFlag(Flag); 524 break; 525 } 526 case AArch64::STPXi: 527 case AArch64::LDPXi: { 528 unsigned Reg0 = MBBI->getOperand(0).getReg(); 529 unsigned Reg1 = MBBI->getOperand(1).getReg(); 530 if (Reg0 == AArch64::FP && Reg1 == AArch64::LR) 531 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFPLR)) 532 .addImm(Imm * 8) 533 .setMIFlag(Flag); 534 else 535 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveRegP)) 536 .addImm(RegInfo->getSEHRegNum(Reg0)) 537 .addImm(RegInfo->getSEHRegNum(Reg1)) 538 .addImm(Imm * 8) 539 .setMIFlag(Flag); 540 break; 541 } 542 case AArch64::STRXui: 543 case AArch64::LDRXui: { 544 int Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 545 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveReg)) 546 .addImm(Reg) 547 .addImm(Imm * 8) 548 .setMIFlag(Flag); 549 break; 550 } 551 case AArch64::STRDui: 552 case AArch64::LDRDui: { 553 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 554 MIB = BuildMI(MF, DL, TII.get(AArch64::SEH_SaveFReg)) 555 .addImm(Reg) 556 .addImm(Imm * 8) 557 .setMIFlag(Flag); 558 break; 559 } 560 } 561 auto I = MBB->insertAfter(MBBI, MIB); 562 return I; 563 } 564 565 // Fix up the SEH opcode associated with the save/restore instruction. 566 static void fixupSEHOpcode(MachineBasicBlock::iterator MBBI, 567 unsigned LocalStackSize) { 568 MachineOperand *ImmOpnd = nullptr; 569 unsigned ImmIdx = MBBI->getNumOperands() - 1; 570 switch (MBBI->getOpcode()) { 571 default: 572 llvm_unreachable("Fix the offset in the SEH instruction"); 573 case AArch64::SEH_SaveFPLR: 574 case AArch64::SEH_SaveRegP: 575 case AArch64::SEH_SaveReg: 576 case AArch64::SEH_SaveFRegP: 577 case AArch64::SEH_SaveFReg: 578 ImmOpnd = &MBBI->getOperand(ImmIdx); 579 break; 580 } 581 if (ImmOpnd) 582 ImmOpnd->setImm(ImmOpnd->getImm() + LocalStackSize); 583 } 584 585 // Convert callee-save register save/restore instruction to do stack pointer 586 // decrement/increment to allocate/deallocate the callee-save stack area by 587 // converting store/load to use pre/post increment version. 588 static MachineBasicBlock::iterator convertCalleeSaveRestoreToSPPrePostIncDec( 589 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, 590 const DebugLoc &DL, const TargetInstrInfo *TII, int CSStackSizeInc, 591 bool NeedsWinCFI, bool InProlog = true) { 592 // Ignore instructions that do not operate on SP, i.e. shadow call stack 593 // instructions and associated CFI instruction. 594 while (MBBI->getOpcode() == AArch64::STRXpost || 595 MBBI->getOpcode() == AArch64::LDRXpre || 596 MBBI->getOpcode() == AArch64::CFI_INSTRUCTION) { 597 if (MBBI->getOpcode() != AArch64::CFI_INSTRUCTION) 598 assert(MBBI->getOperand(0).getReg() != AArch64::SP); 599 ++MBBI; 600 } 601 unsigned NewOpc; 602 int Scale = 1; 603 switch (MBBI->getOpcode()) { 604 default: 605 llvm_unreachable("Unexpected callee-save save/restore opcode!"); 606 case AArch64::STPXi: 607 NewOpc = AArch64::STPXpre; 608 Scale = 8; 609 break; 610 case AArch64::STPDi: 611 NewOpc = AArch64::STPDpre; 612 Scale = 8; 613 break; 614 case AArch64::STPQi: 615 NewOpc = AArch64::STPQpre; 616 Scale = 16; 617 break; 618 case AArch64::STRXui: 619 NewOpc = AArch64::STRXpre; 620 break; 621 case AArch64::STRDui: 622 NewOpc = AArch64::STRDpre; 623 break; 624 case AArch64::STRQui: 625 NewOpc = AArch64::STRQpre; 626 break; 627 case AArch64::LDPXi: 628 NewOpc = AArch64::LDPXpost; 629 Scale = 8; 630 break; 631 case AArch64::LDPDi: 632 NewOpc = AArch64::LDPDpost; 633 Scale = 8; 634 break; 635 case AArch64::LDPQi: 636 NewOpc = AArch64::LDPQpost; 637 Scale = 16; 638 break; 639 case AArch64::LDRXui: 640 NewOpc = AArch64::LDRXpost; 641 break; 642 case AArch64::LDRDui: 643 NewOpc = AArch64::LDRDpost; 644 break; 645 case AArch64::LDRQui: 646 NewOpc = AArch64::LDRQpost; 647 break; 648 } 649 // Get rid of the SEH code associated with the old instruction. 650 if (NeedsWinCFI) { 651 auto SEH = std::next(MBBI); 652 if (AArch64InstrInfo::isSEHInstruction(*SEH)) 653 SEH->eraseFromParent(); 654 } 655 656 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, DL, TII->get(NewOpc)); 657 MIB.addReg(AArch64::SP, RegState::Define); 658 659 // Copy all operands other than the immediate offset. 660 unsigned OpndIdx = 0; 661 for (unsigned OpndEnd = MBBI->getNumOperands() - 1; OpndIdx < OpndEnd; 662 ++OpndIdx) 663 MIB.add(MBBI->getOperand(OpndIdx)); 664 665 assert(MBBI->getOperand(OpndIdx).getImm() == 0 && 666 "Unexpected immediate offset in first/last callee-save save/restore " 667 "instruction!"); 668 assert(MBBI->getOperand(OpndIdx - 1).getReg() == AArch64::SP && 669 "Unexpected base register in callee-save save/restore instruction!"); 670 assert(CSStackSizeInc % Scale == 0); 671 MIB.addImm(CSStackSizeInc / Scale); 672 673 MIB.setMIFlags(MBBI->getFlags()); 674 MIB.setMemRefs(MBBI->memoperands()); 675 676 // Generate a new SEH code that corresponds to the new instruction. 677 if (NeedsWinCFI) 678 InsertSEH(*MIB, *TII, 679 InProlog ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy); 680 681 return std::prev(MBB.erase(MBBI)); 682 } 683 684 // Fixup callee-save register save/restore instructions to take into account 685 // combined SP bump by adding the local stack size to the stack offsets. 686 static void fixupCalleeSaveRestoreStackOffset(MachineInstr &MI, 687 unsigned LocalStackSize, 688 bool NeedsWinCFI) { 689 if (AArch64InstrInfo::isSEHInstruction(MI)) 690 return; 691 692 unsigned Opc = MI.getOpcode(); 693 694 // Ignore instructions that do not operate on SP, i.e. shadow call stack 695 // instructions and associated CFI instruction. 696 if (Opc == AArch64::STRXpost || Opc == AArch64::LDRXpre || 697 Opc == AArch64::CFI_INSTRUCTION) { 698 if (Opc != AArch64::CFI_INSTRUCTION) 699 assert(MI.getOperand(0).getReg() != AArch64::SP); 700 return; 701 } 702 703 unsigned Scale; 704 switch (Opc) { 705 case AArch64::STPXi: 706 case AArch64::STRXui: 707 case AArch64::STPDi: 708 case AArch64::STRDui: 709 case AArch64::LDPXi: 710 case AArch64::LDRXui: 711 case AArch64::LDPDi: 712 case AArch64::LDRDui: 713 Scale = 8; 714 break; 715 case AArch64::STPQi: 716 case AArch64::STRQui: 717 case AArch64::LDPQi: 718 case AArch64::LDRQui: 719 Scale = 16; 720 break; 721 default: 722 llvm_unreachable("Unexpected callee-save save/restore opcode!"); 723 } 724 725 unsigned OffsetIdx = MI.getNumExplicitOperands() - 1; 726 assert(MI.getOperand(OffsetIdx - 1).getReg() == AArch64::SP && 727 "Unexpected base register in callee-save save/restore instruction!"); 728 // Last operand is immediate offset that needs fixing. 729 MachineOperand &OffsetOpnd = MI.getOperand(OffsetIdx); 730 // All generated opcodes have scaled offsets. 731 assert(LocalStackSize % Scale == 0); 732 OffsetOpnd.setImm(OffsetOpnd.getImm() + LocalStackSize / Scale); 733 734 if (NeedsWinCFI) { 735 auto MBBI = std::next(MachineBasicBlock::iterator(MI)); 736 assert(MBBI != MI.getParent()->end() && "Expecting a valid instruction"); 737 assert(AArch64InstrInfo::isSEHInstruction(*MBBI) && 738 "Expecting a SEH instruction"); 739 fixupSEHOpcode(MBBI, LocalStackSize); 740 } 741 } 742 743 static void adaptForLdStOpt(MachineBasicBlock &MBB, 744 MachineBasicBlock::iterator FirstSPPopI, 745 MachineBasicBlock::iterator LastPopI) { 746 // Sometimes (when we restore in the same order as we save), we can end up 747 // with code like this: 748 // 749 // ldp x26, x25, [sp] 750 // ldp x24, x23, [sp, #16] 751 // ldp x22, x21, [sp, #32] 752 // ldp x20, x19, [sp, #48] 753 // add sp, sp, #64 754 // 755 // In this case, it is always better to put the first ldp at the end, so 756 // that the load-store optimizer can run and merge the ldp and the add into 757 // a post-index ldp. 758 // If we managed to grab the first pop instruction, move it to the end. 759 if (ReverseCSRRestoreSeq) 760 MBB.splice(FirstSPPopI, &MBB, LastPopI); 761 // We should end up with something like this now: 762 // 763 // ldp x24, x23, [sp, #16] 764 // ldp x22, x21, [sp, #32] 765 // ldp x20, x19, [sp, #48] 766 // ldp x26, x25, [sp] 767 // add sp, sp, #64 768 // 769 // and the load-store optimizer can merge the last two instructions into: 770 // 771 // ldp x26, x25, [sp], #64 772 // 773 } 774 775 static bool ShouldSignWithAKey(MachineFunction &MF) { 776 const Function &F = MF.getFunction(); 777 if (!F.hasFnAttribute("sign-return-address-key")) 778 return true; 779 780 const StringRef Key = 781 F.getFnAttribute("sign-return-address-key").getValueAsString(); 782 assert(Key.equals_lower("a_key") || Key.equals_lower("b_key")); 783 return Key.equals_lower("a_key"); 784 } 785 786 static bool needsWinCFI(const MachineFunction &MF) { 787 const Function &F = MF.getFunction(); 788 return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() && 789 F.needsUnwindTableEntry(); 790 } 791 792 void AArch64FrameLowering::emitPrologue(MachineFunction &MF, 793 MachineBasicBlock &MBB) const { 794 MachineBasicBlock::iterator MBBI = MBB.begin(); 795 const MachineFrameInfo &MFI = MF.getFrameInfo(); 796 const Function &F = MF.getFunction(); 797 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 798 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 799 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 800 MachineModuleInfo &MMI = MF.getMMI(); 801 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 802 bool needsFrameMoves = (MMI.hasDebugInfo() || F.needsUnwindTableEntry()) && 803 !MF.getTarget().getMCAsmInfo()->usesWindowsCFI(); 804 bool HasFP = hasFP(MF); 805 bool NeedsWinCFI = needsWinCFI(MF); 806 MF.setHasWinCFI(NeedsWinCFI); 807 bool IsFunclet = MBB.isEHFuncletEntry(); 808 809 // At this point, we're going to decide whether or not the function uses a 810 // redzone. In most cases, the function doesn't have a redzone so let's 811 // assume that's false and set it to true in the case that there's a redzone. 812 AFI->setHasRedZone(false); 813 814 // Debug location must be unknown since the first debug location is used 815 // to determine the end of the prologue. 816 DebugLoc DL; 817 818 if (ShouldSignReturnAddress(MF)) { 819 if (ShouldSignWithAKey(MF)) 820 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIASP)) 821 .setMIFlag(MachineInstr::FrameSetup); 822 else { 823 BuildMI(MBB, MBBI, DL, TII->get(AArch64::EMITBKEY)) 824 .setMIFlag(MachineInstr::FrameSetup); 825 BuildMI(MBB, MBBI, DL, TII->get(AArch64::PACIBSP)) 826 .setMIFlag(MachineInstr::FrameSetup); 827 } 828 829 unsigned CFIIndex = 830 MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr)); 831 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 832 .addCFIIndex(CFIIndex) 833 .setMIFlags(MachineInstr::FrameSetup); 834 } 835 836 // All calls are tail calls in GHC calling conv, and functions have no 837 // prologue/epilogue. 838 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 839 return; 840 841 // getStackSize() includes all the locals in its size calculation. We don't 842 // include these locals when computing the stack size of a funclet, as they 843 // are allocated in the parent's stack frame and accessed via the frame 844 // pointer from the funclet. We only save the callee saved registers in the 845 // funclet, which are really the callee saved registers of the parent 846 // function, including the funclet. 847 int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF) 848 : (int)MFI.getStackSize(); 849 if (!AFI->hasStackFrame() && !windowsRequiresStackProbe(MF, NumBytes)) { 850 assert(!HasFP && "unexpected function without stack frame but with FP"); 851 // All of the stack allocation is for locals. 852 AFI->setLocalStackSize(NumBytes); 853 if (!NumBytes) 854 return; 855 // REDZONE: If the stack size is less than 128 bytes, we don't need 856 // to actually allocate. 857 if (canUseRedZone(MF)) { 858 AFI->setHasRedZone(true); 859 ++NumRedZoneFunctions; 860 } else { 861 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII, 862 MachineInstr::FrameSetup, false, NeedsWinCFI); 863 if (!NeedsWinCFI) { 864 // Label used to tie together the PROLOG_LABEL and the MachineMoves. 865 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol(); 866 // Encode the stack size of the leaf function. 867 unsigned CFIIndex = MF.addFrameInst( 868 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes)); 869 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 870 .addCFIIndex(CFIIndex) 871 .setMIFlags(MachineInstr::FrameSetup); 872 } 873 } 874 875 if (NeedsWinCFI) 876 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd)) 877 .setMIFlag(MachineInstr::FrameSetup); 878 879 return; 880 } 881 882 bool IsWin64 = 883 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()); 884 // Var args are accounted for in the containing function, so don't 885 // include them for funclets. 886 unsigned FixedObject = (IsWin64 && !IsFunclet) ? 887 alignTo(AFI->getVarArgsGPRSize(), 16) : 0; 888 889 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject; 890 // All of the remaining stack allocations are for locals. 891 AFI->setLocalStackSize(NumBytes - PrologueSaveSize); 892 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes); 893 if (CombineSPBump) { 894 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII, 895 MachineInstr::FrameSetup, false, NeedsWinCFI); 896 NumBytes = 0; 897 } else if (PrologueSaveSize != 0) { 898 MBBI = convertCalleeSaveRestoreToSPPrePostIncDec( 899 MBB, MBBI, DL, TII, -PrologueSaveSize, NeedsWinCFI); 900 NumBytes -= PrologueSaveSize; 901 } 902 assert(NumBytes >= 0 && "Negative stack allocation size!?"); 903 904 // Move past the saves of the callee-saved registers, fixing up the offsets 905 // and pre-inc if we decided to combine the callee-save and local stack 906 // pointer bump above. 907 MachineBasicBlock::iterator End = MBB.end(); 908 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) { 909 if (CombineSPBump) 910 fixupCalleeSaveRestoreStackOffset(*MBBI, AFI->getLocalStackSize(), 911 NeedsWinCFI); 912 ++MBBI; 913 } 914 915 // The code below is not applicable to funclets. We have emitted all the SEH 916 // opcodes that we needed to emit. The FP and BP belong to the containing 917 // function. 918 if (IsFunclet) { 919 if (NeedsWinCFI) 920 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd)) 921 .setMIFlag(MachineInstr::FrameSetup); 922 return; 923 } 924 925 if (HasFP) { 926 // Only set up FP if we actually need to. Frame pointer is fp = 927 // sp - fixedobject - 16. 928 int FPOffset = AFI->getCalleeSavedStackSize() - 16; 929 if (CombineSPBump) 930 FPOffset += AFI->getLocalStackSize(); 931 932 // Issue sub fp, sp, FPOffset or 933 // mov fp,sp when FPOffset is zero. 934 // Note: All stores of callee-saved registers are marked as "FrameSetup". 935 // This code marks the instruction(s) that set the FP also. 936 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII, 937 MachineInstr::FrameSetup, false, NeedsWinCFI); 938 } 939 940 if (windowsRequiresStackProbe(MF, NumBytes)) { 941 uint32_t NumWords = NumBytes >> 4; 942 if (NeedsWinCFI) { 943 // alloc_l can hold at most 256MB, so assume that NumBytes doesn't 944 // exceed this amount. We need to move at most 2^24 - 1 into x15. 945 // This is at most two instructions, MOVZ follwed by MOVK. 946 // TODO: Fix to use multiple stack alloc unwind codes for stacks 947 // exceeding 256MB in size. 948 if (NumBytes >= (1 << 28)) 949 report_fatal_error("Stack size cannot exceed 256MB for stack " 950 "unwinding purposes"); 951 952 uint32_t LowNumWords = NumWords & 0xFFFF; 953 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVZXi), AArch64::X15) 954 .addImm(LowNumWords) 955 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0)) 956 .setMIFlag(MachineInstr::FrameSetup); 957 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 958 .setMIFlag(MachineInstr::FrameSetup); 959 if ((NumWords & 0xFFFF0000) != 0) { 960 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVKXi), AArch64::X15) 961 .addReg(AArch64::X15) 962 .addImm((NumWords & 0xFFFF0000) >> 16) // High half 963 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 16)) 964 .setMIFlag(MachineInstr::FrameSetup); 965 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 966 .setMIFlag(MachineInstr::FrameSetup); 967 } 968 } else { 969 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVi64imm), AArch64::X15) 970 .addImm(NumWords) 971 .setMIFlags(MachineInstr::FrameSetup); 972 } 973 974 switch (MF.getTarget().getCodeModel()) { 975 case CodeModel::Tiny: 976 case CodeModel::Small: 977 case CodeModel::Medium: 978 case CodeModel::Kernel: 979 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BL)) 980 .addExternalSymbol("__chkstk") 981 .addReg(AArch64::X15, RegState::Implicit) 982 .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead) 983 .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead) 984 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead) 985 .setMIFlags(MachineInstr::FrameSetup); 986 if (NeedsWinCFI) 987 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 988 .setMIFlag(MachineInstr::FrameSetup); 989 break; 990 case CodeModel::Large: 991 BuildMI(MBB, MBBI, DL, TII->get(AArch64::MOVaddrEXT)) 992 .addReg(AArch64::X16, RegState::Define) 993 .addExternalSymbol("__chkstk") 994 .addExternalSymbol("__chkstk") 995 .setMIFlags(MachineInstr::FrameSetup); 996 if (NeedsWinCFI) 997 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 998 .setMIFlag(MachineInstr::FrameSetup); 999 1000 BuildMI(MBB, MBBI, DL, TII->get(AArch64::BLR)) 1001 .addReg(AArch64::X16, RegState::Kill) 1002 .addReg(AArch64::X15, RegState::Implicit | RegState::Define) 1003 .addReg(AArch64::X16, RegState::Implicit | RegState::Define | RegState::Dead) 1004 .addReg(AArch64::X17, RegState::Implicit | RegState::Define | RegState::Dead) 1005 .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define | RegState::Dead) 1006 .setMIFlags(MachineInstr::FrameSetup); 1007 if (NeedsWinCFI) 1008 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 1009 .setMIFlag(MachineInstr::FrameSetup); 1010 break; 1011 } 1012 1013 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SUBXrx64), AArch64::SP) 1014 .addReg(AArch64::SP, RegState::Kill) 1015 .addReg(AArch64::X15, RegState::Kill) 1016 .addImm(AArch64_AM::getArithExtendImm(AArch64_AM::UXTX, 4)) 1017 .setMIFlags(MachineInstr::FrameSetup); 1018 if (NeedsWinCFI) 1019 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc)) 1020 .addImm(NumBytes) 1021 .setMIFlag(MachineInstr::FrameSetup); 1022 NumBytes = 0; 1023 } 1024 1025 // Allocate space for the rest of the frame. 1026 if (NumBytes) { 1027 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF); 1028 unsigned scratchSPReg = AArch64::SP; 1029 1030 if (NeedsRealignment) { 1031 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB); 1032 assert(scratchSPReg != AArch64::NoRegister); 1033 } 1034 1035 // If we're a leaf function, try using the red zone. 1036 if (!canUseRedZone(MF)) 1037 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have 1038 // the correct value here, as NumBytes also includes padding bytes, 1039 // which shouldn't be counted here. 1040 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII, 1041 MachineInstr::FrameSetup, false, NeedsWinCFI); 1042 1043 if (NeedsRealignment) { 1044 const unsigned Alignment = MFI.getMaxAlignment(); 1045 const unsigned NrBitsToZero = countTrailingZeros(Alignment); 1046 assert(NrBitsToZero > 1); 1047 assert(scratchSPReg != AArch64::SP); 1048 1049 // SUB X9, SP, NumBytes 1050 // -- X9 is temporary register, so shouldn't contain any live data here, 1051 // -- free to use. This is already produced by emitFrameOffset above. 1052 // AND SP, X9, 0b11111...0000 1053 // The logical immediates have a non-trivial encoding. The following 1054 // formula computes the encoded immediate with all ones but 1055 // NrBitsToZero zero bits as least significant bits. 1056 uint32_t andMaskEncoded = (1 << 12) // = N 1057 | ((64 - NrBitsToZero) << 6) // immr 1058 | ((64 - NrBitsToZero - 1) << 0); // imms 1059 1060 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP) 1061 .addReg(scratchSPReg, RegState::Kill) 1062 .addImm(andMaskEncoded); 1063 AFI->setStackRealigned(true); 1064 if (NeedsWinCFI) 1065 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc)) 1066 .addImm(NumBytes & andMaskEncoded) 1067 .setMIFlag(MachineInstr::FrameSetup); 1068 } 1069 } 1070 1071 // If we need a base pointer, set it up here. It's whatever the value of the 1072 // stack pointer is at this point. Any variable size objects will be allocated 1073 // after this, so we can still use the base pointer to reference locals. 1074 // 1075 // FIXME: Clarify FrameSetup flags here. 1076 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is 1077 // needed. 1078 if (RegInfo->hasBasePointer(MF)) { 1079 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP, 1080 false); 1081 if (NeedsWinCFI) 1082 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_Nop)) 1083 .setMIFlag(MachineInstr::FrameSetup); 1084 } 1085 1086 // The very last FrameSetup instruction indicates the end of prologue. Emit a 1087 // SEH opcode indicating the prologue end. 1088 if (NeedsWinCFI) 1089 BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_PrologEnd)) 1090 .setMIFlag(MachineInstr::FrameSetup); 1091 1092 if (needsFrameMoves) { 1093 const DataLayout &TD = MF.getDataLayout(); 1094 const int StackGrowth = -TD.getPointerSize(0); 1095 unsigned FramePtr = RegInfo->getFrameRegister(MF); 1096 // An example of the prologue: 1097 // 1098 // .globl __foo 1099 // .align 2 1100 // __foo: 1101 // Ltmp0: 1102 // .cfi_startproc 1103 // .cfi_personality 155, ___gxx_personality_v0 1104 // Leh_func_begin: 1105 // .cfi_lsda 16, Lexception33 1106 // 1107 // stp xa,bx, [sp, -#offset]! 1108 // ... 1109 // stp x28, x27, [sp, #offset-32] 1110 // stp fp, lr, [sp, #offset-16] 1111 // add fp, sp, #offset - 16 1112 // sub sp, sp, #1360 1113 // 1114 // The Stack: 1115 // +-------------------------------------------+ 1116 // 10000 | ........ | ........ | ........ | ........ | 1117 // 10004 | ........ | ........ | ........ | ........ | 1118 // +-------------------------------------------+ 1119 // 10008 | ........ | ........ | ........ | ........ | 1120 // 1000c | ........ | ........ | ........ | ........ | 1121 // +===========================================+ 1122 // 10010 | X28 Register | 1123 // 10014 | X28 Register | 1124 // +-------------------------------------------+ 1125 // 10018 | X27 Register | 1126 // 1001c | X27 Register | 1127 // +===========================================+ 1128 // 10020 | Frame Pointer | 1129 // 10024 | Frame Pointer | 1130 // +-------------------------------------------+ 1131 // 10028 | Link Register | 1132 // 1002c | Link Register | 1133 // +===========================================+ 1134 // 10030 | ........ | ........ | ........ | ........ | 1135 // 10034 | ........ | ........ | ........ | ........ | 1136 // +-------------------------------------------+ 1137 // 10038 | ........ | ........ | ........ | ........ | 1138 // 1003c | ........ | ........ | ........ | ........ | 1139 // +-------------------------------------------+ 1140 // 1141 // [sp] = 10030 :: >>initial value<< 1142 // sp = 10020 :: stp fp, lr, [sp, #-16]! 1143 // fp = sp == 10020 :: mov fp, sp 1144 // [sp] == 10020 :: stp x28, x27, [sp, #-16]! 1145 // sp == 10010 :: >>final value<< 1146 // 1147 // The frame pointer (w29) points to address 10020. If we use an offset of 1148 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24 1149 // for w27, and -32 for w28: 1150 // 1151 // Ltmp1: 1152 // .cfi_def_cfa w29, 16 1153 // Ltmp2: 1154 // .cfi_offset w30, -8 1155 // Ltmp3: 1156 // .cfi_offset w29, -16 1157 // Ltmp4: 1158 // .cfi_offset w27, -24 1159 // Ltmp5: 1160 // .cfi_offset w28, -32 1161 1162 if (HasFP) { 1163 // Define the current CFA rule to use the provided FP. 1164 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true); 1165 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa( 1166 nullptr, Reg, 2 * StackGrowth - FixedObject)); 1167 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 1168 .addCFIIndex(CFIIndex) 1169 .setMIFlags(MachineInstr::FrameSetup); 1170 } else { 1171 // Encode the stack size of the leaf function. 1172 unsigned CFIIndex = MF.addFrameInst( 1173 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI.getStackSize())); 1174 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 1175 .addCFIIndex(CFIIndex) 1176 .setMIFlags(MachineInstr::FrameSetup); 1177 } 1178 1179 // Now emit the moves for whatever callee saved regs we have (including FP, 1180 // LR if those are saved). 1181 emitCalleeSavedFrameMoves(MBB, MBBI); 1182 } 1183 } 1184 1185 static void InsertReturnAddressAuth(MachineFunction &MF, 1186 MachineBasicBlock &MBB) { 1187 if (!ShouldSignReturnAddress(MF)) 1188 return; 1189 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1190 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1191 1192 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); 1193 DebugLoc DL; 1194 if (MBBI != MBB.end()) 1195 DL = MBBI->getDebugLoc(); 1196 1197 // The AUTIASP instruction assembles to a hint instruction before v8.3a so 1198 // this instruction can safely used for any v8a architecture. 1199 // From v8.3a onwards there are optimised authenticate LR and return 1200 // instructions, namely RETA{A,B}, that can be used instead. 1201 if (Subtarget.hasV8_3aOps() && MBBI != MBB.end() && 1202 MBBI->getOpcode() == AArch64::RET_ReallyLR) { 1203 BuildMI(MBB, MBBI, DL, 1204 TII->get(ShouldSignWithAKey(MF) ? AArch64::RETAA : AArch64::RETAB)) 1205 .copyImplicitOps(*MBBI); 1206 MBB.erase(MBBI); 1207 } else { 1208 BuildMI( 1209 MBB, MBBI, DL, 1210 TII->get(ShouldSignWithAKey(MF) ? AArch64::AUTIASP : AArch64::AUTIBSP)) 1211 .setMIFlag(MachineInstr::FrameDestroy); 1212 } 1213 } 1214 1215 static bool isFuncletReturnInstr(const MachineInstr &MI) { 1216 switch (MI.getOpcode()) { 1217 default: 1218 return false; 1219 case AArch64::CATCHRET: 1220 case AArch64::CLEANUPRET: 1221 return true; 1222 } 1223 } 1224 1225 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF, 1226 MachineBasicBlock &MBB) const { 1227 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 1228 MachineFrameInfo &MFI = MF.getFrameInfo(); 1229 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1230 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 1231 DebugLoc DL; 1232 bool IsTailCallReturn = false; 1233 bool NeedsWinCFI = needsWinCFI(MF); 1234 bool IsFunclet = false; 1235 1236 if (MBB.end() != MBBI) { 1237 DL = MBBI->getDebugLoc(); 1238 unsigned RetOpcode = MBBI->getOpcode(); 1239 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi || 1240 RetOpcode == AArch64::TCRETURNri || 1241 RetOpcode == AArch64::TCRETURNriBTI; 1242 IsFunclet = isFuncletReturnInstr(*MBBI); 1243 } 1244 1245 int NumBytes = IsFunclet ? (int)getWinEHFuncletFrameSize(MF) 1246 : MFI.getStackSize(); 1247 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1248 1249 // All calls are tail calls in GHC calling conv, and functions have no 1250 // prologue/epilogue. 1251 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 1252 return; 1253 1254 // Initial and residual are named for consistency with the prologue. Note that 1255 // in the epilogue, the residual adjustment is executed first. 1256 uint64_t ArgumentPopSize = 0; 1257 if (IsTailCallReturn) { 1258 MachineOperand &StackAdjust = MBBI->getOperand(1); 1259 1260 // For a tail-call in a callee-pops-arguments environment, some or all of 1261 // the stack may actually be in use for the call's arguments, this is 1262 // calculated during LowerCall and consumed here... 1263 ArgumentPopSize = StackAdjust.getImm(); 1264 } else { 1265 // ... otherwise the amount to pop is *all* of the argument space, 1266 // conveniently stored in the MachineFunctionInfo by 1267 // LowerFormalArguments. This will, of course, be zero for the C calling 1268 // convention. 1269 ArgumentPopSize = AFI->getArgumentStackToRestore(); 1270 } 1271 1272 // The stack frame should be like below, 1273 // 1274 // ---------------------- --- 1275 // | | | 1276 // | BytesInStackArgArea| CalleeArgStackSize 1277 // | (NumReusableBytes) | (of tail call) 1278 // | | --- 1279 // | | | 1280 // ---------------------| --- | 1281 // | | | | 1282 // | CalleeSavedReg | | | 1283 // | (CalleeSavedStackSize)| | | 1284 // | | | | 1285 // ---------------------| | NumBytes 1286 // | | StackSize (StackAdjustUp) 1287 // | LocalStackSize | | | 1288 // | (covering callee | | | 1289 // | args) | | | 1290 // | | | | 1291 // ---------------------- --- --- 1292 // 1293 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize 1294 // = StackSize + ArgumentPopSize 1295 // 1296 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps 1297 // it as the 2nd argument of AArch64ISD::TC_RETURN. 1298 1299 auto Cleanup = make_scope_exit([&] { InsertReturnAddressAuth(MF, MBB); }); 1300 1301 bool IsWin64 = 1302 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()); 1303 // Var args are accounted for in the containing function, so don't 1304 // include them for funclets. 1305 unsigned FixedObject = 1306 (IsWin64 && !IsFunclet) ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0; 1307 1308 uint64_t AfterCSRPopSize = ArgumentPopSize; 1309 auto PrologueSaveSize = AFI->getCalleeSavedStackSize() + FixedObject; 1310 // We cannot rely on the local stack size set in emitPrologue if the function 1311 // has funclets, as funclets have different local stack size requirements, and 1312 // the current value set in emitPrologue may be that of the containing 1313 // function. 1314 if (MF.hasEHFunclets()) 1315 AFI->setLocalStackSize(NumBytes - PrologueSaveSize); 1316 bool CombineSPBump = shouldCombineCSRLocalStackBump(MF, NumBytes); 1317 // Assume we can't combine the last pop with the sp restore. 1318 1319 if (!CombineSPBump && PrologueSaveSize != 0) { 1320 MachineBasicBlock::iterator Pop = std::prev(MBB.getFirstTerminator()); 1321 while (AArch64InstrInfo::isSEHInstruction(*Pop)) 1322 Pop = std::prev(Pop); 1323 // Converting the last ldp to a post-index ldp is valid only if the last 1324 // ldp's offset is 0. 1325 const MachineOperand &OffsetOp = Pop->getOperand(Pop->getNumOperands() - 1); 1326 // If the offset is 0, convert it to a post-index ldp. 1327 if (OffsetOp.getImm() == 0) 1328 convertCalleeSaveRestoreToSPPrePostIncDec( 1329 MBB, Pop, DL, TII, PrologueSaveSize, NeedsWinCFI, false); 1330 else { 1331 // If not, make sure to emit an add after the last ldp. 1332 // We're doing this by transfering the size to be restored from the 1333 // adjustment *before* the CSR pops to the adjustment *after* the CSR 1334 // pops. 1335 AfterCSRPopSize += PrologueSaveSize; 1336 } 1337 } 1338 1339 // Move past the restores of the callee-saved registers. 1340 // If we plan on combining the sp bump of the local stack size and the callee 1341 // save stack size, we might need to adjust the CSR save and restore offsets. 1342 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator(); 1343 MachineBasicBlock::iterator Begin = MBB.begin(); 1344 while (LastPopI != Begin) { 1345 --LastPopI; 1346 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) { 1347 ++LastPopI; 1348 break; 1349 } else if (CombineSPBump) 1350 fixupCalleeSaveRestoreStackOffset(*LastPopI, AFI->getLocalStackSize(), 1351 NeedsWinCFI); 1352 } 1353 1354 if (NeedsWinCFI) 1355 BuildMI(MBB, LastPopI, DL, TII->get(AArch64::SEH_EpilogStart)) 1356 .setMIFlag(MachineInstr::FrameDestroy); 1357 1358 // If there is a single SP update, insert it before the ret and we're done. 1359 if (CombineSPBump) { 1360 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP, 1361 NumBytes + AfterCSRPopSize, TII, MachineInstr::FrameDestroy, 1362 false, NeedsWinCFI); 1363 if (NeedsWinCFI) 1364 BuildMI(MBB, MBB.getFirstTerminator(), DL, 1365 TII->get(AArch64::SEH_EpilogEnd)) 1366 .setMIFlag(MachineInstr::FrameDestroy); 1367 return; 1368 } 1369 1370 NumBytes -= PrologueSaveSize; 1371 assert(NumBytes >= 0 && "Negative stack allocation size!?"); 1372 1373 if (!hasFP(MF)) { 1374 bool RedZone = canUseRedZone(MF); 1375 // If this was a redzone leaf function, we don't need to restore the 1376 // stack pointer (but we may need to pop stack args for fastcc). 1377 if (RedZone && AfterCSRPopSize == 0) 1378 return; 1379 1380 bool NoCalleeSaveRestore = PrologueSaveSize == 0; 1381 int StackRestoreBytes = RedZone ? 0 : NumBytes; 1382 if (NoCalleeSaveRestore) 1383 StackRestoreBytes += AfterCSRPopSize; 1384 1385 // If we were able to combine the local stack pop with the argument pop, 1386 // then we're done. 1387 bool Done = NoCalleeSaveRestore || AfterCSRPopSize == 0; 1388 1389 // If we're done after this, make sure to help the load store optimizer. 1390 if (Done) 1391 adaptForLdStOpt(MBB, MBB.getFirstTerminator(), LastPopI); 1392 1393 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, 1394 StackRestoreBytes, TII, MachineInstr::FrameDestroy, false, 1395 NeedsWinCFI); 1396 if (Done) { 1397 if (NeedsWinCFI) 1398 BuildMI(MBB, MBB.getFirstTerminator(), DL, 1399 TII->get(AArch64::SEH_EpilogEnd)) 1400 .setMIFlag(MachineInstr::FrameDestroy); 1401 return; 1402 } 1403 1404 NumBytes = 0; 1405 } 1406 1407 // Restore the original stack pointer. 1408 // FIXME: Rather than doing the math here, we should instead just use 1409 // non-post-indexed loads for the restores if we aren't actually going to 1410 // be able to save any instructions. 1411 if (!IsFunclet && (MFI.hasVarSizedObjects() || AFI->isStackRealigned())) 1412 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP, 1413 -AFI->getCalleeSavedStackSize() + 16, TII, 1414 MachineInstr::FrameDestroy, false, NeedsWinCFI); 1415 else if (NumBytes) 1416 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, NumBytes, TII, 1417 MachineInstr::FrameDestroy, false, NeedsWinCFI); 1418 1419 // This must be placed after the callee-save restore code because that code 1420 // assumes the SP is at the same location as it was after the callee-save save 1421 // code in the prologue. 1422 if (AfterCSRPopSize) { 1423 // Find an insertion point for the first ldp so that it goes before the 1424 // shadow call stack epilog instruction. This ensures that the restore of 1425 // lr from x18 is placed after the restore from sp. 1426 auto FirstSPPopI = MBB.getFirstTerminator(); 1427 while (FirstSPPopI != Begin) { 1428 auto Prev = std::prev(FirstSPPopI); 1429 if (Prev->getOpcode() != AArch64::LDRXpre || 1430 Prev->getOperand(0).getReg() == AArch64::SP) 1431 break; 1432 FirstSPPopI = Prev; 1433 } 1434 1435 adaptForLdStOpt(MBB, FirstSPPopI, LastPopI); 1436 1437 emitFrameOffset(MBB, FirstSPPopI, DL, AArch64::SP, AArch64::SP, 1438 AfterCSRPopSize, TII, MachineInstr::FrameDestroy, false, 1439 NeedsWinCFI); 1440 } 1441 if (NeedsWinCFI) 1442 BuildMI(MBB, MBB.getFirstTerminator(), DL, TII->get(AArch64::SEH_EpilogEnd)) 1443 .setMIFlag(MachineInstr::FrameDestroy); 1444 } 1445 1446 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 1447 /// debug info. It's the same as what we use for resolving the code-gen 1448 /// references for now. FIXME: This can go wrong when references are 1449 /// SP-relative and simple call frames aren't used. 1450 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, 1451 int FI, 1452 unsigned &FrameReg) const { 1453 return resolveFrameIndexReference(MF, FI, FrameReg); 1454 } 1455 1456 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF, 1457 int FI, unsigned &FrameReg, 1458 bool PreferFP) const { 1459 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1460 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>( 1461 MF.getSubtarget().getRegisterInfo()); 1462 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1463 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1464 bool IsWin64 = 1465 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()); 1466 unsigned FixedObject = IsWin64 ? alignTo(AFI->getVarArgsGPRSize(), 16) : 0; 1467 int FPOffset = MFI.getObjectOffset(FI) + FixedObject + 16; 1468 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize(); 1469 bool isFixed = MFI.isFixedObjectIndex(FI); 1470 bool isCSR = !isFixed && MFI.getObjectOffset(FI) >= 1471 -((int)AFI->getCalleeSavedStackSize()); 1472 1473 // Use frame pointer to reference fixed objects. Use it for locals if 1474 // there are VLAs or a dynamically realigned SP (and thus the SP isn't 1475 // reliable as a base). Make sure useFPForScavengingIndex() does the 1476 // right thing for the emergency spill slot. 1477 bool UseFP = false; 1478 if (AFI->hasStackFrame()) { 1479 // Note: Keeping the following as multiple 'if' statements rather than 1480 // merging to a single expression for readability. 1481 // 1482 // Argument access should always use the FP. 1483 if (isFixed) { 1484 UseFP = hasFP(MF); 1485 } else if (isCSR && RegInfo->needsStackRealignment(MF)) { 1486 // References to the CSR area must use FP if we're re-aligning the stack 1487 // since the dynamically-sized alignment padding is between the SP/BP and 1488 // the CSR area. 1489 assert(hasFP(MF) && "Re-aligned stack must have frame pointer"); 1490 UseFP = true; 1491 } else if (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) { 1492 // If the FPOffset is negative, we have to keep in mind that the 1493 // available offset range for negative offsets is smaller than for 1494 // positive ones. If an offset is 1495 // available via the FP and the SP, use whichever is closest. 1496 bool FPOffsetFits = FPOffset >= -256; 1497 PreferFP |= Offset > -FPOffset; 1498 1499 if (MFI.hasVarSizedObjects()) { 1500 // If we have variable sized objects, we can use either FP or BP, as the 1501 // SP offset is unknown. We can use the base pointer if we have one and 1502 // FP is not preferred. If not, we're stuck with using FP. 1503 bool CanUseBP = RegInfo->hasBasePointer(MF); 1504 if (FPOffsetFits && CanUseBP) // Both are ok. Pick the best. 1505 UseFP = PreferFP; 1506 else if (!CanUseBP) // Can't use BP. Forced to use FP. 1507 UseFP = true; 1508 // else we can use BP and FP, but the offset from FP won't fit. 1509 // That will make us scavenge registers which we can probably avoid by 1510 // using BP. If it won't fit for BP either, we'll scavenge anyway. 1511 } else if (FPOffset >= 0) { 1512 // Use SP or FP, whichever gives us the best chance of the offset 1513 // being in range for direct access. If the FPOffset is positive, 1514 // that'll always be best, as the SP will be even further away. 1515 UseFP = true; 1516 } else if (MF.hasEHFunclets() && !RegInfo->hasBasePointer(MF)) { 1517 // Funclets access the locals contained in the parent's stack frame 1518 // via the frame pointer, so we have to use the FP in the parent 1519 // function. 1520 assert( 1521 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()) && 1522 "Funclets should only be present on Win64"); 1523 UseFP = true; 1524 } else { 1525 // We have the choice between FP and (SP or BP). 1526 if (FPOffsetFits && PreferFP) // If FP is the best fit, use it. 1527 UseFP = true; 1528 } 1529 } 1530 } 1531 1532 assert(((isFixed || isCSR) || !RegInfo->needsStackRealignment(MF) || !UseFP) && 1533 "In the presence of dynamic stack pointer realignment, " 1534 "non-argument/CSR objects cannot be accessed through the frame pointer"); 1535 1536 if (UseFP) { 1537 FrameReg = RegInfo->getFrameRegister(MF); 1538 return FPOffset; 1539 } 1540 1541 // Use the base pointer if we have one. 1542 if (RegInfo->hasBasePointer(MF)) 1543 FrameReg = RegInfo->getBaseRegister(); 1544 else { 1545 assert(!MFI.hasVarSizedObjects() && 1546 "Can't use SP when we have var sized objects."); 1547 FrameReg = AArch64::SP; 1548 // If we're using the red zone for this function, the SP won't actually 1549 // be adjusted, so the offsets will be negative. They're also all 1550 // within range of the signed 9-bit immediate instructions. 1551 if (canUseRedZone(MF)) 1552 Offset -= AFI->getLocalStackSize(); 1553 } 1554 1555 return Offset; 1556 } 1557 1558 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) { 1559 // Do not set a kill flag on values that are also marked as live-in. This 1560 // happens with the @llvm-returnaddress intrinsic and with arguments passed in 1561 // callee saved registers. 1562 // Omitting the kill flags is conservatively correct even if the live-in 1563 // is not used after all. 1564 bool IsLiveIn = MF.getRegInfo().isLiveIn(Reg); 1565 return getKillRegState(!IsLiveIn); 1566 } 1567 1568 static bool produceCompactUnwindFrame(MachineFunction &MF) { 1569 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 1570 AttributeList Attrs = MF.getFunction().getAttributes(); 1571 return Subtarget.isTargetMachO() && 1572 !(Subtarget.getTargetLowering()->supportSwiftError() && 1573 Attrs.hasAttrSomewhere(Attribute::SwiftError)); 1574 } 1575 1576 static bool invalidateWindowsRegisterPairing(unsigned Reg1, unsigned Reg2, 1577 bool NeedsWinCFI) { 1578 // If we are generating register pairs for a Windows function that requires 1579 // EH support, then pair consecutive registers only. There are no unwind 1580 // opcodes for saves/restores of non-consectuve register pairs. 1581 // The unwind opcodes are save_regp, save_regp_x, save_fregp, save_frepg_x. 1582 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling 1583 1584 // TODO: LR can be paired with any register. We don't support this yet in 1585 // the MCLayer. We need to add support for the save_lrpair unwind code. 1586 if (!NeedsWinCFI) 1587 return false; 1588 if (Reg2 == Reg1 + 1) 1589 return false; 1590 return true; 1591 } 1592 1593 namespace { 1594 1595 struct RegPairInfo { 1596 unsigned Reg1 = AArch64::NoRegister; 1597 unsigned Reg2 = AArch64::NoRegister; 1598 int FrameIdx; 1599 int Offset; 1600 enum RegType { GPR, FPR64, FPR128 } Type; 1601 1602 RegPairInfo() = default; 1603 1604 bool isPaired() const { return Reg2 != AArch64::NoRegister; } 1605 }; 1606 1607 } // end anonymous namespace 1608 1609 static void computeCalleeSaveRegisterPairs( 1610 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI, 1611 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs, 1612 bool &NeedShadowCallStackProlog) { 1613 1614 if (CSI.empty()) 1615 return; 1616 1617 bool NeedsWinCFI = needsWinCFI(MF); 1618 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1619 MachineFrameInfo &MFI = MF.getFrameInfo(); 1620 CallingConv::ID CC = MF.getFunction().getCallingConv(); 1621 unsigned Count = CSI.size(); 1622 (void)CC; 1623 // MachO's compact unwind format relies on all registers being stored in 1624 // pairs. 1625 assert((!produceCompactUnwindFrame(MF) || 1626 CC == CallingConv::PreserveMost || 1627 (Count & 1) == 0) && 1628 "Odd number of callee-saved regs to spill!"); 1629 int Offset = AFI->getCalleeSavedStackSize(); 1630 // On Linux, we will have either one or zero non-paired register. On Windows 1631 // with CFI, we can have multiple unpaired registers in order to utilize the 1632 // available unwind codes. This flag assures that the alignment fixup is done 1633 // only once, as intened. 1634 bool FixupDone = false; 1635 for (unsigned i = 0; i < Count; ++i) { 1636 RegPairInfo RPI; 1637 RPI.Reg1 = CSI[i].getReg(); 1638 1639 if (AArch64::GPR64RegClass.contains(RPI.Reg1)) 1640 RPI.Type = RegPairInfo::GPR; 1641 else if (AArch64::FPR64RegClass.contains(RPI.Reg1)) 1642 RPI.Type = RegPairInfo::FPR64; 1643 else if (AArch64::FPR128RegClass.contains(RPI.Reg1)) 1644 RPI.Type = RegPairInfo::FPR128; 1645 else 1646 llvm_unreachable("Unsupported register class."); 1647 1648 // Add the next reg to the pair if it is in the same register class. 1649 if (i + 1 < Count) { 1650 unsigned NextReg = CSI[i + 1].getReg(); 1651 switch (RPI.Type) { 1652 case RegPairInfo::GPR: 1653 if (AArch64::GPR64RegClass.contains(NextReg) && 1654 !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI)) 1655 RPI.Reg2 = NextReg; 1656 break; 1657 case RegPairInfo::FPR64: 1658 if (AArch64::FPR64RegClass.contains(NextReg) && 1659 !invalidateWindowsRegisterPairing(RPI.Reg1, NextReg, NeedsWinCFI)) 1660 RPI.Reg2 = NextReg; 1661 break; 1662 case RegPairInfo::FPR128: 1663 if (AArch64::FPR128RegClass.contains(NextReg)) 1664 RPI.Reg2 = NextReg; 1665 break; 1666 } 1667 } 1668 1669 // If either of the registers to be saved is the lr register, it means that 1670 // we also need to save lr in the shadow call stack. 1671 if ((RPI.Reg1 == AArch64::LR || RPI.Reg2 == AArch64::LR) && 1672 MF.getFunction().hasFnAttribute(Attribute::ShadowCallStack)) { 1673 if (!MF.getSubtarget<AArch64Subtarget>().isXRegisterReserved(18)) 1674 report_fatal_error("Must reserve x18 to use shadow call stack"); 1675 NeedShadowCallStackProlog = true; 1676 } 1677 1678 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI 1679 // list to come in sorted by frame index so that we can issue the store 1680 // pair instructions directly. Assert if we see anything otherwise. 1681 // 1682 // The order of the registers in the list is controlled by 1683 // getCalleeSavedRegs(), so they will always be in-order, as well. 1684 assert((!RPI.isPaired() || 1685 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) && 1686 "Out of order callee saved regs!"); 1687 1688 // MachO's compact unwind format relies on all registers being stored in 1689 // adjacent register pairs. 1690 assert((!produceCompactUnwindFrame(MF) || 1691 CC == CallingConv::PreserveMost || 1692 (RPI.isPaired() && 1693 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) || 1694 RPI.Reg1 + 1 == RPI.Reg2))) && 1695 "Callee-save registers not saved as adjacent register pair!"); 1696 1697 RPI.FrameIdx = CSI[i].getFrameIdx(); 1698 1699 int Scale = RPI.Type == RegPairInfo::FPR128 ? 16 : 8; 1700 Offset -= RPI.isPaired() ? 2 * Scale : Scale; 1701 1702 // Round up size of non-pair to pair size if we need to pad the 1703 // callee-save area to ensure 16-byte alignment. 1704 if (AFI->hasCalleeSaveStackFreeSpace() && !FixupDone && 1705 RPI.Type != RegPairInfo::FPR128 && !RPI.isPaired()) { 1706 FixupDone = true; 1707 Offset -= 8; 1708 assert(Offset % 16 == 0); 1709 assert(MFI.getObjectAlignment(RPI.FrameIdx) <= 16); 1710 MFI.setObjectAlignment(RPI.FrameIdx, 16); 1711 } 1712 1713 assert(Offset % Scale == 0); 1714 RPI.Offset = Offset / Scale; 1715 assert((RPI.Offset >= -64 && RPI.Offset <= 63) && 1716 "Offset out of bounds for LDP/STP immediate"); 1717 1718 RegPairs.push_back(RPI); 1719 if (RPI.isPaired()) 1720 ++i; 1721 } 1722 } 1723 1724 bool AArch64FrameLowering::spillCalleeSavedRegisters( 1725 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 1726 const std::vector<CalleeSavedInfo> &CSI, 1727 const TargetRegisterInfo *TRI) const { 1728 MachineFunction &MF = *MBB.getParent(); 1729 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1730 bool NeedsWinCFI = needsWinCFI(MF); 1731 DebugLoc DL; 1732 SmallVector<RegPairInfo, 8> RegPairs; 1733 1734 bool NeedShadowCallStackProlog = false; 1735 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, 1736 NeedShadowCallStackProlog); 1737 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1738 1739 if (NeedShadowCallStackProlog) { 1740 // Shadow call stack prolog: str x30, [x18], #8 1741 BuildMI(MBB, MI, DL, TII.get(AArch64::STRXpost)) 1742 .addReg(AArch64::X18, RegState::Define) 1743 .addReg(AArch64::LR) 1744 .addReg(AArch64::X18) 1745 .addImm(8) 1746 .setMIFlag(MachineInstr::FrameSetup); 1747 1748 if (NeedsWinCFI) 1749 BuildMI(MBB, MI, DL, TII.get(AArch64::SEH_Nop)) 1750 .setMIFlag(MachineInstr::FrameSetup); 1751 1752 if (!MF.getFunction().hasFnAttribute(Attribute::NoUnwind)) { 1753 // Emit a CFI instruction that causes 8 to be subtracted from the value of 1754 // x18 when unwinding past this frame. 1755 static const char CFIInst[] = { 1756 dwarf::DW_CFA_val_expression, 1757 18, // register 1758 2, // length 1759 static_cast<char>(unsigned(dwarf::DW_OP_breg18)), 1760 static_cast<char>(-8) & 0x7f, // addend (sleb128) 1761 }; 1762 unsigned CFIIndex = 1763 MF.addFrameInst(MCCFIInstruction::createEscape(nullptr, CFIInst)); 1764 BuildMI(MBB, MI, DL, TII.get(AArch64::CFI_INSTRUCTION)) 1765 .addCFIIndex(CFIIndex) 1766 .setMIFlag(MachineInstr::FrameSetup); 1767 } 1768 1769 // This instruction also makes x18 live-in to the entry block. 1770 MBB.addLiveIn(AArch64::X18); 1771 } 1772 1773 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE; 1774 ++RPII) { 1775 RegPairInfo RPI = *RPII; 1776 unsigned Reg1 = RPI.Reg1; 1777 unsigned Reg2 = RPI.Reg2; 1778 unsigned StrOpc; 1779 1780 // Issue sequence of spills for cs regs. The first spill may be converted 1781 // to a pre-decrement store later by emitPrologue if the callee-save stack 1782 // area allocation can't be combined with the local stack area allocation. 1783 // For example: 1784 // stp x22, x21, [sp, #0] // addImm(+0) 1785 // stp x20, x19, [sp, #16] // addImm(+2) 1786 // stp fp, lr, [sp, #32] // addImm(+4) 1787 // Rationale: This sequence saves uop updates compared to a sequence of 1788 // pre-increment spills like stp xi,xj,[sp,#-16]! 1789 // Note: Similar rationale and sequence for restores in epilog. 1790 unsigned Size, Align; 1791 switch (RPI.Type) { 1792 case RegPairInfo::GPR: 1793 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui; 1794 Size = 8; 1795 Align = 8; 1796 break; 1797 case RegPairInfo::FPR64: 1798 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui; 1799 Size = 8; 1800 Align = 8; 1801 break; 1802 case RegPairInfo::FPR128: 1803 StrOpc = RPI.isPaired() ? AArch64::STPQi : AArch64::STRQui; 1804 Size = 16; 1805 Align = 16; 1806 break; 1807 } 1808 LLVM_DEBUG(dbgs() << "CSR spill: (" << printReg(Reg1, TRI); 1809 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI); 1810 dbgs() << ") -> fi#(" << RPI.FrameIdx; 1811 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1; 1812 dbgs() << ")\n"); 1813 1814 assert((!NeedsWinCFI || !(Reg1 == AArch64::LR && Reg2 == AArch64::FP)) && 1815 "Windows unwdinding requires a consecutive (FP,LR) pair"); 1816 // Windows unwind codes require consecutive registers if registers are 1817 // paired. Make the switch here, so that the code below will save (x,x+1) 1818 // and not (x+1,x). 1819 unsigned FrameIdxReg1 = RPI.FrameIdx; 1820 unsigned FrameIdxReg2 = RPI.FrameIdx + 1; 1821 if (NeedsWinCFI && RPI.isPaired()) { 1822 std::swap(Reg1, Reg2); 1823 std::swap(FrameIdxReg1, FrameIdxReg2); 1824 } 1825 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc)); 1826 if (!MRI.isReserved(Reg1)) 1827 MBB.addLiveIn(Reg1); 1828 if (RPI.isPaired()) { 1829 if (!MRI.isReserved(Reg2)) 1830 MBB.addLiveIn(Reg2); 1831 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2)); 1832 MIB.addMemOperand(MF.getMachineMemOperand( 1833 MachinePointerInfo::getFixedStack(MF, FrameIdxReg2), 1834 MachineMemOperand::MOStore, Size, Align)); 1835 } 1836 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1)) 1837 .addReg(AArch64::SP) 1838 .addImm(RPI.Offset) // [sp, #offset*scale], 1839 // where factor*scale is implicit 1840 .setMIFlag(MachineInstr::FrameSetup); 1841 MIB.addMemOperand(MF.getMachineMemOperand( 1842 MachinePointerInfo::getFixedStack(MF,FrameIdxReg1), 1843 MachineMemOperand::MOStore, Size, Align)); 1844 if (NeedsWinCFI) 1845 InsertSEH(MIB, TII, MachineInstr::FrameSetup); 1846 1847 } 1848 return true; 1849 } 1850 1851 bool AArch64FrameLowering::restoreCalleeSavedRegisters( 1852 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 1853 std::vector<CalleeSavedInfo> &CSI, 1854 const TargetRegisterInfo *TRI) const { 1855 MachineFunction &MF = *MBB.getParent(); 1856 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1857 DebugLoc DL; 1858 SmallVector<RegPairInfo, 8> RegPairs; 1859 bool NeedsWinCFI = needsWinCFI(MF); 1860 1861 if (MI != MBB.end()) 1862 DL = MI->getDebugLoc(); 1863 1864 bool NeedShadowCallStackProlog = false; 1865 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs, 1866 NeedShadowCallStackProlog); 1867 1868 auto EmitMI = [&](const RegPairInfo &RPI) { 1869 unsigned Reg1 = RPI.Reg1; 1870 unsigned Reg2 = RPI.Reg2; 1871 1872 // Issue sequence of restores for cs regs. The last restore may be converted 1873 // to a post-increment load later by emitEpilogue if the callee-save stack 1874 // area allocation can't be combined with the local stack area allocation. 1875 // For example: 1876 // ldp fp, lr, [sp, #32] // addImm(+4) 1877 // ldp x20, x19, [sp, #16] // addImm(+2) 1878 // ldp x22, x21, [sp, #0] // addImm(+0) 1879 // Note: see comment in spillCalleeSavedRegisters() 1880 unsigned LdrOpc; 1881 unsigned Size, Align; 1882 switch (RPI.Type) { 1883 case RegPairInfo::GPR: 1884 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui; 1885 Size = 8; 1886 Align = 8; 1887 break; 1888 case RegPairInfo::FPR64: 1889 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui; 1890 Size = 8; 1891 Align = 8; 1892 break; 1893 case RegPairInfo::FPR128: 1894 LdrOpc = RPI.isPaired() ? AArch64::LDPQi : AArch64::LDRQui; 1895 Size = 16; 1896 Align = 16; 1897 break; 1898 } 1899 LLVM_DEBUG(dbgs() << "CSR restore: (" << printReg(Reg1, TRI); 1900 if (RPI.isPaired()) dbgs() << ", " << printReg(Reg2, TRI); 1901 dbgs() << ") -> fi#(" << RPI.FrameIdx; 1902 if (RPI.isPaired()) dbgs() << ", " << RPI.FrameIdx + 1; 1903 dbgs() << ")\n"); 1904 1905 // Windows unwind codes require consecutive registers if registers are 1906 // paired. Make the switch here, so that the code below will save (x,x+1) 1907 // and not (x+1,x). 1908 unsigned FrameIdxReg1 = RPI.FrameIdx; 1909 unsigned FrameIdxReg2 = RPI.FrameIdx + 1; 1910 if (NeedsWinCFI && RPI.isPaired()) { 1911 std::swap(Reg1, Reg2); 1912 std::swap(FrameIdxReg1, FrameIdxReg2); 1913 } 1914 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc)); 1915 if (RPI.isPaired()) { 1916 MIB.addReg(Reg2, getDefRegState(true)); 1917 MIB.addMemOperand(MF.getMachineMemOperand( 1918 MachinePointerInfo::getFixedStack(MF, FrameIdxReg2), 1919 MachineMemOperand::MOLoad, Size, Align)); 1920 } 1921 MIB.addReg(Reg1, getDefRegState(true)) 1922 .addReg(AArch64::SP) 1923 .addImm(RPI.Offset) // [sp, #offset*scale] 1924 // where factor*scale is implicit 1925 .setMIFlag(MachineInstr::FrameDestroy); 1926 MIB.addMemOperand(MF.getMachineMemOperand( 1927 MachinePointerInfo::getFixedStack(MF, FrameIdxReg1), 1928 MachineMemOperand::MOLoad, Size, Align)); 1929 if (NeedsWinCFI) 1930 InsertSEH(MIB, TII, MachineInstr::FrameDestroy); 1931 }; 1932 if (ReverseCSRRestoreSeq) 1933 for (const RegPairInfo &RPI : reverse(RegPairs)) 1934 EmitMI(RPI); 1935 else 1936 for (const RegPairInfo &RPI : RegPairs) 1937 EmitMI(RPI); 1938 1939 if (NeedShadowCallStackProlog) { 1940 // Shadow call stack epilog: ldr x30, [x18, #-8]! 1941 BuildMI(MBB, MI, DL, TII.get(AArch64::LDRXpre)) 1942 .addReg(AArch64::X18, RegState::Define) 1943 .addReg(AArch64::LR, RegState::Define) 1944 .addReg(AArch64::X18) 1945 .addImm(-8) 1946 .setMIFlag(MachineInstr::FrameDestroy); 1947 } 1948 1949 return true; 1950 } 1951 1952 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF, 1953 BitVector &SavedRegs, 1954 RegScavenger *RS) const { 1955 // All calls are tail calls in GHC calling conv, and functions have no 1956 // prologue/epilogue. 1957 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 1958 return; 1959 1960 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 1961 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>( 1962 MF.getSubtarget().getRegisterInfo()); 1963 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 1964 unsigned UnspilledCSGPR = AArch64::NoRegister; 1965 unsigned UnspilledCSGPRPaired = AArch64::NoRegister; 1966 1967 MachineFrameInfo &MFI = MF.getFrameInfo(); 1968 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs(); 1969 1970 unsigned BasePointerReg = RegInfo->hasBasePointer(MF) 1971 ? RegInfo->getBaseRegister() 1972 : (unsigned)AArch64::NoRegister; 1973 1974 unsigned ExtraCSSpill = 0; 1975 // Figure out which callee-saved registers to save/restore. 1976 for (unsigned i = 0; CSRegs[i]; ++i) { 1977 const unsigned Reg = CSRegs[i]; 1978 1979 // Add the base pointer register to SavedRegs if it is callee-save. 1980 if (Reg == BasePointerReg) 1981 SavedRegs.set(Reg); 1982 1983 bool RegUsed = SavedRegs.test(Reg); 1984 unsigned PairedReg = CSRegs[i ^ 1]; 1985 if (!RegUsed) { 1986 if (AArch64::GPR64RegClass.contains(Reg) && 1987 !RegInfo->isReservedReg(MF, Reg)) { 1988 UnspilledCSGPR = Reg; 1989 UnspilledCSGPRPaired = PairedReg; 1990 } 1991 continue; 1992 } 1993 1994 // MachO's compact unwind format relies on all registers being stored in 1995 // pairs. 1996 // FIXME: the usual format is actually better if unwinding isn't needed. 1997 if (produceCompactUnwindFrame(MF) && PairedReg != AArch64::NoRegister && 1998 !SavedRegs.test(PairedReg)) { 1999 SavedRegs.set(PairedReg); 2000 if (AArch64::GPR64RegClass.contains(PairedReg) && 2001 !RegInfo->isReservedReg(MF, PairedReg)) 2002 ExtraCSSpill = PairedReg; 2003 } 2004 } 2005 2006 // Calculates the callee saved stack size. 2007 unsigned CSStackSize = 0; 2008 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 2009 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2010 for (unsigned Reg : SavedRegs.set_bits()) 2011 CSStackSize += TRI->getRegSizeInBits(Reg, MRI) / 8; 2012 2013 // Save number of saved regs, so we can easily update CSStackSize later. 2014 unsigned NumSavedRegs = SavedRegs.count(); 2015 2016 // The frame record needs to be created by saving the appropriate registers 2017 unsigned EstimatedStackSize = MFI.estimateStackSize(MF); 2018 if (hasFP(MF) || 2019 windowsRequiresStackProbe(MF, EstimatedStackSize + CSStackSize + 16)) { 2020 SavedRegs.set(AArch64::FP); 2021 SavedRegs.set(AArch64::LR); 2022 } 2023 2024 LLVM_DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:"; 2025 for (unsigned Reg 2026 : SavedRegs.set_bits()) dbgs() 2027 << ' ' << printReg(Reg, RegInfo); 2028 dbgs() << "\n";); 2029 2030 // If any callee-saved registers are used, the frame cannot be eliminated. 2031 bool CanEliminateFrame = SavedRegs.count() == 0; 2032 2033 // The CSR spill slots have not been allocated yet, so estimateStackSize 2034 // won't include them. 2035 unsigned EstimatedStackSizeLimit = estimateRSStackSizeLimit(MF); 2036 bool BigStack = (EstimatedStackSize + CSStackSize) > EstimatedStackSizeLimit; 2037 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) 2038 AFI->setHasStackFrame(true); 2039 2040 // Estimate if we might need to scavenge a register at some point in order 2041 // to materialize a stack offset. If so, either spill one additional 2042 // callee-saved register or reserve a special spill slot to facilitate 2043 // register scavenging. If we already spilled an extra callee-saved register 2044 // above to keep the number of spills even, we don't need to do anything else 2045 // here. 2046 if (BigStack) { 2047 if (!ExtraCSSpill && UnspilledCSGPR != AArch64::NoRegister) { 2048 LLVM_DEBUG(dbgs() << "Spilling " << printReg(UnspilledCSGPR, RegInfo) 2049 << " to get a scratch register.\n"); 2050 SavedRegs.set(UnspilledCSGPR); 2051 // MachO's compact unwind format relies on all registers being stored in 2052 // pairs, so if we need to spill one extra for BigStack, then we need to 2053 // store the pair. 2054 if (produceCompactUnwindFrame(MF)) 2055 SavedRegs.set(UnspilledCSGPRPaired); 2056 ExtraCSSpill = UnspilledCSGPRPaired; 2057 } 2058 2059 // If we didn't find an extra callee-saved register to spill, create 2060 // an emergency spill slot. 2061 if (!ExtraCSSpill || MF.getRegInfo().isPhysRegUsed(ExtraCSSpill)) { 2062 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 2063 const TargetRegisterClass &RC = AArch64::GPR64RegClass; 2064 unsigned Size = TRI->getSpillSize(RC); 2065 unsigned Align = TRI->getSpillAlignment(RC); 2066 int FI = MFI.CreateStackObject(Size, Align, false); 2067 RS->addScavengingFrameIndex(FI); 2068 LLVM_DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI 2069 << " as the emergency spill slot.\n"); 2070 } 2071 } 2072 2073 // Adding the size of additional 64bit GPR saves. 2074 CSStackSize += 8 * (SavedRegs.count() - NumSavedRegs); 2075 unsigned AlignedCSStackSize = alignTo(CSStackSize, 16); 2076 LLVM_DEBUG(dbgs() << "Estimated stack frame size: " 2077 << EstimatedStackSize + AlignedCSStackSize 2078 << " bytes.\n"); 2079 2080 // Round up to register pair alignment to avoid additional SP adjustment 2081 // instructions. 2082 AFI->setCalleeSavedStackSize(AlignedCSStackSize); 2083 AFI->setCalleeSaveStackHasFreeSpace(AlignedCSStackSize != CSStackSize); 2084 } 2085 2086 bool AArch64FrameLowering::enableStackSlotScavenging( 2087 const MachineFunction &MF) const { 2088 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 2089 return AFI->hasCalleeSaveStackFreeSpace(); 2090 } 2091 2092 void AArch64FrameLowering::processFunctionBeforeFrameFinalized( 2093 MachineFunction &MF, RegScavenger *RS) const { 2094 // If this function isn't doing Win64-style C++ EH, we don't need to do 2095 // anything. 2096 if (!MF.hasEHFunclets()) 2097 return; 2098 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 2099 MachineFrameInfo &MFI = MF.getFrameInfo(); 2100 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo(); 2101 2102 MachineBasicBlock &MBB = MF.front(); 2103 auto MBBI = MBB.begin(); 2104 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) 2105 ++MBBI; 2106 2107 if (MBBI->isTerminator()) 2108 return; 2109 2110 // Create an UnwindHelp object. 2111 int UnwindHelpFI = 2112 MFI.CreateStackObject(/*size*/8, /*alignment*/16, false); 2113 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI; 2114 // We need to store -2 into the UnwindHelp object at the start of the 2115 // function. 2116 DebugLoc DL; 2117 RS->enterBasicBlock(MBB); 2118 unsigned DstReg = RS->scavengeRegister(&AArch64::GPR64RegClass, MBBI, 0); 2119 BuildMI(MBB, MBBI, DL, TII.get(AArch64::MOVi64imm), DstReg).addImm(-2); 2120 BuildMI(MBB, MBBI, DL, TII.get(AArch64::STURXi)) 2121 .addReg(DstReg, getKillRegState(true)) 2122 .addFrameIndex(UnwindHelpFI) 2123 .addImm(0); 2124 } 2125 2126 /// For Win64 AArch64 EH, the offset to the Unwind object is from the SP before 2127 /// the update. This is easily retrieved as it is exactly the offset that is set 2128 /// in processFunctionBeforeFrameFinalized. 2129 int AArch64FrameLowering::getFrameIndexReferencePreferSP( 2130 const MachineFunction &MF, int FI, unsigned &FrameReg, 2131 bool IgnoreSPUpdates) const { 2132 const MachineFrameInfo &MFI = MF.getFrameInfo(); 2133 LLVM_DEBUG(dbgs() << "Offset from the SP for " << FI << " is " 2134 << MFI.getObjectOffset(FI) << "\n"); 2135 FrameReg = AArch64::SP; 2136 return MFI.getObjectOffset(FI); 2137 } 2138 2139 /// The parent frame offset (aka dispFrame) is only used on X86_64 to retrieve 2140 /// the parent's frame pointer 2141 unsigned AArch64FrameLowering::getWinEHParentFrameOffset( 2142 const MachineFunction &MF) const { 2143 return 0; 2144 } 2145 2146 /// Funclets only need to account for space for the callee saved registers, 2147 /// as the locals are accounted for in the parent's stack frame. 2148 unsigned AArch64FrameLowering::getWinEHFuncletFrameSize( 2149 const MachineFunction &MF) const { 2150 // This is the size of the pushed CSRs. 2151 unsigned CSSize = 2152 MF.getInfo<AArch64FunctionInfo>()->getCalleeSavedStackSize(); 2153 // This is the amount of stack a funclet needs to allocate. 2154 return alignTo(CSSize + MF.getFrameInfo().getMaxCallFrameSize(), 2155 getStackAlignment()); 2156 } 2157