1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the ARM implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
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"
35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36 cl::desc("Align ARM NEON spills in prolog and epilog"));
38 static MachineBasicBlock::iterator
39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
42 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
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.
49 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
50 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
52 // iOS requires FP not to be clobbered for backtracing purpose.
53 if (STI.isTargetIOS())
56 const MachineFrameInfo *MFI = MF.getFrameInfo();
57 // Always eliminate non-leaf frame pointers.
58 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
60 RegInfo->needsStackRealignment(MF) ||
61 MFI->hasVarSizedObjects() ||
62 MFI->isFrameAddressTaken());
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.
70 bool 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
80 return !MF.getFrameInfo()->hasVarSizedObjects();
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.
88 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
89 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
92 static 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))
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)
114 static 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) {
122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123 Pred, PredReg, TII, MIFlags);
125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126 Pred, PredReg, TII, MIFlags);
129 static 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);
139 static int sizeOfSPAdjustment(const MachineInstr *MI) {
141 switch (MI->getOpcode()) {
142 case ARM::VSTMDDB_UPD:
146 case ARM::t2STMDB_UPD:
150 case ARM::STR_PRE_IMM:
153 llvm_unreachable("Unknown push or pop like instruction");
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)
164 static 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")
172 .getAsInteger(0, StackProbeSize);
173 return StackSizeInBytes >= StackProbeSize;
177 struct StackAdjustingInsts {
179 MachineBasicBlock::iterator I;
184 SmallVector<InstInfo, 4> Insts;
186 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
187 bool BeforeFPSet = false) {
188 InstInfo Info = {I, SPAdjust, BeforeFPSet};
189 Insts.push_back(Info);
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;
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)
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);
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
225 static 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
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
246 // lsr Reg, Reg, log2(Alignment)
247 // lsl Reg, Reg, log2(Alignment)
249 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
250 .addReg(Reg, RegState::Kill)
251 .addImm(~AlignMask));
252 } else if (AlignMask <= 255) {
254 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
255 .addReg(Reg, RegState::Kill)
256 .addImm(AlignMask)));
258 assert(!MustBeSingleInstruction &&
259 "Shouldn't call emitAligningInstructions demanding a single "
260 "instruction to be emitted for large stack alignment for a target "
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))));
272 // Since this is only reached for Thumb-2 targets, the BFC instruction
273 // should always be available.
275 AddDefaultPred(BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
276 .addReg(Reg, RegState::Kill)
277 .addImm(~AlignMask));
281 void ARMFrameLowering::emitPrologue(MachineFunction &MF,
282 MachineBasicBlock &MBB) const {
283 assert(&MBB == &MF.front() && "Shrink-wrapping not yet implemented");
284 MachineBasicBlock::iterator MBBI = MBB.begin();
285 MachineFrameInfo *MFI = MF.getFrameInfo();
286 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
287 MachineModuleInfo &MMI = MF.getMMI();
288 MCContext &Context = MMI.getContext();
289 const TargetMachine &TM = MF.getTarget();
290 const MCRegisterInfo *MRI = Context.getRegisterInfo();
291 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
292 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
293 assert(!AFI->isThumb1OnlyFunction() &&
294 "This emitPrologue does not support Thumb1!");
295 bool isARM = !AFI->isThumbFunction();
296 unsigned Align = STI.getFrameLowering()->getStackAlignment();
297 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
298 unsigned NumBytes = MFI->getStackSize();
299 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
300 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
301 unsigned FramePtr = RegInfo->getFrameRegister(MF);
303 // Determine the sizes of each callee-save spill areas and record which frame
304 // belongs to which callee-save spill areas.
305 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
306 int FramePtrSpillFI = 0;
309 // All calls are tail calls in GHC calling conv, and functions have no
310 // prologue/epilogue.
311 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
314 StackAdjustingInsts DefCFAOffsetCandidates;
315 bool HasFP = hasFP(MF);
317 // Allocate the vararg register save area.
318 if (ArgRegsSaveSize) {
319 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
320 MachineInstr::FrameSetup);
321 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
324 if (!AFI->hasStackFrame() &&
325 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
326 if (NumBytes - ArgRegsSaveSize != 0) {
327 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
328 MachineInstr::FrameSetup);
329 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
330 NumBytes - ArgRegsSaveSize, true);
332 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
336 // Determine spill area sizes.
337 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
338 unsigned Reg = CSI[i].getReg();
339 int FI = CSI[i].getFrameIdx();
346 if (STI.isTargetDarwin()) {
361 FramePtrSpillFI = FI;
365 // This is a DPR. Exclude the aligned DPRCS2 spills.
368 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
374 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
375 if (GPRCS1Size > 0) {
376 GPRCS1Push = LastPush = MBBI++;
377 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
380 // Determine starting offsets of spill areas.
381 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
382 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
383 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
384 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
385 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
386 int FramePtrOffsetInPush = 0;
388 FramePtrOffsetInPush =
389 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
390 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
393 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
394 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
395 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
398 if (GPRCS2Size > 0) {
399 GPRCS2Push = LastPush = MBBI++;
400 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
403 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
404 // .cfi_offset operations will reflect that.
406 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
407 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
408 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
410 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
411 MachineInstr::FrameSetup);
412 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
418 // Since vpush register list cannot have gaps, there may be multiple vpush
419 // instructions in the prologue.
420 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
421 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
426 // Move past the aligned DPRCS2 area.
427 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
428 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
429 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
430 // leaves the stack pointer pointing to the DPRCS2 area.
432 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
433 NumBytes += MFI->getObjectOffset(D8SpillFI);
435 NumBytes = DPRCSOffset;
437 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
438 uint32_t NumWords = NumBytes >> 2;
440 if (NumWords < 65536)
441 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
443 .setMIFlags(MachineInstr::FrameSetup));
445 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
447 .setMIFlags(MachineInstr::FrameSetup);
449 switch (TM.getCodeModel()) {
450 case CodeModel::Small:
451 case CodeModel::Medium:
452 case CodeModel::Default:
453 case CodeModel::Kernel:
454 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
455 .addImm((unsigned)ARMCC::AL).addReg(0)
456 .addExternalSymbol("__chkstk")
457 .addReg(ARM::R4, RegState::Implicit)
458 .setMIFlags(MachineInstr::FrameSetup);
460 case CodeModel::Large:
461 case CodeModel::JITDefault:
462 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
463 .addExternalSymbol("__chkstk")
464 .setMIFlags(MachineInstr::FrameSetup);
466 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
467 .addImm((unsigned)ARMCC::AL).addReg(0)
468 .addReg(ARM::R12, RegState::Kill)
469 .addReg(ARM::R4, RegState::Implicit)
470 .setMIFlags(MachineInstr::FrameSetup);
474 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
476 .addReg(ARM::SP, RegState::Define)
477 .addReg(ARM::R4, RegState::Kill)
478 .setMIFlags(MachineInstr::FrameSetup)));
483 // Adjust SP after all the callee-save spills.
484 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
485 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
487 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
488 MachineInstr::FrameSetup);
489 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
493 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
494 // Note it's not safe to do this in Thumb2 mode because it would have
495 // taken two instructions:
498 // If an interrupt is taken between the two instructions, then sp is in
499 // an inconsistent state (pointing to the middle of callee-saved area).
500 // The interrupt handler can end up clobbering the registers.
501 AFI->setShouldRestoreSPFromFP(true);
504 // Set FP to point to the stack slot that contains the previous FP.
505 // For iOS, FP is R7, which has now been stored in spill area 1.
506 // Otherwise, if this is not iOS, all the callee-saved registers go
507 // into spill area 1, including the FP in R11. In either case, it
508 // is in area one and the adjustment needs to take place just after
511 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
512 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
513 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
514 dl, TII, FramePtr, ARM::SP,
515 PushSize + FramePtrOffsetInPush,
516 MachineInstr::FrameSetup);
517 if (FramePtrOffsetInPush + PushSize != 0) {
518 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
519 nullptr, MRI->getDwarfRegNum(FramePtr, true),
520 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
521 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
522 .addCFIIndex(CFIIndex)
523 .setMIFlags(MachineInstr::FrameSetup);
526 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
527 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
528 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
529 .addCFIIndex(CFIIndex)
530 .setMIFlags(MachineInstr::FrameSetup);
534 // Now that the prologue's actual instructions are finalised, we can insert
535 // the necessary DWARF cf instructions to describe the situation. Start by
536 // recording where each register ended up:
537 if (GPRCS1Size > 0) {
538 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
540 for (const auto &Entry : CSI) {
541 unsigned Reg = Entry.getReg();
542 int FI = Entry.getFrameIdx();
549 if (STI.isTargetDarwin())
561 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
562 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
563 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
564 .addCFIIndex(CFIIndex)
565 .setMIFlags(MachineInstr::FrameSetup);
571 if (GPRCS2Size > 0) {
572 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
573 for (const auto &Entry : CSI) {
574 unsigned Reg = Entry.getReg();
575 int FI = Entry.getFrameIdx();
582 if (STI.isTargetDarwin()) {
583 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
584 unsigned Offset = MFI->getObjectOffset(FI);
585 unsigned CFIIndex = MMI.addFrameInst(
586 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
587 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
588 .addCFIIndex(CFIIndex)
589 .setMIFlags(MachineInstr::FrameSetup);
597 // Since vpush register list cannot have gaps, there may be multiple vpush
598 // instructions in the prologue.
599 MachineBasicBlock::iterator Pos = std::next(LastPush);
600 for (const auto &Entry : CSI) {
601 unsigned Reg = Entry.getReg();
602 int FI = Entry.getFrameIdx();
603 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
604 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
605 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
606 unsigned Offset = MFI->getObjectOffset(FI);
607 unsigned CFIIndex = MMI.addFrameInst(
608 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
609 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
610 .addCFIIndex(CFIIndex)
611 .setMIFlags(MachineInstr::FrameSetup);
616 // Now we can emit descriptions of where the canonical frame address was
617 // throughout the process. If we have a frame pointer, it takes over the job
618 // half-way through, so only the first few .cfi_def_cfa_offset instructions
619 // actually get emitted.
620 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
622 if (STI.isTargetELF() && hasFP(MF))
623 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
624 AFI->getFramePtrSpillOffset());
626 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
627 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
628 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
629 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
631 // If we need dynamic stack realignment, do it here. Be paranoid and make
632 // sure if we also have VLAs, we have a base pointer for frame access.
633 // If aligned NEON registers were spilled, the stack has already been
635 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
636 unsigned MaxAlign = MFI->getMaxAlignment();
637 assert(!AFI->isThumb1OnlyFunction());
638 if (!AFI->isThumbFunction()) {
639 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
642 // We cannot use sp as source/dest register here, thus we're using r4 to
643 // perform the calculations. We're emitting the following sequence:
645 // -- use emitAligningInstructions to produce best sequence to zero
646 // -- out lower bits in r4
648 // FIXME: It will be better just to find spare register here.
649 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
650 .addReg(ARM::SP, RegState::Kill));
651 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
653 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
654 .addReg(ARM::R4, RegState::Kill));
657 AFI->setShouldRestoreSPFromFP(true);
660 // If we need a base pointer, set it up here. It's whatever the value
661 // of the stack pointer is at this point. Any variable size objects
662 // will be allocated after this, so we can still use the base pointer
663 // to reference locals.
664 // FIXME: Clarify FrameSetup flags here.
665 if (RegInfo->hasBasePointer(MF)) {
667 BuildMI(MBB, MBBI, dl,
668 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
670 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
672 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
673 RegInfo->getBaseRegister())
677 // If the frame has variable sized objects then the epilogue must restore
678 // the sp from fp. We can assume there's an FP here since hasFP already
679 // checks for hasVarSizedObjects.
680 if (MFI->hasVarSizedObjects())
681 AFI->setShouldRestoreSPFromFP(true);
684 // Resolve TCReturn pseudo-instruction
685 void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
686 MachineBasicBlock &MBB) const {
687 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
688 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
689 unsigned RetOpcode = MBBI->getOpcode();
690 DebugLoc dl = MBBI->getDebugLoc();
691 const ARMBaseInstrInfo &TII =
692 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
694 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
697 // Tail call return: adjust the stack pointer and jump to callee.
698 MBBI = MBB.getLastNonDebugInstr();
699 MachineOperand &JumpTarget = MBBI->getOperand(0);
701 // Jump to label or value in register.
702 if (RetOpcode == ARM::TCRETURNdi) {
703 unsigned TCOpcode = STI.isThumb() ?
704 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
706 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
707 if (JumpTarget.isGlobal())
708 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
709 JumpTarget.getTargetFlags());
711 assert(JumpTarget.isSymbol());
712 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
713 JumpTarget.getTargetFlags());
716 // Add the default predicate in Thumb mode.
717 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
718 } else if (RetOpcode == ARM::TCRETURNri) {
719 BuildMI(MBB, MBBI, dl,
720 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
721 addReg(JumpTarget.getReg(), RegState::Kill);
724 MachineInstr *NewMI = std::prev(MBBI);
725 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
726 NewMI->addOperand(MBBI->getOperand(i));
728 // Delete the pseudo instruction TCRETURN.
733 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
734 MachineBasicBlock &MBB) const {
735 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
736 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
737 DebugLoc dl = MBBI->getDebugLoc();
738 MachineFrameInfo *MFI = MF.getFrameInfo();
739 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
740 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
741 const ARMBaseInstrInfo &TII =
742 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
743 assert(!AFI->isThumb1OnlyFunction() &&
744 "This emitEpilogue does not support Thumb1!");
745 bool isARM = !AFI->isThumbFunction();
747 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
748 int NumBytes = (int)MFI->getStackSize();
749 unsigned FramePtr = RegInfo->getFrameRegister(MF);
751 // All calls are tail calls in GHC calling conv, and functions have no
752 // prologue/epilogue.
753 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
754 fixTCReturn(MF, MBB);
758 if (!AFI->hasStackFrame()) {
759 if (NumBytes - ArgRegsSaveSize != 0)
760 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
762 // Unwind MBBI to point to first LDR / VLDRD.
763 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
764 if (MBBI != MBB.begin()) {
767 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
768 if (!isCSRestore(MBBI, TII, CSRegs))
772 // Move SP to start of FP callee save spill area.
773 NumBytes -= (ArgRegsSaveSize +
774 AFI->getGPRCalleeSavedArea1Size() +
775 AFI->getGPRCalleeSavedArea2Size() +
776 AFI->getDPRCalleeSavedGapSize() +
777 AFI->getDPRCalleeSavedAreaSize());
779 // Reset SP based on frame pointer only if the stack frame extends beyond
780 // frame pointer stack slot or target is ELF and the function has FP.
781 if (AFI->shouldRestoreSPFromFP()) {
782 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
785 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
788 // It's not possible to restore SP from FP in a single instruction.
789 // For iOS, this looks like:
792 // This is bad, if an interrupt is taken after the mov, sp is in an
793 // inconsistent state.
794 // Use the first callee-saved register as a scratch register.
795 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
796 "No scratch register to restore SP from FP!");
797 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
799 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
806 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
807 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
809 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
813 } else if (NumBytes &&
814 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
815 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
817 // Increment past our save areas.
818 if (AFI->getDPRCalleeSavedAreaSize()) {
820 // Since vpop register list cannot have gaps, there may be multiple vpop
821 // instructions in the epilogue.
822 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
825 if (AFI->getDPRCalleeSavedGapSize()) {
826 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
827 "unexpected DPR alignment gap");
828 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
831 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
832 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
835 fixTCReturn(MF, MBB);
838 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
841 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
842 /// debug info. It's the same as what we use for resolving the code-gen
843 /// references for now. FIXME: This can go wrong when references are
844 /// SP-relative and simple call frames aren't used.
846 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
847 unsigned &FrameReg) const {
848 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
852 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
853 int FI, unsigned &FrameReg,
855 const MachineFrameInfo *MFI = MF.getFrameInfo();
856 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
857 MF.getSubtarget().getRegisterInfo());
858 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
859 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
860 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
861 bool isFixed = MFI->isFixedObjectIndex(FI);
866 // SP can move around if there are allocas. We may also lose track of SP
867 // when emergency spilling inside a non-reserved call frame setup.
868 bool hasMovingSP = !hasReservedCallFrame(MF);
870 // When dynamically realigning the stack, use the frame pointer for
871 // parameters, and the stack/base pointer for locals.
872 if (RegInfo->needsStackRealignment(MF)) {
873 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
875 FrameReg = RegInfo->getFrameRegister(MF);
877 } else if (hasMovingSP) {
878 assert(RegInfo->hasBasePointer(MF) &&
879 "VLAs and dynamic stack alignment, but missing base pointer!");
880 FrameReg = RegInfo->getBaseRegister();
885 // If there is a frame pointer, use it when we can.
886 if (hasFP(MF) && AFI->hasStackFrame()) {
887 // Use frame pointer to reference fixed objects. Use it for locals if
888 // there are VLAs (and thus the SP isn't reliable as a base).
889 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
890 FrameReg = RegInfo->getFrameRegister(MF);
892 } else if (hasMovingSP) {
893 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
894 if (AFI->isThumb2Function()) {
895 // Try to use the frame pointer if we can, else use the base pointer
896 // since it's available. This is handy for the emergency spill slot, in
898 if (FPOffset >= -255 && FPOffset < 0) {
899 FrameReg = RegInfo->getFrameRegister(MF);
903 } else if (AFI->isThumb2Function()) {
904 // Use add <rd>, sp, #<imm8>
905 // ldr <rd>, [sp, #<imm8>]
906 // if at all possible to save space.
907 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
909 // In Thumb2 mode, the negative offset is very limited. Try to avoid
910 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
911 if (FPOffset >= -255 && FPOffset < 0) {
912 FrameReg = RegInfo->getFrameRegister(MF);
915 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
916 // Otherwise, use SP or FP, whichever is closer to the stack slot.
917 FrameReg = RegInfo->getFrameRegister(MF);
921 // Use the base pointer if we have one.
922 if (RegInfo->hasBasePointer(MF))
923 FrameReg = RegInfo->getBaseRegister();
927 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
930 return getFrameIndexReference(MF, FI, FrameReg);
933 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
934 MachineBasicBlock::iterator MI,
935 const std::vector<CalleeSavedInfo> &CSI,
936 unsigned StmOpc, unsigned StrOpc,
938 bool(*Func)(unsigned, bool),
939 unsigned NumAlignedDPRCS2Regs,
940 unsigned MIFlags) const {
941 MachineFunction &MF = *MBB.getParent();
942 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
945 if (MI != MBB.end()) DL = MI->getDebugLoc();
947 SmallVector<std::pair<unsigned,bool>, 4> Regs;
948 unsigned i = CSI.size();
950 unsigned LastReg = 0;
951 for (; i != 0; --i) {
952 unsigned Reg = CSI[i-1].getReg();
953 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
955 // D-registers in the aligned area DPRCS2 are NOT spilled here.
956 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
959 // Add the callee-saved register as live-in unless it's LR and
960 // @llvm.returnaddress is called. If LR is returned for
961 // @llvm.returnaddress then it's already added to the function and
962 // entry block live-in sets.
964 if (Reg == ARM::LR) {
965 if (MF.getFrameInfo()->isReturnAddressTaken() &&
966 MF.getRegInfo().isLiveIn(Reg))
973 // If NoGap is true, push consecutive registers and then leave the rest
974 // for other instructions. e.g.
975 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
976 if (NoGap && LastReg && LastReg != Reg-1)
979 Regs.push_back(std::make_pair(Reg, isKill));
984 if (Regs.size() > 1 || StrOpc== 0) {
985 MachineInstrBuilder MIB =
986 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
987 .addReg(ARM::SP).setMIFlags(MIFlags));
988 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
989 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
990 } else if (Regs.size() == 1) {
991 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
993 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
994 .addReg(ARM::SP).setMIFlags(MIFlags)
1000 // Put any subsequent vpush instructions before this one: they will refer to
1001 // higher register numbers so need to be pushed first in order to preserve
1007 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1008 MachineBasicBlock::iterator MI,
1009 const std::vector<CalleeSavedInfo> &CSI,
1010 unsigned LdmOpc, unsigned LdrOpc,
1011 bool isVarArg, bool NoGap,
1012 bool(*Func)(unsigned, bool),
1013 unsigned NumAlignedDPRCS2Regs) const {
1014 MachineFunction &MF = *MBB.getParent();
1015 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1016 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1017 DebugLoc DL = MI->getDebugLoc();
1018 unsigned RetOpcode = MI->getOpcode();
1019 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
1020 RetOpcode == ARM::TCRETURNri);
1022 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1024 SmallVector<unsigned, 4> Regs;
1025 unsigned i = CSI.size();
1027 unsigned LastReg = 0;
1028 bool DeleteRet = false;
1029 for (; i != 0; --i) {
1030 unsigned Reg = CSI[i-1].getReg();
1031 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
1033 // The aligned reloads from area DPRCS2 are not inserted here.
1034 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1037 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1040 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1041 // Fold the return instruction into the LDM.
1045 // If NoGap is true, pop consecutive registers and then leave the rest
1046 // for other instructions. e.g.
1047 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1048 if (NoGap && LastReg && LastReg != Reg-1)
1052 Regs.push_back(Reg);
1057 if (Regs.size() > 1 || LdrOpc == 0) {
1058 MachineInstrBuilder MIB =
1059 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1061 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1062 MIB.addReg(Regs[i], getDefRegState(true));
1064 MIB.copyImplicitOps(&*MI);
1065 MI->eraseFromParent();
1068 } else if (Regs.size() == 1) {
1069 // If we adjusted the reg to PC from LR above, switch it back here. We
1070 // only do that for LDM.
1071 if (Regs[0] == ARM::PC)
1073 MachineInstrBuilder MIB =
1074 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1075 .addReg(ARM::SP, RegState::Define)
1077 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1078 // that refactoring is complete (eventually).
1079 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1081 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1084 AddDefaultPred(MIB);
1088 // Put any subsequent vpop instructions after this one: they will refer to
1089 // higher register numbers so need to be popped afterwards.
1094 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1095 /// starting from d8. Also insert stack realignment code and leave the stack
1096 /// pointer pointing to the d8 spill slot.
1097 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1098 MachineBasicBlock::iterator MI,
1099 unsigned NumAlignedDPRCS2Regs,
1100 const std::vector<CalleeSavedInfo> &CSI,
1101 const TargetRegisterInfo *TRI) {
1102 MachineFunction &MF = *MBB.getParent();
1103 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1104 DebugLoc DL = MI->getDebugLoc();
1105 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1106 MachineFrameInfo &MFI = *MF.getFrameInfo();
1108 // Mark the D-register spill slots as properly aligned. Since MFI computes
1109 // stack slot layout backwards, this can actually mean that the d-reg stack
1110 // slot offsets can be wrong. The offset for d8 will always be correct.
1111 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1112 unsigned DNum = CSI[i].getReg() - ARM::D8;
1115 int FI = CSI[i].getFrameIdx();
1116 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1117 // registers will be 8-byte aligned.
1118 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1120 // The stack slot for D8 needs to be maximally aligned because this is
1121 // actually the point where we align the stack pointer. MachineFrameInfo
1122 // computes all offsets relative to the incoming stack pointer which is a
1123 // bit weird when realigning the stack. Any extra padding for this
1124 // over-alignment is not realized because the code inserted below adjusts
1125 // the stack pointer by numregs * 8 before aligning the stack pointer.
1127 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1130 // Move the stack pointer to the d8 spill slot, and align it at the same
1131 // time. Leave the stack slot address in the scratch register r4.
1133 // sub r4, sp, #numregs * 8
1134 // bic r4, r4, #align - 1
1137 bool isThumb = AFI->isThumbFunction();
1138 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1139 AFI->setShouldRestoreSPFromFP(true);
1141 // sub r4, sp, #numregs * 8
1142 // The immediate is <= 64, so it doesn't need any special encoding.
1143 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1144 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1146 .addImm(8 * NumAlignedDPRCS2Regs)));
1148 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1149 // We must set parameter MustBeSingleInstruction to true, since
1150 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1151 // stack alignment. Luckily, this can always be done since all ARM
1152 // architecture versions that support Neon also support the BFC
1154 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1157 // The stack pointer must be adjusted before spilling anything, otherwise
1158 // the stack slots could be clobbered by an interrupt handler.
1159 // Leave r4 live, it is used below.
1160 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1161 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1163 MIB = AddDefaultPred(MIB);
1167 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1168 // r4 holds the stack slot address.
1169 unsigned NextReg = ARM::D8;
1171 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1172 // The writeback is only needed when emitting two vst1.64 instructions.
1173 if (NumAlignedDPRCS2Regs >= 6) {
1174 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1175 &ARM::QQPRRegClass);
1176 MBB.addLiveIn(SupReg);
1177 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1179 .addReg(ARM::R4, RegState::Kill).addImm(16)
1181 .addReg(SupReg, RegState::ImplicitKill));
1183 NumAlignedDPRCS2Regs -= 4;
1186 // We won't modify r4 beyond this point. It currently points to the next
1187 // register to be spilled.
1188 unsigned R4BaseReg = NextReg;
1190 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1191 if (NumAlignedDPRCS2Regs >= 4) {
1192 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1193 &ARM::QQPRRegClass);
1194 MBB.addLiveIn(SupReg);
1195 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1196 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1197 .addReg(SupReg, RegState::ImplicitKill));
1199 NumAlignedDPRCS2Regs -= 4;
1202 // 16-byte aligned vst1.64 with 2 d-regs.
1203 if (NumAlignedDPRCS2Regs >= 2) {
1204 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1206 MBB.addLiveIn(SupReg);
1207 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1208 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1210 NumAlignedDPRCS2Regs -= 2;
1213 // Finally, use a vanilla vstr.64 for the odd last register.
1214 if (NumAlignedDPRCS2Regs) {
1215 MBB.addLiveIn(NextReg);
1216 // vstr.64 uses addrmode5 which has an offset scale of 4.
1217 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1219 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1222 // The last spill instruction inserted should kill the scratch register r4.
1223 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1226 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1227 /// iterator to the following instruction.
1228 static MachineBasicBlock::iterator
1229 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1230 unsigned NumAlignedDPRCS2Regs) {
1231 // sub r4, sp, #numregs * 8
1232 // bic r4, r4, #align - 1
1235 assert(MI->mayStore() && "Expecting spill instruction");
1237 // These switches all fall through.
1238 switch(NumAlignedDPRCS2Regs) {
1241 assert(MI->mayStore() && "Expecting spill instruction");
1244 assert(MI->mayStore() && "Expecting spill instruction");
1248 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1254 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1255 /// starting from d8. These instructions are assumed to execute while the
1256 /// stack is still aligned, unlike the code inserted by emitPopInst.
1257 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1258 MachineBasicBlock::iterator MI,
1259 unsigned NumAlignedDPRCS2Regs,
1260 const std::vector<CalleeSavedInfo> &CSI,
1261 const TargetRegisterInfo *TRI) {
1262 MachineFunction &MF = *MBB.getParent();
1263 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1264 DebugLoc DL = MI->getDebugLoc();
1265 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1267 // Find the frame index assigned to d8.
1269 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1270 if (CSI[i].getReg() == ARM::D8) {
1271 D8SpillFI = CSI[i].getFrameIdx();
1275 // Materialize the address of the d8 spill slot into the scratch register r4.
1276 // This can be fairly complicated if the stack frame is large, so just use
1277 // the normal frame index elimination mechanism to do it. This code runs as
1278 // the initial part of the epilog where the stack and base pointers haven't
1279 // been changed yet.
1280 bool isThumb = AFI->isThumbFunction();
1281 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1283 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1284 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1285 .addFrameIndex(D8SpillFI).addImm(0)));
1287 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1288 unsigned NextReg = ARM::D8;
1290 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1291 if (NumAlignedDPRCS2Regs >= 6) {
1292 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1293 &ARM::QQPRRegClass);
1294 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1295 .addReg(ARM::R4, RegState::Define)
1296 .addReg(ARM::R4, RegState::Kill).addImm(16)
1297 .addReg(SupReg, RegState::ImplicitDefine));
1299 NumAlignedDPRCS2Regs -= 4;
1302 // We won't modify r4 beyond this point. It currently points to the next
1303 // register to be spilled.
1304 unsigned R4BaseReg = NextReg;
1306 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1307 if (NumAlignedDPRCS2Regs >= 4) {
1308 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1309 &ARM::QQPRRegClass);
1310 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1311 .addReg(ARM::R4).addImm(16)
1312 .addReg(SupReg, RegState::ImplicitDefine));
1314 NumAlignedDPRCS2Regs -= 4;
1317 // 16-byte aligned vld1.64 with 2 d-regs.
1318 if (NumAlignedDPRCS2Regs >= 2) {
1319 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1321 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1322 .addReg(ARM::R4).addImm(16));
1324 NumAlignedDPRCS2Regs -= 2;
1327 // Finally, use a vanilla vldr.64 for the remaining odd register.
1328 if (NumAlignedDPRCS2Regs)
1329 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1330 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1332 // Last store kills r4.
1333 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1336 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1337 MachineBasicBlock::iterator MI,
1338 const std::vector<CalleeSavedInfo> &CSI,
1339 const TargetRegisterInfo *TRI) const {
1343 MachineFunction &MF = *MBB.getParent();
1344 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1346 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1347 unsigned PushOneOpc = AFI->isThumbFunction() ?
1348 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1349 unsigned FltOpc = ARM::VSTMDDB_UPD;
1350 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1351 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1352 MachineInstr::FrameSetup);
1353 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1354 MachineInstr::FrameSetup);
1355 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1356 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1358 // The code above does not insert spill code for the aligned DPRCS2 registers.
1359 // The stack realignment code will be inserted between the push instructions
1360 // and these spills.
1361 if (NumAlignedDPRCS2Regs)
1362 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1367 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1368 MachineBasicBlock::iterator MI,
1369 const std::vector<CalleeSavedInfo> &CSI,
1370 const TargetRegisterInfo *TRI) const {
1374 MachineFunction &MF = *MBB.getParent();
1375 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1376 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1377 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1379 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1380 // registers. Do that here instead.
1381 if (NumAlignedDPRCS2Regs)
1382 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1384 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1385 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1386 unsigned FltOpc = ARM::VLDMDIA_UPD;
1387 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1388 NumAlignedDPRCS2Regs);
1389 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1390 &isARMArea2Register, 0);
1391 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1392 &isARMArea1Register, 0);
1397 // FIXME: Make generic?
1398 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1399 const ARMBaseInstrInfo &TII) {
1400 unsigned FnSize = 0;
1401 for (auto &MBB : MF) {
1402 for (auto &MI : MBB)
1403 FnSize += TII.GetInstSizeInBytes(&MI);
1408 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1409 /// frames and return the stack size limit beyond which some of these
1410 /// instructions will require a scratch register during their expansion later.
1411 // FIXME: Move to TII?
1412 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1413 const TargetFrameLowering *TFI) {
1414 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1415 unsigned Limit = (1 << 12) - 1;
1416 for (auto &MBB : MF) {
1417 for (auto &MI : MBB) {
1418 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1419 if (!MI.getOperand(i).isFI())
1422 // When using ADDri to get the address of a stack object, 255 is the
1423 // largest offset guaranteed to fit in the immediate offset.
1424 if (MI.getOpcode() == ARM::ADDri) {
1425 Limit = std::min(Limit, (1U << 8) - 1);
1429 // Otherwise check the addressing mode.
1430 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1431 case ARMII::AddrMode3:
1432 case ARMII::AddrModeT2_i8:
1433 Limit = std::min(Limit, (1U << 8) - 1);
1435 case ARMII::AddrMode5:
1436 case ARMII::AddrModeT2_i8s4:
1437 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1439 case ARMII::AddrModeT2_i12:
1440 // i12 supports only positive offset so these will be converted to
1441 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1442 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1443 Limit = std::min(Limit, (1U << 8) - 1);
1445 case ARMII::AddrMode4:
1446 case ARMII::AddrMode6:
1447 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1448 // immediate offset for stack references.
1453 break; // At most one FI per instruction
1461 // In functions that realign the stack, it can be an advantage to spill the
1462 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1463 // instructions take alignment hints that can improve performance.
1465 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1466 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1467 if (!SpillAlignedNEONRegs)
1470 // Naked functions don't spill callee-saved registers.
1471 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1474 // We are planning to use NEON instructions vst1 / vld1.
1475 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1478 // Don't bother if the default stack alignment is sufficiently high.
1479 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1482 // Aligned spills require stack realignment.
1483 if (!static_cast<const ARMBaseRegisterInfo *>(
1484 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1487 // We always spill contiguous d-registers starting from d8. Count how many
1488 // needs spilling. The register allocator will almost always use the
1489 // callee-saved registers in order, but it can happen that there are holes in
1490 // the range. Registers above the hole will be spilled to the standard DPRCS
1492 MachineRegisterInfo &MRI = MF.getRegInfo();
1493 unsigned NumSpills = 0;
1494 for (; NumSpills < 8; ++NumSpills)
1495 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1498 // Don't do this for just one d-register. It's not worth it.
1502 // Spill the first NumSpills D-registers after realigning the stack.
1503 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1505 // A scratch register is required for the vst1 / vld1 instructions.
1506 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1510 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1511 RegScavenger *RS) const {
1512 // This tells PEI to spill the FP as if it is any other callee-save register
1513 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1514 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1515 // to combine multiple loads / stores.
1516 bool CanEliminateFrame = true;
1517 bool CS1Spilled = false;
1518 bool LRSpilled = false;
1519 unsigned NumGPRSpills = 0;
1520 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1521 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1522 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1523 MF.getSubtarget().getRegisterInfo());
1524 const ARMBaseInstrInfo &TII =
1525 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1526 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1527 MachineFrameInfo *MFI = MF.getFrameInfo();
1528 MachineRegisterInfo &MRI = MF.getRegInfo();
1529 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1531 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1532 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1533 // since it's not always possible to restore sp from fp in a single
1535 // FIXME: It will be better just to find spare register here.
1536 if (AFI->isThumb2Function() &&
1537 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1538 MRI.setPhysRegUsed(ARM::R4);
1540 if (AFI->isThumb1OnlyFunction()) {
1541 // Spill LR if Thumb1 function uses variable length argument lists.
1542 if (AFI->getArgRegsSaveSize() > 0)
1543 MRI.setPhysRegUsed(ARM::LR);
1545 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1546 // for sure what the stack size will be, but for this, an estimate is good
1547 // enough. If there anything changes it, it'll be a spill, which implies
1548 // we've used all the registers and so R4 is already used, so not marking
1549 // it here will be OK.
1550 // FIXME: It will be better just to find spare register here.
1551 unsigned StackSize = MFI->estimateStackSize(MF);
1552 if (MFI->hasVarSizedObjects() || StackSize > 508)
1553 MRI.setPhysRegUsed(ARM::R4);
1556 // See if we can spill vector registers to aligned stack.
1557 checkNumAlignedDPRCS2Regs(MF);
1559 // Spill the BasePtr if it's used.
1560 if (RegInfo->hasBasePointer(MF))
1561 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1563 // Don't spill FP if the frame can be eliminated. This is determined
1564 // by scanning the callee-save registers to see if any is used.
1565 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1566 for (unsigned i = 0; CSRegs[i]; ++i) {
1567 unsigned Reg = CSRegs[i];
1568 bool Spilled = false;
1569 if (MRI.isPhysRegUsed(Reg)) {
1571 CanEliminateFrame = false;
1574 if (!ARM::GPRRegClass.contains(Reg))
1580 if (!STI.isTargetDarwin()) {
1587 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1592 case ARM::R0: case ARM::R1:
1593 case ARM::R2: case ARM::R3:
1594 case ARM::R4: case ARM::R5:
1595 case ARM::R6: case ARM::R7:
1602 if (!STI.isTargetDarwin()) {
1603 UnspilledCS1GPRs.push_back(Reg);
1608 case ARM::R0: case ARM::R1:
1609 case ARM::R2: case ARM::R3:
1610 case ARM::R4: case ARM::R5:
1611 case ARM::R6: case ARM::R7:
1613 UnspilledCS1GPRs.push_back(Reg);
1616 UnspilledCS2GPRs.push_back(Reg);
1622 bool ForceLRSpill = false;
1623 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1624 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1625 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1626 // use of BL to implement far jump. If it turns out that it's not needed
1627 // then the branch fix up path will undo it.
1628 if (FnSize >= (1 << 11)) {
1629 CanEliminateFrame = false;
1630 ForceLRSpill = true;
1634 // If any of the stack slot references may be out of range of an immediate
1635 // offset, make sure a register (or a spill slot) is available for the
1636 // register scavenger. Note that if we're indexing off the frame pointer, the
1637 // effective stack size is 4 bytes larger since the FP points to the stack
1638 // slot of the previous FP. Also, if we have variable sized objects in the
1639 // function, stack slot references will often be negative, and some of
1640 // our instructions are positive-offset only, so conservatively consider
1641 // that case to want a spill slot (or register) as well. Similarly, if
1642 // the function adjusts the stack pointer during execution and the
1643 // adjustments aren't already part of our stack size estimate, our offset
1644 // calculations may be off, so be conservative.
1645 // FIXME: We could add logic to be more precise about negative offsets
1646 // and which instructions will need a scratch register for them. Is it
1647 // worth the effort and added fragility?
1650 (MFI->estimateStackSize(MF) +
1651 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1652 estimateRSStackSizeLimit(MF, this)))
1653 || MFI->hasVarSizedObjects()
1654 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1656 bool ExtraCSSpill = false;
1657 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1658 AFI->setHasStackFrame(true);
1660 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1661 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1662 if (!LRSpilled && CS1Spilled) {
1663 MRI.setPhysRegUsed(ARM::LR);
1665 SmallVectorImpl<unsigned>::iterator LRPos;
1666 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1668 if (LRPos != UnspilledCS1GPRs.end())
1669 UnspilledCS1GPRs.erase(LRPos);
1671 ForceLRSpill = false;
1672 ExtraCSSpill = true;
1676 MRI.setPhysRegUsed(FramePtr);
1677 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1679 if (FPPos != UnspilledCS1GPRs.end())
1680 UnspilledCS1GPRs.erase(FPPos);
1684 // If stack and double are 8-byte aligned and we are spilling an odd number
1685 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1686 // the integer and double callee save areas.
1687 unsigned TargetAlign = getStackAlignment();
1688 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1689 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1690 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1691 unsigned Reg = UnspilledCS1GPRs[i];
1692 // Don't spill high register if the function is thumb
1693 if (!AFI->isThumbFunction() ||
1694 isARMLowRegister(Reg) || Reg == ARM::LR) {
1695 MRI.setPhysRegUsed(Reg);
1696 if (!MRI.isReserved(Reg))
1697 ExtraCSSpill = true;
1701 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1702 unsigned Reg = UnspilledCS2GPRs.front();
1703 MRI.setPhysRegUsed(Reg);
1704 if (!MRI.isReserved(Reg))
1705 ExtraCSSpill = true;
1709 // Estimate if we might need to scavenge a register at some point in order
1710 // to materialize a stack offset. If so, either spill one additional
1711 // callee-saved register or reserve a special spill slot to facilitate
1712 // register scavenging. Thumb1 needs a spill slot for stack pointer
1713 // adjustments also, even when the frame itself is small.
1714 if (BigStack && !ExtraCSSpill) {
1715 // If any non-reserved CS register isn't spilled, just spill one or two
1716 // extra. That should take care of it!
1717 unsigned NumExtras = TargetAlign / 4;
1718 SmallVector<unsigned, 2> Extras;
1719 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1720 unsigned Reg = UnspilledCS1GPRs.back();
1721 UnspilledCS1GPRs.pop_back();
1722 if (!MRI.isReserved(Reg) &&
1723 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1725 Extras.push_back(Reg);
1729 // For non-Thumb1 functions, also check for hi-reg CS registers
1730 if (!AFI->isThumb1OnlyFunction()) {
1731 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1732 unsigned Reg = UnspilledCS2GPRs.back();
1733 UnspilledCS2GPRs.pop_back();
1734 if (!MRI.isReserved(Reg)) {
1735 Extras.push_back(Reg);
1740 if (Extras.size() && NumExtras == 0) {
1741 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1742 MRI.setPhysRegUsed(Extras[i]);
1744 } else if (!AFI->isThumb1OnlyFunction()) {
1745 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1746 // closest to SP or frame pointer.
1747 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1748 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1756 MRI.setPhysRegUsed(ARM::LR);
1757 AFI->setLRIsSpilledForFarJump(true);
1762 void ARMFrameLowering::
1763 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1764 MachineBasicBlock::iterator I) const {
1765 const ARMBaseInstrInfo &TII =
1766 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1767 if (!hasReservedCallFrame(MF)) {
1768 // If we have alloca, convert as follows:
1769 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1770 // ADJCALLSTACKUP -> add, sp, sp, amount
1771 MachineInstr *Old = I;
1772 DebugLoc dl = Old->getDebugLoc();
1773 unsigned Amount = Old->getOperand(0).getImm();
1775 // We need to keep the stack aligned properly. To do this, we round the
1776 // amount of space needed for the outgoing arguments up to the next
1777 // alignment boundary.
1778 unsigned Align = getStackAlignment();
1779 Amount = (Amount+Align-1)/Align*Align;
1781 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1782 assert(!AFI->isThumb1OnlyFunction() &&
1783 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1784 bool isARM = !AFI->isThumbFunction();
1786 // Replace the pseudo instruction with a new instruction...
1787 unsigned Opc = Old->getOpcode();
1788 int PIdx = Old->findFirstPredOperandIdx();
1789 ARMCC::CondCodes Pred = (PIdx == -1)
1790 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1791 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1792 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1793 unsigned PredReg = Old->getOperand(2).getReg();
1794 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1797 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1798 unsigned PredReg = Old->getOperand(3).getReg();
1799 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1800 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1808 /// Get the minimum constant for ARM that is greater than or equal to the
1809 /// argument. In ARM, constants can have any value that can be produced by
1810 /// rotating an 8-bit value to the right by an even number of bits within a
1812 static uint32_t alignToARMConstant(uint32_t Value) {
1813 unsigned Shifted = 0;
1818 while (!(Value & 0xC0000000)) {
1823 bool Carry = (Value & 0x00FFFFFF);
1824 Value = ((Value & 0xFF000000) >> 24) + Carry;
1826 if (Value & 0x0000100)
1827 Value = Value & 0x000001FC;
1830 Value = Value >> (Shifted - 24);
1832 Value = Value << (24 - Shifted);
1837 // The stack limit in the TCB is set to this many bytes above the actual
1839 static const uint64_t kSplitStackAvailable = 256;
1841 // Adjust the function prologue to enable split stacks. This currently only
1842 // supports android and linux.
1844 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1845 // must be well defined in order to allow for consistent implementations of the
1846 // __morestack helper function. The ABI is also not a normal ABI in that it
1847 // doesn't follow the normal calling conventions because this allows the
1848 // prologue of each function to be optimized further.
1850 // Currently, the ABI looks like (when calling __morestack)
1852 // * r4 holds the minimum stack size requested for this function call
1853 // * r5 holds the stack size of the arguments to the function
1854 // * the beginning of the function is 3 instructions after the call to
1857 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1858 // place the arguments on to the new stack, and the 3-instruction knowledge to
1859 // jump directly to the body of the function when working on the new stack.
1861 // An old (and possibly no longer compatible) implementation of __morestack for
1862 // ARM can be found at [1].
1864 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1865 void ARMFrameLowering::adjustForSegmentedStacks(
1866 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1869 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
1870 bool Thumb = ST->isThumb();
1872 // Sadly, this currently doesn't support varargs, platforms other than
1873 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1874 if (MF.getFunction()->isVarArg())
1875 report_fatal_error("Segmented stacks do not support vararg functions.");
1876 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1877 report_fatal_error("Segmented stacks not supported on this platform.");
1879 assert(&PrologueMBB == &MF.front() && "Shrink-wrapping not yet implemented");
1880 MachineFrameInfo *MFI = MF.getFrameInfo();
1881 MachineModuleInfo &MMI = MF.getMMI();
1882 MCContext &Context = MMI.getContext();
1883 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1884 const ARMBaseInstrInfo &TII =
1885 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1886 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1889 uint64_t StackSize = MFI->getStackSize();
1891 // Do not generate a prologue for functions with a stack of size zero
1895 // Use R4 and R5 as scratch registers.
1896 // We save R4 and R5 before use and restore them before leaving the function.
1897 unsigned ScratchReg0 = ARM::R4;
1898 unsigned ScratchReg1 = ARM::R5;
1899 uint64_t AlignedStackSize;
1901 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1902 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1903 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1904 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1905 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1907 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1908 e = PrologueMBB.livein_end();
1910 AllocMBB->addLiveIn(*i);
1911 GetMBB->addLiveIn(*i);
1912 McrMBB->addLiveIn(*i);
1913 PrevStackMBB->addLiveIn(*i);
1914 PostStackMBB->addLiveIn(*i);
1917 MF.push_front(PostStackMBB);
1918 MF.push_front(AllocMBB);
1919 MF.push_front(GetMBB);
1920 MF.push_front(McrMBB);
1921 MF.push_front(PrevStackMBB);
1923 // The required stack size that is aligned to ARM constant criterion.
1924 AlignedStackSize = alignToARMConstant(StackSize);
1926 // When the frame size is less than 256 we just compare the stack
1927 // boundary directly to the value of the stack pointer, per gcc.
1928 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1930 // We will use two of the callee save registers as scratch registers so we
1931 // need to save those registers onto the stack.
1932 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1933 // requested and arguments for __morestack().
1934 // SR0: Scratch Register #0
1935 // SR1: Scratch Register #1
1938 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1939 .addReg(ScratchReg0).addReg(ScratchReg1);
1941 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1942 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1943 .addReg(ScratchReg0).addReg(ScratchReg1);
1946 // Emit the relevant DWARF information about the change in stack pointer as
1947 // well as where to find both r4 and r5 (the callee-save registers)
1949 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1950 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1951 .addCFIIndex(CFIIndex);
1952 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1953 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1954 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1955 .addCFIIndex(CFIIndex);
1956 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1957 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1958 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1959 .addCFIIndex(CFIIndex);
1963 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1965 } else if (CompareStackPointer) {
1966 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1967 .addReg(ARM::SP)).addReg(0);
1970 // sub SR1, sp, #StackSize
1971 if (!CompareStackPointer && Thumb) {
1973 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1974 .addReg(ScratchReg1).addImm(AlignedStackSize));
1975 } else if (!CompareStackPointer) {
1976 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1977 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1980 if (Thumb && ST->isThumb1Only()) {
1981 unsigned PCLabelId = ARMFI->createPICLabelUId();
1982 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1983 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1984 MachineConstantPool *MCP = MF.getConstantPool();
1985 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1987 // ldr SR0, [pc, offset(STACK_LIMIT)]
1988 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1989 .addConstantPoolIndex(CPI));
1992 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1993 .addReg(ScratchReg0).addImm(0));
1995 // Get TLS base address from the coprocessor
1996 // mrc p15, #0, SR0, c13, c0, #3
1997 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2004 // Use the last tls slot on android and a private field of the TCP on linux.
2005 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2006 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2008 // Get the stack limit from the right offset
2009 // ldr SR0, [sr0, #4 * TlsOffset]
2010 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2011 .addReg(ScratchReg0).addImm(4 * TlsOffset));
2014 // Compare stack limit with stack size requested.
2016 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2017 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
2018 .addReg(ScratchReg0)
2019 .addReg(ScratchReg1));
2021 // This jump is taken if StackLimit < SP - stack required.
2022 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2023 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2028 // Calling __morestack(StackSize, Size of stack arguments).
2029 // __morestack knows that the stack size requested is in SR0(r4)
2030 // and amount size of stack arguments is in SR1(r5).
2032 // Pass first argument for the __morestack by Scratch Register #0.
2033 // The amount size of stack required
2035 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
2036 ScratchReg0)).addImm(AlignedStackSize));
2038 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2039 .addImm(AlignedStackSize)).addReg(0);
2041 // Pass second argument for the __morestack by Scratch Register #1.
2042 // The amount size of stack consumed to save function arguments.
2045 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
2046 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
2048 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2049 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
2053 // push {lr} - Save return address of this function.
2055 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
2058 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2059 .addReg(ARM::SP, RegState::Define)
2064 // Emit the DWARF info about the change in stack as well as where to find the
2065 // previous link register
2067 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2068 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2069 .addCFIIndex(CFIIndex);
2070 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2071 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2072 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2073 .addCFIIndex(CFIIndex);
2075 // Call __morestack().
2077 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2078 .addExternalSymbol("__morestack");
2080 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2081 .addExternalSymbol("__morestack");
2084 // pop {lr} - Restore return address of this original function.
2086 if (ST->isThumb1Only()) {
2087 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2088 .addReg(ScratchReg0);
2089 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2090 .addReg(ScratchReg0));
2092 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2093 .addReg(ARM::LR, RegState::Define)
2094 .addReg(ARM::SP, RegState::Define)
2099 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2100 .addReg(ARM::SP, RegState::Define)
2105 // Restore SR0 and SR1 in case of __morestack() was called.
2106 // __morestack() will skip PostStackMBB block so we need to restore
2107 // scratch registers from here.
2110 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2111 .addReg(ScratchReg0)
2112 .addReg(ScratchReg1);
2114 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2115 .addReg(ARM::SP, RegState::Define)
2117 .addReg(ScratchReg0)
2118 .addReg(ScratchReg1);
2121 // Update the CFA offset now that we've popped
2122 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2123 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2124 .addCFIIndex(CFIIndex);
2126 // bx lr - Return from this function.
2127 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2128 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2130 // Restore SR0 and SR1 in case of __morestack() was not called.
2133 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2134 .addReg(ScratchReg0)
2135 .addReg(ScratchReg1);
2137 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2138 .addReg(ARM::SP, RegState::Define)
2140 .addReg(ScratchReg0)
2141 .addReg(ScratchReg1);
2144 // Update the CFA offset now that we've popped
2145 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2146 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2147 .addCFIIndex(CFIIndex);
2149 // Tell debuggers that r4 and r5 are now the same as they were in the
2150 // previous function, that they're the "Same Value".
2151 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2152 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2153 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2154 .addCFIIndex(CFIIndex);
2155 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2156 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2157 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2158 .addCFIIndex(CFIIndex);
2160 // Organizing MBB lists
2161 PostStackMBB->addSuccessor(&PrologueMBB);
2163 AllocMBB->addSuccessor(PostStackMBB);
2165 GetMBB->addSuccessor(PostStackMBB);
2166 GetMBB->addSuccessor(AllocMBB);
2168 McrMBB->addSuccessor(GetMBB);
2170 PrevStackMBB->addSuccessor(McrMBB);