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