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