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