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