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