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