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 // | prev_fp, prev_lr | 45 // | (a.k.a. "frame record") | 46 // |-----------------------------------| <- fp(=x29) 47 // | | 48 // | other callee-saved registers | 49 // | | 50 // |-----------------------------------| 51 // |.empty.space.to.make.part.below....| 52 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at 53 // |.the.standard.16-byte.alignment....| compile time; if present) 54 // |-----------------------------------| 55 // | | 56 // | local variables of fixed size | 57 // | including spill slots | 58 // |-----------------------------------| <- bp(not defined by ABI, 59 // |.variable-sized.local.variables....| LLVM chooses X19) 60 // |.(VLAs)............................| (size of this area is unknown at 61 // |...................................| compile time) 62 // |-----------------------------------| <- sp 63 // | | Lower address 64 // 65 // 66 // To access the data in a frame, at-compile time, a constant offset must be 67 // computable from one of the pointers (fp, bp, sp) to access it. The size 68 // of the areas with a dotted background cannot be computed at compile-time 69 // if they are present, making it required to have all three of fp, bp and 70 // sp to be set up to be able to access all contents in the frame areas, 71 // assuming all of the frame areas are non-empty. 72 // 73 // For most functions, some of the frame areas are empty. For those functions, 74 // it may not be necessary to set up fp or bp: 75 // * A base pointer is definitely needed when there are both VLAs and local 76 // variables with more-than-default alignment requirements. 77 // * A frame pointer is definitely needed when there are local variables with 78 // more-than-default alignment requirements. 79 // 80 // In some cases when a base pointer is not strictly needed, it is generated 81 // anyway when offsets from the frame pointer to access local variables become 82 // so large that the offset can't be encoded in the immediate fields of loads 83 // or stores. 84 // 85 // FIXME: also explain the redzone concept. 86 // FIXME: also explain the concept of reserved call frames. 87 // 88 //===----------------------------------------------------------------------===// 89 90 #include "AArch64FrameLowering.h" 91 #include "AArch64InstrInfo.h" 92 #include "AArch64MachineFunctionInfo.h" 93 #include "AArch64Subtarget.h" 94 #include "AArch64TargetMachine.h" 95 #include "llvm/ADT/Statistic.h" 96 #include "llvm/CodeGen/MachineFrameInfo.h" 97 #include "llvm/CodeGen/MachineFunction.h" 98 #include "llvm/CodeGen/MachineInstrBuilder.h" 99 #include "llvm/CodeGen/MachineModuleInfo.h" 100 #include "llvm/CodeGen/MachineRegisterInfo.h" 101 #include "llvm/CodeGen/RegisterScavenging.h" 102 #include "llvm/IR/DataLayout.h" 103 #include "llvm/IR/Function.h" 104 #include "llvm/Support/CommandLine.h" 105 #include "llvm/Support/Debug.h" 106 #include "llvm/Support/raw_ostream.h" 107 108 using namespace llvm; 109 110 #define DEBUG_TYPE "frame-info" 111 112 static cl::opt<bool> EnableRedZone("aarch64-redzone", 113 cl::desc("enable use of redzone on AArch64"), 114 cl::init(false), cl::Hidden); 115 116 STATISTIC(NumRedZoneFunctions, "Number of functions using red zone"); 117 118 bool AArch64FrameLowering::canUseRedZone(const MachineFunction &MF) const { 119 if (!EnableRedZone) 120 return false; 121 // Don't use the red zone if the function explicitly asks us not to. 122 // This is typically used for kernel code. 123 if (MF.getFunction()->hasFnAttribute(Attribute::NoRedZone)) 124 return false; 125 126 const MachineFrameInfo *MFI = MF.getFrameInfo(); 127 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 128 unsigned NumBytes = AFI->getLocalStackSize(); 129 130 return !(MFI->hasCalls() || hasFP(MF) || NumBytes > 128); 131 } 132 133 /// hasFP - Return true if the specified function should have a dedicated frame 134 /// pointer register. 135 bool AArch64FrameLowering::hasFP(const MachineFunction &MF) const { 136 const MachineFrameInfo *MFI = MF.getFrameInfo(); 137 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 138 // Retain behavior of always omitting the FP for leaf functions when possible. 139 return (MFI->hasCalls() && 140 MF.getTarget().Options.DisableFramePointerElim(MF)) || 141 MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken() || 142 MFI->hasStackMap() || MFI->hasPatchPoint() || 143 RegInfo->needsStackRealignment(MF); 144 } 145 146 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 147 /// not required, we reserve argument space for call sites in the function 148 /// immediately on entry to the current function. This eliminates the need for 149 /// add/sub sp brackets around call sites. Returns true if the call frame is 150 /// included as part of the stack frame. 151 bool 152 AArch64FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 153 return !MF.getFrameInfo()->hasVarSizedObjects(); 154 } 155 156 void AArch64FrameLowering::eliminateCallFramePseudoInstr( 157 MachineFunction &MF, MachineBasicBlock &MBB, 158 MachineBasicBlock::iterator I) const { 159 const AArch64InstrInfo *TII = 160 static_cast<const AArch64InstrInfo *>(MF.getSubtarget().getInstrInfo()); 161 DebugLoc DL = I->getDebugLoc(); 162 unsigned Opc = I->getOpcode(); 163 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode(); 164 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0; 165 166 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 167 if (!TFI->hasReservedCallFrame(MF)) { 168 unsigned Align = getStackAlignment(); 169 170 int64_t Amount = I->getOperand(0).getImm(); 171 Amount = alignTo(Amount, Align); 172 if (!IsDestroy) 173 Amount = -Amount; 174 175 // N.b. if CalleePopAmount is valid but zero (i.e. callee would pop, but it 176 // doesn't have to pop anything), then the first operand will be zero too so 177 // this adjustment is a no-op. 178 if (CalleePopAmount == 0) { 179 // FIXME: in-function stack adjustment for calls is limited to 24-bits 180 // because there's no guaranteed temporary register available. 181 // 182 // ADD/SUB (immediate) has only LSL #0 and LSL #12 available. 183 // 1) For offset <= 12-bit, we use LSL #0 184 // 2) For 12-bit <= offset <= 24-bit, we use two instructions. One uses 185 // LSL #0, and the other uses LSL #12. 186 // 187 // Most call frames will be allocated at the start of a function so 188 // this is OK, but it is a limitation that needs dealing with. 189 assert(Amount > -0xffffff && Amount < 0xffffff && "call frame too large"); 190 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, Amount, TII); 191 } 192 } else if (CalleePopAmount != 0) { 193 // If the calling convention demands that the callee pops arguments from the 194 // stack, we want to add it back if we have a reserved call frame. 195 assert(CalleePopAmount < 0xffffff && "call frame too large"); 196 emitFrameOffset(MBB, I, DL, AArch64::SP, AArch64::SP, -CalleePopAmount, 197 TII); 198 } 199 MBB.erase(I); 200 } 201 202 void AArch64FrameLowering::emitCalleeSavedFrameMoves( 203 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const { 204 MachineFunction &MF = *MBB.getParent(); 205 MachineFrameInfo *MFI = MF.getFrameInfo(); 206 MachineModuleInfo &MMI = MF.getMMI(); 207 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo(); 208 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 209 DebugLoc DL = MBB.findDebugLoc(MBBI); 210 211 // Add callee saved registers to move list. 212 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 213 if (CSI.empty()) 214 return; 215 216 for (const auto &Info : CSI) { 217 unsigned Reg = Info.getReg(); 218 int64_t Offset = 219 MFI->getObjectOffset(Info.getFrameIdx()) - getOffsetOfLocalArea(); 220 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true); 221 unsigned CFIIndex = MMI.addFrameInst( 222 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset)); 223 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 224 .addCFIIndex(CFIIndex) 225 .setMIFlags(MachineInstr::FrameSetup); 226 } 227 } 228 229 // Find a scratch register that we can use at the start of the prologue to 230 // re-align the stack pointer. We avoid using callee-save registers since they 231 // may appear to be free when this is called from canUseAsPrologue (during 232 // shrink wrapping), but then no longer be free when this is called from 233 // emitPrologue. 234 // 235 // FIXME: This is a bit conservative, since in the above case we could use one 236 // of the callee-save registers as a scratch temp to re-align the stack pointer, 237 // but we would then have to make sure that we were in fact saving at least one 238 // callee-save register in the prologue, which is additional complexity that 239 // doesn't seem worth the benefit. 240 static unsigned findScratchNonCalleeSaveRegister(MachineBasicBlock *MBB) { 241 MachineFunction *MF = MBB->getParent(); 242 243 // If MBB is an entry block, use X9 as the scratch register 244 if (&MF->front() == MBB) 245 return AArch64::X9; 246 247 RegScavenger RS; 248 RS.enterBasicBlock(MBB); 249 250 // Prefer X9 since it was historically used for the prologue scratch reg. 251 if (!RS.isRegUsed(AArch64::X9)) 252 return AArch64::X9; 253 254 // Find a free non callee-save reg. 255 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>(); 256 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 257 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(MF); 258 BitVector CalleeSaveRegs(RegInfo->getNumRegs()); 259 for (unsigned i = 0; CSRegs[i]; ++i) 260 CalleeSaveRegs.set(CSRegs[i]); 261 262 BitVector Available = RS.getRegsAvailable(&AArch64::GPR64RegClass); 263 for (int AvailReg = Available.find_first(); AvailReg != -1; 264 AvailReg = Available.find_next(AvailReg)) 265 if (!CalleeSaveRegs.test(AvailReg)) 266 return AvailReg; 267 268 return AArch64::NoRegister; 269 } 270 271 bool AArch64FrameLowering::canUseAsPrologue( 272 const MachineBasicBlock &MBB) const { 273 const MachineFunction *MF = MBB.getParent(); 274 MachineBasicBlock *TmpMBB = const_cast<MachineBasicBlock *>(&MBB); 275 const AArch64Subtarget &Subtarget = MF->getSubtarget<AArch64Subtarget>(); 276 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 277 278 // Don't need a scratch register if we're not going to re-align the stack. 279 if (!RegInfo->needsStackRealignment(*MF)) 280 return true; 281 // Otherwise, we can use any block as long as it has a scratch register 282 // available. 283 return findScratchNonCalleeSaveRegister(TmpMBB) != AArch64::NoRegister; 284 } 285 286 void AArch64FrameLowering::emitPrologue(MachineFunction &MF, 287 MachineBasicBlock &MBB) const { 288 MachineBasicBlock::iterator MBBI = MBB.begin(); 289 const MachineFrameInfo *MFI = MF.getFrameInfo(); 290 const Function *Fn = MF.getFunction(); 291 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 292 const AArch64RegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 293 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 294 MachineModuleInfo &MMI = MF.getMMI(); 295 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 296 bool needsFrameMoves = MMI.hasDebugInfo() || Fn->needsUnwindTableEntry(); 297 bool HasFP = hasFP(MF); 298 299 // Debug location must be unknown since the first debug location is used 300 // to determine the end of the prologue. 301 DebugLoc DL; 302 303 // All calls are tail calls in GHC calling conv, and functions have no 304 // prologue/epilogue. 305 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 306 return; 307 308 int NumBytes = (int)MFI->getStackSize(); 309 if (!AFI->hasStackFrame()) { 310 assert(!HasFP && "unexpected function without stack frame but with FP"); 311 312 // All of the stack allocation is for locals. 313 AFI->setLocalStackSize(NumBytes); 314 315 // Label used to tie together the PROLOG_LABEL and the MachineMoves. 316 MCSymbol *FrameLabel = MMI.getContext().createTempSymbol(); 317 318 // REDZONE: If the stack size is less than 128 bytes, we don't need 319 // to actually allocate. 320 if (NumBytes && !canUseRedZone(MF)) { 321 emitFrameOffset(MBB, MBBI, DL, AArch64::SP, AArch64::SP, -NumBytes, TII, 322 MachineInstr::FrameSetup); 323 324 // Encode the stack size of the leaf function. 325 unsigned CFIIndex = MMI.addFrameInst( 326 MCCFIInstruction::createDefCfaOffset(FrameLabel, -NumBytes)); 327 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 328 .addCFIIndex(CFIIndex) 329 .setMIFlags(MachineInstr::FrameSetup); 330 } else if (NumBytes) { 331 ++NumRedZoneFunctions; 332 } 333 334 return; 335 } 336 337 // Only set up FP if we actually need to. 338 int FPOffset = 0; 339 if (HasFP) 340 // Frame pointer is fp = sp - 16. 341 FPOffset = AFI->getCalleeSavedStackSize() - 16; 342 343 // Move past the saves of the callee-saved registers. 344 MachineBasicBlock::iterator End = MBB.end(); 345 while (MBBI != End && MBBI->getFlag(MachineInstr::FrameSetup)) 346 ++MBBI; 347 NumBytes -= AFI->getCalleeSavedStackSize(); 348 assert(NumBytes >= 0 && "Negative stack allocation size!?"); 349 if (HasFP) { 350 // Issue sub fp, sp, FPOffset or 351 // mov fp,sp when FPOffset is zero. 352 // Note: All stores of callee-saved registers are marked as "FrameSetup". 353 // This code marks the instruction(s) that set the FP also. 354 emitFrameOffset(MBB, MBBI, DL, AArch64::FP, AArch64::SP, FPOffset, TII, 355 MachineInstr::FrameSetup); 356 } 357 358 // All of the remaining stack allocations are for locals. 359 AFI->setLocalStackSize(NumBytes); 360 361 // Allocate space for the rest of the frame. 362 363 const unsigned Alignment = MFI->getMaxAlignment(); 364 const bool NeedsRealignment = RegInfo->needsStackRealignment(MF); 365 unsigned scratchSPReg = AArch64::SP; 366 if (NumBytes && NeedsRealignment) { 367 scratchSPReg = findScratchNonCalleeSaveRegister(&MBB); 368 assert(scratchSPReg != AArch64::NoRegister); 369 } 370 371 // If we're a leaf function, try using the red zone. 372 if (NumBytes && !canUseRedZone(MF)) 373 // FIXME: in the case of dynamic re-alignment, NumBytes doesn't have 374 // the correct value here, as NumBytes also includes padding bytes, 375 // which shouldn't be counted here. 376 emitFrameOffset(MBB, MBBI, DL, scratchSPReg, AArch64::SP, -NumBytes, TII, 377 MachineInstr::FrameSetup); 378 379 if (NumBytes && NeedsRealignment) { 380 const unsigned NrBitsToZero = countTrailingZeros(Alignment); 381 assert(NrBitsToZero > 1); 382 assert(scratchSPReg != AArch64::SP); 383 384 // SUB X9, SP, NumBytes 385 // -- X9 is temporary register, so shouldn't contain any live data here, 386 // -- free to use. This is already produced by emitFrameOffset above. 387 // AND SP, X9, 0b11111...0000 388 // The logical immediates have a non-trivial encoding. The following 389 // formula computes the encoded immediate with all ones but 390 // NrBitsToZero zero bits as least significant bits. 391 uint32_t andMaskEncoded = 392 (1 <<12) // = N 393 | ((64-NrBitsToZero) << 6) // immr 394 | ((64-NrBitsToZero-1) << 0) // imms 395 ; 396 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ANDXri), AArch64::SP) 397 .addReg(scratchSPReg, RegState::Kill) 398 .addImm(andMaskEncoded); 399 } 400 401 // If we need a base pointer, set it up here. It's whatever the value of the 402 // stack pointer is at this point. Any variable size objects will be allocated 403 // after this, so we can still use the base pointer to reference locals. 404 // 405 // FIXME: Clarify FrameSetup flags here. 406 // Note: Use emitFrameOffset() like above for FP if the FrameSetup flag is 407 // needed. 408 if (RegInfo->hasBasePointer(MF)) { 409 TII->copyPhysReg(MBB, MBBI, DL, RegInfo->getBaseRegister(), AArch64::SP, 410 false); 411 } 412 413 if (needsFrameMoves) { 414 const DataLayout &TD = MF.getDataLayout(); 415 const int StackGrowth = -TD.getPointerSize(0); 416 unsigned FramePtr = RegInfo->getFrameRegister(MF); 417 // An example of the prologue: 418 // 419 // .globl __foo 420 // .align 2 421 // __foo: 422 // Ltmp0: 423 // .cfi_startproc 424 // .cfi_personality 155, ___gxx_personality_v0 425 // Leh_func_begin: 426 // .cfi_lsda 16, Lexception33 427 // 428 // stp xa,bx, [sp, -#offset]! 429 // ... 430 // stp x28, x27, [sp, #offset-32] 431 // stp fp, lr, [sp, #offset-16] 432 // add fp, sp, #offset - 16 433 // sub sp, sp, #1360 434 // 435 // The Stack: 436 // +-------------------------------------------+ 437 // 10000 | ........ | ........ | ........ | ........ | 438 // 10004 | ........ | ........ | ........ | ........ | 439 // +-------------------------------------------+ 440 // 10008 | ........ | ........ | ........ | ........ | 441 // 1000c | ........ | ........ | ........ | ........ | 442 // +===========================================+ 443 // 10010 | X28 Register | 444 // 10014 | X28 Register | 445 // +-------------------------------------------+ 446 // 10018 | X27 Register | 447 // 1001c | X27 Register | 448 // +===========================================+ 449 // 10020 | Frame Pointer | 450 // 10024 | Frame Pointer | 451 // +-------------------------------------------+ 452 // 10028 | Link Register | 453 // 1002c | Link Register | 454 // +===========================================+ 455 // 10030 | ........ | ........ | ........ | ........ | 456 // 10034 | ........ | ........ | ........ | ........ | 457 // +-------------------------------------------+ 458 // 10038 | ........ | ........ | ........ | ........ | 459 // 1003c | ........ | ........ | ........ | ........ | 460 // +-------------------------------------------+ 461 // 462 // [sp] = 10030 :: >>initial value<< 463 // sp = 10020 :: stp fp, lr, [sp, #-16]! 464 // fp = sp == 10020 :: mov fp, sp 465 // [sp] == 10020 :: stp x28, x27, [sp, #-16]! 466 // sp == 10010 :: >>final value<< 467 // 468 // The frame pointer (w29) points to address 10020. If we use an offset of 469 // '16' from 'w29', we get the CFI offsets of -8 for w30, -16 for w29, -24 470 // for w27, and -32 for w28: 471 // 472 // Ltmp1: 473 // .cfi_def_cfa w29, 16 474 // Ltmp2: 475 // .cfi_offset w30, -8 476 // Ltmp3: 477 // .cfi_offset w29, -16 478 // Ltmp4: 479 // .cfi_offset w27, -24 480 // Ltmp5: 481 // .cfi_offset w28, -32 482 483 if (HasFP) { 484 // Define the current CFA rule to use the provided FP. 485 unsigned Reg = RegInfo->getDwarfRegNum(FramePtr, true); 486 unsigned CFIIndex = MMI.addFrameInst( 487 MCCFIInstruction::createDefCfa(nullptr, Reg, 2 * StackGrowth)); 488 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 489 .addCFIIndex(CFIIndex) 490 .setMIFlags(MachineInstr::FrameSetup); 491 } else { 492 // Encode the stack size of the leaf function. 493 unsigned CFIIndex = MMI.addFrameInst( 494 MCCFIInstruction::createDefCfaOffset(nullptr, -MFI->getStackSize())); 495 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION)) 496 .addCFIIndex(CFIIndex) 497 .setMIFlags(MachineInstr::FrameSetup); 498 } 499 500 // Now emit the moves for whatever callee saved regs we have (including FP, 501 // LR if those are saved). 502 emitCalleeSavedFrameMoves(MBB, MBBI); 503 } 504 } 505 506 void AArch64FrameLowering::emitEpilogue(MachineFunction &MF, 507 MachineBasicBlock &MBB) const { 508 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 509 MachineFrameInfo *MFI = MF.getFrameInfo(); 510 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 511 const TargetInstrInfo *TII = Subtarget.getInstrInfo(); 512 DebugLoc DL; 513 bool IsTailCallReturn = false; 514 if (MBB.end() != MBBI) { 515 DL = MBBI->getDebugLoc(); 516 unsigned RetOpcode = MBBI->getOpcode(); 517 IsTailCallReturn = RetOpcode == AArch64::TCRETURNdi || 518 RetOpcode == AArch64::TCRETURNri; 519 } 520 int NumBytes = MFI->getStackSize(); 521 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 522 523 // All calls are tail calls in GHC calling conv, and functions have no 524 // prologue/epilogue. 525 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 526 return; 527 528 // Initial and residual are named for consistency with the prologue. Note that 529 // in the epilogue, the residual adjustment is executed first. 530 uint64_t ArgumentPopSize = 0; 531 if (IsTailCallReturn) { 532 MachineOperand &StackAdjust = MBBI->getOperand(1); 533 534 // For a tail-call in a callee-pops-arguments environment, some or all of 535 // the stack may actually be in use for the call's arguments, this is 536 // calculated during LowerCall and consumed here... 537 ArgumentPopSize = StackAdjust.getImm(); 538 } else { 539 // ... otherwise the amount to pop is *all* of the argument space, 540 // conveniently stored in the MachineFunctionInfo by 541 // LowerFormalArguments. This will, of course, be zero for the C calling 542 // convention. 543 ArgumentPopSize = AFI->getArgumentStackToRestore(); 544 } 545 546 // The stack frame should be like below, 547 // 548 // ---------------------- --- 549 // | | | 550 // | BytesInStackArgArea| CalleeArgStackSize 551 // | (NumReusableBytes) | (of tail call) 552 // | | --- 553 // | | | 554 // ---------------------| --- | 555 // | | | | 556 // | CalleeSavedReg | | | 557 // | (CalleeSavedStackSize)| | | 558 // | | | | 559 // ---------------------| | NumBytes 560 // | | StackSize (StackAdjustUp) 561 // | LocalStackSize | | | 562 // | (covering callee | | | 563 // | args) | | | 564 // | | | | 565 // ---------------------- --- --- 566 // 567 // So NumBytes = StackSize + BytesInStackArgArea - CalleeArgStackSize 568 // = StackSize + ArgumentPopSize 569 // 570 // AArch64TargetLowering::LowerCall figures out ArgumentPopSize and keeps 571 // it as the 2nd argument of AArch64ISD::TC_RETURN. 572 573 // Move past the restores of the callee-saved registers. 574 MachineBasicBlock::iterator LastPopI = MBB.getFirstTerminator(); 575 MachineBasicBlock::iterator Begin = MBB.begin(); 576 while (LastPopI != Begin) { 577 --LastPopI; 578 if (!LastPopI->getFlag(MachineInstr::FrameDestroy)) { 579 ++LastPopI; 580 break; 581 } 582 } 583 NumBytes -= AFI->getCalleeSavedStackSize(); 584 assert(NumBytes >= 0 && "Negative stack allocation size!?"); 585 586 if (!hasFP(MF)) { 587 bool RedZone = canUseRedZone(MF); 588 // If this was a redzone leaf function, we don't need to restore the 589 // stack pointer (but we may need to pop stack args for fastcc). 590 if (RedZone && ArgumentPopSize == 0) 591 return; 592 593 bool NoCalleeSaveRestore = AFI->getCalleeSavedStackSize() == 0; 594 int StackRestoreBytes = RedZone ? 0 : NumBytes; 595 if (NoCalleeSaveRestore) 596 StackRestoreBytes += ArgumentPopSize; 597 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::SP, 598 StackRestoreBytes, TII, MachineInstr::FrameDestroy); 599 // If we were able to combine the local stack pop with the argument pop, 600 // then we're done. 601 if (NoCalleeSaveRestore || ArgumentPopSize == 0) 602 return; 603 NumBytes = 0; 604 } 605 606 // Restore the original stack pointer. 607 // FIXME: Rather than doing the math here, we should instead just use 608 // non-post-indexed loads for the restores if we aren't actually going to 609 // be able to save any instructions. 610 if (NumBytes || MFI->hasVarSizedObjects()) 611 emitFrameOffset(MBB, LastPopI, DL, AArch64::SP, AArch64::FP, 612 -AFI->getCalleeSavedStackSize() + 16, TII, 613 MachineInstr::FrameDestroy); 614 615 // This must be placed after the callee-save restore code because that code 616 // assumes the SP is at the same location as it was after the callee-save save 617 // code in the prologue. 618 if (ArgumentPopSize) 619 emitFrameOffset(MBB, MBB.getFirstTerminator(), DL, AArch64::SP, AArch64::SP, 620 ArgumentPopSize, TII, MachineInstr::FrameDestroy); 621 } 622 623 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 624 /// debug info. It's the same as what we use for resolving the code-gen 625 /// references for now. FIXME: This can go wrong when references are 626 /// SP-relative and simple call frames aren't used. 627 int AArch64FrameLowering::getFrameIndexReference(const MachineFunction &MF, 628 int FI, 629 unsigned &FrameReg) const { 630 return resolveFrameIndexReference(MF, FI, FrameReg); 631 } 632 633 int AArch64FrameLowering::resolveFrameIndexReference(const MachineFunction &MF, 634 int FI, unsigned &FrameReg, 635 bool PreferFP) const { 636 const MachineFrameInfo *MFI = MF.getFrameInfo(); 637 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>( 638 MF.getSubtarget().getRegisterInfo()); 639 const AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 640 int FPOffset = MFI->getObjectOffset(FI) + 16; 641 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize(); 642 bool isFixed = MFI->isFixedObjectIndex(FI); 643 644 // Use frame pointer to reference fixed objects. Use it for locals if 645 // there are VLAs or a dynamically realigned SP (and thus the SP isn't 646 // reliable as a base). Make sure useFPForScavengingIndex() does the 647 // right thing for the emergency spill slot. 648 bool UseFP = false; 649 if (AFI->hasStackFrame()) { 650 // Note: Keeping the following as multiple 'if' statements rather than 651 // merging to a single expression for readability. 652 // 653 // Argument access should always use the FP. 654 if (isFixed) { 655 UseFP = hasFP(MF); 656 } else if (hasFP(MF) && !RegInfo->hasBasePointer(MF) && 657 !RegInfo->needsStackRealignment(MF)) { 658 // Use SP or FP, whichever gives us the best chance of the offset 659 // being in range for direct access. If the FPOffset is positive, 660 // that'll always be best, as the SP will be even further away. 661 // If the FPOffset is negative, we have to keep in mind that the 662 // available offset range for negative offsets is smaller than for 663 // positive ones. If we have variable sized objects, we're stuck with 664 // using the FP regardless, though, as the SP offset is unknown 665 // and we don't have a base pointer available. If an offset is 666 // available via the FP and the SP, use whichever is closest. 667 if (PreferFP || MFI->hasVarSizedObjects() || FPOffset >= 0 || 668 (FPOffset >= -256 && Offset > -FPOffset)) 669 UseFP = true; 670 } 671 } 672 673 assert((isFixed || !RegInfo->needsStackRealignment(MF) || !UseFP) && 674 "In the presence of dynamic stack pointer realignment, " 675 "non-argument objects cannot be accessed through the frame pointer"); 676 677 if (UseFP) { 678 FrameReg = RegInfo->getFrameRegister(MF); 679 return FPOffset; 680 } 681 682 // Use the base pointer if we have one. 683 if (RegInfo->hasBasePointer(MF)) 684 FrameReg = RegInfo->getBaseRegister(); 685 else { 686 FrameReg = AArch64::SP; 687 // If we're using the red zone for this function, the SP won't actually 688 // be adjusted, so the offsets will be negative. They're also all 689 // within range of the signed 9-bit immediate instructions. 690 if (canUseRedZone(MF)) 691 Offset -= AFI->getLocalStackSize(); 692 } 693 694 return Offset; 695 } 696 697 static unsigned getPrologueDeath(MachineFunction &MF, unsigned Reg) { 698 if (Reg != AArch64::LR) 699 return getKillRegState(true); 700 701 // LR maybe referred to later by an @llvm.returnaddress intrinsic. 702 bool LRLiveIn = MF.getRegInfo().isLiveIn(AArch64::LR); 703 bool LRKill = !(LRLiveIn && MF.getFrameInfo()->isReturnAddressTaken()); 704 return getKillRegState(LRKill); 705 } 706 707 struct RegPairInfo { 708 RegPairInfo() : Reg1(AArch64::NoRegister), Reg2(AArch64::NoRegister) {} 709 unsigned Reg1; 710 unsigned Reg2; 711 int FrameIdx; 712 int Offset; 713 bool IsGPR; 714 bool isPaired() const { return Reg2 != AArch64::NoRegister; } 715 }; 716 717 static void computeCalleeSaveRegisterPairs( 718 MachineFunction &MF, const std::vector<CalleeSavedInfo> &CSI, 719 const TargetRegisterInfo *TRI, SmallVectorImpl<RegPairInfo> &RegPairs) { 720 721 if (CSI.empty()) 722 return; 723 724 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 725 MachineFrameInfo *MFI = MF.getFrameInfo(); 726 unsigned Count = CSI.size(); 727 // MachO's compact unwind format relies on all registers being stored in 728 // pairs. 729 assert((!MF.getSubtarget<AArch64Subtarget>().isTargetMachO() || 730 (Count & 1) == 0) && 731 "Odd number of callee-saved regs to spill!"); 732 unsigned Offset = AFI->getCalleeSavedStackSize(); 733 734 for (unsigned i = 0; i < Count; ++i) { 735 RegPairInfo RPI; 736 RPI.Reg1 = CSI[i].getReg(); 737 738 assert(AArch64::GPR64RegClass.contains(RPI.Reg1) || 739 AArch64::FPR64RegClass.contains(RPI.Reg1)); 740 RPI.IsGPR = AArch64::GPR64RegClass.contains(RPI.Reg1); 741 742 // Add the next reg to the pair if it is in the same register class. 743 if (i + 1 < Count) { 744 unsigned NextReg = CSI[i + 1].getReg(); 745 if ((RPI.IsGPR && AArch64::GPR64RegClass.contains(NextReg)) || 746 (!RPI.IsGPR && AArch64::FPR64RegClass.contains(NextReg))) 747 RPI.Reg2 = NextReg; 748 } 749 750 // GPRs and FPRs are saved in pairs of 64-bit regs. We expect the CSI 751 // list to come in sorted by frame index so that we can issue the store 752 // pair instructions directly. Assert if we see anything otherwise. 753 // 754 // The order of the registers in the list is controlled by 755 // getCalleeSavedRegs(), so they will always be in-order, as well. 756 assert((!RPI.isPaired() || 757 (CSI[i].getFrameIdx() + 1 == CSI[i + 1].getFrameIdx())) && 758 "Out of order callee saved regs!"); 759 760 // MachO's compact unwind format relies on all registers being stored in 761 // adjacent register pairs. 762 assert((!MF.getSubtarget<AArch64Subtarget>().isTargetMachO() || 763 (RPI.isPaired() && 764 ((RPI.Reg1 == AArch64::LR && RPI.Reg2 == AArch64::FP) || 765 RPI.Reg1 + 1 == RPI.Reg2))) && 766 "Callee-save registers not saved as adjacent register pair!"); 767 768 RPI.FrameIdx = CSI[i].getFrameIdx(); 769 770 if (Count * 8 != AFI->getCalleeSavedStackSize() && !RPI.isPaired()) { 771 // Round up size of non-pair to pair size if we need to pad the 772 // callee-save area to ensure 16-byte alignment. 773 Offset -= 16; 774 assert(MFI->getObjectAlignment(RPI.FrameIdx) <= 16); 775 MFI->setObjectSize(RPI.FrameIdx, 16); 776 } else 777 Offset -= RPI.isPaired() ? 16 : 8; 778 assert(Offset % 8 == 0); 779 RPI.Offset = Offset / 8; 780 assert((RPI.Offset >= -64 && RPI.Offset <= 63) && 781 "Offset out of bounds for LDP/STP immediate"); 782 783 RegPairs.push_back(RPI); 784 if (RPI.isPaired()) 785 ++i; 786 } 787 788 // Align first offset to even 16-byte boundary to avoid additional SP 789 // adjustment instructions. 790 // Last pair offset is size of whole callee-save region for SP 791 // pre-dec/post-inc. 792 RegPairInfo &LastPair = RegPairs.back(); 793 assert(AFI->getCalleeSavedStackSize() % 8 == 0); 794 LastPair.Offset = AFI->getCalleeSavedStackSize() / 8; 795 } 796 797 bool AArch64FrameLowering::spillCalleeSavedRegisters( 798 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 799 const std::vector<CalleeSavedInfo> &CSI, 800 const TargetRegisterInfo *TRI) const { 801 MachineFunction &MF = *MBB.getParent(); 802 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 803 DebugLoc DL; 804 SmallVector<RegPairInfo, 8> RegPairs; 805 806 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs); 807 808 for (auto RPII = RegPairs.rbegin(), RPIE = RegPairs.rend(); RPII != RPIE; 809 ++RPII) { 810 RegPairInfo RPI = *RPII; 811 unsigned Reg1 = RPI.Reg1; 812 unsigned Reg2 = RPI.Reg2; 813 unsigned StrOpc; 814 815 // Issue sequence of non-sp increment and pi sp spills for cs regs. The 816 // first spill is a pre-increment that allocates the stack. 817 // For example: 818 // stp x22, x21, [sp, #-48]! // addImm(-6) 819 // stp x20, x19, [sp, #16] // addImm(+2) 820 // stp fp, lr, [sp, #32] // addImm(+4) 821 // Rationale: This sequence saves uop updates compared to a sequence of 822 // pre-increment spills like stp xi,xj,[sp,#-16]! 823 // Note: Similar rationale and sequence for restores in epilog. 824 bool BumpSP = RPII == RegPairs.rbegin(); 825 if (RPI.IsGPR) { 826 // For first spill use pre-increment store. 827 if (BumpSP) 828 StrOpc = RPI.isPaired() ? AArch64::STPXpre : AArch64::STRXpre; 829 else 830 StrOpc = RPI.isPaired() ? AArch64::STPXi : AArch64::STRXui; 831 } else { 832 // For first spill use pre-increment store. 833 if (BumpSP) 834 StrOpc = RPI.isPaired() ? AArch64::STPDpre : AArch64::STRDpre; 835 else 836 StrOpc = RPI.isPaired() ? AArch64::STPDi : AArch64::STRDui; 837 } 838 DEBUG(dbgs() << "CSR spill: (" << TRI->getName(Reg1); 839 if (RPI.isPaired()) 840 dbgs() << ", " << TRI->getName(Reg2); 841 dbgs() << ") -> fi#(" << RPI.FrameIdx; 842 if (RPI.isPaired()) 843 dbgs() << ", " << RPI.FrameIdx+1; 844 dbgs() << ")\n"); 845 846 const int Offset = BumpSP ? -RPI.Offset : RPI.Offset; 847 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc)); 848 if (BumpSP) 849 MIB.addReg(AArch64::SP, RegState::Define); 850 851 if (RPI.isPaired()) { 852 MBB.addLiveIn(Reg1); 853 MBB.addLiveIn(Reg2); 854 MIB.addReg(Reg2, getPrologueDeath(MF, Reg2)) 855 .addReg(Reg1, getPrologueDeath(MF, Reg1)) 856 .addReg(AArch64::SP) 857 .addImm(Offset) // [sp, #offset * 8], where factor * 8 is implicit 858 .setMIFlag(MachineInstr::FrameSetup); 859 } else { 860 MBB.addLiveIn(Reg1); 861 MIB.addReg(Reg1, getPrologueDeath(MF, Reg1)) 862 .addReg(AArch64::SP) 863 .addImm(BumpSP ? Offset * 8 : Offset) // pre-inc version is unscaled 864 .setMIFlag(MachineInstr::FrameSetup); 865 } 866 } 867 return true; 868 } 869 870 bool AArch64FrameLowering::restoreCalleeSavedRegisters( 871 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 872 const std::vector<CalleeSavedInfo> &CSI, 873 const TargetRegisterInfo *TRI) const { 874 MachineFunction &MF = *MBB.getParent(); 875 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 876 DebugLoc DL; 877 SmallVector<RegPairInfo, 8> RegPairs; 878 879 if (MI != MBB.end()) 880 DL = MI->getDebugLoc(); 881 882 computeCalleeSaveRegisterPairs(MF, CSI, TRI, RegPairs); 883 884 for (auto RPII = RegPairs.begin(), RPIE = RegPairs.end(); RPII != RPIE; 885 ++RPII) { 886 RegPairInfo RPI = *RPII; 887 unsigned Reg1 = RPI.Reg1; 888 unsigned Reg2 = RPI.Reg2; 889 890 // Issue sequence of non-sp increment and sp-pi restores for cs regs. Only 891 // the last load is sp-pi post-increment and de-allocates the stack: 892 // For example: 893 // ldp fp, lr, [sp, #32] // addImm(+4) 894 // ldp x20, x19, [sp, #16] // addImm(+2) 895 // ldp x22, x21, [sp], #48 // addImm(+6) 896 // Note: see comment in spillCalleeSavedRegisters() 897 unsigned LdrOpc; 898 bool BumpSP = RPII == std::prev(RegPairs.end()); 899 if (RPI.IsGPR) { 900 if (BumpSP) 901 LdrOpc = RPI.isPaired() ? AArch64::LDPXpost : AArch64::LDRXpost; 902 else 903 LdrOpc = RPI.isPaired() ? AArch64::LDPXi : AArch64::LDRXui; 904 } else { 905 if (BumpSP) 906 LdrOpc = RPI.isPaired() ? AArch64::LDPDpost : AArch64::LDRDpost; 907 else 908 LdrOpc = RPI.isPaired() ? AArch64::LDPDi : AArch64::LDRDui; 909 } 910 DEBUG(dbgs() << "CSR restore: (" << TRI->getName(Reg1); 911 if (RPI.isPaired()) 912 dbgs() << ", " << TRI->getName(Reg2); 913 dbgs() << ") -> fi#(" << RPI.FrameIdx; 914 if (RPI.isPaired()) 915 dbgs() << ", " << RPI.FrameIdx+1; 916 dbgs() << ")\n"); 917 918 const int Offset = RPI.Offset; 919 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdrOpc)); 920 if (BumpSP) 921 MIB.addReg(AArch64::SP, RegState::Define); 922 923 if (RPI.isPaired()) 924 MIB.addReg(Reg2, getDefRegState(true)) 925 .addReg(Reg1, getDefRegState(true)) 926 .addReg(AArch64::SP) 927 .addImm(Offset) // [sp], #offset * 8 or [sp, #offset * 8] 928 // where the factor * 8 is implicit 929 .setMIFlag(MachineInstr::FrameDestroy); 930 else 931 MIB.addReg(Reg1, getDefRegState(true)) 932 .addReg(AArch64::SP) 933 .addImm(BumpSP ? Offset * 8 : Offset) // post-dec version is unscaled 934 .setMIFlag(MachineInstr::FrameDestroy); 935 } 936 return true; 937 } 938 939 void AArch64FrameLowering::determineCalleeSaves(MachineFunction &MF, 940 BitVector &SavedRegs, 941 RegScavenger *RS) const { 942 // All calls are tail calls in GHC calling conv, and functions have no 943 // prologue/epilogue. 944 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) 945 return; 946 947 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 948 const AArch64RegisterInfo *RegInfo = static_cast<const AArch64RegisterInfo *>( 949 MF.getSubtarget().getRegisterInfo()); 950 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>(); 951 const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>(); 952 unsigned UnspilledCSGPR = AArch64::NoRegister; 953 unsigned UnspilledCSGPRPaired = AArch64::NoRegister; 954 955 // The frame record needs to be created by saving the appropriate registers 956 if (hasFP(MF)) { 957 SavedRegs.set(AArch64::FP); 958 SavedRegs.set(AArch64::LR); 959 } 960 961 unsigned BasePointerReg = AArch64::NoRegister; 962 if (RegInfo->hasBasePointer(MF)) 963 BasePointerReg = RegInfo->getBaseRegister(); 964 965 bool ExtraCSSpill = false; 966 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 967 // Figure out which callee-saved registers to save/restore. 968 for (unsigned i = 0; CSRegs[i]; ++i) { 969 const unsigned Reg = CSRegs[i]; 970 971 // Add the base pointer register to SavedRegs if it is callee-save. 972 if (Reg == BasePointerReg) 973 SavedRegs.set(Reg); 974 975 bool RegUsed = SavedRegs.test(Reg); 976 unsigned PairedReg = CSRegs[i ^ 1]; 977 if (!RegUsed) { 978 if (AArch64::GPR64RegClass.contains(Reg) && 979 !RegInfo->isReservedReg(MF, Reg)) { 980 UnspilledCSGPR = Reg; 981 UnspilledCSGPRPaired = PairedReg; 982 } 983 continue; 984 } 985 986 // MachO's compact unwind format relies on all registers being stored in 987 // pairs. 988 // FIXME: the usual format is actually better if unwinding isn't needed. 989 if (Subtarget.isTargetMachO() && !SavedRegs.test(PairedReg)) { 990 SavedRegs.set(PairedReg); 991 ExtraCSSpill = true; 992 } 993 } 994 995 DEBUG(dbgs() << "*** determineCalleeSaves\nUsed CSRs:"; 996 for (int Reg = SavedRegs.find_first(); Reg != -1; 997 Reg = SavedRegs.find_next(Reg)) 998 dbgs() << ' ' << PrintReg(Reg, RegInfo); 999 dbgs() << "\n";); 1000 1001 // If any callee-saved registers are used, the frame cannot be eliminated. 1002 unsigned NumRegsSpilled = SavedRegs.count(); 1003 bool CanEliminateFrame = NumRegsSpilled == 0; 1004 1005 // FIXME: Set BigStack if any stack slot references may be out of range. 1006 // For now, just conservatively guestimate based on unscaled indexing 1007 // range. We'll end up allocating an unnecessary spill slot a lot, but 1008 // realistically that's not a big deal at this stage of the game. 1009 // The CSR spill slots have not been allocated yet, so estimateStackSize 1010 // won't include them. 1011 MachineFrameInfo *MFI = MF.getFrameInfo(); 1012 unsigned CFSize = MFI->estimateStackSize(MF) + 8 * NumRegsSpilled; 1013 DEBUG(dbgs() << "Estimated stack frame size: " << CFSize << " bytes.\n"); 1014 bool BigStack = (CFSize >= 256); 1015 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) 1016 AFI->setHasStackFrame(true); 1017 1018 // Estimate if we might need to scavenge a register at some point in order 1019 // to materialize a stack offset. If so, either spill one additional 1020 // callee-saved register or reserve a special spill slot to facilitate 1021 // register scavenging. If we already spilled an extra callee-saved register 1022 // above to keep the number of spills even, we don't need to do anything else 1023 // here. 1024 if (BigStack && !ExtraCSSpill) { 1025 if (UnspilledCSGPR != AArch64::NoRegister) { 1026 DEBUG(dbgs() << "Spilling " << PrintReg(UnspilledCSGPR, RegInfo) 1027 << " to get a scratch register.\n"); 1028 SavedRegs.set(UnspilledCSGPR); 1029 // MachO's compact unwind format relies on all registers being stored in 1030 // pairs, so if we need to spill one extra for BigStack, then we need to 1031 // store the pair. 1032 if (Subtarget.isTargetMachO()) 1033 SavedRegs.set(UnspilledCSGPRPaired); 1034 ExtraCSSpill = true; 1035 NumRegsSpilled = SavedRegs.count(); 1036 } 1037 1038 // If we didn't find an extra callee-saved register to spill, create 1039 // an emergency spill slot. 1040 if (!ExtraCSSpill) { 1041 const TargetRegisterClass *RC = &AArch64::GPR64RegClass; 1042 int FI = MFI->CreateStackObject(RC->getSize(), RC->getAlignment(), false); 1043 RS->addScavengingFrameIndex(FI); 1044 DEBUG(dbgs() << "No available CS registers, allocated fi#" << FI 1045 << " as the emergency spill slot.\n"); 1046 } 1047 } 1048 1049 // Round up to register pair alignment to avoid additional SP adjustment 1050 // instructions. 1051 AFI->setCalleeSavedStackSize(alignTo(8 * NumRegsSpilled, 16)); 1052 } 1053