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