1 //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains the ARM implementation of TargetFrameLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 // 13 // This file contains the ARM implementation of TargetFrameLowering class. 14 // 15 // On ARM, stack frames are structured as follows: 16 // 17 // The stack grows downward. 18 // 19 // All of the individual frame areas on the frame below are optional, i.e. it's 20 // possible to create a function so that the particular area isn't present 21 // in the frame. 22 // 23 // At function entry, the "frame" looks as follows: 24 // 25 // | | Higher address 26 // |-----------------------------------| 27 // | | 28 // | arguments passed on the stack | 29 // | | 30 // |-----------------------------------| <- sp 31 // | | Lower address 32 // 33 // 34 // After the prologue has run, the frame has the following general structure. 35 // Technically the last frame area (VLAs) doesn't get created until in the 36 // main function body, after the prologue is run. However, it's depicted here 37 // for completeness. 38 // 39 // | | Higher address 40 // |-----------------------------------| 41 // | | 42 // | arguments passed on the stack | 43 // | | 44 // |-----------------------------------| <- (sp at function entry) 45 // | | 46 // | varargs from registers | 47 // | | 48 // |-----------------------------------| 49 // | | 50 // | prev_lr | 51 // | prev_fp | 52 // | (a.k.a. "frame record") | 53 // | | 54 // |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11) 55 // | | 56 // | callee-saved gpr registers | 57 // | | 58 // |-----------------------------------| 59 // | | 60 // | callee-saved fp/simd regs | 61 // | | 62 // |-----------------------------------| 63 // |.empty.space.to.make.part.below....| 64 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at 65 // |.the.standard.8-byte.alignment.....| compile time; if present) 66 // |-----------------------------------| 67 // | | 68 // | local variables of fixed size | 69 // | including spill slots | 70 // |-----------------------------------| <- base pointer (not defined by ABI, 71 // |.variable-sized.local.variables....| LLVM chooses r6) 72 // |.(VLAs)............................| (size of this area is unknown at 73 // |...................................| compile time) 74 // |-----------------------------------| <- sp 75 // | | Lower address 76 // 77 // 78 // To access the data in a frame, at-compile time, a constant offset must be 79 // computable from one of the pointers (fp, bp, sp) to access it. The size 80 // of the areas with a dotted background cannot be computed at compile-time 81 // if they are present, making it required to have all three of fp, bp and 82 // sp to be set up to be able to access all contents in the frame areas, 83 // assuming all of the frame areas are non-empty. 84 // 85 // For most functions, some of the frame areas are empty. For those functions, 86 // it may not be necessary to set up fp or bp: 87 // * A base pointer is definitely needed when there are both VLAs and local 88 // variables with more-than-default alignment requirements. 89 // * A frame pointer is definitely needed when there are local variables with 90 // more-than-default alignment requirements. 91 // 92 // In some cases when a base pointer is not strictly needed, it is generated 93 // anyway when offsets from the frame pointer to access local variables become 94 // so large that the offset can't be encoded in the immediate fields of loads 95 // or stores. 96 // 97 // The frame pointer might be chosen to be r7 or r11, depending on the target 98 // architecture and operating system. See ARMSubtarget::getFramePointerReg for 99 // details. 100 // 101 // Outgoing function arguments must be at the bottom of the stack frame when 102 // calling another function. If we do not have variable-sized stack objects, we 103 // can allocate a "reserved call frame" area at the bottom of the local 104 // variable area, large enough for all outgoing calls. If we do have VLAs, then 105 // the stack pointer must be decremented and incremented around each call to 106 // make space for the arguments below the VLAs. 107 // 108 //===----------------------------------------------------------------------===// 109 110 #include "ARMFrameLowering.h" 111 #include "ARMBaseInstrInfo.h" 112 #include "ARMBaseRegisterInfo.h" 113 #include "ARMConstantPoolValue.h" 114 #include "ARMMachineFunctionInfo.h" 115 #include "ARMSubtarget.h" 116 #include "MCTargetDesc/ARMAddressingModes.h" 117 #include "MCTargetDesc/ARMBaseInfo.h" 118 #include "Utils/ARMBaseInfo.h" 119 #include "llvm/ADT/BitVector.h" 120 #include "llvm/ADT/STLExtras.h" 121 #include "llvm/ADT/SmallPtrSet.h" 122 #include "llvm/ADT/SmallVector.h" 123 #include "llvm/CodeGen/MachineBasicBlock.h" 124 #include "llvm/CodeGen/MachineConstantPool.h" 125 #include "llvm/CodeGen/MachineFrameInfo.h" 126 #include "llvm/CodeGen/MachineFunction.h" 127 #include "llvm/CodeGen/MachineInstr.h" 128 #include "llvm/CodeGen/MachineInstrBuilder.h" 129 #include "llvm/CodeGen/MachineJumpTableInfo.h" 130 #include "llvm/CodeGen/MachineModuleInfo.h" 131 #include "llvm/CodeGen/MachineOperand.h" 132 #include "llvm/CodeGen/MachineRegisterInfo.h" 133 #include "llvm/CodeGen/RegisterScavenging.h" 134 #include "llvm/CodeGen/TargetInstrInfo.h" 135 #include "llvm/CodeGen/TargetOpcodes.h" 136 #include "llvm/CodeGen/TargetRegisterInfo.h" 137 #include "llvm/CodeGen/TargetSubtargetInfo.h" 138 #include "llvm/IR/Attributes.h" 139 #include "llvm/IR/CallingConv.h" 140 #include "llvm/IR/DebugLoc.h" 141 #include "llvm/IR/Function.h" 142 #include "llvm/MC/MCAsmInfo.h" 143 #include "llvm/MC/MCContext.h" 144 #include "llvm/MC/MCDwarf.h" 145 #include "llvm/MC/MCInstrDesc.h" 146 #include "llvm/MC/MCRegisterInfo.h" 147 #include "llvm/Support/CodeGen.h" 148 #include "llvm/Support/CommandLine.h" 149 #include "llvm/Support/Compiler.h" 150 #include "llvm/Support/Debug.h" 151 #include "llvm/Support/ErrorHandling.h" 152 #include "llvm/Support/MathExtras.h" 153 #include "llvm/Support/raw_ostream.h" 154 #include "llvm/Target/TargetMachine.h" 155 #include "llvm/Target/TargetOptions.h" 156 #include <algorithm> 157 #include <cassert> 158 #include <cstddef> 159 #include <cstdint> 160 #include <iterator> 161 #include <utility> 162 #include <vector> 163 164 #define DEBUG_TYPE "arm-frame-lowering" 165 166 using namespace llvm; 167 168 static cl::opt<bool> 169 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true), 170 cl::desc("Align ARM NEON spills in prolog and epilog")); 171 172 static MachineBasicBlock::iterator 173 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 174 unsigned NumAlignedDPRCS2Regs); 175 176 enum class SpillArea { 177 GPRCS1, 178 GPRCS2, 179 DPRCS1, 180 DPRCS2, 181 FPCXT, 182 }; 183 184 /// Get the spill area that Reg should be saved into in the prologue. 185 SpillArea getSpillArea(Register Reg, 186 ARMSubtarget::PushPopSplitVariation Variation, 187 unsigned NumAlignedDPRCS2Regs, 188 const ARMBaseRegisterInfo *RegInfo) { 189 // NoSplit: 190 // push {r0-r12, lr} GPRCS1 191 // vpush {r8-d15} DPRCS1 192 // 193 // SplitR7: 194 // push {r0-r7, lr} GPRCS1 195 // push {r8-r12} GPRCS2 196 // vpush {r8-d15} DPRCS1 197 // 198 // SplitR11WindowsSEH: 199 // push {r0-r10, r12} GPRCS1 200 // vpush {r8-d15} DPRCS1 201 // push {r11, lr} GPRCS2 202 // 203 // SplitR11AAPCSSignRA: 204 // push {r0-r10, r12} GPRSC1 205 // push {r11, lr} GPRCS2 206 // vpush {r8-d15} DPRCS1 207 208 // If FPCXTNS is spilled (for CMSE secure entryfunctions), it is always at 209 // the top of the stack frame. 210 // The DPRCS2 region is used for ABIs which only guarantee 4-byte alignment 211 // of SP. If used, it will be below the other save areas, after the stack has 212 // been re-aligned. 213 214 switch (Reg) { 215 default: 216 dbgs() << "Don't know where to spill " << printReg(Reg, RegInfo) << "\n"; 217 llvm_unreachable("Don't know where to spill this register"); 218 break; 219 220 case ARM::FPCXTNS: 221 return SpillArea::FPCXT; 222 223 case ARM::R0: 224 case ARM::R1: 225 case ARM::R2: 226 case ARM::R3: 227 case ARM::R4: 228 case ARM::R5: 229 case ARM::R6: 230 case ARM::R7: 231 return SpillArea::GPRCS1; 232 233 case ARM::R8: 234 case ARM::R9: 235 case ARM::R10: 236 if (Variation == ARMSubtarget::SplitR7) 237 return SpillArea::GPRCS2; 238 else 239 return SpillArea::GPRCS1; 240 241 case ARM::R11: 242 if (Variation == ARMSubtarget::NoSplit) 243 return SpillArea::GPRCS1; 244 else 245 return SpillArea::GPRCS2; 246 247 case ARM::R12: 248 if (Variation == ARMSubtarget::SplitR7) 249 return SpillArea::GPRCS2; 250 else 251 return SpillArea::GPRCS1; 252 253 case ARM::LR: 254 if (Variation == ARMSubtarget::SplitR11WindowsSEH || 255 Variation == ARMSubtarget::SplitR11AAPCSSignRA) 256 return SpillArea::GPRCS2; 257 else 258 return SpillArea::GPRCS1; 259 260 case ARM::D0: 261 case ARM::D1: 262 case ARM::D2: 263 case ARM::D3: 264 case ARM::D4: 265 case ARM::D5: 266 case ARM::D6: 267 case ARM::D7: 268 return SpillArea::DPRCS1; 269 270 case ARM::D8: 271 case ARM::D9: 272 case ARM::D10: 273 case ARM::D11: 274 case ARM::D12: 275 case ARM::D13: 276 case ARM::D14: 277 case ARM::D15: 278 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs) 279 return SpillArea::DPRCS2; 280 else 281 return SpillArea::DPRCS1; 282 283 case ARM::D16: 284 case ARM::D17: 285 case ARM::D18: 286 case ARM::D19: 287 case ARM::D20: 288 case ARM::D21: 289 case ARM::D22: 290 case ARM::D23: 291 case ARM::D24: 292 case ARM::D25: 293 case ARM::D26: 294 case ARM::D27: 295 case ARM::D28: 296 case ARM::D29: 297 case ARM::D30: 298 case ARM::D31: 299 return SpillArea::DPRCS1; 300 } 301 } 302 303 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti) 304 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)), 305 STI(sti) {} 306 307 bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const { 308 // iOS always has a FP for backtracking, force other targets to keep their FP 309 // when doing FastISel. The emitted code is currently superior, and in cases 310 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated. 311 return MF.getSubtarget<ARMSubtarget>().useFastISel(); 312 } 313 314 /// Returns true if the target can safely skip saving callee-saved registers 315 /// for noreturn nounwind functions. 316 bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const { 317 assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) && 318 MF.getFunction().hasFnAttribute(Attribute::NoUnwind) && 319 !MF.getFunction().hasFnAttribute(Attribute::UWTable)); 320 321 // Frame pointer and link register are not treated as normal CSR, thus we 322 // can always skip CSR saves for nonreturning functions. 323 return true; 324 } 325 326 /// hasFPImpl - Return true if the specified function should have a dedicated 327 /// frame pointer register. This is true if the function has variable sized 328 /// allocas or if frame pointer elimination is disabled. 329 bool ARMFrameLowering::hasFPImpl(const MachineFunction &MF) const { 330 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 331 const MachineFrameInfo &MFI = MF.getFrameInfo(); 332 333 // Check to see if the target want to forcibly keep frame pointer. 334 if (keepFramePointer(MF)) 335 return true; 336 337 // ABI-required frame pointer. 338 if (MF.getTarget().Options.DisableFramePointerElim(MF)) 339 return true; 340 341 // Frame pointer required for use within this function. 342 return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() || 343 MFI.isFrameAddressTaken()); 344 } 345 346 /// isFPReserved - Return true if the frame pointer register should be 347 /// considered a reserved register on the scope of the specified function. 348 bool ARMFrameLowering::isFPReserved(const MachineFunction &MF) const { 349 return hasFP(MF) || MF.getTarget().Options.FramePointerIsReserved(MF); 350 } 351 352 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is 353 /// not required, we reserve argument space for call sites in the function 354 /// immediately on entry to the current function. This eliminates the need for 355 /// add/sub sp brackets around call sites. Returns true if the call frame is 356 /// included as part of the stack frame. 357 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const { 358 const MachineFrameInfo &MFI = MF.getFrameInfo(); 359 unsigned CFSize = MFI.getMaxCallFrameSize(); 360 // It's not always a good idea to include the call frame as part of the 361 // stack frame. ARM (especially Thumb) has small immediate offset to 362 // address the stack frame. So a large call frame can cause poor codegen 363 // and may even makes it impossible to scavenge a register. 364 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12 365 return false; 366 367 return !MFI.hasVarSizedObjects(); 368 } 369 370 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the 371 /// call frame pseudos can be simplified. Unlike most targets, having a FP 372 /// is not sufficient here since we still may reference some objects via SP 373 /// even when FP is available in Thumb2 mode. 374 bool 375 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const { 376 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects(); 377 } 378 379 // Returns how much of the incoming argument stack area we should clean up in an 380 // epilogue. For the C calling convention this will be 0, for guaranteed tail 381 // call conventions it can be positive (a normal return or a tail call to a 382 // function that uses less stack space for arguments) or negative (for a tail 383 // call to a function that needs more stack space than us for arguments). 384 static int getArgumentStackToRestore(MachineFunction &MF, 385 MachineBasicBlock &MBB) { 386 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); 387 bool IsTailCallReturn = false; 388 if (MBB.end() != MBBI) { 389 unsigned RetOpcode = MBBI->getOpcode(); 390 IsTailCallReturn = RetOpcode == ARM::TCRETURNdi || 391 RetOpcode == ARM::TCRETURNri || 392 RetOpcode == ARM::TCRETURNrinotr12; 393 } 394 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 395 396 int ArgumentPopSize = 0; 397 if (IsTailCallReturn) { 398 MachineOperand &StackAdjust = MBBI->getOperand(1); 399 400 // For a tail-call in a callee-pops-arguments environment, some or all of 401 // the stack may actually be in use for the call's arguments, this is 402 // calculated during LowerCall and consumed here... 403 ArgumentPopSize = StackAdjust.getImm(); 404 } else { 405 // ... otherwise the amount to pop is *all* of the argument space, 406 // conveniently stored in the MachineFunctionInfo by 407 // LowerFormalArguments. This will, of course, be zero for the C calling 408 // convention. 409 ArgumentPopSize = AFI->getArgumentStackToRestore(); 410 } 411 412 return ArgumentPopSize; 413 } 414 415 static bool needsWinCFI(const MachineFunction &MF) { 416 const Function &F = MF.getFunction(); 417 return MF.getTarget().getMCAsmInfo()->usesWindowsCFI() && 418 F.needsUnwindTableEntry(); 419 } 420 421 // Given a load or a store instruction, generate an appropriate unwinding SEH 422 // code on Windows. 423 static MachineBasicBlock::iterator insertSEH(MachineBasicBlock::iterator MBBI, 424 const TargetInstrInfo &TII, 425 unsigned Flags) { 426 unsigned Opc = MBBI->getOpcode(); 427 MachineBasicBlock *MBB = MBBI->getParent(); 428 MachineFunction &MF = *MBB->getParent(); 429 DebugLoc DL = MBBI->getDebugLoc(); 430 MachineInstrBuilder MIB; 431 const ARMSubtarget &Subtarget = MF.getSubtarget<ARMSubtarget>(); 432 const ARMBaseRegisterInfo *RegInfo = Subtarget.getRegisterInfo(); 433 434 Flags |= MachineInstr::NoMerge; 435 436 switch (Opc) { 437 default: 438 report_fatal_error("No SEH Opcode for instruction " + TII.getName(Opc)); 439 break; 440 case ARM::t2ADDri: // add.w r11, sp, #xx 441 case ARM::t2ADDri12: // add.w r11, sp, #xx 442 case ARM::t2MOVTi16: // movt r4, #xx 443 case ARM::tBL: // bl __chkstk 444 // These are harmless if used for just setting up a frame pointer, 445 // but that frame pointer can't be relied upon for unwinding, unless 446 // set up with SEH_SaveSP. 447 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)) 448 .addImm(/*Wide=*/1) 449 .setMIFlags(Flags); 450 break; 451 452 case ARM::t2MOVi16: { // mov(w) r4, #xx 453 bool Wide = MBBI->getOperand(1).getImm() >= 256; 454 if (!Wide) { 455 MachineInstrBuilder NewInstr = 456 BuildMI(MF, DL, TII.get(ARM::tMOVi8)).setMIFlags(MBBI->getFlags()); 457 NewInstr.add(MBBI->getOperand(0)); 458 NewInstr.add(t1CondCodeOp(/*isDead=*/true)); 459 for (MachineOperand &MO : llvm::drop_begin(MBBI->operands())) 460 NewInstr.add(MO); 461 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr); 462 MBB->erase(MBBI); 463 MBBI = NewMBBI; 464 } 465 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)).addImm(Wide).setMIFlags(Flags); 466 break; 467 } 468 469 case ARM::tBLXr: // blx r12 (__chkstk) 470 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)) 471 .addImm(/*Wide=*/0) 472 .setMIFlags(Flags); 473 break; 474 475 case ARM::t2MOVi32imm: // movw+movt 476 // This pseudo instruction expands into two mov instructions. If the 477 // second operand is a symbol reference, this will stay as two wide 478 // instructions, movw+movt. If they're immediates, the first one can 479 // end up as a narrow mov though. 480 // As two SEH instructions are appended here, they won't get interleaved 481 // between the two final movw/movt instructions, but it doesn't make any 482 // practical difference. 483 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)) 484 .addImm(/*Wide=*/1) 485 .setMIFlags(Flags); 486 MBB->insertAfter(MBBI, MIB); 487 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop)) 488 .addImm(/*Wide=*/1) 489 .setMIFlags(Flags); 490 break; 491 492 case ARM::t2STR_PRE: 493 if (MBBI->getOperand(0).getReg() == ARM::SP && 494 MBBI->getOperand(2).getReg() == ARM::SP && 495 MBBI->getOperand(3).getImm() == -4) { 496 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 497 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveRegs)) 498 .addImm(1ULL << Reg) 499 .addImm(/*Wide=*/1) 500 .setMIFlags(Flags); 501 } else { 502 report_fatal_error("No matching SEH Opcode for t2STR_PRE"); 503 } 504 break; 505 506 case ARM::t2LDR_POST: 507 if (MBBI->getOperand(1).getReg() == ARM::SP && 508 MBBI->getOperand(2).getReg() == ARM::SP && 509 MBBI->getOperand(3).getImm() == 4) { 510 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 511 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveRegs)) 512 .addImm(1ULL << Reg) 513 .addImm(/*Wide=*/1) 514 .setMIFlags(Flags); 515 } else { 516 report_fatal_error("No matching SEH Opcode for t2LDR_POST"); 517 } 518 break; 519 520 case ARM::t2LDMIA_RET: 521 case ARM::t2LDMIA_UPD: 522 case ARM::t2STMDB_UPD: { 523 unsigned Mask = 0; 524 bool Wide = false; 525 for (unsigned i = 4, NumOps = MBBI->getNumOperands(); i != NumOps; ++i) { 526 const MachineOperand &MO = MBBI->getOperand(i); 527 if (!MO.isReg() || MO.isImplicit()) 528 continue; 529 unsigned Reg = RegInfo->getSEHRegNum(MO.getReg()); 530 if (Reg == 15) 531 Reg = 14; 532 if (Reg >= 8 && Reg <= 13) 533 Wide = true; 534 else if (Opc == ARM::t2LDMIA_UPD && Reg == 14) 535 Wide = true; 536 Mask |= 1 << Reg; 537 } 538 if (!Wide) { 539 unsigned NewOpc; 540 switch (Opc) { 541 case ARM::t2LDMIA_RET: 542 NewOpc = ARM::tPOP_RET; 543 break; 544 case ARM::t2LDMIA_UPD: 545 NewOpc = ARM::tPOP; 546 break; 547 case ARM::t2STMDB_UPD: 548 NewOpc = ARM::tPUSH; 549 break; 550 default: 551 llvm_unreachable(""); 552 } 553 MachineInstrBuilder NewInstr = 554 BuildMI(MF, DL, TII.get(NewOpc)).setMIFlags(MBBI->getFlags()); 555 for (unsigned i = 2, NumOps = MBBI->getNumOperands(); i != NumOps; ++i) 556 NewInstr.add(MBBI->getOperand(i)); 557 MachineBasicBlock::iterator NewMBBI = MBB->insertAfter(MBBI, NewInstr); 558 MBB->erase(MBBI); 559 MBBI = NewMBBI; 560 } 561 unsigned SEHOpc = 562 (Opc == ARM::t2LDMIA_RET) ? ARM::SEH_SaveRegs_Ret : ARM::SEH_SaveRegs; 563 MIB = BuildMI(MF, DL, TII.get(SEHOpc)) 564 .addImm(Mask) 565 .addImm(Wide ? 1 : 0) 566 .setMIFlags(Flags); 567 break; 568 } 569 case ARM::VSTMDDB_UPD: 570 case ARM::VLDMDIA_UPD: { 571 int First = -1, Last = 0; 572 for (const MachineOperand &MO : llvm::drop_begin(MBBI->operands(), 4)) { 573 unsigned Reg = RegInfo->getSEHRegNum(MO.getReg()); 574 if (First == -1) 575 First = Reg; 576 Last = Reg; 577 } 578 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveFRegs)) 579 .addImm(First) 580 .addImm(Last) 581 .setMIFlags(Flags); 582 break; 583 } 584 case ARM::tSUBspi: 585 case ARM::tADDspi: 586 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc)) 587 .addImm(MBBI->getOperand(2).getImm() * 4) 588 .addImm(/*Wide=*/0) 589 .setMIFlags(Flags); 590 break; 591 case ARM::t2SUBspImm: 592 case ARM::t2SUBspImm12: 593 case ARM::t2ADDspImm: 594 case ARM::t2ADDspImm12: 595 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_StackAlloc)) 596 .addImm(MBBI->getOperand(2).getImm()) 597 .addImm(/*Wide=*/1) 598 .setMIFlags(Flags); 599 break; 600 601 case ARM::tMOVr: 602 if (MBBI->getOperand(1).getReg() == ARM::SP && 603 (Flags & MachineInstr::FrameSetup)) { 604 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(0).getReg()); 605 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP)) 606 .addImm(Reg) 607 .setMIFlags(Flags); 608 } else if (MBBI->getOperand(0).getReg() == ARM::SP && 609 (Flags & MachineInstr::FrameDestroy)) { 610 unsigned Reg = RegInfo->getSEHRegNum(MBBI->getOperand(1).getReg()); 611 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_SaveSP)) 612 .addImm(Reg) 613 .setMIFlags(Flags); 614 } else { 615 report_fatal_error("No SEH Opcode for MOV"); 616 } 617 break; 618 619 case ARM::tBX_RET: 620 case ARM::TCRETURNri: 621 case ARM::TCRETURNrinotr12: 622 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret)) 623 .addImm(/*Wide=*/0) 624 .setMIFlags(Flags); 625 break; 626 627 case ARM::TCRETURNdi: 628 MIB = BuildMI(MF, DL, TII.get(ARM::SEH_Nop_Ret)) 629 .addImm(/*Wide=*/1) 630 .setMIFlags(Flags); 631 break; 632 } 633 return MBB->insertAfter(MBBI, MIB); 634 } 635 636 static MachineBasicBlock::iterator 637 initMBBRange(MachineBasicBlock &MBB, const MachineBasicBlock::iterator &MBBI) { 638 if (MBBI == MBB.begin()) 639 return MachineBasicBlock::iterator(); 640 return std::prev(MBBI); 641 } 642 643 static void insertSEHRange(MachineBasicBlock &MBB, 644 MachineBasicBlock::iterator Start, 645 const MachineBasicBlock::iterator &End, 646 const ARMBaseInstrInfo &TII, unsigned MIFlags) { 647 if (Start.isValid()) 648 Start = std::next(Start); 649 else 650 Start = MBB.begin(); 651 652 for (auto MI = Start; MI != End;) { 653 auto Next = std::next(MI); 654 // Check if this instruction already has got a SEH opcode added. In that 655 // case, don't do this generic mapping. 656 if (Next != End && isSEHInstruction(*Next)) { 657 MI = std::next(Next); 658 while (MI != End && isSEHInstruction(*MI)) 659 ++MI; 660 continue; 661 } 662 insertSEH(MI, TII, MIFlags); 663 MI = Next; 664 } 665 } 666 667 static void emitRegPlusImmediate( 668 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI, 669 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg, 670 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags, 671 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) { 672 if (isARM) 673 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 674 Pred, PredReg, TII, MIFlags); 675 else 676 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes, 677 Pred, PredReg, TII, MIFlags); 678 } 679 680 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB, 681 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl, 682 const ARMBaseInstrInfo &TII, int NumBytes, 683 unsigned MIFlags = MachineInstr::NoFlags, 684 ARMCC::CondCodes Pred = ARMCC::AL, 685 unsigned PredReg = 0) { 686 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes, 687 MIFlags, Pred, PredReg); 688 } 689 690 static int sizeOfSPAdjustment(const MachineInstr &MI) { 691 int RegSize; 692 switch (MI.getOpcode()) { 693 case ARM::VSTMDDB_UPD: 694 RegSize = 8; 695 break; 696 case ARM::STMDB_UPD: 697 case ARM::t2STMDB_UPD: 698 RegSize = 4; 699 break; 700 case ARM::t2STR_PRE: 701 case ARM::STR_PRE_IMM: 702 return 4; 703 default: 704 llvm_unreachable("Unknown push or pop like instruction"); 705 } 706 707 int count = 0; 708 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+ 709 // pred) so the list starts at 4. 710 for (int i = MI.getNumOperands() - 1; i >= 4; --i) 711 count += RegSize; 712 return count; 713 } 714 715 static bool WindowsRequiresStackProbe(const MachineFunction &MF, 716 size_t StackSizeInBytes) { 717 const MachineFrameInfo &MFI = MF.getFrameInfo(); 718 const Function &F = MF.getFunction(); 719 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096; 720 721 StackProbeSize = 722 F.getFnAttributeAsParsedInteger("stack-probe-size", StackProbeSize); 723 return (StackSizeInBytes >= StackProbeSize) && 724 !F.hasFnAttribute("no-stack-arg-probe"); 725 } 726 727 namespace { 728 729 struct StackAdjustingInsts { 730 struct InstInfo { 731 MachineBasicBlock::iterator I; 732 unsigned SPAdjust; 733 bool BeforeFPSet; 734 735 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 736 void dump() { 737 dbgs() << " " << (BeforeFPSet ? "before-fp " : " ") 738 << "sp-adjust=" << SPAdjust; 739 I->dump(); 740 } 741 #endif 742 }; 743 744 SmallVector<InstInfo, 4> Insts; 745 746 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust, 747 bool BeforeFPSet = false) { 748 InstInfo Info = {I, SPAdjust, BeforeFPSet}; 749 Insts.push_back(Info); 750 } 751 752 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) { 753 auto Info = 754 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; }); 755 assert(Info != Insts.end() && "invalid sp adjusting instruction"); 756 Info->SPAdjust += ExtraBytes; 757 } 758 759 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl, 760 const ARMBaseInstrInfo &TII, bool HasFP) { 761 MachineFunction &MF = *MBB.getParent(); 762 unsigned CFAOffset = 0; 763 for (auto &Info : Insts) { 764 if (HasFP && !Info.BeforeFPSet) 765 return; 766 767 CFAOffset += Info.SPAdjust; 768 unsigned CFIIndex = MF.addFrameInst( 769 MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset)); 770 BuildMI(MBB, std::next(Info.I), dl, 771 TII.get(TargetOpcode::CFI_INSTRUCTION)) 772 .addCFIIndex(CFIIndex) 773 .setMIFlags(MachineInstr::FrameSetup); 774 } 775 } 776 777 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 778 void dump() { 779 dbgs() << "StackAdjustingInsts:\n"; 780 for (auto &Info : Insts) 781 Info.dump(); 782 } 783 #endif 784 }; 785 786 } // end anonymous namespace 787 788 /// Emit an instruction sequence that will align the address in 789 /// register Reg by zero-ing out the lower bits. For versions of the 790 /// architecture that support Neon, this must be done in a single 791 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a 792 /// single instruction. That function only gets called when optimizing 793 /// spilling of D registers on a core with the Neon instruction set 794 /// present. 795 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI, 796 const TargetInstrInfo &TII, 797 MachineBasicBlock &MBB, 798 MachineBasicBlock::iterator MBBI, 799 const DebugLoc &DL, const unsigned Reg, 800 const Align Alignment, 801 const bool MustBeSingleInstruction) { 802 const ARMSubtarget &AST = MF.getSubtarget<ARMSubtarget>(); 803 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops(); 804 const unsigned AlignMask = Alignment.value() - 1U; 805 const unsigned NrBitsToZero = Log2(Alignment); 806 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported"); 807 if (!AFI->isThumbFunction()) { 808 // if the BFC instruction is available, use that to zero the lower 809 // bits: 810 // bfc Reg, #0, log2(Alignment) 811 // otherwise use BIC, if the mask to zero the required number of bits 812 // can be encoded in the bic immediate field 813 // bic Reg, Reg, Alignment-1 814 // otherwise, emit 815 // lsr Reg, Reg, log2(Alignment) 816 // lsl Reg, Reg, log2(Alignment) 817 if (CanUseBFC) { 818 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg) 819 .addReg(Reg, RegState::Kill) 820 .addImm(~AlignMask) 821 .add(predOps(ARMCC::AL)); 822 } else if (AlignMask <= 255) { 823 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg) 824 .addReg(Reg, RegState::Kill) 825 .addImm(AlignMask) 826 .add(predOps(ARMCC::AL)) 827 .add(condCodeOp()); 828 } else { 829 assert(!MustBeSingleInstruction && 830 "Shouldn't call emitAligningInstructions demanding a single " 831 "instruction to be emitted for large stack alignment for a target " 832 "without BFC."); 833 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg) 834 .addReg(Reg, RegState::Kill) 835 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero)) 836 .add(predOps(ARMCC::AL)) 837 .add(condCodeOp()); 838 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg) 839 .addReg(Reg, RegState::Kill) 840 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero)) 841 .add(predOps(ARMCC::AL)) 842 .add(condCodeOp()); 843 } 844 } else { 845 // Since this is only reached for Thumb-2 targets, the BFC instruction 846 // should always be available. 847 assert(CanUseBFC); 848 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg) 849 .addReg(Reg, RegState::Kill) 850 .addImm(~AlignMask) 851 .add(predOps(ARMCC::AL)); 852 } 853 } 854 855 /// We need the offset of the frame pointer relative to other MachineFrameInfo 856 /// offsets which are encoded relative to SP at function begin. 857 /// See also emitPrologue() for how the FP is set up. 858 /// Unfortunately we cannot determine this value in determineCalleeSaves() yet 859 /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use 860 /// this to produce a conservative estimate that we check in an assert() later. 861 static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI, 862 const MachineFunction &MF) { 863 ARMSubtarget::PushPopSplitVariation PushPopSplit = 864 STI.getPushPopSplitVariation(MF); 865 // For Thumb1, push.w isn't available, so the first push will always push 866 // r7 and lr onto the stack first. 867 if (AFI.isThumb1OnlyFunction()) 868 return -AFI.getArgRegsSaveSize() - (2 * 4); 869 // This is a conservative estimation: Assume the frame pointer being r7 and 870 // pc("r15") up to r8 getting spilled before (= 8 registers). 871 int MaxRegBytes = 8 * 4; 872 if (PushPopSplit == ARMSubtarget::SplitR11AAPCSSignRA) 873 // Here, r11 can be stored below all of r4-r15. 874 MaxRegBytes = 11 * 4; 875 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) { 876 // Here, r11 can be stored below all of r4-r15 plus d8-d15. 877 MaxRegBytes = 11 * 4 + 8 * 8; 878 } 879 int FPCXTSaveSize = 880 (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0; 881 return -FPCXTSaveSize - AFI.getArgRegsSaveSize() - MaxRegBytes; 882 } 883 884 void ARMFrameLowering::emitPrologue(MachineFunction &MF, 885 MachineBasicBlock &MBB) const { 886 MachineBasicBlock::iterator MBBI = MBB.begin(); 887 MachineFrameInfo &MFI = MF.getFrameInfo(); 888 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 889 MCContext &Context = MF.getContext(); 890 const TargetMachine &TM = MF.getTarget(); 891 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 892 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo(); 893 const ARMBaseInstrInfo &TII = *STI.getInstrInfo(); 894 assert(!AFI->isThumb1OnlyFunction() && 895 "This emitPrologue does not support Thumb1!"); 896 bool isARM = !AFI->isThumbFunction(); 897 Align Alignment = STI.getFrameLowering()->getStackAlign(); 898 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(); 899 unsigned NumBytes = MFI.getStackSize(); 900 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 901 int FPCXTSaveSize = 0; 902 bool NeedsWinCFI = needsWinCFI(MF); 903 ARMSubtarget::PushPopSplitVariation PushPopSplit = 904 STI.getPushPopSplitVariation(MF); 905 906 LLVM_DEBUG(dbgs() << "Emitting prologue for " << MF.getName() << "\n"); 907 908 // Debug location must be unknown since the first debug location is used 909 // to determine the end of the prologue. 910 DebugLoc dl; 911 912 Register FramePtr = RegInfo->getFrameRegister(MF); 913 914 // Determine the sizes of each callee-save spill areas and record which frame 915 // belongs to which callee-save spill areas. 916 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0; 917 int FramePtrSpillFI = 0; 918 int D8SpillFI = 0; 919 920 // All calls are tail calls in GHC calling conv, and functions have no 921 // prologue/epilogue. 922 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 923 return; 924 925 StackAdjustingInsts DefCFAOffsetCandidates; 926 bool HasFP = hasFP(MF); 927 928 if (!AFI->hasStackFrame() && 929 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) { 930 if (NumBytes != 0) { 931 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 932 MachineInstr::FrameSetup); 933 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes, true); 934 } 935 if (!NeedsWinCFI) 936 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP); 937 if (NeedsWinCFI && MBBI != MBB.begin()) { 938 insertSEHRange(MBB, {}, MBBI, TII, MachineInstr::FrameSetup); 939 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_PrologEnd)) 940 .setMIFlag(MachineInstr::FrameSetup); 941 MF.setHasWinCFI(true); 942 } 943 return; 944 } 945 946 // Determine spill area sizes, and some important frame indices. 947 SpillArea FramePtrSpillArea; 948 bool BeforeFPPush = true; 949 for (const CalleeSavedInfo &I : CSI) { 950 Register Reg = I.getReg(); 951 int FI = I.getFrameIdx(); 952 953 SpillArea Area = getSpillArea(Reg, PushPopSplit, 954 AFI->getNumAlignedDPRCS2Regs(), RegInfo); 955 956 if (Reg == FramePtr) { 957 FramePtrSpillFI = FI; 958 FramePtrSpillArea = Area; 959 } 960 if (Reg == ARM::D8) 961 D8SpillFI = FI; 962 963 switch (Area) { 964 case SpillArea::FPCXT: 965 FPCXTSaveSize += 4; 966 break; 967 case SpillArea::GPRCS1: 968 GPRCS1Size += 4; 969 break; 970 case SpillArea::GPRCS2: 971 GPRCS2Size += 4; 972 break; 973 case SpillArea::DPRCS1: 974 DPRCSSize += 8; 975 break; 976 case SpillArea::DPRCS2: 977 break; 978 } 979 } 980 981 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push; 982 983 // Move past the PAC computation. 984 if (AFI->shouldSignReturnAddress()) 985 LastPush = MBBI++; 986 987 // Move past FPCXT area. 988 if (FPCXTSaveSize > 0) { 989 LastPush = MBBI++; 990 DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, BeforeFPPush); 991 } 992 993 // Allocate the vararg register save area. 994 if (ArgRegsSaveSize) { 995 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize, 996 MachineInstr::FrameSetup); 997 LastPush = std::prev(MBBI); 998 DefCFAOffsetCandidates.addInst(LastPush, ArgRegsSaveSize, BeforeFPPush); 999 } 1000 1001 // Move past area 1. 1002 if (GPRCS1Size > 0) { 1003 GPRCS1Push = LastPush = MBBI++; 1004 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, BeforeFPPush); 1005 if (FramePtrSpillArea == SpillArea::GPRCS1) 1006 BeforeFPPush = false; 1007 } 1008 1009 // Determine starting offsets of spill areas. These offsets are all positive 1010 // offsets from the bottom of the lowest-addressed callee-save area 1011 // (excluding DPRCS2, which is th the re-aligned stack region) to the bottom 1012 // of the spill area in question. 1013 unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize; 1014 unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size; 1015 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size; 1016 Align DPRAlign = DPRCSSize ? std::min(Align(8), Alignment) : Align(4); 1017 unsigned DPRGapSize = GPRCS1Size + FPCXTSaveSize + ArgRegsSaveSize; 1018 if (PushPopSplit != ARMSubtarget::SplitR11WindowsSEH) { 1019 DPRGapSize += GPRCS2Size; 1020 } 1021 DPRGapSize %= DPRAlign.value(); 1022 1023 unsigned DPRCSOffset; 1024 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) { 1025 DPRCSOffset = GPRCS1Offset - DPRGapSize - DPRCSSize; 1026 GPRCS2Offset = DPRCSOffset - GPRCS2Size; 1027 } else { 1028 DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize; 1029 } 1030 if (HasFP) { 1031 // Offset from the CFA to the saved frame pointer, will be negative. 1032 [[maybe_unused]] int FPOffset = MFI.getObjectOffset(FramePtrSpillFI); 1033 LLVM_DEBUG(dbgs() << "FramePtrSpillFI: " << FramePtrSpillFI 1034 << ", FPOffset: " << FPOffset << "\n"); 1035 assert(getMaxFPOffset(STI, *AFI, MF) <= FPOffset && 1036 "Max FP estimation is wrong"); 1037 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) + 1038 NumBytes); 1039 } 1040 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset); 1041 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset); 1042 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset); 1043 1044 // Move GPRCS2, unless using SplitR11WindowsSEH, in which case it will be 1045 // after DPRCS1. 1046 if (GPRCS2Size > 0 && PushPopSplit != ARMSubtarget::SplitR11WindowsSEH) { 1047 GPRCS2Push = LastPush = MBBI++; 1048 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size, BeforeFPPush); 1049 if (FramePtrSpillArea == SpillArea::GPRCS2) 1050 BeforeFPPush = false; 1051 } 1052 1053 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our 1054 // .cfi_offset operations will reflect that. 1055 if (DPRGapSize) { 1056 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs"); 1057 if (LastPush != MBB.end() && 1058 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize)) 1059 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize); 1060 else { 1061 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize, 1062 MachineInstr::FrameSetup); 1063 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize, BeforeFPPush); 1064 } 1065 } 1066 1067 // Move past DPRCS1. 1068 if (DPRCSSize > 0) { 1069 // Since vpush register list cannot have gaps, there may be multiple vpush 1070 // instructions in the prologue. 1071 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) { 1072 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI), 1073 BeforeFPPush); 1074 LastPush = MBBI++; 1075 } 1076 } 1077 1078 // Move past the aligned DPRCS2 area. 1079 if (AFI->getNumAlignedDPRCS2Regs() > 0) { 1080 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs()); 1081 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and 1082 // leaves the stack pointer pointing to the DPRCS2 area. 1083 // 1084 // Adjust NumBytes to represent the stack slots below the DPRCS2 area. 1085 NumBytes += MFI.getObjectOffset(D8SpillFI); 1086 } else 1087 NumBytes = DPRCSOffset; 1088 1089 // Move GPRCS2, if using using SplitR11WindowsSEH. 1090 if (GPRCS2Size > 0 && PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) { 1091 GPRCS2Push = LastPush = MBBI++; 1092 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size, BeforeFPPush); 1093 if (FramePtrSpillArea == SpillArea::GPRCS2) 1094 BeforeFPPush = false; 1095 } 1096 1097 bool NeedsWinCFIStackAlloc = NeedsWinCFI; 1098 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH && HasFP) 1099 NeedsWinCFIStackAlloc = false; 1100 1101 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) { 1102 uint32_t NumWords = NumBytes >> 2; 1103 1104 if (NumWords < 65536) { 1105 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4) 1106 .addImm(NumWords) 1107 .setMIFlags(MachineInstr::FrameSetup) 1108 .add(predOps(ARMCC::AL)); 1109 } else { 1110 // Split into two instructions here, instead of using t2MOVi32imm, 1111 // to allow inserting accurate SEH instructions (including accurate 1112 // instruction size for each of them). 1113 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4) 1114 .addImm(NumWords & 0xffff) 1115 .setMIFlags(MachineInstr::FrameSetup) 1116 .add(predOps(ARMCC::AL)); 1117 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVTi16), ARM::R4) 1118 .addReg(ARM::R4) 1119 .addImm(NumWords >> 16) 1120 .setMIFlags(MachineInstr::FrameSetup) 1121 .add(predOps(ARMCC::AL)); 1122 } 1123 1124 switch (TM.getCodeModel()) { 1125 case CodeModel::Tiny: 1126 llvm_unreachable("Tiny code model not available on ARM."); 1127 case CodeModel::Small: 1128 case CodeModel::Medium: 1129 case CodeModel::Kernel: 1130 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL)) 1131 .add(predOps(ARMCC::AL)) 1132 .addExternalSymbol("__chkstk") 1133 .addReg(ARM::R4, RegState::Implicit) 1134 .setMIFlags(MachineInstr::FrameSetup); 1135 break; 1136 case CodeModel::Large: 1137 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12) 1138 .addExternalSymbol("__chkstk") 1139 .setMIFlags(MachineInstr::FrameSetup); 1140 1141 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr)) 1142 .add(predOps(ARMCC::AL)) 1143 .addReg(ARM::R12, RegState::Kill) 1144 .addReg(ARM::R4, RegState::Implicit) 1145 .setMIFlags(MachineInstr::FrameSetup); 1146 break; 1147 } 1148 1149 MachineInstrBuilder Instr, SEH; 1150 Instr = BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP) 1151 .addReg(ARM::SP, RegState::Kill) 1152 .addReg(ARM::R4, RegState::Kill) 1153 .setMIFlags(MachineInstr::FrameSetup) 1154 .add(predOps(ARMCC::AL)) 1155 .add(condCodeOp()); 1156 if (NeedsWinCFIStackAlloc) { 1157 SEH = BuildMI(MF, dl, TII.get(ARM::SEH_StackAlloc)) 1158 .addImm(NumBytes) 1159 .addImm(/*Wide=*/1) 1160 .setMIFlags(MachineInstr::FrameSetup); 1161 MBB.insertAfter(Instr, SEH); 1162 } 1163 NumBytes = 0; 1164 } 1165 1166 if (NumBytes) { 1167 // Adjust SP after all the callee-save spills. 1168 if (AFI->getNumAlignedDPRCS2Regs() == 0 && 1169 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes)) 1170 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes); 1171 else { 1172 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes, 1173 MachineInstr::FrameSetup); 1174 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes); 1175 } 1176 1177 if (HasFP && isARM) 1178 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24 1179 // Note it's not safe to do this in Thumb2 mode because it would have 1180 // taken two instructions: 1181 // mov sp, r7 1182 // sub sp, #24 1183 // If an interrupt is taken between the two instructions, then sp is in 1184 // an inconsistent state (pointing to the middle of callee-saved area). 1185 // The interrupt handler can end up clobbering the registers. 1186 AFI->setShouldRestoreSPFromFP(true); 1187 } 1188 1189 // Set FP to point to the stack slot that contains the previous FP. 1190 // For iOS, FP is R7, which has now been stored in spill area 1. 1191 // Otherwise, if this is not iOS, all the callee-saved registers go 1192 // into spill area 1, including the FP in R11. In either case, it 1193 // is in area one and the adjustment needs to take place just after 1194 // that push. 1195 MachineBasicBlock::iterator AfterPush; 1196 if (HasFP) { 1197 MachineBasicBlock::iterator FPPushInst; 1198 // Offset from SP immediately after the push which saved the FP to the FP 1199 // save slot. 1200 int64_t FPOffsetAfterPush; 1201 switch (FramePtrSpillArea) { 1202 case SpillArea::GPRCS1: 1203 FPPushInst = GPRCS1Push; 1204 FPOffsetAfterPush = MFI.getObjectOffset(FramePtrSpillFI) + 1205 ArgRegsSaveSize + FPCXTSaveSize + 1206 sizeOfSPAdjustment(*FPPushInst); 1207 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS1, offset " 1208 << FPOffsetAfterPush << " after that push\n"); 1209 break; 1210 case SpillArea::GPRCS2: 1211 FPPushInst = GPRCS2Push; 1212 FPOffsetAfterPush = MFI.getObjectOffset(FramePtrSpillFI) + 1213 ArgRegsSaveSize + FPCXTSaveSize + GPRCS1Size + 1214 sizeOfSPAdjustment(*FPPushInst); 1215 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) 1216 FPOffsetAfterPush += DPRCSSize + DPRGapSize; 1217 LLVM_DEBUG(dbgs() << "Frame pointer in GPRCS2, offset " 1218 << FPOffsetAfterPush << " after that push\n"); 1219 break; 1220 default: 1221 llvm_unreachable("frame pointer in unknown spill area"); 1222 break; 1223 } 1224 AfterPush = std::next(FPPushInst); 1225 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) 1226 assert(FPOffsetAfterPush == 0); 1227 1228 // Emit the MOV or ADD to set up the frame pointer register. 1229 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush, dl, TII, 1230 FramePtr, ARM::SP, FPOffsetAfterPush, 1231 MachineInstr::FrameSetup); 1232 1233 if (!NeedsWinCFI) { 1234 // Emit DWARF info to find the CFA using the frame pointer from this 1235 // point onward. 1236 if (FPOffsetAfterPush != 0) { 1237 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa( 1238 nullptr, MRI->getDwarfRegNum(FramePtr, true), 1239 -MFI.getObjectOffset(FramePtrSpillFI))); 1240 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1241 .addCFIIndex(CFIIndex) 1242 .setMIFlags(MachineInstr::FrameSetup); 1243 } else { 1244 unsigned CFIIndex = 1245 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister( 1246 nullptr, MRI->getDwarfRegNum(FramePtr, true))); 1247 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1248 .addCFIIndex(CFIIndex) 1249 .setMIFlags(MachineInstr::FrameSetup); 1250 } 1251 } 1252 } 1253 1254 // Emit a SEH opcode indicating the prologue end. The rest of the prologue 1255 // instructions below don't need to be replayed to unwind the stack. 1256 if (NeedsWinCFI && MBBI != MBB.begin()) { 1257 MachineBasicBlock::iterator End = MBBI; 1258 if (HasFP && PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) 1259 End = AfterPush; 1260 insertSEHRange(MBB, {}, End, TII, MachineInstr::FrameSetup); 1261 BuildMI(MBB, End, dl, TII.get(ARM::SEH_PrologEnd)) 1262 .setMIFlag(MachineInstr::FrameSetup); 1263 MF.setHasWinCFI(true); 1264 } 1265 1266 // Now that the prologue's actual instructions are finalised, we can insert 1267 // the necessary DWARF cf instructions to describe the situation. Start by 1268 // recording where each register ended up: 1269 if (!NeedsWinCFI) { 1270 for (const auto &Entry : reverse(CSI)) { 1271 Register Reg = Entry.getReg(); 1272 int FI = Entry.getFrameIdx(); 1273 MachineBasicBlock::iterator CFIPos; 1274 switch (getSpillArea(Reg, PushPopSplit, AFI->getNumAlignedDPRCS2Regs(), 1275 RegInfo)) { 1276 case SpillArea::GPRCS1: 1277 CFIPos = std::next(GPRCS1Push); 1278 break; 1279 case SpillArea::GPRCS2: 1280 CFIPos = std::next(GPRCS2Push); 1281 break; 1282 case SpillArea::DPRCS1: 1283 CFIPos = std::next(LastPush); 1284 break; 1285 case SpillArea::FPCXT: 1286 case SpillArea::DPRCS2: 1287 // FPCXT and DPRCS2 are not represented in the DWARF info. 1288 break; 1289 } 1290 1291 if (CFIPos.isValid()) { 1292 int CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 1293 nullptr, 1294 MRI->getDwarfRegNum(Reg == ARM::R12 ? ARM::RA_AUTH_CODE : Reg, 1295 true), 1296 MFI.getObjectOffset(FI))); 1297 BuildMI(MBB, CFIPos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION)) 1298 .addCFIIndex(CFIIndex) 1299 .setMIFlags(MachineInstr::FrameSetup); 1300 } 1301 } 1302 } 1303 1304 // Now we can emit descriptions of where the canonical frame address was 1305 // throughout the process. If we have a frame pointer, it takes over the job 1306 // half-way through, so only the first few .cfi_def_cfa_offset instructions 1307 // actually get emitted. 1308 if (!NeedsWinCFI) { 1309 LLVM_DEBUG(DefCFAOffsetCandidates.dump()); 1310 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP); 1311 } 1312 1313 if (STI.isTargetELF() && hasFP(MF)) 1314 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() - 1315 AFI->getFramePtrSpillOffset()); 1316 1317 AFI->setFPCXTSaveAreaSize(FPCXTSaveSize); 1318 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size); 1319 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size); 1320 AFI->setDPRCalleeSavedGapSize(DPRGapSize); 1321 AFI->setDPRCalleeSavedAreaSize(DPRCSSize); 1322 1323 // If we need dynamic stack realignment, do it here. Be paranoid and make 1324 // sure if we also have VLAs, we have a base pointer for frame access. 1325 // If aligned NEON registers were spilled, the stack has already been 1326 // realigned. 1327 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) { 1328 Align MaxAlign = MFI.getMaxAlign(); 1329 assert(!AFI->isThumb1OnlyFunction()); 1330 if (!AFI->isThumbFunction()) { 1331 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign, 1332 false); 1333 } else { 1334 // We cannot use sp as source/dest register here, thus we're using r4 to 1335 // perform the calculations. We're emitting the following sequence: 1336 // mov r4, sp 1337 // -- use emitAligningInstructions to produce best sequence to zero 1338 // -- out lower bits in r4 1339 // mov sp, r4 1340 // FIXME: It will be better just to find spare register here. 1341 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4) 1342 .addReg(ARM::SP, RegState::Kill) 1343 .add(predOps(ARMCC::AL)); 1344 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign, 1345 false); 1346 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 1347 .addReg(ARM::R4, RegState::Kill) 1348 .add(predOps(ARMCC::AL)); 1349 } 1350 1351 AFI->setShouldRestoreSPFromFP(true); 1352 } 1353 1354 // If we need a base pointer, set it up here. It's whatever the value 1355 // of the stack pointer is at this point. Any variable size objects 1356 // will be allocated after this, so we can still use the base pointer 1357 // to reference locals. 1358 // FIXME: Clarify FrameSetup flags here. 1359 if (RegInfo->hasBasePointer(MF)) { 1360 if (isARM) 1361 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister()) 1362 .addReg(ARM::SP) 1363 .add(predOps(ARMCC::AL)) 1364 .add(condCodeOp()); 1365 else 1366 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister()) 1367 .addReg(ARM::SP) 1368 .add(predOps(ARMCC::AL)); 1369 } 1370 1371 // If the frame has variable sized objects then the epilogue must restore 1372 // the sp from fp. We can assume there's an FP here since hasFP already 1373 // checks for hasVarSizedObjects. 1374 if (MFI.hasVarSizedObjects()) 1375 AFI->setShouldRestoreSPFromFP(true); 1376 } 1377 1378 void ARMFrameLowering::emitEpilogue(MachineFunction &MF, 1379 MachineBasicBlock &MBB) const { 1380 MachineFrameInfo &MFI = MF.getFrameInfo(); 1381 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1382 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 1383 const ARMBaseInstrInfo &TII = 1384 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 1385 assert(!AFI->isThumb1OnlyFunction() && 1386 "This emitEpilogue does not support Thumb1!"); 1387 bool isARM = !AFI->isThumbFunction(); 1388 ARMSubtarget::PushPopSplitVariation PushPopSplit = 1389 STI.getPushPopSplitVariation(MF); 1390 1391 LLVM_DEBUG(dbgs() << "Emitting epilogue for " << MF.getName() << "\n"); 1392 1393 // Amount of stack space we reserved next to incoming args for either 1394 // varargs registers or stack arguments in tail calls made by this function. 1395 unsigned ReservedArgStack = AFI->getArgRegsSaveSize(); 1396 1397 // How much of the stack used by incoming arguments this function is expected 1398 // to restore in this particular epilogue. 1399 int IncomingArgStackToRestore = getArgumentStackToRestore(MF, MBB); 1400 int NumBytes = (int)MFI.getStackSize(); 1401 Register FramePtr = RegInfo->getFrameRegister(MF); 1402 1403 // All calls are tail calls in GHC calling conv, and functions have no 1404 // prologue/epilogue. 1405 if (MF.getFunction().getCallingConv() == CallingConv::GHC) 1406 return; 1407 1408 // First put ourselves on the first (from top) terminator instructions. 1409 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator(); 1410 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); 1411 1412 MachineBasicBlock::iterator RangeStart; 1413 if (!AFI->hasStackFrame()) { 1414 if (MF.hasWinCFI()) { 1415 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart)) 1416 .setMIFlag(MachineInstr::FrameDestroy); 1417 RangeStart = initMBBRange(MBB, MBBI); 1418 } 1419 1420 if (NumBytes + IncomingArgStackToRestore != 0) 1421 emitSPUpdate(isARM, MBB, MBBI, dl, TII, 1422 NumBytes + IncomingArgStackToRestore, 1423 MachineInstr::FrameDestroy); 1424 } else { 1425 // Unwind MBBI to point to first LDR / VLDRD. 1426 if (MBBI != MBB.begin()) { 1427 do { 1428 --MBBI; 1429 } while (MBBI != MBB.begin() && 1430 MBBI->getFlag(MachineInstr::FrameDestroy)); 1431 if (!MBBI->getFlag(MachineInstr::FrameDestroy)) 1432 ++MBBI; 1433 } 1434 1435 if (MF.hasWinCFI()) { 1436 BuildMI(MBB, MBBI, dl, TII.get(ARM::SEH_EpilogStart)) 1437 .setMIFlag(MachineInstr::FrameDestroy); 1438 RangeStart = initMBBRange(MBB, MBBI); 1439 } 1440 1441 // Move SP to start of FP callee save spill area. 1442 NumBytes -= (ReservedArgStack + 1443 AFI->getFPCXTSaveAreaSize() + 1444 AFI->getGPRCalleeSavedArea1Size() + 1445 AFI->getGPRCalleeSavedArea2Size() + 1446 AFI->getDPRCalleeSavedGapSize() + 1447 AFI->getDPRCalleeSavedAreaSize()); 1448 1449 // Reset SP based on frame pointer only if the stack frame extends beyond 1450 // frame pointer stack slot or target is ELF and the function has FP. 1451 if (AFI->shouldRestoreSPFromFP()) { 1452 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes; 1453 if (NumBytes) { 1454 if (isARM) 1455 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes, 1456 ARMCC::AL, 0, TII, 1457 MachineInstr::FrameDestroy); 1458 else { 1459 // It's not possible to restore SP from FP in a single instruction. 1460 // For iOS, this looks like: 1461 // mov sp, r7 1462 // sub sp, #24 1463 // This is bad, if an interrupt is taken after the mov, sp is in an 1464 // inconsistent state. 1465 // Use the first callee-saved register as a scratch register. 1466 assert(!MFI.getPristineRegs(MF).test(ARM::R4) && 1467 "No scratch register to restore SP from FP!"); 1468 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes, 1469 ARMCC::AL, 0, TII, MachineInstr::FrameDestroy); 1470 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 1471 .addReg(ARM::R4) 1472 .add(predOps(ARMCC::AL)) 1473 .setMIFlag(MachineInstr::FrameDestroy); 1474 } 1475 } else { 1476 // Thumb2 or ARM. 1477 if (isARM) 1478 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP) 1479 .addReg(FramePtr) 1480 .add(predOps(ARMCC::AL)) 1481 .add(condCodeOp()) 1482 .setMIFlag(MachineInstr::FrameDestroy); 1483 else 1484 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP) 1485 .addReg(FramePtr) 1486 .add(predOps(ARMCC::AL)) 1487 .setMIFlag(MachineInstr::FrameDestroy); 1488 } 1489 } else if (NumBytes && 1490 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes)) 1491 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes, 1492 MachineInstr::FrameDestroy); 1493 1494 // Increment past our save areas. 1495 if (AFI->getGPRCalleeSavedArea2Size() && 1496 PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) 1497 MBBI++; 1498 1499 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) { 1500 MBBI++; 1501 // Since vpop register list cannot have gaps, there may be multiple vpop 1502 // instructions in the epilogue. 1503 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD) 1504 MBBI++; 1505 } 1506 if (AFI->getDPRCalleeSavedGapSize()) { 1507 assert(AFI->getDPRCalleeSavedGapSize() == 4 && 1508 "unexpected DPR alignment gap"); 1509 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(), 1510 MachineInstr::FrameDestroy); 1511 } 1512 1513 if (AFI->getGPRCalleeSavedArea2Size() && 1514 PushPopSplit != ARMSubtarget::SplitR11WindowsSEH) 1515 MBBI++; 1516 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++; 1517 1518 if (ReservedArgStack || IncomingArgStackToRestore) { 1519 assert((int)ReservedArgStack + IncomingArgStackToRestore >= 0 && 1520 "attempting to restore negative stack amount"); 1521 emitSPUpdate(isARM, MBB, MBBI, dl, TII, 1522 ReservedArgStack + IncomingArgStackToRestore, 1523 MachineInstr::FrameDestroy); 1524 } 1525 1526 // Validate PAC, It should have been already popped into R12. For CMSE entry 1527 // function, the validation instruction is emitted during expansion of the 1528 // tBXNS_RET, since the validation must use the value of SP at function 1529 // entry, before saving, resp. after restoring, FPCXTNS. 1530 if (AFI->shouldSignReturnAddress() && !AFI->isCmseNSEntryFunction()) 1531 BuildMI(MBB, MBBI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2AUT)); 1532 } 1533 1534 if (MF.hasWinCFI()) { 1535 insertSEHRange(MBB, RangeStart, MBB.end(), TII, MachineInstr::FrameDestroy); 1536 BuildMI(MBB, MBB.end(), dl, TII.get(ARM::SEH_EpilogEnd)) 1537 .setMIFlag(MachineInstr::FrameDestroy); 1538 } 1539 } 1540 1541 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for 1542 /// debug info. It's the same as what we use for resolving the code-gen 1543 /// references for now. FIXME: This can go wrong when references are 1544 /// SP-relative and simple call frames aren't used. 1545 StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, 1546 int FI, 1547 Register &FrameReg) const { 1548 return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0)); 1549 } 1550 1551 int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF, 1552 int FI, Register &FrameReg, 1553 int SPAdj) const { 1554 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1555 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>( 1556 MF.getSubtarget().getRegisterInfo()); 1557 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1558 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize(); 1559 int FPOffset = Offset - AFI->getFramePtrSpillOffset(); 1560 bool isFixed = MFI.isFixedObjectIndex(FI); 1561 1562 FrameReg = ARM::SP; 1563 Offset += SPAdj; 1564 1565 // SP can move around if there are allocas. We may also lose track of SP 1566 // when emergency spilling inside a non-reserved call frame setup. 1567 bool hasMovingSP = !hasReservedCallFrame(MF); 1568 1569 // When dynamically realigning the stack, use the frame pointer for 1570 // parameters, and the stack/base pointer for locals. 1571 if (RegInfo->hasStackRealignment(MF)) { 1572 assert(hasFP(MF) && "dynamic stack realignment without a FP!"); 1573 if (isFixed) { 1574 FrameReg = RegInfo->getFrameRegister(MF); 1575 Offset = FPOffset; 1576 } else if (hasMovingSP) { 1577 assert(RegInfo->hasBasePointer(MF) && 1578 "VLAs and dynamic stack alignment, but missing base pointer!"); 1579 FrameReg = RegInfo->getBaseRegister(); 1580 Offset -= SPAdj; 1581 } 1582 return Offset; 1583 } 1584 1585 // If there is a frame pointer, use it when we can. 1586 if (hasFP(MF) && AFI->hasStackFrame()) { 1587 // Use frame pointer to reference fixed objects. Use it for locals if 1588 // there are VLAs (and thus the SP isn't reliable as a base). 1589 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) { 1590 FrameReg = RegInfo->getFrameRegister(MF); 1591 return FPOffset; 1592 } else if (hasMovingSP) { 1593 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!"); 1594 if (AFI->isThumb2Function()) { 1595 // Try to use the frame pointer if we can, else use the base pointer 1596 // since it's available. This is handy for the emergency spill slot, in 1597 // particular. 1598 if (FPOffset >= -255 && FPOffset < 0) { 1599 FrameReg = RegInfo->getFrameRegister(MF); 1600 return FPOffset; 1601 } 1602 } 1603 } else if (AFI->isThumbFunction()) { 1604 // Prefer SP to base pointer, if the offset is suitably aligned and in 1605 // range as the effective range of the immediate offset is bigger when 1606 // basing off SP. 1607 // Use add <rd>, sp, #<imm8> 1608 // ldr <rd>, [sp, #<imm8>] 1609 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020) 1610 return Offset; 1611 // In Thumb2 mode, the negative offset is very limited. Try to avoid 1612 // out of range references. ldr <rt>,[<rn>, #-<imm8>] 1613 if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) { 1614 FrameReg = RegInfo->getFrameRegister(MF); 1615 return FPOffset; 1616 } 1617 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) { 1618 // Otherwise, use SP or FP, whichever is closer to the stack slot. 1619 FrameReg = RegInfo->getFrameRegister(MF); 1620 return FPOffset; 1621 } 1622 } 1623 // Use the base pointer if we have one. 1624 // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper? 1625 // That can happen if we forced a base pointer for a large call frame. 1626 if (RegInfo->hasBasePointer(MF)) { 1627 FrameReg = RegInfo->getBaseRegister(); 1628 Offset -= SPAdj; 1629 } 1630 return Offset; 1631 } 1632 1633 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB, 1634 MachineBasicBlock::iterator MI, 1635 ArrayRef<CalleeSavedInfo> CSI, 1636 unsigned StmOpc, unsigned StrOpc, 1637 bool NoGap, 1638 function_ref<bool(unsigned)> Func) const { 1639 MachineFunction &MF = *MBB.getParent(); 1640 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1641 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 1642 1643 DebugLoc DL; 1644 1645 using RegAndKill = std::pair<unsigned, bool>; 1646 1647 SmallVector<RegAndKill, 4> Regs; 1648 unsigned i = CSI.size(); 1649 while (i != 0) { 1650 unsigned LastReg = 0; 1651 for (; i != 0; --i) { 1652 Register Reg = CSI[i-1].getReg(); 1653 if (!Func(Reg)) 1654 continue; 1655 1656 const MachineRegisterInfo &MRI = MF.getRegInfo(); 1657 bool isLiveIn = MRI.isLiveIn(Reg); 1658 if (!isLiveIn && !MRI.isReserved(Reg)) 1659 MBB.addLiveIn(Reg); 1660 // If NoGap is true, push consecutive registers and then leave the rest 1661 // for other instructions. e.g. 1662 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11} 1663 if (NoGap && LastReg && LastReg != Reg-1) 1664 break; 1665 LastReg = Reg; 1666 // Do not set a kill flag on values that are also marked as live-in. This 1667 // happens with the @llvm-returnaddress intrinsic and with arguments 1668 // passed in callee saved registers. 1669 // Omitting the kill flags is conservatively correct even if the live-in 1670 // is not used after all. 1671 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn)); 1672 } 1673 1674 if (Regs.empty()) 1675 continue; 1676 1677 llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) { 1678 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first); 1679 }); 1680 1681 if (Regs.size() > 1 || StrOpc== 0) { 1682 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP) 1683 .addReg(ARM::SP) 1684 .setMIFlags(MachineInstr::FrameSetup) 1685 .add(predOps(ARMCC::AL)); 1686 for (unsigned i = 0, e = Regs.size(); i < e; ++i) 1687 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second)); 1688 } else if (Regs.size() == 1) { 1689 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP) 1690 .addReg(Regs[0].first, getKillRegState(Regs[0].second)) 1691 .addReg(ARM::SP) 1692 .setMIFlags(MachineInstr::FrameSetup) 1693 .addImm(-4) 1694 .add(predOps(ARMCC::AL)); 1695 } 1696 Regs.clear(); 1697 1698 // Put any subsequent vpush instructions before this one: they will refer to 1699 // higher register numbers so need to be pushed first in order to preserve 1700 // monotonicity. 1701 if (MI != MBB.begin()) 1702 --MI; 1703 } 1704 } 1705 1706 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB, 1707 MachineBasicBlock::iterator MI, 1708 MutableArrayRef<CalleeSavedInfo> CSI, 1709 unsigned LdmOpc, unsigned LdrOpc, 1710 bool isVarArg, bool NoGap, 1711 function_ref<bool(unsigned)> Func) const { 1712 MachineFunction &MF = *MBB.getParent(); 1713 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1714 const TargetRegisterInfo &TRI = *STI.getRegisterInfo(); 1715 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1716 bool hasPAC = AFI->shouldSignReturnAddress(); 1717 DebugLoc DL; 1718 bool isTailCall = false; 1719 bool isInterrupt = false; 1720 bool isTrap = false; 1721 bool isCmseEntry = false; 1722 ARMSubtarget::PushPopSplitVariation PushPopSplit = 1723 STI.getPushPopSplitVariation(MF); 1724 if (MBB.end() != MI) { 1725 DL = MI->getDebugLoc(); 1726 unsigned RetOpcode = MI->getOpcode(); 1727 isTailCall = 1728 (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri || 1729 RetOpcode == ARM::TCRETURNrinotr12); 1730 isInterrupt = 1731 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR; 1732 isTrap = 1733 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl || 1734 RetOpcode == ARM::tTRAP; 1735 isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET); 1736 } 1737 1738 SmallVector<unsigned, 4> Regs; 1739 unsigned i = CSI.size(); 1740 while (i != 0) { 1741 unsigned LastReg = 0; 1742 bool DeleteRet = false; 1743 for (; i != 0; --i) { 1744 CalleeSavedInfo &Info = CSI[i-1]; 1745 Register Reg = Info.getReg(); 1746 if (!Func(Reg)) 1747 continue; 1748 1749 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt && 1750 !isCmseEntry && !isTrap && AFI->getArgumentStackToRestore() == 0 && 1751 STI.hasV5TOps() && MBB.succ_empty() && !hasPAC && 1752 (PushPopSplit != ARMSubtarget::SplitR11WindowsSEH && 1753 PushPopSplit != ARMSubtarget::SplitR11AAPCSSignRA)) { 1754 Reg = ARM::PC; 1755 // Fold the return instruction into the LDM. 1756 DeleteRet = true; 1757 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET; 1758 } 1759 1760 // If NoGap is true, pop consecutive registers and then leave the rest 1761 // for other instructions. e.g. 1762 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11} 1763 if (NoGap && LastReg && LastReg != Reg-1) 1764 break; 1765 1766 LastReg = Reg; 1767 Regs.push_back(Reg); 1768 } 1769 1770 if (Regs.empty()) 1771 continue; 1772 1773 llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) { 1774 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS); 1775 }); 1776 1777 if (Regs.size() > 1 || LdrOpc == 0) { 1778 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP) 1779 .addReg(ARM::SP) 1780 .add(predOps(ARMCC::AL)) 1781 .setMIFlags(MachineInstr::FrameDestroy); 1782 for (unsigned Reg : Regs) 1783 MIB.addReg(Reg, getDefRegState(true)); 1784 if (DeleteRet) { 1785 if (MI != MBB.end()) { 1786 MIB.copyImplicitOps(*MI); 1787 MI->eraseFromParent(); 1788 } 1789 } 1790 MI = MIB; 1791 } else if (Regs.size() == 1) { 1792 // If we adjusted the reg to PC from LR above, switch it back here. We 1793 // only do that for LDM. 1794 if (Regs[0] == ARM::PC) 1795 Regs[0] = ARM::LR; 1796 MachineInstrBuilder MIB = 1797 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0]) 1798 .addReg(ARM::SP, RegState::Define) 1799 .addReg(ARM::SP) 1800 .setMIFlags(MachineInstr::FrameDestroy); 1801 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once 1802 // that refactoring is complete (eventually). 1803 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) { 1804 MIB.addReg(0); 1805 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift)); 1806 } else 1807 MIB.addImm(4); 1808 MIB.add(predOps(ARMCC::AL)); 1809 } 1810 Regs.clear(); 1811 1812 // Put any subsequent vpop instructions after this one: they will refer to 1813 // higher register numbers so need to be popped afterwards. 1814 if (MI != MBB.end()) 1815 ++MI; 1816 } 1817 } 1818 1819 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers 1820 /// starting from d8. Also insert stack realignment code and leave the stack 1821 /// pointer pointing to the d8 spill slot. 1822 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB, 1823 MachineBasicBlock::iterator MI, 1824 unsigned NumAlignedDPRCS2Regs, 1825 ArrayRef<CalleeSavedInfo> CSI, 1826 const TargetRegisterInfo *TRI) { 1827 MachineFunction &MF = *MBB.getParent(); 1828 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 1829 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc(); 1830 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1831 MachineFrameInfo &MFI = MF.getFrameInfo(); 1832 1833 // Mark the D-register spill slots as properly aligned. Since MFI computes 1834 // stack slot layout backwards, this can actually mean that the d-reg stack 1835 // slot offsets can be wrong. The offset for d8 will always be correct. 1836 for (const CalleeSavedInfo &I : CSI) { 1837 unsigned DNum = I.getReg() - ARM::D8; 1838 if (DNum > NumAlignedDPRCS2Regs - 1) 1839 continue; 1840 int FI = I.getFrameIdx(); 1841 // The even-numbered registers will be 16-byte aligned, the odd-numbered 1842 // registers will be 8-byte aligned. 1843 MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16)); 1844 1845 // The stack slot for D8 needs to be maximally aligned because this is 1846 // actually the point where we align the stack pointer. MachineFrameInfo 1847 // computes all offsets relative to the incoming stack pointer which is a 1848 // bit weird when realigning the stack. Any extra padding for this 1849 // over-alignment is not realized because the code inserted below adjusts 1850 // the stack pointer by numregs * 8 before aligning the stack pointer. 1851 if (DNum == 0) 1852 MFI.setObjectAlignment(FI, MFI.getMaxAlign()); 1853 } 1854 1855 // Move the stack pointer to the d8 spill slot, and align it at the same 1856 // time. Leave the stack slot address in the scratch register r4. 1857 // 1858 // sub r4, sp, #numregs * 8 1859 // bic r4, r4, #align - 1 1860 // mov sp, r4 1861 // 1862 bool isThumb = AFI->isThumbFunction(); 1863 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 1864 AFI->setShouldRestoreSPFromFP(true); 1865 1866 // sub r4, sp, #numregs * 8 1867 // The immediate is <= 64, so it doesn't need any special encoding. 1868 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri; 1869 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 1870 .addReg(ARM::SP) 1871 .addImm(8 * NumAlignedDPRCS2Regs) 1872 .add(predOps(ARMCC::AL)) 1873 .add(condCodeOp()); 1874 1875 Align MaxAlign = MF.getFrameInfo().getMaxAlign(); 1876 // We must set parameter MustBeSingleInstruction to true, since 1877 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform 1878 // stack alignment. Luckily, this can always be done since all ARM 1879 // architecture versions that support Neon also support the BFC 1880 // instruction. 1881 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true); 1882 1883 // mov sp, r4 1884 // The stack pointer must be adjusted before spilling anything, otherwise 1885 // the stack slots could be clobbered by an interrupt handler. 1886 // Leave r4 live, it is used below. 1887 Opc = isThumb ? ARM::tMOVr : ARM::MOVr; 1888 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP) 1889 .addReg(ARM::R4) 1890 .add(predOps(ARMCC::AL)); 1891 if (!isThumb) 1892 MIB.add(condCodeOp()); 1893 1894 // Now spill NumAlignedDPRCS2Regs registers starting from d8. 1895 // r4 holds the stack slot address. 1896 unsigned NextReg = ARM::D8; 1897 1898 // 16-byte aligned vst1.64 with 4 d-regs and address writeback. 1899 // The writeback is only needed when emitting two vst1.64 instructions. 1900 if (NumAlignedDPRCS2Regs >= 6) { 1901 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1902 &ARM::QQPRRegClass); 1903 MBB.addLiveIn(SupReg); 1904 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4) 1905 .addReg(ARM::R4, RegState::Kill) 1906 .addImm(16) 1907 .addReg(NextReg) 1908 .addReg(SupReg, RegState::ImplicitKill) 1909 .add(predOps(ARMCC::AL)); 1910 NextReg += 4; 1911 NumAlignedDPRCS2Regs -= 4; 1912 } 1913 1914 // We won't modify r4 beyond this point. It currently points to the next 1915 // register to be spilled. 1916 unsigned R4BaseReg = NextReg; 1917 1918 // 16-byte aligned vst1.64 with 4 d-regs, no writeback. 1919 if (NumAlignedDPRCS2Regs >= 4) { 1920 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1921 &ARM::QQPRRegClass); 1922 MBB.addLiveIn(SupReg); 1923 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q)) 1924 .addReg(ARM::R4) 1925 .addImm(16) 1926 .addReg(NextReg) 1927 .addReg(SupReg, RegState::ImplicitKill) 1928 .add(predOps(ARMCC::AL)); 1929 NextReg += 4; 1930 NumAlignedDPRCS2Regs -= 4; 1931 } 1932 1933 // 16-byte aligned vst1.64 with 2 d-regs. 1934 if (NumAlignedDPRCS2Regs >= 2) { 1935 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 1936 &ARM::QPRRegClass); 1937 MBB.addLiveIn(SupReg); 1938 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64)) 1939 .addReg(ARM::R4) 1940 .addImm(16) 1941 .addReg(SupReg) 1942 .add(predOps(ARMCC::AL)); 1943 NextReg += 2; 1944 NumAlignedDPRCS2Regs -= 2; 1945 } 1946 1947 // Finally, use a vanilla vstr.64 for the odd last register. 1948 if (NumAlignedDPRCS2Regs) { 1949 MBB.addLiveIn(NextReg); 1950 // vstr.64 uses addrmode5 which has an offset scale of 4. 1951 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD)) 1952 .addReg(NextReg) 1953 .addReg(ARM::R4) 1954 .addImm((NextReg - R4BaseReg) * 2) 1955 .add(predOps(ARMCC::AL)); 1956 } 1957 1958 // The last spill instruction inserted should kill the scratch register r4. 1959 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 1960 } 1961 1962 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an 1963 /// iterator to the following instruction. 1964 static MachineBasicBlock::iterator 1965 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI, 1966 unsigned NumAlignedDPRCS2Regs) { 1967 // sub r4, sp, #numregs * 8 1968 // bic r4, r4, #align - 1 1969 // mov sp, r4 1970 ++MI; ++MI; ++MI; 1971 assert(MI->mayStore() && "Expecting spill instruction"); 1972 1973 // These switches all fall through. 1974 switch(NumAlignedDPRCS2Regs) { 1975 case 7: 1976 ++MI; 1977 assert(MI->mayStore() && "Expecting spill instruction"); 1978 [[fallthrough]]; 1979 default: 1980 ++MI; 1981 assert(MI->mayStore() && "Expecting spill instruction"); 1982 [[fallthrough]]; 1983 case 1: 1984 case 2: 1985 case 4: 1986 assert(MI->killsRegister(ARM::R4, /*TRI=*/nullptr) && "Missed kill flag"); 1987 ++MI; 1988 } 1989 return MI; 1990 } 1991 1992 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers 1993 /// starting from d8. These instructions are assumed to execute while the 1994 /// stack is still aligned, unlike the code inserted by emitPopInst. 1995 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB, 1996 MachineBasicBlock::iterator MI, 1997 unsigned NumAlignedDPRCS2Regs, 1998 ArrayRef<CalleeSavedInfo> CSI, 1999 const TargetRegisterInfo *TRI) { 2000 MachineFunction &MF = *MBB.getParent(); 2001 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2002 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc(); 2003 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 2004 2005 // Find the frame index assigned to d8. 2006 int D8SpillFI = 0; 2007 for (const CalleeSavedInfo &I : CSI) 2008 if (I.getReg() == ARM::D8) { 2009 D8SpillFI = I.getFrameIdx(); 2010 break; 2011 } 2012 2013 // Materialize the address of the d8 spill slot into the scratch register r4. 2014 // This can be fairly complicated if the stack frame is large, so just use 2015 // the normal frame index elimination mechanism to do it. This code runs as 2016 // the initial part of the epilog where the stack and base pointers haven't 2017 // been changed yet. 2018 bool isThumb = AFI->isThumbFunction(); 2019 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1"); 2020 2021 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri; 2022 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4) 2023 .addFrameIndex(D8SpillFI) 2024 .addImm(0) 2025 .add(predOps(ARMCC::AL)) 2026 .add(condCodeOp()); 2027 2028 // Now restore NumAlignedDPRCS2Regs registers starting from d8. 2029 unsigned NextReg = ARM::D8; 2030 2031 // 16-byte aligned vld1.64 with 4 d-regs and writeback. 2032 if (NumAlignedDPRCS2Regs >= 6) { 2033 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 2034 &ARM::QQPRRegClass); 2035 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg) 2036 .addReg(ARM::R4, RegState::Define) 2037 .addReg(ARM::R4, RegState::Kill) 2038 .addImm(16) 2039 .addReg(SupReg, RegState::ImplicitDefine) 2040 .add(predOps(ARMCC::AL)); 2041 NextReg += 4; 2042 NumAlignedDPRCS2Regs -= 4; 2043 } 2044 2045 // We won't modify r4 beyond this point. It currently points to the next 2046 // register to be spilled. 2047 unsigned R4BaseReg = NextReg; 2048 2049 // 16-byte aligned vld1.64 with 4 d-regs, no writeback. 2050 if (NumAlignedDPRCS2Regs >= 4) { 2051 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 2052 &ARM::QQPRRegClass); 2053 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg) 2054 .addReg(ARM::R4) 2055 .addImm(16) 2056 .addReg(SupReg, RegState::ImplicitDefine) 2057 .add(predOps(ARMCC::AL)); 2058 NextReg += 4; 2059 NumAlignedDPRCS2Regs -= 4; 2060 } 2061 2062 // 16-byte aligned vld1.64 with 2 d-regs. 2063 if (NumAlignedDPRCS2Regs >= 2) { 2064 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0, 2065 &ARM::QPRRegClass); 2066 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg) 2067 .addReg(ARM::R4) 2068 .addImm(16) 2069 .add(predOps(ARMCC::AL)); 2070 NextReg += 2; 2071 NumAlignedDPRCS2Regs -= 2; 2072 } 2073 2074 // Finally, use a vanilla vldr.64 for the remaining odd register. 2075 if (NumAlignedDPRCS2Regs) 2076 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg) 2077 .addReg(ARM::R4) 2078 .addImm(2 * (NextReg - R4BaseReg)) 2079 .add(predOps(ARMCC::AL)); 2080 2081 // Last store kills r4. 2082 std::prev(MI)->addRegisterKilled(ARM::R4, TRI); 2083 } 2084 2085 bool ARMFrameLowering::spillCalleeSavedRegisters( 2086 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 2087 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 2088 if (CSI.empty()) 2089 return false; 2090 2091 MachineFunction &MF = *MBB.getParent(); 2092 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2093 ARMSubtarget::PushPopSplitVariation PushPopSplit = 2094 STI.getPushPopSplitVariation(MF); 2095 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo(); 2096 2097 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD; 2098 unsigned PushOneOpc = AFI->isThumbFunction() ? 2099 ARM::t2STR_PRE : ARM::STR_PRE_IMM; 2100 unsigned FltOpc = ARM::VSTMDDB_UPD; 2101 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 2102 // Compute PAC in R12. 2103 if (AFI->shouldSignReturnAddress()) { 2104 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::t2PAC)) 2105 .setMIFlags(MachineInstr::FrameSetup); 2106 } 2107 // Save the non-secure floating point context. 2108 if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) { 2109 return C.getReg() == ARM::FPCXTNS; 2110 })) { 2111 BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre), 2112 ARM::SP) 2113 .addReg(ARM::SP) 2114 .addImm(-4) 2115 .add(predOps(ARMCC::AL)); 2116 } 2117 2118 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs, 2119 RegInfo](unsigned Reg, SpillArea TestArea) { 2120 return getSpillArea(Reg, PushPopSplit, NumAlignedDPRCS2Regs, RegInfo) == 2121 TestArea; 2122 }; 2123 auto IsGPRCS1 = [&CheckRegArea](unsigned Reg) { 2124 return CheckRegArea(Reg, SpillArea::GPRCS1); 2125 }; 2126 auto IsGPRCS2 = [&CheckRegArea](unsigned Reg) { 2127 return CheckRegArea(Reg, SpillArea::GPRCS2); 2128 }; 2129 auto IsDPRCS1 = [&CheckRegArea](unsigned Reg) { 2130 return CheckRegArea(Reg, SpillArea::DPRCS1); 2131 }; 2132 2133 // Windows SEH requires the floating-point registers to be pushed between the 2134 // two blocks of GPRs in some situations. In all other cases, they are pushed 2135 // below the GPRs. 2136 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) { 2137 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS1); 2138 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, IsDPRCS1); 2139 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS2); 2140 } else { 2141 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS1); 2142 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, IsGPRCS2); 2143 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, IsDPRCS1); 2144 } 2145 2146 // The code above does not insert spill code for the aligned DPRCS2 registers. 2147 // The stack realignment code will be inserted between the push instructions 2148 // and these spills. 2149 if (NumAlignedDPRCS2Regs) 2150 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 2151 2152 return true; 2153 } 2154 2155 bool ARMFrameLowering::restoreCalleeSavedRegisters( 2156 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, 2157 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const { 2158 if (CSI.empty()) 2159 return false; 2160 2161 MachineFunction &MF = *MBB.getParent(); 2162 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2163 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo(); 2164 2165 bool isVarArg = AFI->getArgRegsSaveSize() > 0; 2166 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs(); 2167 ARMSubtarget::PushPopSplitVariation PushPopSplit = 2168 STI.getPushPopSplitVariation(MF); 2169 2170 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2 2171 // registers. Do that here instead. 2172 if (NumAlignedDPRCS2Regs) 2173 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI); 2174 2175 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD; 2176 unsigned LdrOpc = 2177 AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST_IMM; 2178 unsigned FltOpc = ARM::VLDMDIA_UPD; 2179 2180 auto CheckRegArea = [PushPopSplit, NumAlignedDPRCS2Regs, 2181 RegInfo](unsigned Reg, SpillArea TestArea) { 2182 return getSpillArea(Reg, PushPopSplit, NumAlignedDPRCS2Regs, RegInfo) == 2183 TestArea; 2184 }; 2185 auto IsGPRCS1 = [&CheckRegArea](unsigned Reg) { 2186 return CheckRegArea(Reg, SpillArea::GPRCS1); 2187 }; 2188 auto IsGPRCS2 = [&CheckRegArea](unsigned Reg) { 2189 return CheckRegArea(Reg, SpillArea::GPRCS2); 2190 }; 2191 auto IsDPRCS1 = [&CheckRegArea](unsigned Reg) { 2192 return CheckRegArea(Reg, SpillArea::DPRCS1); 2193 }; 2194 2195 if (PushPopSplit == ARMSubtarget::SplitR11WindowsSEH) { 2196 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS2); 2197 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, IsDPRCS1); 2198 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS1); 2199 } else { 2200 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, IsDPRCS1); 2201 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS2); 2202 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false, IsGPRCS1); 2203 } 2204 2205 return true; 2206 } 2207 2208 // FIXME: Make generic? 2209 static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF, 2210 const ARMBaseInstrInfo &TII) { 2211 unsigned FnSize = 0; 2212 for (auto &MBB : MF) { 2213 for (auto &MI : MBB) 2214 FnSize += TII.getInstSizeInBytes(MI); 2215 } 2216 if (MF.getJumpTableInfo()) 2217 for (auto &Table: MF.getJumpTableInfo()->getJumpTables()) 2218 FnSize += Table.MBBs.size() * 4; 2219 FnSize += MF.getConstantPool()->getConstants().size() * 4; 2220 return FnSize; 2221 } 2222 2223 /// estimateRSStackSizeLimit - Look at each instruction that references stack 2224 /// frames and return the stack size limit beyond which some of these 2225 /// instructions will require a scratch register during their expansion later. 2226 // FIXME: Move to TII? 2227 static unsigned estimateRSStackSizeLimit(MachineFunction &MF, 2228 const TargetFrameLowering *TFI, 2229 bool &HasNonSPFrameIndex) { 2230 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2231 const ARMBaseInstrInfo &TII = 2232 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 2233 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 2234 unsigned Limit = (1 << 12) - 1; 2235 for (auto &MBB : MF) { 2236 for (auto &MI : MBB) { 2237 if (MI.isDebugInstr()) 2238 continue; 2239 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 2240 if (!MI.getOperand(i).isFI()) 2241 continue; 2242 2243 // When using ADDri to get the address of a stack object, 255 is the 2244 // largest offset guaranteed to fit in the immediate offset. 2245 if (MI.getOpcode() == ARM::ADDri) { 2246 Limit = std::min(Limit, (1U << 8) - 1); 2247 break; 2248 } 2249 // t2ADDri will not require an extra register, it can reuse the 2250 // destination. 2251 if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12) 2252 break; 2253 2254 const MCInstrDesc &MCID = MI.getDesc(); 2255 const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF); 2256 if (RegClass && !RegClass->contains(ARM::SP)) 2257 HasNonSPFrameIndex = true; 2258 2259 // Otherwise check the addressing mode. 2260 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) { 2261 case ARMII::AddrMode_i12: 2262 case ARMII::AddrMode2: 2263 // Default 12 bit limit. 2264 break; 2265 case ARMII::AddrMode3: 2266 case ARMII::AddrModeT2_i8neg: 2267 Limit = std::min(Limit, (1U << 8) - 1); 2268 break; 2269 case ARMII::AddrMode5FP16: 2270 Limit = std::min(Limit, ((1U << 8) - 1) * 2); 2271 break; 2272 case ARMII::AddrMode5: 2273 case ARMII::AddrModeT2_i8s4: 2274 case ARMII::AddrModeT2_ldrex: 2275 Limit = std::min(Limit, ((1U << 8) - 1) * 4); 2276 break; 2277 case ARMII::AddrModeT2_i12: 2278 // i12 supports only positive offset so these will be converted to 2279 // i8 opcodes. See llvm::rewriteT2FrameIndex. 2280 if (TFI->hasFP(MF) && AFI->hasStackFrame()) 2281 Limit = std::min(Limit, (1U << 8) - 1); 2282 break; 2283 case ARMII::AddrMode4: 2284 case ARMII::AddrMode6: 2285 // Addressing modes 4 & 6 (load/store) instructions can't encode an 2286 // immediate offset for stack references. 2287 return 0; 2288 case ARMII::AddrModeT2_i7: 2289 Limit = std::min(Limit, ((1U << 7) - 1) * 1); 2290 break; 2291 case ARMII::AddrModeT2_i7s2: 2292 Limit = std::min(Limit, ((1U << 7) - 1) * 2); 2293 break; 2294 case ARMII::AddrModeT2_i7s4: 2295 Limit = std::min(Limit, ((1U << 7) - 1) * 4); 2296 break; 2297 default: 2298 llvm_unreachable("Unhandled addressing mode in stack size limit calculation"); 2299 } 2300 break; // At most one FI per instruction 2301 } 2302 } 2303 } 2304 2305 return Limit; 2306 } 2307 2308 // In functions that realign the stack, it can be an advantage to spill the 2309 // callee-saved vector registers after realigning the stack. The vst1 and vld1 2310 // instructions take alignment hints that can improve performance. 2311 static void 2312 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) { 2313 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0); 2314 if (!SpillAlignedNEONRegs) 2315 return; 2316 2317 // Naked functions don't spill callee-saved registers. 2318 if (MF.getFunction().hasFnAttribute(Attribute::Naked)) 2319 return; 2320 2321 // We are planning to use NEON instructions vst1 / vld1. 2322 if (!MF.getSubtarget<ARMSubtarget>().hasNEON()) 2323 return; 2324 2325 // Don't bother if the default stack alignment is sufficiently high. 2326 if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8)) 2327 return; 2328 2329 // Aligned spills require stack realignment. 2330 if (!static_cast<const ARMBaseRegisterInfo *>( 2331 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF)) 2332 return; 2333 2334 // We always spill contiguous d-registers starting from d8. Count how many 2335 // needs spilling. The register allocator will almost always use the 2336 // callee-saved registers in order, but it can happen that there are holes in 2337 // the range. Registers above the hole will be spilled to the standard DPRCS 2338 // area. 2339 unsigned NumSpills = 0; 2340 for (; NumSpills < 8; ++NumSpills) 2341 if (!SavedRegs.test(ARM::D8 + NumSpills)) 2342 break; 2343 2344 // Don't do this for just one d-register. It's not worth it. 2345 if (NumSpills < 2) 2346 return; 2347 2348 // Spill the first NumSpills D-registers after realigning the stack. 2349 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills); 2350 2351 // A scratch register is required for the vst1 / vld1 instructions. 2352 SavedRegs.set(ARM::R4); 2353 } 2354 2355 bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const { 2356 // For CMSE entry functions, we want to save the FPCXT_NS immediately 2357 // upon function entry (resp. restore it immmediately before return) 2358 if (STI.hasV8_1MMainlineOps() && 2359 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) 2360 return false; 2361 2362 // We are disabling shrinkwrapping for now when PAC is enabled, as 2363 // shrinkwrapping can cause clobbering of r12 when the PAC code is 2364 // generated. A follow-up patch will fix this in a more performant manner. 2365 if (MF.getInfo<ARMFunctionInfo>()->shouldSignReturnAddress( 2366 true /* SpillsLR */)) 2367 return false; 2368 2369 return true; 2370 } 2371 2372 bool ARMFrameLowering::requiresAAPCSFrameRecord( 2373 const MachineFunction &MF) const { 2374 const auto &Subtarget = MF.getSubtarget<ARMSubtarget>(); 2375 return Subtarget.createAAPCSFrameChain() && hasFP(MF); 2376 } 2377 2378 // Thumb1 may require a spill when storing to a frame index through FP (or any 2379 // access with execute-only), for cases where FP is a high register (R11). This 2380 // scans the function for cases where this may happen. 2381 static bool canSpillOnFrameIndexAccess(const MachineFunction &MF, 2382 const TargetFrameLowering &TFI) { 2383 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2384 if (!AFI->isThumb1OnlyFunction()) 2385 return false; 2386 2387 const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>(); 2388 for (const auto &MBB : MF) 2389 for (const auto &MI : MBB) 2390 if (MI.getOpcode() == ARM::tSTRspi || MI.getOpcode() == ARM::tSTRi || 2391 STI.genExecuteOnly()) 2392 for (const auto &Op : MI.operands()) 2393 if (Op.isFI()) { 2394 Register Reg; 2395 TFI.getFrameIndexReference(MF, Op.getIndex(), Reg); 2396 if (ARM::hGPRRegClass.contains(Reg) && Reg != ARM::SP) 2397 return true; 2398 } 2399 return false; 2400 } 2401 2402 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF, 2403 BitVector &SavedRegs, 2404 RegScavenger *RS) const { 2405 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS); 2406 // This tells PEI to spill the FP as if it is any other callee-save register 2407 // to take advantage the eliminateFrameIndex machinery. This also ensures it 2408 // is spilled in the order specified by getCalleeSavedRegs() to make it easier 2409 // to combine multiple loads / stores. 2410 bool CanEliminateFrame = !(requiresAAPCSFrameRecord(MF) && hasFP(MF)) && 2411 !MF.getTarget().Options.DisableFramePointerElim(MF); 2412 bool CS1Spilled = false; 2413 bool LRSpilled = false; 2414 unsigned NumGPRSpills = 0; 2415 unsigned NumFPRSpills = 0; 2416 SmallVector<unsigned, 4> UnspilledCS1GPRs; 2417 SmallVector<unsigned, 4> UnspilledCS2GPRs; 2418 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>( 2419 MF.getSubtarget().getRegisterInfo()); 2420 const ARMBaseInstrInfo &TII = 2421 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 2422 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2423 MachineFrameInfo &MFI = MF.getFrameInfo(); 2424 MachineRegisterInfo &MRI = MF.getRegInfo(); 2425 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 2426 (void)TRI; // Silence unused warning in non-assert builds. 2427 Register FramePtr = RegInfo->getFrameRegister(MF); 2428 ARMSubtarget::PushPopSplitVariation PushPopSplit = 2429 STI.getPushPopSplitVariation(MF); 2430 2431 // Spill R4 if Thumb2 function requires stack realignment - it will be used as 2432 // scratch register. Also spill R4 if Thumb2 function has varsized objects, 2433 // since it's not always possible to restore sp from fp in a single 2434 // instruction. 2435 // FIXME: It will be better just to find spare register here. 2436 if (AFI->isThumb2Function() && 2437 (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF))) 2438 SavedRegs.set(ARM::R4); 2439 2440 // If a stack probe will be emitted, spill R4 and LR, since they are 2441 // clobbered by the stack probe call. 2442 // This estimate should be a safe, conservative estimate. The actual 2443 // stack probe is enabled based on the size of the local objects; 2444 // this estimate also includes the varargs store size. 2445 if (STI.isTargetWindows() && 2446 WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) { 2447 SavedRegs.set(ARM::R4); 2448 SavedRegs.set(ARM::LR); 2449 } 2450 2451 if (AFI->isThumb1OnlyFunction()) { 2452 // Spill LR if Thumb1 function uses variable length argument lists. 2453 if (AFI->getArgRegsSaveSize() > 0) 2454 SavedRegs.set(ARM::LR); 2455 2456 // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function 2457 // requires stack alignment. We don't know for sure what the stack size 2458 // will be, but for this, an estimate is good enough. If there anything 2459 // changes it, it'll be a spill, which implies we've used all the registers 2460 // and so R4 is already used, so not marking it here will be OK. 2461 // FIXME: It will be better just to find spare register here. 2462 if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) || 2463 MFI.estimateStackSize(MF) > 508) 2464 SavedRegs.set(ARM::R4); 2465 } 2466 2467 // See if we can spill vector registers to aligned stack. 2468 checkNumAlignedDPRCS2Regs(MF, SavedRegs); 2469 2470 // Spill the BasePtr if it's used. 2471 if (RegInfo->hasBasePointer(MF)) 2472 SavedRegs.set(RegInfo->getBaseRegister()); 2473 2474 // On v8.1-M.Main CMSE entry functions save/restore FPCXT. 2475 if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction()) 2476 CanEliminateFrame = false; 2477 2478 // When return address signing is enabled R12 is treated as callee-saved. 2479 if (AFI->shouldSignReturnAddress()) 2480 CanEliminateFrame = false; 2481 2482 // Don't spill FP if the frame can be eliminated. This is determined 2483 // by scanning the callee-save registers to see if any is modified. 2484 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF); 2485 for (unsigned i = 0; CSRegs[i]; ++i) { 2486 unsigned Reg = CSRegs[i]; 2487 bool Spilled = false; 2488 if (SavedRegs.test(Reg)) { 2489 Spilled = true; 2490 CanEliminateFrame = false; 2491 } 2492 2493 if (!ARM::GPRRegClass.contains(Reg)) { 2494 if (Spilled) { 2495 if (ARM::SPRRegClass.contains(Reg)) 2496 NumFPRSpills++; 2497 else if (ARM::DPRRegClass.contains(Reg)) 2498 NumFPRSpills += 2; 2499 else if (ARM::QPRRegClass.contains(Reg)) 2500 NumFPRSpills += 4; 2501 } 2502 continue; 2503 } 2504 2505 if (Spilled) { 2506 NumGPRSpills++; 2507 2508 if (PushPopSplit != ARMSubtarget::SplitR7) { 2509 if (Reg == ARM::LR) 2510 LRSpilled = true; 2511 CS1Spilled = true; 2512 continue; 2513 } 2514 2515 // Keep track if LR and any of R4, R5, R6, and R7 is spilled. 2516 switch (Reg) { 2517 case ARM::LR: 2518 LRSpilled = true; 2519 [[fallthrough]]; 2520 case ARM::R0: case ARM::R1: 2521 case ARM::R2: case ARM::R3: 2522 case ARM::R4: case ARM::R5: 2523 case ARM::R6: case ARM::R7: 2524 CS1Spilled = true; 2525 break; 2526 default: 2527 break; 2528 } 2529 } else { 2530 if (PushPopSplit != ARMSubtarget::SplitR7) { 2531 UnspilledCS1GPRs.push_back(Reg); 2532 continue; 2533 } 2534 2535 switch (Reg) { 2536 case ARM::R0: case ARM::R1: 2537 case ARM::R2: case ARM::R3: 2538 case ARM::R4: case ARM::R5: 2539 case ARM::R6: case ARM::R7: 2540 case ARM::LR: 2541 UnspilledCS1GPRs.push_back(Reg); 2542 break; 2543 default: 2544 UnspilledCS2GPRs.push_back(Reg); 2545 break; 2546 } 2547 } 2548 } 2549 2550 bool ForceLRSpill = false; 2551 if (!LRSpilled && AFI->isThumb1OnlyFunction()) { 2552 unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII); 2553 // Force LR to be spilled if the Thumb function size is > 2048. This enables 2554 // use of BL to implement far jump. 2555 if (FnSize >= (1 << 11)) { 2556 CanEliminateFrame = false; 2557 ForceLRSpill = true; 2558 } 2559 } 2560 2561 // If any of the stack slot references may be out of range of an immediate 2562 // offset, make sure a register (or a spill slot) is available for the 2563 // register scavenger. Note that if we're indexing off the frame pointer, the 2564 // effective stack size is 4 bytes larger since the FP points to the stack 2565 // slot of the previous FP. Also, if we have variable sized objects in the 2566 // function, stack slot references will often be negative, and some of 2567 // our instructions are positive-offset only, so conservatively consider 2568 // that case to want a spill slot (or register) as well. Similarly, if 2569 // the function adjusts the stack pointer during execution and the 2570 // adjustments aren't already part of our stack size estimate, our offset 2571 // calculations may be off, so be conservative. 2572 // FIXME: We could add logic to be more precise about negative offsets 2573 // and which instructions will need a scratch register for them. Is it 2574 // worth the effort and added fragility? 2575 unsigned EstimatedStackSize = 2576 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills); 2577 2578 // Determine biggest (positive) SP offset in MachineFrameInfo. 2579 int MaxFixedOffset = 0; 2580 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) { 2581 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I); 2582 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset); 2583 } 2584 2585 bool HasFP = hasFP(MF); 2586 if (HasFP) { 2587 if (AFI->hasStackFrame()) 2588 EstimatedStackSize += 4; 2589 } else { 2590 // If FP is not used, SP will be used to access arguments, so count the 2591 // size of arguments into the estimation. 2592 EstimatedStackSize += MaxFixedOffset; 2593 } 2594 EstimatedStackSize += 16; // For possible paddings. 2595 2596 unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit; 2597 bool HasNonSPFrameIndex = false; 2598 if (AFI->isThumb1OnlyFunction()) { 2599 // For Thumb1, don't bother to iterate over the function. The only 2600 // instruction that requires an emergency spill slot is a store to a 2601 // frame index. 2602 // 2603 // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned 2604 // immediate. tSTRi, which is used for bp- and fp-relative accesses, has 2605 // a 5-bit unsigned immediate. 2606 // 2607 // We could try to check if the function actually contains a tSTRspi 2608 // that might need the spill slot, but it's not really important. 2609 // Functions with VLAs or extremely large call frames are rare, and 2610 // if a function is allocating more than 1KB of stack, an extra 4-byte 2611 // slot probably isn't relevant. 2612 // 2613 // A special case is the scenario where r11 is used as FP, where accesses 2614 // to a frame index will require its value to be moved into a low reg. 2615 // This is handled later on, once we are able to determine if we have any 2616 // fp-relative accesses. 2617 if (RegInfo->hasBasePointer(MF)) 2618 EstimatedRSStackSizeLimit = (1U << 5) * 4; 2619 else 2620 EstimatedRSStackSizeLimit = (1U << 8) * 4; 2621 EstimatedRSFixedSizeLimit = (1U << 5) * 4; 2622 } else { 2623 EstimatedRSStackSizeLimit = 2624 estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex); 2625 EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit; 2626 } 2627 // Final estimate of whether sp or bp-relative accesses might require 2628 // scavenging. 2629 bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit; 2630 2631 // If the stack pointer moves and we don't have a base pointer, the 2632 // estimate logic doesn't work. The actual offsets might be larger when 2633 // we're constructing a call frame, or we might need to use negative 2634 // offsets from fp. 2635 bool HasMovingSP = MFI.hasVarSizedObjects() || 2636 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF)); 2637 bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP; 2638 2639 // If we have a frame pointer, we assume arguments will be accessed 2640 // relative to the frame pointer. Check whether fp-relative accesses to 2641 // arguments require scavenging. 2642 // 2643 // We could do slightly better on Thumb1; in some cases, an sp-relative 2644 // offset would be legal even though an fp-relative offset is not. 2645 int MaxFPOffset = getMaxFPOffset(STI, *AFI, MF); 2646 bool HasLargeArgumentList = 2647 HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit; 2648 2649 bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP || 2650 HasLargeArgumentList || HasNonSPFrameIndex; 2651 LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit 2652 << "; EstimatedStack: " << EstimatedStackSize 2653 << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset 2654 << "; BigFrameOffsets: " << BigFrameOffsets << "\n"); 2655 if (BigFrameOffsets || 2656 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) { 2657 AFI->setHasStackFrame(true); 2658 2659 if (HasFP) { 2660 SavedRegs.set(FramePtr); 2661 // If the frame pointer is required by the ABI, also spill LR so that we 2662 // emit a complete frame record. 2663 if ((requiresAAPCSFrameRecord(MF) || 2664 MF.getTarget().Options.DisableFramePointerElim(MF)) && 2665 !LRSpilled) { 2666 SavedRegs.set(ARM::LR); 2667 LRSpilled = true; 2668 NumGPRSpills++; 2669 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR); 2670 if (LRPos != UnspilledCS1GPRs.end()) 2671 UnspilledCS1GPRs.erase(LRPos); 2672 } 2673 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr); 2674 if (FPPos != UnspilledCS1GPRs.end()) 2675 UnspilledCS1GPRs.erase(FPPos); 2676 NumGPRSpills++; 2677 if (FramePtr == ARM::R7) 2678 CS1Spilled = true; 2679 } 2680 2681 // This is the number of extra spills inserted for callee-save GPRs which 2682 // would not otherwise be used by the function. When greater than zero it 2683 // guaranteees that it is possible to scavenge a register to hold the 2684 // address of a stack slot. On Thumb1, the register must be a valid operand 2685 // to tSTRi, i.e. r4-r7. For other subtargets, this is any GPR, i.e. r4-r11 2686 // or lr. 2687 // 2688 // If we don't insert a spill, we instead allocate an emergency spill 2689 // slot, which can be used by scavenging to spill an arbitrary register. 2690 // 2691 // We currently don't try to figure out whether any specific instruction 2692 // requires scavening an additional register. 2693 unsigned NumExtraCSSpill = 0; 2694 2695 if (AFI->isThumb1OnlyFunction()) { 2696 // For Thumb1-only targets, we need some low registers when we save and 2697 // restore the high registers (which aren't allocatable, but could be 2698 // used by inline assembly) because the push/pop instructions can not 2699 // access high registers. If necessary, we might need to push more low 2700 // registers to ensure that there is at least one free that can be used 2701 // for the saving & restoring, and preferably we should ensure that as 2702 // many as are needed are available so that fewer push/pop instructions 2703 // are required. 2704 2705 // Low registers which are not currently pushed, but could be (r4-r7). 2706 SmallVector<unsigned, 4> AvailableRegs; 2707 2708 // Unused argument registers (r0-r3) can be clobbered in the prologue for 2709 // free. 2710 int EntryRegDeficit = 0; 2711 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) { 2712 if (!MF.getRegInfo().isLiveIn(Reg)) { 2713 --EntryRegDeficit; 2714 LLVM_DEBUG(dbgs() 2715 << printReg(Reg, TRI) 2716 << " is unused argument register, EntryRegDeficit = " 2717 << EntryRegDeficit << "\n"); 2718 } 2719 } 2720 2721 // Unused return registers can be clobbered in the epilogue for free. 2722 int ExitRegDeficit = AFI->getReturnRegsCount() - 4; 2723 LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount() 2724 << " return regs used, ExitRegDeficit = " 2725 << ExitRegDeficit << "\n"); 2726 2727 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit); 2728 LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n"); 2729 2730 // r4-r6 can be used in the prologue if they are pushed by the first push 2731 // instruction. 2732 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) { 2733 if (SavedRegs.test(Reg)) { 2734 --RegDeficit; 2735 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) 2736 << " is saved low register, RegDeficit = " 2737 << RegDeficit << "\n"); 2738 } else { 2739 AvailableRegs.push_back(Reg); 2740 LLVM_DEBUG( 2741 dbgs() 2742 << printReg(Reg, TRI) 2743 << " is non-saved low register, adding to AvailableRegs\n"); 2744 } 2745 } 2746 2747 // r7 can be used if it is not being used as the frame pointer. 2748 if (!HasFP || FramePtr != ARM::R7) { 2749 if (SavedRegs.test(ARM::R7)) { 2750 --RegDeficit; 2751 LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = " 2752 << RegDeficit << "\n"); 2753 } else { 2754 AvailableRegs.push_back(ARM::R7); 2755 LLVM_DEBUG( 2756 dbgs() 2757 << "%r7 is non-saved low register, adding to AvailableRegs\n"); 2758 } 2759 } 2760 2761 // Each of r8-r11 needs to be copied to a low register, then pushed. 2762 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) { 2763 if (SavedRegs.test(Reg)) { 2764 ++RegDeficit; 2765 LLVM_DEBUG(dbgs() << printReg(Reg, TRI) 2766 << " is saved high register, RegDeficit = " 2767 << RegDeficit << "\n"); 2768 } 2769 } 2770 2771 // LR can only be used by PUSH, not POP, and can't be used at all if the 2772 // llvm.returnaddress intrinsic is used. This is only worth doing if we 2773 // are more limited at function entry than exit. 2774 if ((EntryRegDeficit > ExitRegDeficit) && 2775 !(MF.getRegInfo().isLiveIn(ARM::LR) && 2776 MF.getFrameInfo().isReturnAddressTaken())) { 2777 if (SavedRegs.test(ARM::LR)) { 2778 --RegDeficit; 2779 LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = " 2780 << RegDeficit << "\n"); 2781 } else { 2782 AvailableRegs.push_back(ARM::LR); 2783 LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n"); 2784 } 2785 } 2786 2787 // If there are more high registers that need pushing than low registers 2788 // available, push some more low registers so that we can use fewer push 2789 // instructions. This might not reduce RegDeficit all the way to zero, 2790 // because we can only guarantee that r4-r6 are available, but r8-r11 may 2791 // need saving. 2792 LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n"); 2793 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) { 2794 unsigned Reg = AvailableRegs.pop_back_val(); 2795 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI) 2796 << " to make up reg deficit\n"); 2797 SavedRegs.set(Reg); 2798 NumGPRSpills++; 2799 CS1Spilled = true; 2800 assert(!MRI.isReserved(Reg) && "Should not be reserved"); 2801 if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg)) 2802 NumExtraCSSpill++; 2803 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg)); 2804 if (Reg == ARM::LR) 2805 LRSpilled = true; 2806 } 2807 LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit 2808 << "\n"); 2809 } 2810 2811 // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to 2812 // restore LR in that case. 2813 bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall(); 2814 2815 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled. 2816 // Spill LR as well so we can fold BX_RET to the registers restore (LDM). 2817 if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) { 2818 SavedRegs.set(ARM::LR); 2819 NumGPRSpills++; 2820 SmallVectorImpl<unsigned>::iterator LRPos; 2821 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR); 2822 if (LRPos != UnspilledCS1GPRs.end()) 2823 UnspilledCS1GPRs.erase(LRPos); 2824 2825 ForceLRSpill = false; 2826 if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) && 2827 !AFI->isThumb1OnlyFunction()) 2828 NumExtraCSSpill++; 2829 } 2830 2831 // If stack and double are 8-byte aligned and we are spilling an odd number 2832 // of GPRs, spill one extra callee save GPR so we won't have to pad between 2833 // the integer and double callee save areas. 2834 LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n"); 2835 const Align TargetAlign = getStackAlign(); 2836 if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) { 2837 if (CS1Spilled && !UnspilledCS1GPRs.empty()) { 2838 for (unsigned Reg : UnspilledCS1GPRs) { 2839 // Don't spill high register if the function is thumb. In the case of 2840 // Windows on ARM, accept R11 (frame pointer) 2841 if (!AFI->isThumbFunction() || 2842 (STI.isTargetWindows() && Reg == ARM::R11) || 2843 isARMLowRegister(Reg) || 2844 (Reg == ARM::LR && !ExpensiveLRRestore)) { 2845 SavedRegs.set(Reg); 2846 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI) 2847 << " to make up alignment\n"); 2848 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) && 2849 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction())) 2850 NumExtraCSSpill++; 2851 break; 2852 } 2853 } 2854 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) { 2855 unsigned Reg = UnspilledCS2GPRs.front(); 2856 SavedRegs.set(Reg); 2857 LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI) 2858 << " to make up alignment\n"); 2859 if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg)) 2860 NumExtraCSSpill++; 2861 } 2862 } 2863 2864 // Estimate if we might need to scavenge registers at some point in order 2865 // to materialize a stack offset. If so, either spill one additional 2866 // callee-saved register or reserve a special spill slot to facilitate 2867 // register scavenging. Thumb1 needs a spill slot for stack pointer 2868 // adjustments and for frame index accesses when FP is high register, 2869 // even when the frame itself is small. 2870 unsigned RegsNeeded = 0; 2871 if (BigFrameOffsets || canSpillOnFrameIndexAccess(MF, *this)) { 2872 RegsNeeded++; 2873 // With thumb1 execute-only we may need an additional register for saving 2874 // and restoring the CPSR. 2875 if (AFI->isThumb1OnlyFunction() && STI.genExecuteOnly() && !STI.useMovt()) 2876 RegsNeeded++; 2877 } 2878 2879 if (RegsNeeded > NumExtraCSSpill) { 2880 // If any non-reserved CS register isn't spilled, just spill one or two 2881 // extra. That should take care of it! 2882 unsigned NumExtras = TargetAlign.value() / 4; 2883 SmallVector<unsigned, 2> Extras; 2884 while (NumExtras && !UnspilledCS1GPRs.empty()) { 2885 unsigned Reg = UnspilledCS1GPRs.pop_back_val(); 2886 if (!MRI.isReserved(Reg) && 2887 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) { 2888 Extras.push_back(Reg); 2889 NumExtras--; 2890 } 2891 } 2892 // For non-Thumb1 functions, also check for hi-reg CS registers 2893 if (!AFI->isThumb1OnlyFunction()) { 2894 while (NumExtras && !UnspilledCS2GPRs.empty()) { 2895 unsigned Reg = UnspilledCS2GPRs.pop_back_val(); 2896 if (!MRI.isReserved(Reg)) { 2897 Extras.push_back(Reg); 2898 NumExtras--; 2899 } 2900 } 2901 } 2902 if (NumExtras == 0) { 2903 for (unsigned Reg : Extras) { 2904 SavedRegs.set(Reg); 2905 if (!MRI.isPhysRegUsed(Reg)) 2906 NumExtraCSSpill++; 2907 } 2908 } 2909 while ((RegsNeeded > NumExtraCSSpill) && RS) { 2910 // Reserve a slot closest to SP or frame pointer. 2911 LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n"); 2912 const TargetRegisterClass &RC = ARM::GPRRegClass; 2913 unsigned Size = TRI->getSpillSize(RC); 2914 Align Alignment = TRI->getSpillAlign(RC); 2915 RS->addScavengingFrameIndex( 2916 MFI.CreateStackObject(Size, Alignment, false)); 2917 --RegsNeeded; 2918 } 2919 } 2920 } 2921 2922 if (ForceLRSpill) 2923 SavedRegs.set(ARM::LR); 2924 AFI->setLRIsSpilled(SavedRegs.test(ARM::LR)); 2925 } 2926 2927 void ARMFrameLowering::updateLRRestored(MachineFunction &MF) { 2928 MachineFrameInfo &MFI = MF.getFrameInfo(); 2929 if (!MFI.isCalleeSavedInfoValid()) 2930 return; 2931 2932 // Check if all terminators do not implicitly use LR. Then we can 'restore' LR 2933 // into PC so it is not live out of the return block: Clear the Restored bit 2934 // in that case. 2935 for (CalleeSavedInfo &Info : MFI.getCalleeSavedInfo()) { 2936 if (Info.getReg() != ARM::LR) 2937 continue; 2938 if (all_of(MF, [](const MachineBasicBlock &MBB) { 2939 return all_of(MBB.terminators(), [](const MachineInstr &Term) { 2940 return !Term.isReturn() || Term.getOpcode() == ARM::LDMIA_RET || 2941 Term.getOpcode() == ARM::t2LDMIA_RET || 2942 Term.getOpcode() == ARM::tPOP_RET; 2943 }); 2944 })) { 2945 Info.setRestored(false); 2946 break; 2947 } 2948 } 2949 } 2950 2951 void ARMFrameLowering::processFunctionBeforeFrameFinalized( 2952 MachineFunction &MF, RegScavenger *RS) const { 2953 TargetFrameLowering::processFunctionBeforeFrameFinalized(MF, RS); 2954 updateLRRestored(MF); 2955 } 2956 2957 void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF, 2958 BitVector &SavedRegs) const { 2959 TargetFrameLowering::getCalleeSaves(MF, SavedRegs); 2960 2961 // If we have the "returned" parameter attribute which guarantees that we 2962 // return the value which was passed in r0 unmodified (e.g. C++ 'structors), 2963 // record that fact for IPRA. 2964 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 2965 if (AFI->getPreservesR0()) 2966 SavedRegs.set(ARM::R0); 2967 } 2968 2969 bool ARMFrameLowering::assignCalleeSavedSpillSlots( 2970 MachineFunction &MF, const TargetRegisterInfo *TRI, 2971 std::vector<CalleeSavedInfo> &CSI) const { 2972 // For CMSE entry functions, handle floating-point context as if it was a 2973 // callee-saved register. 2974 if (STI.hasV8_1MMainlineOps() && 2975 MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) { 2976 CSI.emplace_back(ARM::FPCXTNS); 2977 CSI.back().setRestored(false); 2978 } 2979 2980 // For functions, which sign their return address, upon function entry, the 2981 // return address PAC is computed in R12. Treat R12 as a callee-saved register 2982 // in this case. 2983 const auto &AFI = *MF.getInfo<ARMFunctionInfo>(); 2984 if (AFI.shouldSignReturnAddress()) { 2985 // The order of register must match the order we push them, because the 2986 // PEI assigns frame indices in that order. That order depends on the 2987 // PushPopSplitVariation, there are only two cases which we use with return 2988 // address signing: 2989 switch (STI.getPushPopSplitVariation(MF)) { 2990 case ARMSubtarget::SplitR7: 2991 // LR, R7, R6, R5, R4, <R12>, R11, R10, R9, R8, D15-D8 2992 CSI.insert(find_if(CSI, 2993 [=](const auto &CS) { 2994 Register Reg = CS.getReg(); 2995 return Reg == ARM::R10 || Reg == ARM::R11 || 2996 Reg == ARM::R8 || Reg == ARM::R9 || 2997 ARM::DPRRegClass.contains(Reg); 2998 }), 2999 CalleeSavedInfo(ARM::R12)); 3000 break; 3001 case ARMSubtarget::SplitR11AAPCSSignRA: 3002 // With SplitR11AAPCSSignRA, R12 will always be the highest-addressed CSR 3003 // on the stack. 3004 CSI.insert(CSI.begin(), CalleeSavedInfo(ARM::R12)); 3005 break; 3006 default: 3007 llvm_unreachable("Unexpected CSR split with return address signing"); 3008 } 3009 } 3010 3011 return false; 3012 } 3013 3014 const TargetFrameLowering::SpillSlot * 3015 ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const { 3016 static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}}; 3017 NumEntries = std::size(FixedSpillOffsets); 3018 return FixedSpillOffsets; 3019 } 3020 3021 MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr( 3022 MachineFunction &MF, MachineBasicBlock &MBB, 3023 MachineBasicBlock::iterator I) const { 3024 const ARMBaseInstrInfo &TII = 3025 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 3026 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>(); 3027 bool isARM = !AFI->isThumbFunction(); 3028 DebugLoc dl = I->getDebugLoc(); 3029 unsigned Opc = I->getOpcode(); 3030 bool IsDestroy = Opc == TII.getCallFrameDestroyOpcode(); 3031 unsigned CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0; 3032 3033 assert(!AFI->isThumb1OnlyFunction() && 3034 "This eliminateCallFramePseudoInstr does not support Thumb1!"); 3035 3036 int PIdx = I->findFirstPredOperandIdx(); 3037 ARMCC::CondCodes Pred = (PIdx == -1) 3038 ? ARMCC::AL 3039 : (ARMCC::CondCodes)I->getOperand(PIdx).getImm(); 3040 unsigned PredReg = TII.getFramePred(*I); 3041 3042 if (!hasReservedCallFrame(MF)) { 3043 // Bail early if the callee is expected to do the adjustment. 3044 if (IsDestroy && CalleePopAmount != -1U) 3045 return MBB.erase(I); 3046 3047 // If we have alloca, convert as follows: 3048 // ADJCALLSTACKDOWN -> sub, sp, sp, amount 3049 // ADJCALLSTACKUP -> add, sp, sp, amount 3050 unsigned Amount = TII.getFrameSize(*I); 3051 if (Amount != 0) { 3052 // We need to keep the stack aligned properly. To do this, we round the 3053 // amount of space needed for the outgoing arguments up to the next 3054 // alignment boundary. 3055 Amount = alignSPAdjust(Amount); 3056 3057 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) { 3058 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags, 3059 Pred, PredReg); 3060 } else { 3061 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP); 3062 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags, 3063 Pred, PredReg); 3064 } 3065 } 3066 } else if (CalleePopAmount != -1U) { 3067 // If the calling convention demands that the callee pops arguments from the 3068 // stack, we want to add it back if we have a reserved call frame. 3069 emitSPUpdate(isARM, MBB, I, dl, TII, -CalleePopAmount, 3070 MachineInstr::NoFlags, Pred, PredReg); 3071 } 3072 return MBB.erase(I); 3073 } 3074 3075 /// Get the minimum constant for ARM that is greater than or equal to the 3076 /// argument. In ARM, constants can have any value that can be produced by 3077 /// rotating an 8-bit value to the right by an even number of bits within a 3078 /// 32-bit word. 3079 static uint32_t alignToARMConstant(uint32_t Value) { 3080 unsigned Shifted = 0; 3081 3082 if (Value == 0) 3083 return 0; 3084 3085 while (!(Value & 0xC0000000)) { 3086 Value = Value << 2; 3087 Shifted += 2; 3088 } 3089 3090 bool Carry = (Value & 0x00FFFFFF); 3091 Value = ((Value & 0xFF000000) >> 24) + Carry; 3092 3093 if (Value & 0x0000100) 3094 Value = Value & 0x000001FC; 3095 3096 if (Shifted > 24) 3097 Value = Value >> (Shifted - 24); 3098 else 3099 Value = Value << (24 - Shifted); 3100 3101 return Value; 3102 } 3103 3104 // The stack limit in the TCB is set to this many bytes above the actual 3105 // stack limit. 3106 static const uint64_t kSplitStackAvailable = 256; 3107 3108 // Adjust the function prologue to enable split stacks. This currently only 3109 // supports android and linux. 3110 // 3111 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but 3112 // must be well defined in order to allow for consistent implementations of the 3113 // __morestack helper function. The ABI is also not a normal ABI in that it 3114 // doesn't follow the normal calling conventions because this allows the 3115 // prologue of each function to be optimized further. 3116 // 3117 // Currently, the ABI looks like (when calling __morestack) 3118 // 3119 // * r4 holds the minimum stack size requested for this function call 3120 // * r5 holds the stack size of the arguments to the function 3121 // * the beginning of the function is 3 instructions after the call to 3122 // __morestack 3123 // 3124 // Implementations of __morestack should use r4 to allocate a new stack, r5 to 3125 // place the arguments on to the new stack, and the 3-instruction knowledge to 3126 // jump directly to the body of the function when working on the new stack. 3127 // 3128 // An old (and possibly no longer compatible) implementation of __morestack for 3129 // ARM can be found at [1]. 3130 // 3131 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S 3132 void ARMFrameLowering::adjustForSegmentedStacks( 3133 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const { 3134 unsigned Opcode; 3135 unsigned CFIIndex; 3136 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>(); 3137 bool Thumb = ST->isThumb(); 3138 bool Thumb2 = ST->isThumb2(); 3139 3140 // Sadly, this currently doesn't support varargs, platforms other than 3141 // android/linux. Note that thumb1/thumb2 are support for android/linux. 3142 if (MF.getFunction().isVarArg()) 3143 report_fatal_error("Segmented stacks do not support vararg functions."); 3144 if (!ST->isTargetAndroid() && !ST->isTargetLinux()) 3145 report_fatal_error("Segmented stacks not supported on this platform."); 3146 3147 MachineFrameInfo &MFI = MF.getFrameInfo(); 3148 MCContext &Context = MF.getContext(); 3149 const MCRegisterInfo *MRI = Context.getRegisterInfo(); 3150 const ARMBaseInstrInfo &TII = 3151 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo()); 3152 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>(); 3153 DebugLoc DL; 3154 3155 if (!MFI.needsSplitStackProlog()) 3156 return; 3157 3158 uint64_t StackSize = MFI.getStackSize(); 3159 3160 // Use R4 and R5 as scratch registers. 3161 // We save R4 and R5 before use and restore them before leaving the function. 3162 unsigned ScratchReg0 = ARM::R4; 3163 unsigned ScratchReg1 = ARM::R5; 3164 unsigned MovOp = ST->useMovt() ? ARM::t2MOVi32imm : ARM::tMOVi32imm; 3165 uint64_t AlignedStackSize; 3166 3167 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock(); 3168 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock(); 3169 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock(); 3170 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock(); 3171 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock(); 3172 3173 // Grab everything that reaches PrologueMBB to update there liveness as well. 3174 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion; 3175 SmallVector<MachineBasicBlock *, 2> WalkList; 3176 WalkList.push_back(&PrologueMBB); 3177 3178 do { 3179 MachineBasicBlock *CurMBB = WalkList.pop_back_val(); 3180 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) { 3181 if (BeforePrologueRegion.insert(PredBB).second) 3182 WalkList.push_back(PredBB); 3183 } 3184 } while (!WalkList.empty()); 3185 3186 // The order in that list is important. 3187 // The blocks will all be inserted before PrologueMBB using that order. 3188 // Therefore the block that should appear first in the CFG should appear 3189 // first in the list. 3190 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB, 3191 PostStackMBB}; 3192 3193 for (MachineBasicBlock *B : AddedBlocks) 3194 BeforePrologueRegion.insert(B); 3195 3196 for (const auto &LI : PrologueMBB.liveins()) { 3197 for (MachineBasicBlock *PredBB : BeforePrologueRegion) 3198 PredBB->addLiveIn(LI); 3199 } 3200 3201 // Remove the newly added blocks from the list, since we know 3202 // we do not have to do the following updates for them. 3203 for (MachineBasicBlock *B : AddedBlocks) { 3204 BeforePrologueRegion.erase(B); 3205 MF.insert(PrologueMBB.getIterator(), B); 3206 } 3207 3208 for (MachineBasicBlock *MBB : BeforePrologueRegion) { 3209 // Make sure the LiveIns are still sorted and unique. 3210 MBB->sortUniqueLiveIns(); 3211 // Replace the edges to PrologueMBB by edges to the sequences 3212 // we are about to add, but only update for immediate predecessors. 3213 if (MBB->isSuccessor(&PrologueMBB)) 3214 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]); 3215 } 3216 3217 // The required stack size that is aligned to ARM constant criterion. 3218 AlignedStackSize = alignToARMConstant(StackSize); 3219 3220 // When the frame size is less than 256 we just compare the stack 3221 // boundary directly to the value of the stack pointer, per gcc. 3222 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable; 3223 3224 // We will use two of the callee save registers as scratch registers so we 3225 // need to save those registers onto the stack. 3226 // We will use SR0 to hold stack limit and SR1 to hold the stack size 3227 // requested and arguments for __morestack(). 3228 // SR0: Scratch Register #0 3229 // SR1: Scratch Register #1 3230 // push {SR0, SR1} 3231 if (Thumb) { 3232 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)) 3233 .add(predOps(ARMCC::AL)) 3234 .addReg(ScratchReg0) 3235 .addReg(ScratchReg1); 3236 } else { 3237 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD)) 3238 .addReg(ARM::SP, RegState::Define) 3239 .addReg(ARM::SP) 3240 .add(predOps(ARMCC::AL)) 3241 .addReg(ScratchReg0) 3242 .addReg(ScratchReg1); 3243 } 3244 3245 // Emit the relevant DWARF information about the change in stack pointer as 3246 // well as where to find both r4 and r5 (the callee-save registers) 3247 if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) { 3248 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 8)); 3249 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3250 .addCFIIndex(CFIIndex); 3251 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 3252 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4)); 3253 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3254 .addCFIIndex(CFIIndex); 3255 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 3256 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8)); 3257 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3258 .addCFIIndex(CFIIndex); 3259 } 3260 3261 // mov SR1, sp 3262 if (Thumb) { 3263 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1) 3264 .addReg(ARM::SP) 3265 .add(predOps(ARMCC::AL)); 3266 } else if (CompareStackPointer) { 3267 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1) 3268 .addReg(ARM::SP) 3269 .add(predOps(ARMCC::AL)) 3270 .add(condCodeOp()); 3271 } 3272 3273 // sub SR1, sp, #StackSize 3274 if (!CompareStackPointer && Thumb) { 3275 if (AlignedStackSize < 256) { 3276 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1) 3277 .add(condCodeOp()) 3278 .addReg(ScratchReg1) 3279 .addImm(AlignedStackSize) 3280 .add(predOps(ARMCC::AL)); 3281 } else { 3282 if (Thumb2 || ST->genExecuteOnly()) { 3283 BuildMI(McrMBB, DL, TII.get(MovOp), ScratchReg0) 3284 .addImm(AlignedStackSize); 3285 } else { 3286 auto MBBI = McrMBB->end(); 3287 auto RegInfo = STI.getRegisterInfo(); 3288 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0, 3289 AlignedStackSize); 3290 } 3291 BuildMI(McrMBB, DL, TII.get(ARM::tSUBrr), ScratchReg1) 3292 .add(condCodeOp()) 3293 .addReg(ScratchReg1) 3294 .addReg(ScratchReg0) 3295 .add(predOps(ARMCC::AL)); 3296 } 3297 } else if (!CompareStackPointer) { 3298 if (AlignedStackSize < 256) { 3299 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1) 3300 .addReg(ARM::SP) 3301 .addImm(AlignedStackSize) 3302 .add(predOps(ARMCC::AL)) 3303 .add(condCodeOp()); 3304 } else { 3305 auto MBBI = McrMBB->end(); 3306 auto RegInfo = STI.getRegisterInfo(); 3307 RegInfo->emitLoadConstPool(*McrMBB, MBBI, DL, ScratchReg0, 0, 3308 AlignedStackSize); 3309 BuildMI(McrMBB, DL, TII.get(ARM::SUBrr), ScratchReg1) 3310 .addReg(ARM::SP) 3311 .addReg(ScratchReg0) 3312 .add(predOps(ARMCC::AL)) 3313 .add(condCodeOp()); 3314 } 3315 } 3316 3317 if (Thumb && ST->isThumb1Only()) { 3318 if (ST->genExecuteOnly()) { 3319 BuildMI(GetMBB, DL, TII.get(MovOp), ScratchReg0) 3320 .addExternalSymbol("__STACK_LIMIT"); 3321 } else { 3322 unsigned PCLabelId = ARMFI->createPICLabelUId(); 3323 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create( 3324 MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0); 3325 MachineConstantPool *MCP = MF.getConstantPool(); 3326 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4)); 3327 3328 // ldr SR0, [pc, offset(STACK_LIMIT)] 3329 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0) 3330 .addConstantPoolIndex(CPI) 3331 .add(predOps(ARMCC::AL)); 3332 } 3333 3334 // ldr SR0, [SR0] 3335 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0) 3336 .addReg(ScratchReg0) 3337 .addImm(0) 3338 .add(predOps(ARMCC::AL)); 3339 } else { 3340 // Get TLS base address from the coprocessor 3341 // mrc p15, #0, SR0, c13, c0, #3 3342 BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC), 3343 ScratchReg0) 3344 .addImm(15) 3345 .addImm(0) 3346 .addImm(13) 3347 .addImm(0) 3348 .addImm(3) 3349 .add(predOps(ARMCC::AL)); 3350 3351 // Use the last tls slot on android and a private field of the TCP on linux. 3352 assert(ST->isTargetAndroid() || ST->isTargetLinux()); 3353 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1; 3354 3355 // Get the stack limit from the right offset 3356 // ldr SR0, [sr0, #4 * TlsOffset] 3357 BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12), 3358 ScratchReg0) 3359 .addReg(ScratchReg0) 3360 .addImm(4 * TlsOffset) 3361 .add(predOps(ARMCC::AL)); 3362 } 3363 3364 // Compare stack limit with stack size requested. 3365 // cmp SR0, SR1 3366 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr; 3367 BuildMI(GetMBB, DL, TII.get(Opcode)) 3368 .addReg(ScratchReg0) 3369 .addReg(ScratchReg1) 3370 .add(predOps(ARMCC::AL)); 3371 3372 // This jump is taken if StackLimit <= SP - stack required. 3373 Opcode = Thumb ? ARM::tBcc : ARM::Bcc; 3374 BuildMI(GetMBB, DL, TII.get(Opcode)) 3375 .addMBB(PostStackMBB) 3376 .addImm(ARMCC::LS) 3377 .addReg(ARM::CPSR); 3378 3379 // Calling __morestack(StackSize, Size of stack arguments). 3380 // __morestack knows that the stack size requested is in SR0(r4) 3381 // and amount size of stack arguments is in SR1(r5). 3382 3383 // Pass first argument for the __morestack by Scratch Register #0. 3384 // The amount size of stack required 3385 if (Thumb) { 3386 if (AlignedStackSize < 256) { 3387 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0) 3388 .add(condCodeOp()) 3389 .addImm(AlignedStackSize) 3390 .add(predOps(ARMCC::AL)); 3391 } else { 3392 if (Thumb2 || ST->genExecuteOnly()) { 3393 BuildMI(AllocMBB, DL, TII.get(MovOp), ScratchReg0) 3394 .addImm(AlignedStackSize); 3395 } else { 3396 auto MBBI = AllocMBB->end(); 3397 auto RegInfo = STI.getRegisterInfo(); 3398 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0, 3399 AlignedStackSize); 3400 } 3401 } 3402 } else { 3403 if (AlignedStackSize < 256) { 3404 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0) 3405 .addImm(AlignedStackSize) 3406 .add(predOps(ARMCC::AL)) 3407 .add(condCodeOp()); 3408 } else { 3409 auto MBBI = AllocMBB->end(); 3410 auto RegInfo = STI.getRegisterInfo(); 3411 RegInfo->emitLoadConstPool(*AllocMBB, MBBI, DL, ScratchReg0, 0, 3412 AlignedStackSize); 3413 } 3414 } 3415 3416 // Pass second argument for the __morestack by Scratch Register #1. 3417 // The amount size of stack consumed to save function arguments. 3418 if (Thumb) { 3419 if (ARMFI->getArgumentStackSize() < 256) { 3420 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1) 3421 .add(condCodeOp()) 3422 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())) 3423 .add(predOps(ARMCC::AL)); 3424 } else { 3425 if (Thumb2 || ST->genExecuteOnly()) { 3426 BuildMI(AllocMBB, DL, TII.get(MovOp), ScratchReg1) 3427 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())); 3428 } else { 3429 auto MBBI = AllocMBB->end(); 3430 auto RegInfo = STI.getRegisterInfo(); 3431 RegInfo->emitLoadConstPool( 3432 *AllocMBB, MBBI, DL, ScratchReg1, 0, 3433 alignToARMConstant(ARMFI->getArgumentStackSize())); 3434 } 3435 } 3436 } else { 3437 if (alignToARMConstant(ARMFI->getArgumentStackSize()) < 256) { 3438 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1) 3439 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())) 3440 .add(predOps(ARMCC::AL)) 3441 .add(condCodeOp()); 3442 } else { 3443 auto MBBI = AllocMBB->end(); 3444 auto RegInfo = STI.getRegisterInfo(); 3445 RegInfo->emitLoadConstPool( 3446 *AllocMBB, MBBI, DL, ScratchReg1, 0, 3447 alignToARMConstant(ARMFI->getArgumentStackSize())); 3448 } 3449 } 3450 3451 // push {lr} - Save return address of this function. 3452 if (Thumb) { 3453 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)) 3454 .add(predOps(ARMCC::AL)) 3455 .addReg(ARM::LR); 3456 } else { 3457 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD)) 3458 .addReg(ARM::SP, RegState::Define) 3459 .addReg(ARM::SP) 3460 .add(predOps(ARMCC::AL)) 3461 .addReg(ARM::LR); 3462 } 3463 3464 // Emit the DWARF info about the change in stack as well as where to find the 3465 // previous link register 3466 if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) { 3467 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 12)); 3468 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3469 .addCFIIndex(CFIIndex); 3470 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset( 3471 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12)); 3472 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3473 .addCFIIndex(CFIIndex); 3474 } 3475 3476 // Call __morestack(). 3477 if (Thumb) { 3478 BuildMI(AllocMBB, DL, TII.get(ARM::tBL)) 3479 .add(predOps(ARMCC::AL)) 3480 .addExternalSymbol("__morestack"); 3481 } else { 3482 BuildMI(AllocMBB, DL, TII.get(ARM::BL)) 3483 .addExternalSymbol("__morestack"); 3484 } 3485 3486 // pop {lr} - Restore return address of this original function. 3487 if (Thumb) { 3488 if (ST->isThumb1Only()) { 3489 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)) 3490 .add(predOps(ARMCC::AL)) 3491 .addReg(ScratchReg0); 3492 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR) 3493 .addReg(ScratchReg0) 3494 .add(predOps(ARMCC::AL)); 3495 } else { 3496 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST)) 3497 .addReg(ARM::LR, RegState::Define) 3498 .addReg(ARM::SP, RegState::Define) 3499 .addReg(ARM::SP) 3500 .addImm(4) 3501 .add(predOps(ARMCC::AL)); 3502 } 3503 } else { 3504 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 3505 .addReg(ARM::SP, RegState::Define) 3506 .addReg(ARM::SP) 3507 .add(predOps(ARMCC::AL)) 3508 .addReg(ARM::LR); 3509 } 3510 3511 // Restore SR0 and SR1 in case of __morestack() was called. 3512 // __morestack() will skip PostStackMBB block so we need to restore 3513 // scratch registers from here. 3514 // pop {SR0, SR1} 3515 if (Thumb) { 3516 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)) 3517 .add(predOps(ARMCC::AL)) 3518 .addReg(ScratchReg0) 3519 .addReg(ScratchReg1); 3520 } else { 3521 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD)) 3522 .addReg(ARM::SP, RegState::Define) 3523 .addReg(ARM::SP) 3524 .add(predOps(ARMCC::AL)) 3525 .addReg(ScratchReg0) 3526 .addReg(ScratchReg1); 3527 } 3528 3529 // Update the CFA offset now that we've popped 3530 if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) { 3531 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0)); 3532 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3533 .addCFIIndex(CFIIndex); 3534 } 3535 3536 // Return from this function. 3537 BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL)); 3538 3539 // Restore SR0 and SR1 in case of __morestack() was not called. 3540 // pop {SR0, SR1} 3541 if (Thumb) { 3542 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)) 3543 .add(predOps(ARMCC::AL)) 3544 .addReg(ScratchReg0) 3545 .addReg(ScratchReg1); 3546 } else { 3547 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD)) 3548 .addReg(ARM::SP, RegState::Define) 3549 .addReg(ARM::SP) 3550 .add(predOps(ARMCC::AL)) 3551 .addReg(ScratchReg0) 3552 .addReg(ScratchReg1); 3553 } 3554 3555 // Update the CFA offset now that we've popped 3556 if (!MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) { 3557 CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0)); 3558 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3559 .addCFIIndex(CFIIndex); 3560 3561 // Tell debuggers that r4 and r5 are now the same as they were in the 3562 // previous function, that they're the "Same Value". 3563 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue( 3564 nullptr, MRI->getDwarfRegNum(ScratchReg0, true))); 3565 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3566 .addCFIIndex(CFIIndex); 3567 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue( 3568 nullptr, MRI->getDwarfRegNum(ScratchReg1, true))); 3569 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION)) 3570 .addCFIIndex(CFIIndex); 3571 } 3572 3573 // Organizing MBB lists 3574 PostStackMBB->addSuccessor(&PrologueMBB); 3575 3576 AllocMBB->addSuccessor(PostStackMBB); 3577 3578 GetMBB->addSuccessor(PostStackMBB); 3579 GetMBB->addSuccessor(AllocMBB); 3580 3581 McrMBB->addSuccessor(GetMBB); 3582 3583 PrevStackMBB->addSuccessor(McrMBB); 3584 3585 #ifdef EXPENSIVE_CHECKS 3586 MF.verify(); 3587 #endif 3588 } 3589