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 "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "MCTargetDesc/ARMBaseInfo.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/RegisterScavenging.h"
36 #include "llvm/IR/Attributes.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCDwarf.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetInstrInfo.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
63 #define DEBUG_TYPE "arm-frame-lowering"
68 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
69 cl::desc("Align ARM NEON spills in prolog and epilog"));
71 static MachineBasicBlock::iterator
72 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
73 unsigned NumAlignedDPRCS2Regs);
75 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
76 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
79 bool ARMFrameLowering::noFramePointerElim(const MachineFunction &MF) const {
80 // iOS always has a FP for backtracking, force other targets to keep their FP
81 // when doing FastISel. The emitted code is currently superior, and in cases
82 // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
83 return TargetFrameLowering::noFramePointerElim(MF) ||
84 MF.getSubtarget<ARMSubtarget>().useFastISel();
87 /// hasFP - Return true if the specified function should have a dedicated frame
88 /// pointer register. This is true if the function has variable sized allocas
89 /// or if frame pointer elimination is disabled.
90 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
91 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
92 const MachineFrameInfo &MFI = MF.getFrameInfo();
94 // ABI-required frame pointer.
95 if (MF.getTarget().Options.DisableFramePointerElim(MF))
98 // Frame pointer required for use within this function.
99 return (RegInfo->needsStackRealignment(MF) ||
100 MFI.hasVarSizedObjects() ||
101 MFI.isFrameAddressTaken());
104 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
105 /// not required, we reserve argument space for call sites in the function
106 /// immediately on entry to the current function. This eliminates the need for
107 /// add/sub sp brackets around call sites. Returns true if the call frame is
108 /// included as part of the stack frame.
109 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
110 const MachineFrameInfo &MFI = MF.getFrameInfo();
111 unsigned CFSize = MFI.getMaxCallFrameSize();
112 // It's not always a good idea to include the call frame as part of the
113 // stack frame. ARM (especially Thumb) has small immediate offset to
114 // address the stack frame. So a large call frame can cause poor codegen
115 // and may even makes it impossible to scavenge a register.
116 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
119 return !MFI.hasVarSizedObjects();
122 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
123 /// call frame pseudos can be simplified. Unlike most targets, having a FP
124 /// is not sufficient here since we still may reference some objects via SP
125 /// even when FP is available in Thumb2 mode.
127 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
128 return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
131 static bool isCSRestore(MachineInstr &MI, const ARMBaseInstrInfo &TII,
132 const MCPhysReg *CSRegs) {
133 // Integer spill area is handled with "pop".
134 if (isPopOpcode(MI.getOpcode())) {
135 // The first two operands are predicates. The last two are
136 // imp-def and imp-use of SP. Check everything in between.
137 for (int i = 5, e = MI.getNumOperands(); i != e; ++i)
138 if (!isCalleeSavedRegister(MI.getOperand(i).getReg(), CSRegs))
142 if ((MI.getOpcode() == ARM::LDR_POST_IMM ||
143 MI.getOpcode() == ARM::LDR_POST_REG ||
144 MI.getOpcode() == ARM::t2LDR_POST) &&
145 isCalleeSavedRegister(MI.getOperand(0).getReg(), CSRegs) &&
146 MI.getOperand(1).getReg() == ARM::SP)
152 static void emitRegPlusImmediate(
153 bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
154 const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
155 unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
156 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
158 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
159 Pred, PredReg, TII, MIFlags);
161 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
162 Pred, PredReg, TII, MIFlags);
165 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
166 MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
167 const ARMBaseInstrInfo &TII, int NumBytes,
168 unsigned MIFlags = MachineInstr::NoFlags,
169 ARMCC::CondCodes Pred = ARMCC::AL,
170 unsigned PredReg = 0) {
171 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
172 MIFlags, Pred, PredReg);
175 static int sizeOfSPAdjustment(const MachineInstr &MI) {
177 switch (MI.getOpcode()) {
178 case ARM::VSTMDDB_UPD:
182 case ARM::t2STMDB_UPD:
186 case ARM::STR_PRE_IMM:
189 llvm_unreachable("Unknown push or pop like instruction");
193 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
194 // pred) so the list starts at 4.
195 for (int i = MI.getNumOperands() - 1; i >= 4; --i)
200 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
201 size_t StackSizeInBytes) {
202 const MachineFrameInfo &MFI = MF.getFrameInfo();
203 const Function *F = MF.getFunction();
204 unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
205 if (F->hasFnAttribute("stack-probe-size"))
206 F->getFnAttribute("stack-probe-size")
208 .getAsInteger(0, StackProbeSize);
209 return StackSizeInBytes >= StackProbeSize;
214 struct StackAdjustingInsts {
216 MachineBasicBlock::iterator I;
221 SmallVector<InstInfo, 4> Insts;
223 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
224 bool BeforeFPSet = false) {
225 InstInfo Info = {I, SPAdjust, BeforeFPSet};
226 Insts.push_back(Info);
229 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
231 llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
232 assert(Info != Insts.end() && "invalid sp adjusting instruction");
233 Info->SPAdjust += ExtraBytes;
236 void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
237 const ARMBaseInstrInfo &TII, bool HasFP) {
238 MachineFunction &MF = *MBB.getParent();
239 unsigned CFAOffset = 0;
240 for (auto &Info : Insts) {
241 if (HasFP && !Info.BeforeFPSet)
244 CFAOffset -= Info.SPAdjust;
245 unsigned CFIIndex = MF.addFrameInst(
246 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
247 BuildMI(MBB, std::next(Info.I), dl,
248 TII.get(TargetOpcode::CFI_INSTRUCTION))
249 .addCFIIndex(CFIIndex)
250 .setMIFlags(MachineInstr::FrameSetup);
255 } // end anonymous namespace
257 /// Emit an instruction sequence that will align the address in
258 /// register Reg by zero-ing out the lower bits. For versions of the
259 /// architecture that support Neon, this must be done in a single
260 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
261 /// single instruction. That function only gets called when optimizing
262 /// spilling of D registers on a core with the Neon instruction set
264 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
265 const TargetInstrInfo &TII,
266 MachineBasicBlock &MBB,
267 MachineBasicBlock::iterator MBBI,
268 const DebugLoc &DL, const unsigned Reg,
269 const unsigned Alignment,
270 const bool MustBeSingleInstruction) {
271 const ARMSubtarget &AST =
272 static_cast<const ARMSubtarget &>(MF.getSubtarget());
273 const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
274 const unsigned AlignMask = Alignment - 1;
275 const unsigned NrBitsToZero = countTrailingZeros(Alignment);
276 assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
277 if (!AFI->isThumbFunction()) {
278 // if the BFC instruction is available, use that to zero the lower
280 // bfc Reg, #0, log2(Alignment)
281 // otherwise use BIC, if the mask to zero the required number of bits
282 // can be encoded in the bic immediate field
283 // bic Reg, Reg, Alignment-1
285 // lsr Reg, Reg, log2(Alignment)
286 // lsl Reg, Reg, log2(Alignment)
288 BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
289 .addReg(Reg, RegState::Kill)
291 .add(predOps(ARMCC::AL));
292 } else if (AlignMask <= 255) {
293 BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
294 .addReg(Reg, RegState::Kill)
296 .add(predOps(ARMCC::AL))
299 assert(!MustBeSingleInstruction &&
300 "Shouldn't call emitAligningInstructions demanding a single "
301 "instruction to be emitted for large stack alignment for a target "
303 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
304 .addReg(Reg, RegState::Kill)
305 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
306 .add(predOps(ARMCC::AL))
308 BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
309 .addReg(Reg, RegState::Kill)
310 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
311 .add(predOps(ARMCC::AL))
315 // Since this is only reached for Thumb-2 targets, the BFC instruction
316 // should always be available.
318 BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
319 .addReg(Reg, RegState::Kill)
321 .add(predOps(ARMCC::AL));
325 void ARMFrameLowering::emitPrologue(MachineFunction &MF,
326 MachineBasicBlock &MBB) const {
327 MachineBasicBlock::iterator MBBI = MBB.begin();
328 MachineFrameInfo &MFI = MF.getFrameInfo();
329 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
330 MachineModuleInfo &MMI = MF.getMMI();
331 MCContext &Context = MMI.getContext();
332 const TargetMachine &TM = MF.getTarget();
333 const MCRegisterInfo *MRI = Context.getRegisterInfo();
334 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
335 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
336 assert(!AFI->isThumb1OnlyFunction() &&
337 "This emitPrologue does not support Thumb1!");
338 bool isARM = !AFI->isThumbFunction();
339 unsigned Align = STI.getFrameLowering()->getStackAlignment();
340 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
341 unsigned NumBytes = MFI.getStackSize();
342 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
344 // Debug location must be unknown since the first debug location is used
345 // to determine the end of the prologue.
348 unsigned FramePtr = RegInfo->getFrameRegister(MF);
350 // Determine the sizes of each callee-save spill areas and record which frame
351 // belongs to which callee-save spill areas.
352 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
353 int FramePtrSpillFI = 0;
356 // All calls are tail calls in GHC calling conv, and functions have no
357 // prologue/epilogue.
358 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
361 StackAdjustingInsts DefCFAOffsetCandidates;
362 bool HasFP = hasFP(MF);
364 // Allocate the vararg register save area.
365 if (ArgRegsSaveSize) {
366 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
367 MachineInstr::FrameSetup);
368 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
371 if (!AFI->hasStackFrame() &&
372 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
373 if (NumBytes - ArgRegsSaveSize != 0) {
374 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
375 MachineInstr::FrameSetup);
376 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
377 NumBytes - ArgRegsSaveSize, true);
379 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
383 // Determine spill area sizes.
384 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
385 unsigned Reg = CSI[i].getReg();
386 int FI = CSI[i].getFrameIdx();
393 if (STI.splitFramePushPop(MF)) {
408 FramePtrSpillFI = FI;
412 // This is a DPR. Exclude the aligned DPRCS2 spills.
415 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
421 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
422 if (GPRCS1Size > 0) {
423 GPRCS1Push = LastPush = MBBI++;
424 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
427 // Determine starting offsets of spill areas.
428 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
429 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
430 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
431 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
432 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
433 int FramePtrOffsetInPush = 0;
435 FramePtrOffsetInPush =
436 MFI.getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
437 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
440 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
441 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
442 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
445 if (GPRCS2Size > 0) {
446 GPRCS2Push = LastPush = MBBI++;
447 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
450 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
451 // .cfi_offset operations will reflect that.
453 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
454 if (LastPush != MBB.end() &&
455 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
456 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
458 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
459 MachineInstr::FrameSetup);
460 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
466 // Since vpush register list cannot have gaps, there may be multiple vpush
467 // instructions in the prologue.
468 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
469 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
474 // Move past the aligned DPRCS2 area.
475 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
476 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
477 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
478 // leaves the stack pointer pointing to the DPRCS2 area.
480 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
481 NumBytes += MFI.getObjectOffset(D8SpillFI);
483 NumBytes = DPRCSOffset;
485 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
486 uint32_t NumWords = NumBytes >> 2;
488 if (NumWords < 65536)
489 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
491 .setMIFlags(MachineInstr::FrameSetup)
492 .add(predOps(ARMCC::AL));
494 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
496 .setMIFlags(MachineInstr::FrameSetup);
498 switch (TM.getCodeModel()) {
499 case CodeModel::Small:
500 case CodeModel::Medium:
501 case CodeModel::Default:
502 case CodeModel::Kernel:
503 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
504 .add(predOps(ARMCC::AL))
505 .addExternalSymbol("__chkstk")
506 .addReg(ARM::R4, RegState::Implicit)
507 .setMIFlags(MachineInstr::FrameSetup);
509 case CodeModel::Large:
510 case CodeModel::JITDefault:
511 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
512 .addExternalSymbol("__chkstk")
513 .setMIFlags(MachineInstr::FrameSetup);
515 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
516 .add(predOps(ARMCC::AL))
517 .addReg(ARM::R12, RegState::Kill)
518 .addReg(ARM::R4, RegState::Implicit)
519 .setMIFlags(MachineInstr::FrameSetup);
523 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
524 .addReg(ARM::SP, RegState::Kill)
525 .addReg(ARM::R4, RegState::Kill)
526 .setMIFlags(MachineInstr::FrameSetup)
527 .add(predOps(ARMCC::AL))
533 // Adjust SP after all the callee-save spills.
534 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
535 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
536 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
538 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
539 MachineInstr::FrameSetup);
540 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
544 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
545 // Note it's not safe to do this in Thumb2 mode because it would have
546 // taken two instructions:
549 // If an interrupt is taken between the two instructions, then sp is in
550 // an inconsistent state (pointing to the middle of callee-saved area).
551 // The interrupt handler can end up clobbering the registers.
552 AFI->setShouldRestoreSPFromFP(true);
555 // Set FP to point to the stack slot that contains the previous FP.
556 // For iOS, FP is R7, which has now been stored in spill area 1.
557 // Otherwise, if this is not iOS, all the callee-saved registers go
558 // into spill area 1, including the FP in R11. In either case, it
559 // is in area one and the adjustment needs to take place just after
562 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
563 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
564 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
565 dl, TII, FramePtr, ARM::SP,
566 PushSize + FramePtrOffsetInPush,
567 MachineInstr::FrameSetup);
568 if (FramePtrOffsetInPush + PushSize != 0) {
569 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
570 nullptr, MRI->getDwarfRegNum(FramePtr, true),
571 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
572 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
573 .addCFIIndex(CFIIndex)
574 .setMIFlags(MachineInstr::FrameSetup);
577 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
578 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
579 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
580 .addCFIIndex(CFIIndex)
581 .setMIFlags(MachineInstr::FrameSetup);
585 // Now that the prologue's actual instructions are finalised, we can insert
586 // the necessary DWARF cf instructions to describe the situation. Start by
587 // recording where each register ended up:
588 if (GPRCS1Size > 0) {
589 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
591 for (const auto &Entry : CSI) {
592 unsigned Reg = Entry.getReg();
593 int FI = Entry.getFrameIdx();
600 if (STI.splitFramePushPop(MF))
612 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
613 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
614 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
615 .addCFIIndex(CFIIndex)
616 .setMIFlags(MachineInstr::FrameSetup);
622 if (GPRCS2Size > 0) {
623 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
624 for (const auto &Entry : CSI) {
625 unsigned Reg = Entry.getReg();
626 int FI = Entry.getFrameIdx();
633 if (STI.splitFramePushPop(MF)) {
634 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
635 unsigned Offset = MFI.getObjectOffset(FI);
636 unsigned CFIIndex = MF.addFrameInst(
637 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
638 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
639 .addCFIIndex(CFIIndex)
640 .setMIFlags(MachineInstr::FrameSetup);
648 // Since vpush register list cannot have gaps, there may be multiple vpush
649 // instructions in the prologue.
650 MachineBasicBlock::iterator Pos = std::next(LastPush);
651 for (const auto &Entry : CSI) {
652 unsigned Reg = Entry.getReg();
653 int FI = Entry.getFrameIdx();
654 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
655 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
656 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
657 unsigned Offset = MFI.getObjectOffset(FI);
658 unsigned CFIIndex = MF.addFrameInst(
659 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
660 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
661 .addCFIIndex(CFIIndex)
662 .setMIFlags(MachineInstr::FrameSetup);
667 // Now we can emit descriptions of where the canonical frame address was
668 // throughout the process. If we have a frame pointer, it takes over the job
669 // half-way through, so only the first few .cfi_def_cfa_offset instructions
670 // actually get emitted.
671 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
673 if (STI.isTargetELF() && hasFP(MF))
674 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
675 AFI->getFramePtrSpillOffset());
677 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
678 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
679 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
680 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
682 // If we need dynamic stack realignment, do it here. Be paranoid and make
683 // sure if we also have VLAs, we have a base pointer for frame access.
684 // If aligned NEON registers were spilled, the stack has already been
686 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
687 unsigned MaxAlign = MFI.getMaxAlignment();
688 assert(!AFI->isThumb1OnlyFunction());
689 if (!AFI->isThumbFunction()) {
690 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
693 // We cannot use sp as source/dest register here, thus we're using r4 to
694 // perform the calculations. We're emitting the following sequence:
696 // -- use emitAligningInstructions to produce best sequence to zero
697 // -- out lower bits in r4
699 // FIXME: It will be better just to find spare register here.
700 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
701 .addReg(ARM::SP, RegState::Kill)
702 .add(predOps(ARMCC::AL));
703 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
705 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
706 .addReg(ARM::R4, RegState::Kill)
707 .add(predOps(ARMCC::AL));
710 AFI->setShouldRestoreSPFromFP(true);
713 // If we need a base pointer, set it up here. It's whatever the value
714 // of the stack pointer is at this point. Any variable size objects
715 // will be allocated after this, so we can still use the base pointer
716 // to reference locals.
717 // FIXME: Clarify FrameSetup flags here.
718 if (RegInfo->hasBasePointer(MF)) {
720 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
722 .add(predOps(ARMCC::AL))
725 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
727 .add(predOps(ARMCC::AL));
730 // If the frame has variable sized objects then the epilogue must restore
731 // the sp from fp. We can assume there's an FP here since hasFP already
732 // checks for hasVarSizedObjects.
733 if (MFI.hasVarSizedObjects())
734 AFI->setShouldRestoreSPFromFP(true);
737 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
738 MachineBasicBlock &MBB) const {
739 MachineFrameInfo &MFI = MF.getFrameInfo();
740 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
741 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
742 const ARMBaseInstrInfo &TII =
743 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
744 assert(!AFI->isThumb1OnlyFunction() &&
745 "This emitEpilogue does not support Thumb1!");
746 bool isARM = !AFI->isThumbFunction();
748 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
749 int NumBytes = (int)MFI.getStackSize();
750 unsigned FramePtr = RegInfo->getFrameRegister(MF);
752 // All calls are tail calls in GHC calling conv, and functions have no
753 // prologue/epilogue.
754 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
757 // First put ourselves on the first (from top) terminator instructions.
758 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
759 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
761 if (!AFI->hasStackFrame()) {
762 if (NumBytes - ArgRegsSaveSize != 0)
763 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
765 // Unwind MBBI to point to first LDR / VLDRD.
766 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
767 if (MBBI != MBB.begin()) {
770 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
771 if (!isCSRestore(*MBBI, TII, CSRegs))
775 // Move SP to start of FP callee save spill area.
776 NumBytes -= (ArgRegsSaveSize +
777 AFI->getGPRCalleeSavedArea1Size() +
778 AFI->getGPRCalleeSavedArea2Size() +
779 AFI->getDPRCalleeSavedGapSize() +
780 AFI->getDPRCalleeSavedAreaSize());
782 // Reset SP based on frame pointer only if the stack frame extends beyond
783 // frame pointer stack slot or target is ELF and the function has FP.
784 if (AFI->shouldRestoreSPFromFP()) {
785 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
788 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
791 // It's not possible to restore SP from FP in a single instruction.
792 // For iOS, this looks like:
795 // This is bad, if an interrupt is taken after the mov, sp is in an
796 // inconsistent state.
797 // Use the first callee-saved register as a scratch register.
798 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
799 "No scratch register to restore SP from FP!");
800 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
802 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
804 .add(predOps(ARMCC::AL));
809 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
811 .add(predOps(ARMCC::AL))
814 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
816 .add(predOps(ARMCC::AL));
818 } else if (NumBytes &&
819 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
820 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
822 // Increment past our save areas.
823 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
825 // Since vpop register list cannot have gaps, there may be multiple vpop
826 // instructions in the epilogue.
827 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
830 if (AFI->getDPRCalleeSavedGapSize()) {
831 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
832 "unexpected DPR alignment gap");
833 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
836 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
837 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
841 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
844 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
845 /// debug info. It's the same as what we use for resolving the code-gen
846 /// references for now. FIXME: This can go wrong when references are
847 /// SP-relative and simple call frames aren't used.
849 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
850 unsigned &FrameReg) const {
851 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
855 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
856 int FI, unsigned &FrameReg,
858 const MachineFrameInfo &MFI = MF.getFrameInfo();
859 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
860 MF.getSubtarget().getRegisterInfo());
861 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
862 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
863 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
864 bool isFixed = MFI.isFixedObjectIndex(FI);
869 // SP can move around if there are allocas. We may also lose track of SP
870 // when emergency spilling inside a non-reserved call frame setup.
871 bool hasMovingSP = !hasReservedCallFrame(MF);
873 // When dynamically realigning the stack, use the frame pointer for
874 // parameters, and the stack/base pointer for locals.
875 if (RegInfo->needsStackRealignment(MF)) {
876 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
878 FrameReg = RegInfo->getFrameRegister(MF);
880 } else if (hasMovingSP) {
881 assert(RegInfo->hasBasePointer(MF) &&
882 "VLAs and dynamic stack alignment, but missing base pointer!");
883 FrameReg = RegInfo->getBaseRegister();
888 // If there is a frame pointer, use it when we can.
889 if (hasFP(MF) && AFI->hasStackFrame()) {
890 // Use frame pointer to reference fixed objects. Use it for locals if
891 // there are VLAs (and thus the SP isn't reliable as a base).
892 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
893 FrameReg = RegInfo->getFrameRegister(MF);
895 } else if (hasMovingSP) {
896 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
897 if (AFI->isThumb2Function()) {
898 // Try to use the frame pointer if we can, else use the base pointer
899 // since it's available. This is handy for the emergency spill slot, in
901 if (FPOffset >= -255 && FPOffset < 0) {
902 FrameReg = RegInfo->getFrameRegister(MF);
906 } else if (AFI->isThumb2Function()) {
907 // Use add <rd>, sp, #<imm8>
908 // ldr <rd>, [sp, #<imm8>]
909 // if at all possible to save space.
910 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
912 // In Thumb2 mode, the negative offset is very limited. Try to avoid
913 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
914 if (FPOffset >= -255 && FPOffset < 0) {
915 FrameReg = RegInfo->getFrameRegister(MF);
918 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
919 // Otherwise, use SP or FP, whichever is closer to the stack slot.
920 FrameReg = RegInfo->getFrameRegister(MF);
924 // Use the base pointer if we have one.
925 if (RegInfo->hasBasePointer(MF))
926 FrameReg = RegInfo->getBaseRegister();
930 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
931 MachineBasicBlock::iterator MI,
932 const std::vector<CalleeSavedInfo> &CSI,
933 unsigned StmOpc, unsigned StrOpc,
935 bool(*Func)(unsigned, bool),
936 unsigned NumAlignedDPRCS2Regs,
937 unsigned MIFlags) const {
938 MachineFunction &MF = *MBB.getParent();
939 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
940 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
944 typedef std::pair<unsigned, bool> RegAndKill;
945 SmallVector<RegAndKill, 4> Regs;
946 unsigned i = CSI.size();
948 unsigned LastReg = 0;
949 for (; i != 0; --i) {
950 unsigned Reg = CSI[i-1].getReg();
951 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
953 // D-registers in the aligned area DPRCS2 are NOT spilled here.
954 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
957 bool isLiveIn = MF.getRegInfo().isLiveIn(Reg);
960 // If NoGap is true, push consecutive registers and then leave the rest
961 // for other instructions. e.g.
962 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
963 if (NoGap && LastReg && LastReg != Reg-1)
966 // Do not set a kill flag on values that are also marked as live-in. This
967 // happens with the @llvm-returnaddress intrinsic and with arguments
968 // passed in callee saved registers.
969 // Omitting the kill flags is conservatively correct even if the live-in
970 // is not used after all.
971 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
977 std::sort(Regs.begin(), Regs.end(), [&](const RegAndKill &LHS,
978 const RegAndKill &RHS) {
979 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
982 if (Regs.size() > 1 || StrOpc== 0) {
983 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
986 .add(predOps(ARMCC::AL));
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 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
991 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
995 .add(predOps(ARMCC::AL));
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
1002 if (MI != MBB.begin())
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 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1017 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1019 bool isTailCall = false;
1020 bool isInterrupt = false;
1021 bool isTrap = false;
1022 if (MBB.end() != MI) {
1023 DL = MI->getDebugLoc();
1024 unsigned RetOpcode = MI->getOpcode();
1025 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1027 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1029 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1030 RetOpcode == ARM::tTRAP;
1033 SmallVector<unsigned, 4> Regs;
1034 unsigned i = CSI.size();
1036 unsigned LastReg = 0;
1037 bool DeleteRet = false;
1038 for (; i != 0; --i) {
1039 unsigned Reg = CSI[i-1].getReg();
1040 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
1042 // The aligned reloads from area DPRCS2 are not inserted here.
1043 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1046 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1047 !isTrap && STI.hasV5TOps()) {
1048 if (MBB.succ_empty()) {
1051 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1053 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1054 // Fold the return instruction into the LDM.
1057 // If NoGap is true, pop consecutive registers and then leave the rest
1058 // for other instructions. e.g.
1059 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1060 if (NoGap && LastReg && LastReg != Reg-1)
1064 Regs.push_back(Reg);
1070 std::sort(Regs.begin(), Regs.end(), [&](unsigned LHS, unsigned RHS) {
1071 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1074 if (Regs.size() > 1 || LdrOpc == 0) {
1075 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1077 .add(predOps(ARMCC::AL));
1078 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1079 MIB.addReg(Regs[i], getDefRegState(true));
1080 if (DeleteRet && MI != MBB.end()) {
1081 MIB.copyImplicitOps(*MI);
1082 MI->eraseFromParent();
1085 } else if (Regs.size() == 1) {
1086 // If we adjusted the reg to PC from LR above, switch it back here. We
1087 // only do that for LDM.
1088 if (Regs[0] == ARM::PC)
1090 MachineInstrBuilder MIB =
1091 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1092 .addReg(ARM::SP, RegState::Define)
1094 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1095 // that refactoring is complete (eventually).
1096 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1098 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1101 MIB.add(predOps(ARMCC::AL));
1105 // Put any subsequent vpop instructions after this one: they will refer to
1106 // higher register numbers so need to be popped afterwards.
1107 if (MI != MBB.end())
1112 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1113 /// starting from d8. Also insert stack realignment code and leave the stack
1114 /// pointer pointing to the d8 spill slot.
1115 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1116 MachineBasicBlock::iterator MI,
1117 unsigned NumAlignedDPRCS2Regs,
1118 const std::vector<CalleeSavedInfo> &CSI,
1119 const TargetRegisterInfo *TRI) {
1120 MachineFunction &MF = *MBB.getParent();
1121 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1122 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1123 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1124 MachineFrameInfo &MFI = MF.getFrameInfo();
1126 // Mark the D-register spill slots as properly aligned. Since MFI computes
1127 // stack slot layout backwards, this can actually mean that the d-reg stack
1128 // slot offsets can be wrong. The offset for d8 will always be correct.
1129 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1130 unsigned DNum = CSI[i].getReg() - ARM::D8;
1131 if (DNum > NumAlignedDPRCS2Regs - 1)
1133 int FI = CSI[i].getFrameIdx();
1134 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1135 // registers will be 8-byte aligned.
1136 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1138 // The stack slot for D8 needs to be maximally aligned because this is
1139 // actually the point where we align the stack pointer. MachineFrameInfo
1140 // computes all offsets relative to the incoming stack pointer which is a
1141 // bit weird when realigning the stack. Any extra padding for this
1142 // over-alignment is not realized because the code inserted below adjusts
1143 // the stack pointer by numregs * 8 before aligning the stack pointer.
1145 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1148 // Move the stack pointer to the d8 spill slot, and align it at the same
1149 // time. Leave the stack slot address in the scratch register r4.
1151 // sub r4, sp, #numregs * 8
1152 // bic r4, r4, #align - 1
1155 bool isThumb = AFI->isThumbFunction();
1156 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1157 AFI->setShouldRestoreSPFromFP(true);
1159 // sub r4, sp, #numregs * 8
1160 // The immediate is <= 64, so it doesn't need any special encoding.
1161 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1162 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1164 .addImm(8 * NumAlignedDPRCS2Regs)
1165 .add(predOps(ARMCC::AL))
1168 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
1169 // We must set parameter MustBeSingleInstruction to true, since
1170 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1171 // stack alignment. Luckily, this can always be done since all ARM
1172 // architecture versions that support Neon also support the BFC
1174 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1177 // The stack pointer must be adjusted before spilling anything, otherwise
1178 // the stack slots could be clobbered by an interrupt handler.
1179 // Leave r4 live, it is used below.
1180 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1181 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1183 .add(predOps(ARMCC::AL));
1185 MIB.add(condCodeOp());
1187 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1188 // r4 holds the stack slot address.
1189 unsigned NextReg = ARM::D8;
1191 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1192 // The writeback is only needed when emitting two vst1.64 instructions.
1193 if (NumAlignedDPRCS2Regs >= 6) {
1194 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1195 &ARM::QQPRRegClass);
1196 MBB.addLiveIn(SupReg);
1197 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1198 .addReg(ARM::R4, RegState::Kill)
1201 .addReg(SupReg, RegState::ImplicitKill)
1202 .add(predOps(ARMCC::AL));
1204 NumAlignedDPRCS2Regs -= 4;
1207 // We won't modify r4 beyond this point. It currently points to the next
1208 // register to be spilled.
1209 unsigned R4BaseReg = NextReg;
1211 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1212 if (NumAlignedDPRCS2Regs >= 4) {
1213 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1214 &ARM::QQPRRegClass);
1215 MBB.addLiveIn(SupReg);
1216 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1220 .addReg(SupReg, RegState::ImplicitKill)
1221 .add(predOps(ARMCC::AL));
1223 NumAlignedDPRCS2Regs -= 4;
1226 // 16-byte aligned vst1.64 with 2 d-regs.
1227 if (NumAlignedDPRCS2Regs >= 2) {
1228 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1230 MBB.addLiveIn(SupReg);
1231 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1235 .add(predOps(ARMCC::AL));
1237 NumAlignedDPRCS2Regs -= 2;
1240 // Finally, use a vanilla vstr.64 for the odd last register.
1241 if (NumAlignedDPRCS2Regs) {
1242 MBB.addLiveIn(NextReg);
1243 // vstr.64 uses addrmode5 which has an offset scale of 4.
1244 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1247 .addImm((NextReg - R4BaseReg) * 2)
1248 .add(predOps(ARMCC::AL));
1251 // The last spill instruction inserted should kill the scratch register r4.
1252 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1255 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1256 /// iterator to the following instruction.
1257 static MachineBasicBlock::iterator
1258 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1259 unsigned NumAlignedDPRCS2Regs) {
1260 // sub r4, sp, #numregs * 8
1261 // bic r4, r4, #align - 1
1264 assert(MI->mayStore() && "Expecting spill instruction");
1266 // These switches all fall through.
1267 switch(NumAlignedDPRCS2Regs) {
1270 assert(MI->mayStore() && "Expecting spill instruction");
1273 assert(MI->mayStore() && "Expecting spill instruction");
1277 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1283 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1284 /// starting from d8. These instructions are assumed to execute while the
1285 /// stack is still aligned, unlike the code inserted by emitPopInst.
1286 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1287 MachineBasicBlock::iterator MI,
1288 unsigned NumAlignedDPRCS2Regs,
1289 const std::vector<CalleeSavedInfo> &CSI,
1290 const TargetRegisterInfo *TRI) {
1291 MachineFunction &MF = *MBB.getParent();
1292 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1293 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1294 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1296 // Find the frame index assigned to d8.
1298 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1299 if (CSI[i].getReg() == ARM::D8) {
1300 D8SpillFI = CSI[i].getFrameIdx();
1304 // Materialize the address of the d8 spill slot into the scratch register r4.
1305 // This can be fairly complicated if the stack frame is large, so just use
1306 // the normal frame index elimination mechanism to do it. This code runs as
1307 // the initial part of the epilog where the stack and base pointers haven't
1308 // been changed yet.
1309 bool isThumb = AFI->isThumbFunction();
1310 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1312 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1313 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1314 .addFrameIndex(D8SpillFI)
1316 .add(predOps(ARMCC::AL))
1319 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1320 unsigned NextReg = ARM::D8;
1322 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1323 if (NumAlignedDPRCS2Regs >= 6) {
1324 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1325 &ARM::QQPRRegClass);
1326 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1327 .addReg(ARM::R4, RegState::Define)
1328 .addReg(ARM::R4, RegState::Kill)
1330 .addReg(SupReg, RegState::ImplicitDefine)
1331 .add(predOps(ARMCC::AL));
1333 NumAlignedDPRCS2Regs -= 4;
1336 // We won't modify r4 beyond this point. It currently points to the next
1337 // register to be spilled.
1338 unsigned R4BaseReg = NextReg;
1340 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1341 if (NumAlignedDPRCS2Regs >= 4) {
1342 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1343 &ARM::QQPRRegClass);
1344 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1347 .addReg(SupReg, RegState::ImplicitDefine)
1348 .add(predOps(ARMCC::AL));
1350 NumAlignedDPRCS2Regs -= 4;
1353 // 16-byte aligned vld1.64 with 2 d-regs.
1354 if (NumAlignedDPRCS2Regs >= 2) {
1355 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1357 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1360 .add(predOps(ARMCC::AL));
1362 NumAlignedDPRCS2Regs -= 2;
1365 // Finally, use a vanilla vldr.64 for the remaining odd register.
1366 if (NumAlignedDPRCS2Regs)
1367 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1369 .addImm(2 * (NextReg - R4BaseReg))
1370 .add(predOps(ARMCC::AL));
1372 // Last store kills r4.
1373 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1376 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1377 MachineBasicBlock::iterator MI,
1378 const std::vector<CalleeSavedInfo> &CSI,
1379 const TargetRegisterInfo *TRI) const {
1383 MachineFunction &MF = *MBB.getParent();
1384 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1386 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1387 unsigned PushOneOpc = AFI->isThumbFunction() ?
1388 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1389 unsigned FltOpc = ARM::VSTMDDB_UPD;
1390 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1391 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1392 MachineInstr::FrameSetup);
1393 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1394 MachineInstr::FrameSetup);
1395 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1396 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1398 // The code above does not insert spill code for the aligned DPRCS2 registers.
1399 // The stack realignment code will be inserted between the push instructions
1400 // and these spills.
1401 if (NumAlignedDPRCS2Regs)
1402 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1407 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1408 MachineBasicBlock::iterator MI,
1409 const std::vector<CalleeSavedInfo> &CSI,
1410 const TargetRegisterInfo *TRI) const {
1414 MachineFunction &MF = *MBB.getParent();
1415 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1416 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1417 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1419 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1420 // registers. Do that here instead.
1421 if (NumAlignedDPRCS2Regs)
1422 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1424 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1425 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1426 unsigned FltOpc = ARM::VLDMDIA_UPD;
1427 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1428 NumAlignedDPRCS2Regs);
1429 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1430 &isARMArea2Register, 0);
1431 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1432 &isARMArea1Register, 0);
1437 // FIXME: Make generic?
1438 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1439 const ARMBaseInstrInfo &TII) {
1440 unsigned FnSize = 0;
1441 for (auto &MBB : MF) {
1442 for (auto &MI : MBB)
1443 FnSize += TII.getInstSizeInBytes(MI);
1448 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1449 /// frames and return the stack size limit beyond which some of these
1450 /// instructions will require a scratch register during their expansion later.
1451 // FIXME: Move to TII?
1452 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1453 const TargetFrameLowering *TFI) {
1454 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1455 unsigned Limit = (1 << 12) - 1;
1456 for (auto &MBB : MF) {
1457 for (auto &MI : MBB) {
1458 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1459 if (!MI.getOperand(i).isFI())
1462 // When using ADDri to get the address of a stack object, 255 is the
1463 // largest offset guaranteed to fit in the immediate offset.
1464 if (MI.getOpcode() == ARM::ADDri) {
1465 Limit = std::min(Limit, (1U << 8) - 1);
1469 // Otherwise check the addressing mode.
1470 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1471 case ARMII::AddrMode3:
1472 case ARMII::AddrModeT2_i8:
1473 Limit = std::min(Limit, (1U << 8) - 1);
1475 case ARMII::AddrMode5:
1476 case ARMII::AddrModeT2_i8s4:
1477 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1479 case ARMII::AddrModeT2_i12:
1480 // i12 supports only positive offset so these will be converted to
1481 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1482 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1483 Limit = std::min(Limit, (1U << 8) - 1);
1485 case ARMII::AddrMode4:
1486 case ARMII::AddrMode6:
1487 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1488 // immediate offset for stack references.
1493 break; // At most one FI per instruction
1501 // In functions that realign the stack, it can be an advantage to spill the
1502 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1503 // instructions take alignment hints that can improve performance.
1506 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1507 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1508 if (!SpillAlignedNEONRegs)
1511 // Naked functions don't spill callee-saved registers.
1512 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1515 // We are planning to use NEON instructions vst1 / vld1.
1516 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1519 // Don't bother if the default stack alignment is sufficiently high.
1520 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1523 // Aligned spills require stack realignment.
1524 if (!static_cast<const ARMBaseRegisterInfo *>(
1525 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1528 // We always spill contiguous d-registers starting from d8. Count how many
1529 // needs spilling. The register allocator will almost always use the
1530 // callee-saved registers in order, but it can happen that there are holes in
1531 // the range. Registers above the hole will be spilled to the standard DPRCS
1533 unsigned NumSpills = 0;
1534 for (; NumSpills < 8; ++NumSpills)
1535 if (!SavedRegs.test(ARM::D8 + NumSpills))
1538 // Don't do this for just one d-register. It's not worth it.
1542 // Spill the first NumSpills D-registers after realigning the stack.
1543 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1545 // A scratch register is required for the vst1 / vld1 instructions.
1546 SavedRegs.set(ARM::R4);
1549 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1550 BitVector &SavedRegs,
1551 RegScavenger *RS) const {
1552 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1553 // This tells PEI to spill the FP as if it is any other callee-save register
1554 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1555 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1556 // to combine multiple loads / stores.
1557 bool CanEliminateFrame = true;
1558 bool CS1Spilled = false;
1559 bool LRSpilled = false;
1560 unsigned NumGPRSpills = 0;
1561 unsigned NumFPRSpills = 0;
1562 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1563 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1564 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1565 MF.getSubtarget().getRegisterInfo());
1566 const ARMBaseInstrInfo &TII =
1567 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1568 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1569 MachineFrameInfo &MFI = MF.getFrameInfo();
1570 MachineRegisterInfo &MRI = MF.getRegInfo();
1571 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1572 (void)TRI; // Silence unused warning in non-assert builds.
1573 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1575 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1576 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1577 // since it's not always possible to restore sp from fp in a single
1579 // FIXME: It will be better just to find spare register here.
1580 if (AFI->isThumb2Function() &&
1581 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1582 SavedRegs.set(ARM::R4);
1584 if (AFI->isThumb1OnlyFunction()) {
1585 // Spill LR if Thumb1 function uses variable length argument lists.
1586 if (AFI->getArgRegsSaveSize() > 0)
1587 SavedRegs.set(ARM::LR);
1589 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1590 // for sure what the stack size will be, but for this, an estimate is good
1591 // enough. If there anything changes it, it'll be a spill, which implies
1592 // we've used all the registers and so R4 is already used, so not marking
1593 // it here will be OK.
1594 // FIXME: It will be better just to find spare register here.
1595 unsigned StackSize = MFI.estimateStackSize(MF);
1596 if (MFI.hasVarSizedObjects() || StackSize > 508)
1597 SavedRegs.set(ARM::R4);
1600 // See if we can spill vector registers to aligned stack.
1601 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1603 // Spill the BasePtr if it's used.
1604 if (RegInfo->hasBasePointer(MF))
1605 SavedRegs.set(RegInfo->getBaseRegister());
1607 // Don't spill FP if the frame can be eliminated. This is determined
1608 // by scanning the callee-save registers to see if any is modified.
1609 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1610 for (unsigned i = 0; CSRegs[i]; ++i) {
1611 unsigned Reg = CSRegs[i];
1612 bool Spilled = false;
1613 if (SavedRegs.test(Reg)) {
1615 CanEliminateFrame = false;
1618 if (!ARM::GPRRegClass.contains(Reg)) {
1620 if (ARM::SPRRegClass.contains(Reg))
1622 else if (ARM::DPRRegClass.contains(Reg))
1624 else if (ARM::QPRRegClass.contains(Reg))
1633 if (!STI.splitFramePushPop(MF)) {
1640 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1645 case ARM::R0: case ARM::R1:
1646 case ARM::R2: case ARM::R3:
1647 case ARM::R4: case ARM::R5:
1648 case ARM::R6: case ARM::R7:
1655 if (!STI.splitFramePushPop(MF)) {
1656 UnspilledCS1GPRs.push_back(Reg);
1661 case ARM::R0: case ARM::R1:
1662 case ARM::R2: case ARM::R3:
1663 case ARM::R4: case ARM::R5:
1664 case ARM::R6: case ARM::R7:
1666 UnspilledCS1GPRs.push_back(Reg);
1669 UnspilledCS2GPRs.push_back(Reg);
1675 bool ForceLRSpill = false;
1676 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1677 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1678 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1679 // use of BL to implement far jump. If it turns out that it's not needed
1680 // then the branch fix up path will undo it.
1681 if (FnSize >= (1 << 11)) {
1682 CanEliminateFrame = false;
1683 ForceLRSpill = true;
1687 // If any of the stack slot references may be out of range of an immediate
1688 // offset, make sure a register (or a spill slot) is available for the
1689 // register scavenger. Note that if we're indexing off the frame pointer, the
1690 // effective stack size is 4 bytes larger since the FP points to the stack
1691 // slot of the previous FP. Also, if we have variable sized objects in the
1692 // function, stack slot references will often be negative, and some of
1693 // our instructions are positive-offset only, so conservatively consider
1694 // that case to want a spill slot (or register) as well. Similarly, if
1695 // the function adjusts the stack pointer during execution and the
1696 // adjustments aren't already part of our stack size estimate, our offset
1697 // calculations may be off, so be conservative.
1698 // FIXME: We could add logic to be more precise about negative offsets
1699 // and which instructions will need a scratch register for them. Is it
1700 // worth the effort and added fragility?
1701 unsigned EstimatedStackSize =
1702 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
1703 bool HasFP = hasFP(MF);
1705 if (AFI->hasStackFrame())
1706 EstimatedStackSize += 4;
1708 // If FP is not used, SP will be used to access arguments, so count the
1709 // size of arguments into the estimation.
1710 EstimatedStackSize += AFI->getArgumentStackSize();
1712 EstimatedStackSize += 16; // For possible paddings.
1714 bool BigStack = EstimatedStackSize >= estimateRSStackSizeLimit(MF, this) ||
1715 MFI.hasVarSizedObjects() ||
1716 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
1717 bool ExtraCSSpill = false;
1718 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1719 AFI->setHasStackFrame(true);
1722 SavedRegs.set(FramePtr);
1723 // If the frame pointer is required by the ABI, also spill LR so that we
1724 // emit a complete frame record.
1725 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1726 SavedRegs.set(ARM::LR);
1729 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
1730 if (LRPos != UnspilledCS1GPRs.end())
1731 UnspilledCS1GPRs.erase(LRPos);
1733 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
1734 if (FPPos != UnspilledCS1GPRs.end())
1735 UnspilledCS1GPRs.erase(FPPos);
1737 if (FramePtr == ARM::R7)
1741 if (AFI->isThumb1OnlyFunction()) {
1742 // For Thumb1-only targets, we need some low registers when we save and
1743 // restore the high registers (which aren't allocatable, but could be
1744 // used by inline assembly) because the push/pop instructions can not
1745 // access high registers. If necessary, we might need to push more low
1746 // registers to ensure that there is at least one free that can be used
1747 // for the saving & restoring, and preferably we should ensure that as
1748 // many as are needed are available so that fewer push/pop instructions
1751 // Low registers which are not currently pushed, but could be (r4-r7).
1752 SmallVector<unsigned, 4> AvailableRegs;
1754 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1756 int EntryRegDeficit = 0;
1757 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1758 if (!MF.getRegInfo().isLiveIn(Reg)) {
1760 DEBUG(dbgs() << PrintReg(Reg, TRI)
1761 << " is unused argument register, EntryRegDeficit = "
1762 << EntryRegDeficit << "\n");
1766 // Unused return registers can be clobbered in the epilogue for free.
1767 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
1768 DEBUG(dbgs() << AFI->getReturnRegsCount()
1769 << " return regs used, ExitRegDeficit = " << ExitRegDeficit
1772 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
1773 DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
1775 // r4-r6 can be used in the prologue if they are pushed by the first push
1777 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1778 if (SavedRegs.test(Reg)) {
1780 DEBUG(dbgs() << PrintReg(Reg, TRI)
1781 << " is saved low register, RegDeficit = " << RegDeficit
1784 AvailableRegs.push_back(Reg);
1786 << PrintReg(Reg, TRI)
1787 << " is non-saved low register, adding to AvailableRegs\n");
1791 // r7 can be used if it is not being used as the frame pointer.
1793 if (SavedRegs.test(ARM::R7)) {
1795 DEBUG(dbgs() << "%R7 is saved low register, RegDeficit = "
1796 << RegDeficit << "\n");
1798 AvailableRegs.push_back(ARM::R7);
1800 << "%R7 is non-saved low register, adding to AvailableRegs\n");
1804 // Each of r8-r11 needs to be copied to a low register, then pushed.
1805 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1806 if (SavedRegs.test(Reg)) {
1808 DEBUG(dbgs() << PrintReg(Reg, TRI)
1809 << " is saved high register, RegDeficit = " << RegDeficit
1814 // LR can only be used by PUSH, not POP, and can't be used at all if the
1815 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1816 // are more limited at function entry than exit.
1817 if ((EntryRegDeficit > ExitRegDeficit) &&
1818 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1819 MF.getFrameInfo().isReturnAddressTaken())) {
1820 if (SavedRegs.test(ARM::LR)) {
1822 DEBUG(dbgs() << "%LR is saved register, RegDeficit = " << RegDeficit
1825 AvailableRegs.push_back(ARM::LR);
1826 DEBUG(dbgs() << "%LR is not saved, adding to AvailableRegs\n");
1830 // If there are more high registers that need pushing than low registers
1831 // available, push some more low registers so that we can use fewer push
1832 // instructions. This might not reduce RegDeficit all the way to zero,
1833 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1835 DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
1836 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1837 unsigned Reg = AvailableRegs.pop_back_val();
1838 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1839 << " to make up reg deficit\n");
1843 ExtraCSSpill = true;
1844 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
1848 DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit << "\n");
1851 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1852 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1853 if (!LRSpilled && CS1Spilled) {
1854 SavedRegs.set(ARM::LR);
1856 SmallVectorImpl<unsigned>::iterator LRPos;
1857 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
1858 if (LRPos != UnspilledCS1GPRs.end())
1859 UnspilledCS1GPRs.erase(LRPos);
1861 ForceLRSpill = false;
1862 ExtraCSSpill = true;
1865 // If stack and double are 8-byte aligned and we are spilling an odd number
1866 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1867 // the integer and double callee save areas.
1868 DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
1869 unsigned TargetAlign = getStackAlignment();
1870 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1871 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1872 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1873 unsigned Reg = UnspilledCS1GPRs[i];
1874 // Don't spill high register if the function is thumb. In the case of
1875 // Windows on ARM, accept R11 (frame pointer)
1876 if (!AFI->isThumbFunction() ||
1877 (STI.isTargetWindows() && Reg == ARM::R11) ||
1878 isARMLowRegister(Reg) || Reg == ARM::LR) {
1880 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1881 << " to make up alignment\n");
1882 if (!MRI.isReserved(Reg))
1883 ExtraCSSpill = true;
1887 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1888 unsigned Reg = UnspilledCS2GPRs.front();
1890 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1891 << " to make up alignment\n");
1892 if (!MRI.isReserved(Reg))
1893 ExtraCSSpill = true;
1897 // Estimate if we might need to scavenge a register at some point in order
1898 // to materialize a stack offset. If so, either spill one additional
1899 // callee-saved register or reserve a special spill slot to facilitate
1900 // register scavenging. Thumb1 needs a spill slot for stack pointer
1901 // adjustments also, even when the frame itself is small.
1902 if (BigStack && !ExtraCSSpill) {
1903 // If any non-reserved CS register isn't spilled, just spill one or two
1904 // extra. That should take care of it!
1905 unsigned NumExtras = TargetAlign / 4;
1906 SmallVector<unsigned, 2> Extras;
1907 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1908 unsigned Reg = UnspilledCS1GPRs.back();
1909 UnspilledCS1GPRs.pop_back();
1910 if (!MRI.isReserved(Reg) &&
1911 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1913 Extras.push_back(Reg);
1917 // For non-Thumb1 functions, also check for hi-reg CS registers
1918 if (!AFI->isThumb1OnlyFunction()) {
1919 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1920 unsigned Reg = UnspilledCS2GPRs.back();
1921 UnspilledCS2GPRs.pop_back();
1922 if (!MRI.isReserved(Reg)) {
1923 Extras.push_back(Reg);
1928 if (Extras.size() && NumExtras == 0) {
1929 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1930 SavedRegs.set(Extras[i]);
1932 } else if (!AFI->isThumb1OnlyFunction()) {
1933 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1934 // closest to SP or frame pointer.
1935 assert(RS && "Register scavenging not provided");
1936 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1937 RS->addScavengingFrameIndex(MFI.CreateStackObject(RC->getSize(),
1945 SavedRegs.set(ARM::LR);
1946 AFI->setLRIsSpilledForFarJump(true);
1950 MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
1951 MachineFunction &MF, MachineBasicBlock &MBB,
1952 MachineBasicBlock::iterator I) const {
1953 const ARMBaseInstrInfo &TII =
1954 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1955 if (!hasReservedCallFrame(MF)) {
1956 // If we have alloca, convert as follows:
1957 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1958 // ADJCALLSTACKUP -> add, sp, sp, amount
1959 MachineInstr &Old = *I;
1960 DebugLoc dl = Old.getDebugLoc();
1961 unsigned Amount = Old.getOperand(0).getImm();
1963 // We need to keep the stack aligned properly. To do this, we round the
1964 // amount of space needed for the outgoing arguments up to the next
1965 // alignment boundary.
1966 Amount = alignSPAdjust(Amount);
1968 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1969 assert(!AFI->isThumb1OnlyFunction() &&
1970 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1971 bool isARM = !AFI->isThumbFunction();
1973 // Replace the pseudo instruction with a new instruction...
1974 unsigned Opc = Old.getOpcode();
1975 int PIdx = Old.findFirstPredOperandIdx();
1976 ARMCC::CondCodes Pred =
1977 (PIdx == -1) ? ARMCC::AL
1978 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
1979 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1980 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1981 unsigned PredReg = Old.getOperand(2).getReg();
1982 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1985 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1986 unsigned PredReg = Old.getOperand(3).getReg();
1987 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1988 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1993 return MBB.erase(I);
1996 /// Get the minimum constant for ARM that is greater than or equal to the
1997 /// argument. In ARM, constants can have any value that can be produced by
1998 /// rotating an 8-bit value to the right by an even number of bits within a
2000 static uint32_t alignToARMConstant(uint32_t Value) {
2001 unsigned Shifted = 0;
2006 while (!(Value & 0xC0000000)) {
2011 bool Carry = (Value & 0x00FFFFFF);
2012 Value = ((Value & 0xFF000000) >> 24) + Carry;
2014 if (Value & 0x0000100)
2015 Value = Value & 0x000001FC;
2018 Value = Value >> (Shifted - 24);
2020 Value = Value << (24 - Shifted);
2025 // The stack limit in the TCB is set to this many bytes above the actual
2027 static const uint64_t kSplitStackAvailable = 256;
2029 // Adjust the function prologue to enable split stacks. This currently only
2030 // supports android and linux.
2032 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2033 // must be well defined in order to allow for consistent implementations of the
2034 // __morestack helper function. The ABI is also not a normal ABI in that it
2035 // doesn't follow the normal calling conventions because this allows the
2036 // prologue of each function to be optimized further.
2038 // Currently, the ABI looks like (when calling __morestack)
2040 // * r4 holds the minimum stack size requested for this function call
2041 // * r5 holds the stack size of the arguments to the function
2042 // * the beginning of the function is 3 instructions after the call to
2045 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
2046 // place the arguments on to the new stack, and the 3-instruction knowledge to
2047 // jump directly to the body of the function when working on the new stack.
2049 // An old (and possibly no longer compatible) implementation of __morestack for
2050 // ARM can be found at [1].
2052 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
2053 void ARMFrameLowering::adjustForSegmentedStacks(
2054 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2057 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
2058 bool Thumb = ST->isThumb();
2060 // Sadly, this currently doesn't support varargs, platforms other than
2061 // android/linux. Note that thumb1/thumb2 are support for android/linux.
2062 if (MF.getFunction()->isVarArg())
2063 report_fatal_error("Segmented stacks do not support vararg functions.");
2064 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
2065 report_fatal_error("Segmented stacks not supported on this platform.");
2067 MachineFrameInfo &MFI = MF.getFrameInfo();
2068 MachineModuleInfo &MMI = MF.getMMI();
2069 MCContext &Context = MMI.getContext();
2070 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2071 const ARMBaseInstrInfo &TII =
2072 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2073 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2076 uint64_t StackSize = MFI.getStackSize();
2078 // Do not generate a prologue for functions with a stack of size zero
2082 // Use R4 and R5 as scratch registers.
2083 // We save R4 and R5 before use and restore them before leaving the function.
2084 unsigned ScratchReg0 = ARM::R4;
2085 unsigned ScratchReg1 = ARM::R5;
2086 uint64_t AlignedStackSize;
2088 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2089 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2090 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2091 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2092 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2094 // Grab everything that reaches PrologueMBB to update there liveness as well.
2095 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2096 SmallVector<MachineBasicBlock *, 2> WalkList;
2097 WalkList.push_back(&PrologueMBB);
2100 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2101 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2102 if (BeforePrologueRegion.insert(PredBB).second)
2103 WalkList.push_back(PredBB);
2105 } while (!WalkList.empty());
2107 // The order in that list is important.
2108 // The blocks will all be inserted before PrologueMBB using that order.
2109 // Therefore the block that should appear first in the CFG should appear
2110 // first in the list.
2111 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2114 for (MachineBasicBlock *B : AddedBlocks)
2115 BeforePrologueRegion.insert(B);
2117 for (const auto &LI : PrologueMBB.liveins()) {
2118 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
2119 PredBB->addLiveIn(LI);
2122 // Remove the newly added blocks from the list, since we know
2123 // we do not have to do the following updates for them.
2124 for (MachineBasicBlock *B : AddedBlocks) {
2125 BeforePrologueRegion.erase(B);
2126 MF.insert(PrologueMBB.getIterator(), B);
2129 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2130 // Make sure the LiveIns are still sorted and unique.
2131 MBB->sortUniqueLiveIns();
2132 // Replace the edges to PrologueMBB by edges to the sequences
2133 // we are about to add.
2134 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2137 // The required stack size that is aligned to ARM constant criterion.
2138 AlignedStackSize = alignToARMConstant(StackSize);
2140 // When the frame size is less than 256 we just compare the stack
2141 // boundary directly to the value of the stack pointer, per gcc.
2142 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2144 // We will use two of the callee save registers as scratch registers so we
2145 // need to save those registers onto the stack.
2146 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2147 // requested and arguments for __morestack().
2148 // SR0: Scratch Register #0
2149 // SR1: Scratch Register #1
2152 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2153 .add(predOps(ARMCC::AL))
2154 .addReg(ScratchReg0)
2155 .addReg(ScratchReg1);
2157 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2158 .addReg(ARM::SP, RegState::Define)
2160 .add(predOps(ARMCC::AL))
2161 .addReg(ScratchReg0)
2162 .addReg(ScratchReg1);
2165 // Emit the relevant DWARF information about the change in stack pointer as
2166 // well as where to find both r4 and r5 (the callee-save registers)
2168 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
2169 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2170 .addCFIIndex(CFIIndex);
2171 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2172 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2173 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2174 .addCFIIndex(CFIIndex);
2175 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2176 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2177 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2178 .addCFIIndex(CFIIndex);
2182 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2184 .add(predOps(ARMCC::AL));
2185 } else if (CompareStackPointer) {
2186 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2188 .add(predOps(ARMCC::AL))
2192 // sub SR1, sp, #StackSize
2193 if (!CompareStackPointer && Thumb) {
2194 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2196 .addReg(ScratchReg1)
2197 .addImm(AlignedStackSize)
2198 .add(predOps(ARMCC::AL));
2199 } else if (!CompareStackPointer) {
2200 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2202 .addImm(AlignedStackSize)
2203 .add(predOps(ARMCC::AL))
2207 if (Thumb && ST->isThumb1Only()) {
2208 unsigned PCLabelId = ARMFI->createPICLabelUId();
2209 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
2210 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
2211 MachineConstantPool *MCP = MF.getConstantPool();
2212 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
2214 // ldr SR0, [pc, offset(STACK_LIMIT)]
2215 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2216 .addConstantPoolIndex(CPI)
2217 .add(predOps(ARMCC::AL));
2220 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2221 .addReg(ScratchReg0)
2223 .add(predOps(ARMCC::AL));
2225 // Get TLS base address from the coprocessor
2226 // mrc p15, #0, SR0, c13, c0, #3
2227 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2233 .add(predOps(ARMCC::AL));
2235 // Use the last tls slot on android and a private field of the TCP on linux.
2236 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2237 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2239 // Get the stack limit from the right offset
2240 // ldr SR0, [sr0, #4 * TlsOffset]
2241 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2242 .addReg(ScratchReg0)
2243 .addImm(4 * TlsOffset)
2244 .add(predOps(ARMCC::AL));
2247 // Compare stack limit with stack size requested.
2249 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2250 BuildMI(GetMBB, DL, TII.get(Opcode))
2251 .addReg(ScratchReg0)
2252 .addReg(ScratchReg1)
2253 .add(predOps(ARMCC::AL));
2255 // This jump is taken if StackLimit < SP - stack required.
2256 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2257 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2262 // Calling __morestack(StackSize, Size of stack arguments).
2263 // __morestack knows that the stack size requested is in SR0(r4)
2264 // and amount size of stack arguments is in SR1(r5).
2266 // Pass first argument for the __morestack by Scratch Register #0.
2267 // The amount size of stack required
2269 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2271 .addImm(AlignedStackSize)
2272 .add(predOps(ARMCC::AL));
2274 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2275 .addImm(AlignedStackSize)
2276 .add(predOps(ARMCC::AL))
2279 // Pass second argument for the __morestack by Scratch Register #1.
2280 // The amount size of stack consumed to save function arguments.
2282 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2284 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2285 .add(predOps(ARMCC::AL));
2287 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2288 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2289 .add(predOps(ARMCC::AL))
2293 // push {lr} - Save return address of this function.
2295 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2296 .add(predOps(ARMCC::AL))
2299 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2300 .addReg(ARM::SP, RegState::Define)
2302 .add(predOps(ARMCC::AL))
2306 // Emit the DWARF info about the change in stack as well as where to find the
2307 // previous link register
2309 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2310 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2311 .addCFIIndex(CFIIndex);
2312 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2313 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2314 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2315 .addCFIIndex(CFIIndex);
2317 // Call __morestack().
2319 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2320 .add(predOps(ARMCC::AL))
2321 .addExternalSymbol("__morestack");
2323 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2324 .addExternalSymbol("__morestack");
2327 // pop {lr} - Restore return address of this original function.
2329 if (ST->isThumb1Only()) {
2330 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2331 .add(predOps(ARMCC::AL))
2332 .addReg(ScratchReg0);
2333 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2334 .addReg(ScratchReg0)
2335 .add(predOps(ARMCC::AL));
2337 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2338 .addReg(ARM::LR, RegState::Define)
2339 .addReg(ARM::SP, RegState::Define)
2342 .add(predOps(ARMCC::AL));
2345 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2346 .addReg(ARM::SP, RegState::Define)
2348 .add(predOps(ARMCC::AL))
2352 // Restore SR0 and SR1 in case of __morestack() was called.
2353 // __morestack() will skip PostStackMBB block so we need to restore
2354 // scratch registers from here.
2357 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2358 .add(predOps(ARMCC::AL))
2359 .addReg(ScratchReg0)
2360 .addReg(ScratchReg1);
2362 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2363 .addReg(ARM::SP, RegState::Define)
2365 .add(predOps(ARMCC::AL))
2366 .addReg(ScratchReg0)
2367 .addReg(ScratchReg1);
2370 // Update the CFA offset now that we've popped
2371 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2372 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2373 .addCFIIndex(CFIIndex);
2375 // bx lr - Return from this function.
2376 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2377 BuildMI(AllocMBB, DL, TII.get(Opcode)).add(predOps(ARMCC::AL));
2379 // Restore SR0 and SR1 in case of __morestack() was not called.
2382 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2383 .add(predOps(ARMCC::AL))
2384 .addReg(ScratchReg0)
2385 .addReg(ScratchReg1);
2387 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2388 .addReg(ARM::SP, RegState::Define)
2390 .add(predOps(ARMCC::AL))
2391 .addReg(ScratchReg0)
2392 .addReg(ScratchReg1);
2395 // Update the CFA offset now that we've popped
2396 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2397 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2398 .addCFIIndex(CFIIndex);
2400 // Tell debuggers that r4 and r5 are now the same as they were in the
2401 // previous function, that they're the "Same Value".
2402 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2403 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2404 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2405 .addCFIIndex(CFIIndex);
2406 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2407 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2408 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2409 .addCFIIndex(CFIIndex);
2411 // Organizing MBB lists
2412 PostStackMBB->addSuccessor(&PrologueMBB);
2414 AllocMBB->addSuccessor(PostStackMBB);
2416 GetMBB->addSuccessor(PostStackMBB);
2417 GetMBB->addSuccessor(AllocMBB);
2419 McrMBB->addSuccessor(GetMBB);
2421 PrevStackMBB->addSuccessor(McrMBB);
2423 #ifdef EXPENSIVE_CHECKS