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 /// We need the offset of the frame pointer relative to other MachineFrameInfo
326 /// offsets which are encoded relative to SP at function begin.
327 /// See also emitPrologue() for how the FP is set up.
328 /// Unfortunately we cannot determine this value in determineCalleeSaves() yet
329 /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
330 /// this to produce a conservative estimate that we check in an assert() later.
331 static int getMaxFPOffset(const Function &F, const ARMFunctionInfo &AFI) {
332 // This is a conservative estimation: Assume the frame pointer being r7 and
333 // pc("r15") up to r8 getting spilled before (= 8 registers).
334 return -AFI.getArgRegsSaveSize() - (8 * 4);
337 void ARMFrameLowering::emitPrologue(MachineFunction &MF,
338 MachineBasicBlock &MBB) const {
339 MachineBasicBlock::iterator MBBI = MBB.begin();
340 MachineFrameInfo &MFI = MF.getFrameInfo();
341 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
342 MachineModuleInfo &MMI = MF.getMMI();
343 MCContext &Context = MMI.getContext();
344 const TargetMachine &TM = MF.getTarget();
345 const MCRegisterInfo *MRI = Context.getRegisterInfo();
346 const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
347 const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
348 assert(!AFI->isThumb1OnlyFunction() &&
349 "This emitPrologue does not support Thumb1!");
350 bool isARM = !AFI->isThumbFunction();
351 unsigned Align = STI.getFrameLowering()->getStackAlignment();
352 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
353 unsigned NumBytes = MFI.getStackSize();
354 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
356 // Debug location must be unknown since the first debug location is used
357 // to determine the end of the prologue.
360 unsigned FramePtr = RegInfo->getFrameRegister(MF);
362 // Determine the sizes of each callee-save spill areas and record which frame
363 // belongs to which callee-save spill areas.
364 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
365 int FramePtrSpillFI = 0;
368 // All calls are tail calls in GHC calling conv, and functions have no
369 // prologue/epilogue.
370 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
373 StackAdjustingInsts DefCFAOffsetCandidates;
374 bool HasFP = hasFP(MF);
376 // Allocate the vararg register save area.
377 if (ArgRegsSaveSize) {
378 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
379 MachineInstr::FrameSetup);
380 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
383 if (!AFI->hasStackFrame() &&
384 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
385 if (NumBytes - ArgRegsSaveSize != 0) {
386 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
387 MachineInstr::FrameSetup);
388 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
389 NumBytes - ArgRegsSaveSize, true);
391 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
395 // Determine spill area sizes.
396 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
397 unsigned Reg = CSI[i].getReg();
398 int FI = CSI[i].getFrameIdx();
405 if (STI.splitFramePushPop(MF)) {
420 FramePtrSpillFI = FI;
424 // This is a DPR. Exclude the aligned DPRCS2 spills.
427 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
433 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
434 if (GPRCS1Size > 0) {
435 GPRCS1Push = LastPush = MBBI++;
436 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
439 // Determine starting offsets of spill areas.
440 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
441 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
442 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
443 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
444 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
445 int FramePtrOffsetInPush = 0;
447 int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
448 assert(getMaxFPOffset(*MF.getFunction(), *AFI) <= FPOffset &&
449 "Max FP estimation is wrong");
450 FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize;
451 AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
454 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
455 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
456 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
459 if (GPRCS2Size > 0) {
460 GPRCS2Push = LastPush = MBBI++;
461 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
464 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
465 // .cfi_offset operations will reflect that.
467 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
468 if (LastPush != MBB.end() &&
469 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
470 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
472 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
473 MachineInstr::FrameSetup);
474 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
480 // Since vpush register list cannot have gaps, there may be multiple vpush
481 // instructions in the prologue.
482 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
483 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
488 // Move past the aligned DPRCS2 area.
489 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
490 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
491 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
492 // leaves the stack pointer pointing to the DPRCS2 area.
494 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
495 NumBytes += MFI.getObjectOffset(D8SpillFI);
497 NumBytes = DPRCSOffset;
499 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
500 uint32_t NumWords = NumBytes >> 2;
502 if (NumWords < 65536)
503 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
505 .setMIFlags(MachineInstr::FrameSetup)
506 .add(predOps(ARMCC::AL));
508 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
510 .setMIFlags(MachineInstr::FrameSetup);
512 switch (TM.getCodeModel()) {
513 case CodeModel::Small:
514 case CodeModel::Medium:
515 case CodeModel::Default:
516 case CodeModel::Kernel:
517 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
518 .add(predOps(ARMCC::AL))
519 .addExternalSymbol("__chkstk")
520 .addReg(ARM::R4, RegState::Implicit)
521 .setMIFlags(MachineInstr::FrameSetup);
523 case CodeModel::Large:
524 case CodeModel::JITDefault:
525 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
526 .addExternalSymbol("__chkstk")
527 .setMIFlags(MachineInstr::FrameSetup);
529 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
530 .add(predOps(ARMCC::AL))
531 .addReg(ARM::R12, RegState::Kill)
532 .addReg(ARM::R4, RegState::Implicit)
533 .setMIFlags(MachineInstr::FrameSetup);
537 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
538 .addReg(ARM::SP, RegState::Kill)
539 .addReg(ARM::R4, RegState::Kill)
540 .setMIFlags(MachineInstr::FrameSetup)
541 .add(predOps(ARMCC::AL))
547 // Adjust SP after all the callee-save spills.
548 if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
549 tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
550 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
552 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
553 MachineInstr::FrameSetup);
554 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
558 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
559 // Note it's not safe to do this in Thumb2 mode because it would have
560 // taken two instructions:
563 // If an interrupt is taken between the two instructions, then sp is in
564 // an inconsistent state (pointing to the middle of callee-saved area).
565 // The interrupt handler can end up clobbering the registers.
566 AFI->setShouldRestoreSPFromFP(true);
569 // Set FP to point to the stack slot that contains the previous FP.
570 // For iOS, FP is R7, which has now been stored in spill area 1.
571 // Otherwise, if this is not iOS, all the callee-saved registers go
572 // into spill area 1, including the FP in R11. In either case, it
573 // is in area one and the adjustment needs to take place just after
576 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
577 unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
578 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
579 dl, TII, FramePtr, ARM::SP,
580 PushSize + FramePtrOffsetInPush,
581 MachineInstr::FrameSetup);
582 if (FramePtrOffsetInPush + PushSize != 0) {
583 unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfa(
584 nullptr, MRI->getDwarfRegNum(FramePtr, true),
585 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
586 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
587 .addCFIIndex(CFIIndex)
588 .setMIFlags(MachineInstr::FrameSetup);
591 MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
592 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
593 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
594 .addCFIIndex(CFIIndex)
595 .setMIFlags(MachineInstr::FrameSetup);
599 // Now that the prologue's actual instructions are finalised, we can insert
600 // the necessary DWARF cf instructions to describe the situation. Start by
601 // recording where each register ended up:
602 if (GPRCS1Size > 0) {
603 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
605 for (const auto &Entry : CSI) {
606 unsigned Reg = Entry.getReg();
607 int FI = Entry.getFrameIdx();
614 if (STI.splitFramePushPop(MF))
626 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
627 nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
628 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
629 .addCFIIndex(CFIIndex)
630 .setMIFlags(MachineInstr::FrameSetup);
636 if (GPRCS2Size > 0) {
637 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
638 for (const auto &Entry : CSI) {
639 unsigned Reg = Entry.getReg();
640 int FI = Entry.getFrameIdx();
647 if (STI.splitFramePushPop(MF)) {
648 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
649 unsigned Offset = MFI.getObjectOffset(FI);
650 unsigned CFIIndex = MF.addFrameInst(
651 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
652 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
653 .addCFIIndex(CFIIndex)
654 .setMIFlags(MachineInstr::FrameSetup);
662 // Since vpush register list cannot have gaps, there may be multiple vpush
663 // instructions in the prologue.
664 MachineBasicBlock::iterator Pos = std::next(LastPush);
665 for (const auto &Entry : CSI) {
666 unsigned Reg = Entry.getReg();
667 int FI = Entry.getFrameIdx();
668 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
669 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
670 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
671 unsigned Offset = MFI.getObjectOffset(FI);
672 unsigned CFIIndex = MF.addFrameInst(
673 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
674 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
675 .addCFIIndex(CFIIndex)
676 .setMIFlags(MachineInstr::FrameSetup);
681 // Now we can emit descriptions of where the canonical frame address was
682 // throughout the process. If we have a frame pointer, it takes over the job
683 // half-way through, so only the first few .cfi_def_cfa_offset instructions
684 // actually get emitted.
685 DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
687 if (STI.isTargetELF() && hasFP(MF))
688 MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
689 AFI->getFramePtrSpillOffset());
691 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
692 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
693 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
694 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
696 // If we need dynamic stack realignment, do it here. Be paranoid and make
697 // sure if we also have VLAs, we have a base pointer for frame access.
698 // If aligned NEON registers were spilled, the stack has already been
700 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
701 unsigned MaxAlign = MFI.getMaxAlignment();
702 assert(!AFI->isThumb1OnlyFunction());
703 if (!AFI->isThumbFunction()) {
704 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
707 // We cannot use sp as source/dest register here, thus we're using r4 to
708 // perform the calculations. We're emitting the following sequence:
710 // -- use emitAligningInstructions to produce best sequence to zero
711 // -- out lower bits in r4
713 // FIXME: It will be better just to find spare register here.
714 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
715 .addReg(ARM::SP, RegState::Kill)
716 .add(predOps(ARMCC::AL));
717 emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
719 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
720 .addReg(ARM::R4, RegState::Kill)
721 .add(predOps(ARMCC::AL));
724 AFI->setShouldRestoreSPFromFP(true);
727 // If we need a base pointer, set it up here. It's whatever the value
728 // of the stack pointer is at this point. Any variable size objects
729 // will be allocated after this, so we can still use the base pointer
730 // to reference locals.
731 // FIXME: Clarify FrameSetup flags here.
732 if (RegInfo->hasBasePointer(MF)) {
734 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
736 .add(predOps(ARMCC::AL))
739 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
741 .add(predOps(ARMCC::AL));
744 // If the frame has variable sized objects then the epilogue must restore
745 // the sp from fp. We can assume there's an FP here since hasFP already
746 // checks for hasVarSizedObjects.
747 if (MFI.hasVarSizedObjects())
748 AFI->setShouldRestoreSPFromFP(true);
751 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
752 MachineBasicBlock &MBB) const {
753 MachineFrameInfo &MFI = MF.getFrameInfo();
754 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
755 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
756 const ARMBaseInstrInfo &TII =
757 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
758 assert(!AFI->isThumb1OnlyFunction() &&
759 "This emitEpilogue does not support Thumb1!");
760 bool isARM = !AFI->isThumbFunction();
762 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
763 int NumBytes = (int)MFI.getStackSize();
764 unsigned FramePtr = RegInfo->getFrameRegister(MF);
766 // All calls are tail calls in GHC calling conv, and functions have no
767 // prologue/epilogue.
768 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
771 // First put ourselves on the first (from top) terminator instructions.
772 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
773 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
775 if (!AFI->hasStackFrame()) {
776 if (NumBytes - ArgRegsSaveSize != 0)
777 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
779 // Unwind MBBI to point to first LDR / VLDRD.
780 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
781 if (MBBI != MBB.begin()) {
784 } while (MBBI != MBB.begin() && isCSRestore(*MBBI, TII, CSRegs));
785 if (!isCSRestore(*MBBI, TII, CSRegs))
789 // Move SP to start of FP callee save spill area.
790 NumBytes -= (ArgRegsSaveSize +
791 AFI->getGPRCalleeSavedArea1Size() +
792 AFI->getGPRCalleeSavedArea2Size() +
793 AFI->getDPRCalleeSavedGapSize() +
794 AFI->getDPRCalleeSavedAreaSize());
796 // Reset SP based on frame pointer only if the stack frame extends beyond
797 // frame pointer stack slot or target is ELF and the function has FP.
798 if (AFI->shouldRestoreSPFromFP()) {
799 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
802 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
805 // It's not possible to restore SP from FP in a single instruction.
806 // For iOS, this looks like:
809 // This is bad, if an interrupt is taken after the mov, sp is in an
810 // inconsistent state.
811 // Use the first callee-saved register as a scratch register.
812 assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
813 "No scratch register to restore SP from FP!");
814 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
816 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
818 .add(predOps(ARMCC::AL));
823 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
825 .add(predOps(ARMCC::AL))
828 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
830 .add(predOps(ARMCC::AL));
832 } else if (NumBytes &&
833 !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
834 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
836 // Increment past our save areas.
837 if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
839 // Since vpop register list cannot have gaps, there may be multiple vpop
840 // instructions in the epilogue.
841 while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
844 if (AFI->getDPRCalleeSavedGapSize()) {
845 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
846 "unexpected DPR alignment gap");
847 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
850 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
851 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
855 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
858 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
859 /// debug info. It's the same as what we use for resolving the code-gen
860 /// references for now. FIXME: This can go wrong when references are
861 /// SP-relative and simple call frames aren't used.
863 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
864 unsigned &FrameReg) const {
865 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
869 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
870 int FI, unsigned &FrameReg,
872 const MachineFrameInfo &MFI = MF.getFrameInfo();
873 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
874 MF.getSubtarget().getRegisterInfo());
875 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
876 int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
877 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
878 bool isFixed = MFI.isFixedObjectIndex(FI);
883 // SP can move around if there are allocas. We may also lose track of SP
884 // when emergency spilling inside a non-reserved call frame setup.
885 bool hasMovingSP = !hasReservedCallFrame(MF);
887 // When dynamically realigning the stack, use the frame pointer for
888 // parameters, and the stack/base pointer for locals.
889 if (RegInfo->needsStackRealignment(MF)) {
890 assert(hasFP(MF) && "dynamic stack realignment without a FP!");
892 FrameReg = RegInfo->getFrameRegister(MF);
894 } else if (hasMovingSP) {
895 assert(RegInfo->hasBasePointer(MF) &&
896 "VLAs and dynamic stack alignment, but missing base pointer!");
897 FrameReg = RegInfo->getBaseRegister();
902 // If there is a frame pointer, use it when we can.
903 if (hasFP(MF) && AFI->hasStackFrame()) {
904 // Use frame pointer to reference fixed objects. Use it for locals if
905 // there are VLAs (and thus the SP isn't reliable as a base).
906 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
907 FrameReg = RegInfo->getFrameRegister(MF);
909 } else if (hasMovingSP) {
910 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
911 if (AFI->isThumb2Function()) {
912 // Try to use the frame pointer if we can, else use the base pointer
913 // since it's available. This is handy for the emergency spill slot, in
915 if (FPOffset >= -255 && FPOffset < 0) {
916 FrameReg = RegInfo->getFrameRegister(MF);
920 } else if (AFI->isThumb2Function()) {
921 // Use add <rd>, sp, #<imm8>
922 // ldr <rd>, [sp, #<imm8>]
923 // if at all possible to save space.
924 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
926 // In Thumb2 mode, the negative offset is very limited. Try to avoid
927 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
928 if (FPOffset >= -255 && FPOffset < 0) {
929 FrameReg = RegInfo->getFrameRegister(MF);
932 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
933 // Otherwise, use SP or FP, whichever is closer to the stack slot.
934 FrameReg = RegInfo->getFrameRegister(MF);
938 // Use the base pointer if we have one.
939 if (RegInfo->hasBasePointer(MF))
940 FrameReg = RegInfo->getBaseRegister();
944 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
945 MachineBasicBlock::iterator MI,
946 const std::vector<CalleeSavedInfo> &CSI,
947 unsigned StmOpc, unsigned StrOpc,
949 bool(*Func)(unsigned, bool),
950 unsigned NumAlignedDPRCS2Regs,
951 unsigned MIFlags) const {
952 MachineFunction &MF = *MBB.getParent();
953 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
954 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
958 typedef std::pair<unsigned, bool> RegAndKill;
959 SmallVector<RegAndKill, 4> Regs;
960 unsigned i = CSI.size();
962 unsigned LastReg = 0;
963 for (; i != 0; --i) {
964 unsigned Reg = CSI[i-1].getReg();
965 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
967 // D-registers in the aligned area DPRCS2 are NOT spilled here.
968 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
971 bool isLiveIn = MF.getRegInfo().isLiveIn(Reg);
974 // If NoGap is true, push consecutive registers and then leave the rest
975 // for other instructions. e.g.
976 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
977 if (NoGap && LastReg && LastReg != Reg-1)
980 // Do not set a kill flag on values that are also marked as live-in. This
981 // happens with the @llvm-returnaddress intrinsic and with arguments
982 // passed in callee saved registers.
983 // Omitting the kill flags is conservatively correct even if the live-in
984 // is not used after all.
985 Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
991 std::sort(Regs.begin(), Regs.end(), [&](const RegAndKill &LHS,
992 const RegAndKill &RHS) {
993 return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
996 if (Regs.size() > 1 || StrOpc== 0) {
997 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1000 .add(predOps(ARMCC::AL));
1001 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1002 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
1003 } else if (Regs.size() == 1) {
1004 BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1005 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1007 .setMIFlags(MIFlags)
1009 .add(predOps(ARMCC::AL));
1013 // Put any subsequent vpush instructions before this one: they will refer to
1014 // higher register numbers so need to be pushed first in order to preserve
1016 if (MI != MBB.begin())
1021 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1022 MachineBasicBlock::iterator MI,
1023 const std::vector<CalleeSavedInfo> &CSI,
1024 unsigned LdmOpc, unsigned LdrOpc,
1025 bool isVarArg, bool NoGap,
1026 bool(*Func)(unsigned, bool),
1027 unsigned NumAlignedDPRCS2Regs) const {
1028 MachineFunction &MF = *MBB.getParent();
1029 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1030 const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1031 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1033 bool isTailCall = false;
1034 bool isInterrupt = false;
1035 bool isTrap = false;
1036 if (MBB.end() != MI) {
1037 DL = MI->getDebugLoc();
1038 unsigned RetOpcode = MI->getOpcode();
1039 isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1041 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1043 RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1044 RetOpcode == ARM::tTRAP;
1047 SmallVector<unsigned, 4> Regs;
1048 unsigned i = CSI.size();
1050 unsigned LastReg = 0;
1051 bool DeleteRet = false;
1052 for (; i != 0; --i) {
1053 unsigned Reg = CSI[i-1].getReg();
1054 if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
1056 // The aligned reloads from area DPRCS2 are not inserted here.
1057 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1060 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1061 !isTrap && STI.hasV5TOps()) {
1062 if (MBB.succ_empty()) {
1065 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1067 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1068 // Fold the return instruction into the LDM.
1071 // If NoGap is true, pop consecutive registers and then leave the rest
1072 // for other instructions. e.g.
1073 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1074 if (NoGap && LastReg && LastReg != Reg-1)
1078 Regs.push_back(Reg);
1084 std::sort(Regs.begin(), Regs.end(), [&](unsigned LHS, unsigned RHS) {
1085 return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1088 if (Regs.size() > 1 || LdrOpc == 0) {
1089 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1091 .add(predOps(ARMCC::AL));
1092 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1093 MIB.addReg(Regs[i], getDefRegState(true));
1094 if (DeleteRet && MI != MBB.end()) {
1095 MIB.copyImplicitOps(*MI);
1096 MI->eraseFromParent();
1099 } else if (Regs.size() == 1) {
1100 // If we adjusted the reg to PC from LR above, switch it back here. We
1101 // only do that for LDM.
1102 if (Regs[0] == ARM::PC)
1104 MachineInstrBuilder MIB =
1105 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1106 .addReg(ARM::SP, RegState::Define)
1108 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1109 // that refactoring is complete (eventually).
1110 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1112 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1115 MIB.add(predOps(ARMCC::AL));
1119 // Put any subsequent vpop instructions after this one: they will refer to
1120 // higher register numbers so need to be popped afterwards.
1121 if (MI != MBB.end())
1126 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1127 /// starting from d8. Also insert stack realignment code and leave the stack
1128 /// pointer pointing to the d8 spill slot.
1129 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1130 MachineBasicBlock::iterator MI,
1131 unsigned NumAlignedDPRCS2Regs,
1132 const std::vector<CalleeSavedInfo> &CSI,
1133 const TargetRegisterInfo *TRI) {
1134 MachineFunction &MF = *MBB.getParent();
1135 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1136 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1137 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1138 MachineFrameInfo &MFI = MF.getFrameInfo();
1140 // Mark the D-register spill slots as properly aligned. Since MFI computes
1141 // stack slot layout backwards, this can actually mean that the d-reg stack
1142 // slot offsets can be wrong. The offset for d8 will always be correct.
1143 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1144 unsigned DNum = CSI[i].getReg() - ARM::D8;
1145 if (DNum > NumAlignedDPRCS2Regs - 1)
1147 int FI = CSI[i].getFrameIdx();
1148 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1149 // registers will be 8-byte aligned.
1150 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1152 // The stack slot for D8 needs to be maximally aligned because this is
1153 // actually the point where we align the stack pointer. MachineFrameInfo
1154 // computes all offsets relative to the incoming stack pointer which is a
1155 // bit weird when realigning the stack. Any extra padding for this
1156 // over-alignment is not realized because the code inserted below adjusts
1157 // the stack pointer by numregs * 8 before aligning the stack pointer.
1159 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1162 // Move the stack pointer to the d8 spill slot, and align it at the same
1163 // time. Leave the stack slot address in the scratch register r4.
1165 // sub r4, sp, #numregs * 8
1166 // bic r4, r4, #align - 1
1169 bool isThumb = AFI->isThumbFunction();
1170 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1171 AFI->setShouldRestoreSPFromFP(true);
1173 // sub r4, sp, #numregs * 8
1174 // The immediate is <= 64, so it doesn't need any special encoding.
1175 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1176 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1178 .addImm(8 * NumAlignedDPRCS2Regs)
1179 .add(predOps(ARMCC::AL))
1182 unsigned MaxAlign = MF.getFrameInfo().getMaxAlignment();
1183 // We must set parameter MustBeSingleInstruction to true, since
1184 // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1185 // stack alignment. Luckily, this can always be done since all ARM
1186 // architecture versions that support Neon also support the BFC
1188 emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1191 // The stack pointer must be adjusted before spilling anything, otherwise
1192 // the stack slots could be clobbered by an interrupt handler.
1193 // Leave r4 live, it is used below.
1194 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1195 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1197 .add(predOps(ARMCC::AL));
1199 MIB.add(condCodeOp());
1201 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1202 // r4 holds the stack slot address.
1203 unsigned NextReg = ARM::D8;
1205 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1206 // The writeback is only needed when emitting two vst1.64 instructions.
1207 if (NumAlignedDPRCS2Regs >= 6) {
1208 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1209 &ARM::QQPRRegClass);
1210 MBB.addLiveIn(SupReg);
1211 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1212 .addReg(ARM::R4, RegState::Kill)
1215 .addReg(SupReg, RegState::ImplicitKill)
1216 .add(predOps(ARMCC::AL));
1218 NumAlignedDPRCS2Regs -= 4;
1221 // We won't modify r4 beyond this point. It currently points to the next
1222 // register to be spilled.
1223 unsigned R4BaseReg = NextReg;
1225 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1226 if (NumAlignedDPRCS2Regs >= 4) {
1227 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1228 &ARM::QQPRRegClass);
1229 MBB.addLiveIn(SupReg);
1230 BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1234 .addReg(SupReg, RegState::ImplicitKill)
1235 .add(predOps(ARMCC::AL));
1237 NumAlignedDPRCS2Regs -= 4;
1240 // 16-byte aligned vst1.64 with 2 d-regs.
1241 if (NumAlignedDPRCS2Regs >= 2) {
1242 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1244 MBB.addLiveIn(SupReg);
1245 BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1249 .add(predOps(ARMCC::AL));
1251 NumAlignedDPRCS2Regs -= 2;
1254 // Finally, use a vanilla vstr.64 for the odd last register.
1255 if (NumAlignedDPRCS2Regs) {
1256 MBB.addLiveIn(NextReg);
1257 // vstr.64 uses addrmode5 which has an offset scale of 4.
1258 BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1261 .addImm((NextReg - R4BaseReg) * 2)
1262 .add(predOps(ARMCC::AL));
1265 // The last spill instruction inserted should kill the scratch register r4.
1266 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1269 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1270 /// iterator to the following instruction.
1271 static MachineBasicBlock::iterator
1272 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1273 unsigned NumAlignedDPRCS2Regs) {
1274 // sub r4, sp, #numregs * 8
1275 // bic r4, r4, #align - 1
1278 assert(MI->mayStore() && "Expecting spill instruction");
1280 // These switches all fall through.
1281 switch(NumAlignedDPRCS2Regs) {
1284 assert(MI->mayStore() && "Expecting spill instruction");
1287 assert(MI->mayStore() && "Expecting spill instruction");
1291 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1297 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1298 /// starting from d8. These instructions are assumed to execute while the
1299 /// stack is still aligned, unlike the code inserted by emitPopInst.
1300 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1301 MachineBasicBlock::iterator MI,
1302 unsigned NumAlignedDPRCS2Regs,
1303 const std::vector<CalleeSavedInfo> &CSI,
1304 const TargetRegisterInfo *TRI) {
1305 MachineFunction &MF = *MBB.getParent();
1306 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1307 DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1308 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1310 // Find the frame index assigned to d8.
1312 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1313 if (CSI[i].getReg() == ARM::D8) {
1314 D8SpillFI = CSI[i].getFrameIdx();
1318 // Materialize the address of the d8 spill slot into the scratch register r4.
1319 // This can be fairly complicated if the stack frame is large, so just use
1320 // the normal frame index elimination mechanism to do it. This code runs as
1321 // the initial part of the epilog where the stack and base pointers haven't
1322 // been changed yet.
1323 bool isThumb = AFI->isThumbFunction();
1324 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1326 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1327 BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1328 .addFrameIndex(D8SpillFI)
1330 .add(predOps(ARMCC::AL))
1333 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1334 unsigned NextReg = ARM::D8;
1336 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1337 if (NumAlignedDPRCS2Regs >= 6) {
1338 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1339 &ARM::QQPRRegClass);
1340 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1341 .addReg(ARM::R4, RegState::Define)
1342 .addReg(ARM::R4, RegState::Kill)
1344 .addReg(SupReg, RegState::ImplicitDefine)
1345 .add(predOps(ARMCC::AL));
1347 NumAlignedDPRCS2Regs -= 4;
1350 // We won't modify r4 beyond this point. It currently points to the next
1351 // register to be spilled.
1352 unsigned R4BaseReg = NextReg;
1354 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1355 if (NumAlignedDPRCS2Regs >= 4) {
1356 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1357 &ARM::QQPRRegClass);
1358 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1361 .addReg(SupReg, RegState::ImplicitDefine)
1362 .add(predOps(ARMCC::AL));
1364 NumAlignedDPRCS2Regs -= 4;
1367 // 16-byte aligned vld1.64 with 2 d-regs.
1368 if (NumAlignedDPRCS2Regs >= 2) {
1369 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1371 BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1374 .add(predOps(ARMCC::AL));
1376 NumAlignedDPRCS2Regs -= 2;
1379 // Finally, use a vanilla vldr.64 for the remaining odd register.
1380 if (NumAlignedDPRCS2Regs)
1381 BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1383 .addImm(2 * (NextReg - R4BaseReg))
1384 .add(predOps(ARMCC::AL));
1386 // Last store kills r4.
1387 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1390 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1391 MachineBasicBlock::iterator MI,
1392 const std::vector<CalleeSavedInfo> &CSI,
1393 const TargetRegisterInfo *TRI) const {
1397 MachineFunction &MF = *MBB.getParent();
1398 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1400 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1401 unsigned PushOneOpc = AFI->isThumbFunction() ?
1402 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1403 unsigned FltOpc = ARM::VSTMDDB_UPD;
1404 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1405 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1406 MachineInstr::FrameSetup);
1407 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1408 MachineInstr::FrameSetup);
1409 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1410 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1412 // The code above does not insert spill code for the aligned DPRCS2 registers.
1413 // The stack realignment code will be inserted between the push instructions
1414 // and these spills.
1415 if (NumAlignedDPRCS2Regs)
1416 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1421 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1422 MachineBasicBlock::iterator MI,
1423 const std::vector<CalleeSavedInfo> &CSI,
1424 const TargetRegisterInfo *TRI) const {
1428 MachineFunction &MF = *MBB.getParent();
1429 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1430 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1431 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1433 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1434 // registers. Do that here instead.
1435 if (NumAlignedDPRCS2Regs)
1436 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1438 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1439 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1440 unsigned FltOpc = ARM::VLDMDIA_UPD;
1441 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1442 NumAlignedDPRCS2Regs);
1443 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1444 &isARMArea2Register, 0);
1445 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1446 &isARMArea1Register, 0);
1451 // FIXME: Make generic?
1452 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1453 const ARMBaseInstrInfo &TII) {
1454 unsigned FnSize = 0;
1455 for (auto &MBB : MF) {
1456 for (auto &MI : MBB)
1457 FnSize += TII.getInstSizeInBytes(MI);
1462 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1463 /// frames and return the stack size limit beyond which some of these
1464 /// instructions will require a scratch register during their expansion later.
1465 // FIXME: Move to TII?
1466 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1467 const TargetFrameLowering *TFI) {
1468 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1469 unsigned Limit = (1 << 12) - 1;
1470 for (auto &MBB : MF) {
1471 for (auto &MI : MBB) {
1472 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1473 if (!MI.getOperand(i).isFI())
1476 // When using ADDri to get the address of a stack object, 255 is the
1477 // largest offset guaranteed to fit in the immediate offset.
1478 if (MI.getOpcode() == ARM::ADDri) {
1479 Limit = std::min(Limit, (1U << 8) - 1);
1483 // Otherwise check the addressing mode.
1484 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1485 case ARMII::AddrMode3:
1486 case ARMII::AddrModeT2_i8:
1487 Limit = std::min(Limit, (1U << 8) - 1);
1489 case ARMII::AddrMode5:
1490 case ARMII::AddrModeT2_i8s4:
1491 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1493 case ARMII::AddrModeT2_i12:
1494 // i12 supports only positive offset so these will be converted to
1495 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1496 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1497 Limit = std::min(Limit, (1U << 8) - 1);
1499 case ARMII::AddrMode4:
1500 case ARMII::AddrMode6:
1501 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1502 // immediate offset for stack references.
1507 break; // At most one FI per instruction
1515 // In functions that realign the stack, it can be an advantage to spill the
1516 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1517 // instructions take alignment hints that can improve performance.
1520 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1521 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1522 if (!SpillAlignedNEONRegs)
1525 // Naked functions don't spill callee-saved registers.
1526 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
1529 // We are planning to use NEON instructions vst1 / vld1.
1530 if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1533 // Don't bother if the default stack alignment is sufficiently high.
1534 if (MF.getSubtarget().getFrameLowering()->getStackAlignment() >= 8)
1537 // Aligned spills require stack realignment.
1538 if (!static_cast<const ARMBaseRegisterInfo *>(
1539 MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1542 // We always spill contiguous d-registers starting from d8. Count how many
1543 // needs spilling. The register allocator will almost always use the
1544 // callee-saved registers in order, but it can happen that there are holes in
1545 // the range. Registers above the hole will be spilled to the standard DPRCS
1547 unsigned NumSpills = 0;
1548 for (; NumSpills < 8; ++NumSpills)
1549 if (!SavedRegs.test(ARM::D8 + NumSpills))
1552 // Don't do this for just one d-register. It's not worth it.
1556 // Spill the first NumSpills D-registers after realigning the stack.
1557 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1559 // A scratch register is required for the vst1 / vld1 instructions.
1560 SavedRegs.set(ARM::R4);
1563 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1564 BitVector &SavedRegs,
1565 RegScavenger *RS) const {
1566 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1567 // This tells PEI to spill the FP as if it is any other callee-save register
1568 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1569 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1570 // to combine multiple loads / stores.
1571 bool CanEliminateFrame = true;
1572 bool CS1Spilled = false;
1573 bool LRSpilled = false;
1574 unsigned NumGPRSpills = 0;
1575 unsigned NumFPRSpills = 0;
1576 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1577 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1578 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1579 MF.getSubtarget().getRegisterInfo());
1580 const ARMBaseInstrInfo &TII =
1581 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1582 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1583 MachineFrameInfo &MFI = MF.getFrameInfo();
1584 MachineRegisterInfo &MRI = MF.getRegInfo();
1585 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1586 (void)TRI; // Silence unused warning in non-assert builds.
1587 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1589 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1590 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1591 // since it's not always possible to restore sp from fp in a single
1593 // FIXME: It will be better just to find spare register here.
1594 if (AFI->isThumb2Function() &&
1595 (MFI.hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1596 SavedRegs.set(ARM::R4);
1598 if (AFI->isThumb1OnlyFunction()) {
1599 // Spill LR if Thumb1 function uses variable length argument lists.
1600 if (AFI->getArgRegsSaveSize() > 0)
1601 SavedRegs.set(ARM::LR);
1603 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1604 // for sure what the stack size will be, but for this, an estimate is good
1605 // enough. If there anything changes it, it'll be a spill, which implies
1606 // we've used all the registers and so R4 is already used, so not marking
1607 // it here will be OK.
1608 // FIXME: It will be better just to find spare register here.
1609 unsigned StackSize = MFI.estimateStackSize(MF);
1610 if (MFI.hasVarSizedObjects() || StackSize > 508)
1611 SavedRegs.set(ARM::R4);
1614 // See if we can spill vector registers to aligned stack.
1615 checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1617 // Spill the BasePtr if it's used.
1618 if (RegInfo->hasBasePointer(MF))
1619 SavedRegs.set(RegInfo->getBaseRegister());
1621 // Don't spill FP if the frame can be eliminated. This is determined
1622 // by scanning the callee-save registers to see if any is modified.
1623 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1624 for (unsigned i = 0; CSRegs[i]; ++i) {
1625 unsigned Reg = CSRegs[i];
1626 bool Spilled = false;
1627 if (SavedRegs.test(Reg)) {
1629 CanEliminateFrame = false;
1632 if (!ARM::GPRRegClass.contains(Reg)) {
1634 if (ARM::SPRRegClass.contains(Reg))
1636 else if (ARM::DPRRegClass.contains(Reg))
1638 else if (ARM::QPRRegClass.contains(Reg))
1647 if (!STI.splitFramePushPop(MF)) {
1654 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1659 case ARM::R0: case ARM::R1:
1660 case ARM::R2: case ARM::R3:
1661 case ARM::R4: case ARM::R5:
1662 case ARM::R6: case ARM::R7:
1669 if (!STI.splitFramePushPop(MF)) {
1670 UnspilledCS1GPRs.push_back(Reg);
1675 case ARM::R0: case ARM::R1:
1676 case ARM::R2: case ARM::R3:
1677 case ARM::R4: case ARM::R5:
1678 case ARM::R6: case ARM::R7:
1680 UnspilledCS1GPRs.push_back(Reg);
1683 UnspilledCS2GPRs.push_back(Reg);
1689 bool ForceLRSpill = false;
1690 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1691 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1692 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1693 // use of BL to implement far jump. If it turns out that it's not needed
1694 // then the branch fix up path will undo it.
1695 if (FnSize >= (1 << 11)) {
1696 CanEliminateFrame = false;
1697 ForceLRSpill = true;
1701 // If any of the stack slot references may be out of range of an immediate
1702 // offset, make sure a register (or a spill slot) is available for the
1703 // register scavenger. Note that if we're indexing off the frame pointer, the
1704 // effective stack size is 4 bytes larger since the FP points to the stack
1705 // slot of the previous FP. Also, if we have variable sized objects in the
1706 // function, stack slot references will often be negative, and some of
1707 // our instructions are positive-offset only, so conservatively consider
1708 // that case to want a spill slot (or register) as well. Similarly, if
1709 // the function adjusts the stack pointer during execution and the
1710 // adjustments aren't already part of our stack size estimate, our offset
1711 // calculations may be off, so be conservative.
1712 // FIXME: We could add logic to be more precise about negative offsets
1713 // and which instructions will need a scratch register for them. Is it
1714 // worth the effort and added fragility?
1715 unsigned EstimatedStackSize =
1716 MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
1718 // Determine biggest (positive) SP offset in MachineFrameInfo.
1719 int MaxFixedOffset = 0;
1720 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1721 int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1722 MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1725 bool HasFP = hasFP(MF);
1727 if (AFI->hasStackFrame())
1728 EstimatedStackSize += 4;
1730 // If FP is not used, SP will be used to access arguments, so count the
1731 // size of arguments into the estimation.
1732 EstimatedStackSize += MaxFixedOffset;
1734 EstimatedStackSize += 16; // For possible paddings.
1736 unsigned EstimatedRSStackSizeLimit = estimateRSStackSizeLimit(MF, this);
1737 int MaxFPOffset = getMaxFPOffset(*MF.getFunction(), *AFI);
1738 bool BigFrameOffsets = EstimatedStackSize >= EstimatedRSStackSizeLimit ||
1739 MFI.hasVarSizedObjects() ||
1740 (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF)) ||
1741 // For large argument stacks fp relative addressed may overflow.
1742 (HasFP && (MaxFixedOffset - MaxFPOffset) >= (int)EstimatedRSStackSizeLimit);
1743 bool ExtraCSSpill = false;
1744 if (BigFrameOffsets ||
1745 !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1746 AFI->setHasStackFrame(true);
1749 SavedRegs.set(FramePtr);
1750 // If the frame pointer is required by the ABI, also spill LR so that we
1751 // emit a complete frame record.
1752 if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
1753 SavedRegs.set(ARM::LR);
1756 auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
1757 if (LRPos != UnspilledCS1GPRs.end())
1758 UnspilledCS1GPRs.erase(LRPos);
1760 auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
1761 if (FPPos != UnspilledCS1GPRs.end())
1762 UnspilledCS1GPRs.erase(FPPos);
1764 if (FramePtr == ARM::R7)
1768 if (AFI->isThumb1OnlyFunction()) {
1769 // For Thumb1-only targets, we need some low registers when we save and
1770 // restore the high registers (which aren't allocatable, but could be
1771 // used by inline assembly) because the push/pop instructions can not
1772 // access high registers. If necessary, we might need to push more low
1773 // registers to ensure that there is at least one free that can be used
1774 // for the saving & restoring, and preferably we should ensure that as
1775 // many as are needed are available so that fewer push/pop instructions
1778 // Low registers which are not currently pushed, but could be (r4-r7).
1779 SmallVector<unsigned, 4> AvailableRegs;
1781 // Unused argument registers (r0-r3) can be clobbered in the prologue for
1783 int EntryRegDeficit = 0;
1784 for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
1785 if (!MF.getRegInfo().isLiveIn(Reg)) {
1787 DEBUG(dbgs() << PrintReg(Reg, TRI)
1788 << " is unused argument register, EntryRegDeficit = "
1789 << EntryRegDeficit << "\n");
1793 // Unused return registers can be clobbered in the epilogue for free.
1794 int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
1795 DEBUG(dbgs() << AFI->getReturnRegsCount()
1796 << " return regs used, ExitRegDeficit = " << ExitRegDeficit
1799 int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
1800 DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
1802 // r4-r6 can be used in the prologue if they are pushed by the first push
1804 for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
1805 if (SavedRegs.test(Reg)) {
1807 DEBUG(dbgs() << PrintReg(Reg, TRI)
1808 << " is saved low register, RegDeficit = " << RegDeficit
1811 AvailableRegs.push_back(Reg);
1813 << PrintReg(Reg, TRI)
1814 << " is non-saved low register, adding to AvailableRegs\n");
1818 // r7 can be used if it is not being used as the frame pointer.
1820 if (SavedRegs.test(ARM::R7)) {
1822 DEBUG(dbgs() << "%R7 is saved low register, RegDeficit = "
1823 << RegDeficit << "\n");
1825 AvailableRegs.push_back(ARM::R7);
1827 << "%R7 is non-saved low register, adding to AvailableRegs\n");
1831 // Each of r8-r11 needs to be copied to a low register, then pushed.
1832 for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
1833 if (SavedRegs.test(Reg)) {
1835 DEBUG(dbgs() << PrintReg(Reg, TRI)
1836 << " is saved high register, RegDeficit = " << RegDeficit
1841 // LR can only be used by PUSH, not POP, and can't be used at all if the
1842 // llvm.returnaddress intrinsic is used. This is only worth doing if we
1843 // are more limited at function entry than exit.
1844 if ((EntryRegDeficit > ExitRegDeficit) &&
1845 !(MF.getRegInfo().isLiveIn(ARM::LR) &&
1846 MF.getFrameInfo().isReturnAddressTaken())) {
1847 if (SavedRegs.test(ARM::LR)) {
1849 DEBUG(dbgs() << "%LR is saved register, RegDeficit = " << RegDeficit
1852 AvailableRegs.push_back(ARM::LR);
1853 DEBUG(dbgs() << "%LR is not saved, adding to AvailableRegs\n");
1857 // If there are more high registers that need pushing than low registers
1858 // available, push some more low registers so that we can use fewer push
1859 // instructions. This might not reduce RegDeficit all the way to zero,
1860 // because we can only guarantee that r4-r6 are available, but r8-r11 may
1862 DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
1863 for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
1864 unsigned Reg = AvailableRegs.pop_back_val();
1865 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1866 << " to make up reg deficit\n");
1870 ExtraCSSpill = true;
1871 UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
1875 DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit << "\n");
1878 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1879 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1880 if (!LRSpilled && CS1Spilled) {
1881 SavedRegs.set(ARM::LR);
1883 SmallVectorImpl<unsigned>::iterator LRPos;
1884 LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
1885 if (LRPos != UnspilledCS1GPRs.end())
1886 UnspilledCS1GPRs.erase(LRPos);
1888 ForceLRSpill = false;
1889 ExtraCSSpill = true;
1892 // If stack and double are 8-byte aligned and we are spilling an odd number
1893 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1894 // the integer and double callee save areas.
1895 DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
1896 unsigned TargetAlign = getStackAlignment();
1897 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1898 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1899 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1900 unsigned Reg = UnspilledCS1GPRs[i];
1901 // Don't spill high register if the function is thumb. In the case of
1902 // Windows on ARM, accept R11 (frame pointer)
1903 if (!AFI->isThumbFunction() ||
1904 (STI.isTargetWindows() && Reg == ARM::R11) ||
1905 isARMLowRegister(Reg) || Reg == ARM::LR) {
1907 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1908 << " to make up alignment\n");
1909 if (!MRI.isReserved(Reg))
1910 ExtraCSSpill = true;
1914 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1915 unsigned Reg = UnspilledCS2GPRs.front();
1917 DEBUG(dbgs() << "Spilling " << PrintReg(Reg, TRI)
1918 << " to make up alignment\n");
1919 if (!MRI.isReserved(Reg))
1920 ExtraCSSpill = true;
1924 // Estimate if we might need to scavenge a register at some point in order
1925 // to materialize a stack offset. If so, either spill one additional
1926 // callee-saved register or reserve a special spill slot to facilitate
1927 // register scavenging. Thumb1 needs a spill slot for stack pointer
1928 // adjustments also, even when the frame itself is small.
1929 if (BigFrameOffsets && !ExtraCSSpill) {
1930 // If any non-reserved CS register isn't spilled, just spill one or two
1931 // extra. That should take care of it!
1932 unsigned NumExtras = TargetAlign / 4;
1933 SmallVector<unsigned, 2> Extras;
1934 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1935 unsigned Reg = UnspilledCS1GPRs.back();
1936 UnspilledCS1GPRs.pop_back();
1937 if (!MRI.isReserved(Reg) &&
1938 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1940 Extras.push_back(Reg);
1944 // For non-Thumb1 functions, also check for hi-reg CS registers
1945 if (!AFI->isThumb1OnlyFunction()) {
1946 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1947 unsigned Reg = UnspilledCS2GPRs.back();
1948 UnspilledCS2GPRs.pop_back();
1949 if (!MRI.isReserved(Reg)) {
1950 Extras.push_back(Reg);
1955 if (Extras.size() && NumExtras == 0) {
1956 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1957 SavedRegs.set(Extras[i]);
1959 } else if (!AFI->isThumb1OnlyFunction()) {
1960 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1961 // closest to SP or frame pointer.
1962 assert(RS && "Register scavenging not provided");
1963 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1964 RS->addScavengingFrameIndex(MFI.CreateStackObject(RC->getSize(),
1972 SavedRegs.set(ARM::LR);
1973 AFI->setLRIsSpilledForFarJump(true);
1977 MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
1978 MachineFunction &MF, MachineBasicBlock &MBB,
1979 MachineBasicBlock::iterator I) const {
1980 const ARMBaseInstrInfo &TII =
1981 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1982 if (!hasReservedCallFrame(MF)) {
1983 // If we have alloca, convert as follows:
1984 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1985 // ADJCALLSTACKUP -> add, sp, sp, amount
1986 MachineInstr &Old = *I;
1987 DebugLoc dl = Old.getDebugLoc();
1988 unsigned Amount = TII.getFrameSize(Old);
1990 // We need to keep the stack aligned properly. To do this, we round the
1991 // amount of space needed for the outgoing arguments up to the next
1992 // alignment boundary.
1993 Amount = alignSPAdjust(Amount);
1995 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1996 assert(!AFI->isThumb1OnlyFunction() &&
1997 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1998 bool isARM = !AFI->isThumbFunction();
2000 // Replace the pseudo instruction with a new instruction...
2001 unsigned Opc = Old.getOpcode();
2002 int PIdx = Old.findFirstPredOperandIdx();
2003 ARMCC::CondCodes Pred =
2004 (PIdx == -1) ? ARMCC::AL
2005 : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
2006 unsigned PredReg = TII.getFramePred(Old);
2007 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
2008 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2011 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2012 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2017 return MBB.erase(I);
2020 /// Get the minimum constant for ARM that is greater than or equal to the
2021 /// argument. In ARM, constants can have any value that can be produced by
2022 /// rotating an 8-bit value to the right by an even number of bits within a
2024 static uint32_t alignToARMConstant(uint32_t Value) {
2025 unsigned Shifted = 0;
2030 while (!(Value & 0xC0000000)) {
2035 bool Carry = (Value & 0x00FFFFFF);
2036 Value = ((Value & 0xFF000000) >> 24) + Carry;
2038 if (Value & 0x0000100)
2039 Value = Value & 0x000001FC;
2042 Value = Value >> (Shifted - 24);
2044 Value = Value << (24 - Shifted);
2049 // The stack limit in the TCB is set to this many bytes above the actual
2051 static const uint64_t kSplitStackAvailable = 256;
2053 // Adjust the function prologue to enable split stacks. This currently only
2054 // supports android and linux.
2056 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2057 // must be well defined in order to allow for consistent implementations of the
2058 // __morestack helper function. The ABI is also not a normal ABI in that it
2059 // doesn't follow the normal calling conventions because this allows the
2060 // prologue of each function to be optimized further.
2062 // Currently, the ABI looks like (when calling __morestack)
2064 // * r4 holds the minimum stack size requested for this function call
2065 // * r5 holds the stack size of the arguments to the function
2066 // * the beginning of the function is 3 instructions after the call to
2069 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
2070 // place the arguments on to the new stack, and the 3-instruction knowledge to
2071 // jump directly to the body of the function when working on the new stack.
2073 // An old (and possibly no longer compatible) implementation of __morestack for
2074 // ARM can be found at [1].
2076 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
2077 void ARMFrameLowering::adjustForSegmentedStacks(
2078 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2081 const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
2082 bool Thumb = ST->isThumb();
2084 // Sadly, this currently doesn't support varargs, platforms other than
2085 // android/linux. Note that thumb1/thumb2 are support for android/linux.
2086 if (MF.getFunction()->isVarArg())
2087 report_fatal_error("Segmented stacks do not support vararg functions.");
2088 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
2089 report_fatal_error("Segmented stacks not supported on this platform.");
2091 MachineFrameInfo &MFI = MF.getFrameInfo();
2092 MachineModuleInfo &MMI = MF.getMMI();
2093 MCContext &Context = MMI.getContext();
2094 const MCRegisterInfo *MRI = Context.getRegisterInfo();
2095 const ARMBaseInstrInfo &TII =
2096 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2097 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2100 uint64_t StackSize = MFI.getStackSize();
2102 // Do not generate a prologue for functions with a stack of size zero
2106 // Use R4 and R5 as scratch registers.
2107 // We save R4 and R5 before use and restore them before leaving the function.
2108 unsigned ScratchReg0 = ARM::R4;
2109 unsigned ScratchReg1 = ARM::R5;
2110 uint64_t AlignedStackSize;
2112 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2113 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2114 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2115 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2116 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2118 // Grab everything that reaches PrologueMBB to update there liveness as well.
2119 SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2120 SmallVector<MachineBasicBlock *, 2> WalkList;
2121 WalkList.push_back(&PrologueMBB);
2124 MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2125 for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2126 if (BeforePrologueRegion.insert(PredBB).second)
2127 WalkList.push_back(PredBB);
2129 } while (!WalkList.empty());
2131 // The order in that list is important.
2132 // The blocks will all be inserted before PrologueMBB using that order.
2133 // Therefore the block that should appear first in the CFG should appear
2134 // first in the list.
2135 MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2138 for (MachineBasicBlock *B : AddedBlocks)
2139 BeforePrologueRegion.insert(B);
2141 for (const auto &LI : PrologueMBB.liveins()) {
2142 for (MachineBasicBlock *PredBB : BeforePrologueRegion)
2143 PredBB->addLiveIn(LI);
2146 // Remove the newly added blocks from the list, since we know
2147 // we do not have to do the following updates for them.
2148 for (MachineBasicBlock *B : AddedBlocks) {
2149 BeforePrologueRegion.erase(B);
2150 MF.insert(PrologueMBB.getIterator(), B);
2153 for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2154 // Make sure the LiveIns are still sorted and unique.
2155 MBB->sortUniqueLiveIns();
2156 // Replace the edges to PrologueMBB by edges to the sequences
2157 // we are about to add.
2158 MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2161 // The required stack size that is aligned to ARM constant criterion.
2162 AlignedStackSize = alignToARMConstant(StackSize);
2164 // When the frame size is less than 256 we just compare the stack
2165 // boundary directly to the value of the stack pointer, per gcc.
2166 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2168 // We will use two of the callee save registers as scratch registers so we
2169 // need to save those registers onto the stack.
2170 // We will use SR0 to hold stack limit and SR1 to hold the stack size
2171 // requested and arguments for __morestack().
2172 // SR0: Scratch Register #0
2173 // SR1: Scratch Register #1
2176 BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2177 .add(predOps(ARMCC::AL))
2178 .addReg(ScratchReg0)
2179 .addReg(ScratchReg1);
2181 BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2182 .addReg(ARM::SP, RegState::Define)
2184 .add(predOps(ARMCC::AL))
2185 .addReg(ScratchReg0)
2186 .addReg(ScratchReg1);
2189 // Emit the relevant DWARF information about the change in stack pointer as
2190 // well as where to find both r4 and r5 (the callee-save registers)
2192 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
2193 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2194 .addCFIIndex(CFIIndex);
2195 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2196 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2197 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2198 .addCFIIndex(CFIIndex);
2199 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2200 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2201 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2202 .addCFIIndex(CFIIndex);
2206 BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2208 .add(predOps(ARMCC::AL));
2209 } else if (CompareStackPointer) {
2210 BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2212 .add(predOps(ARMCC::AL))
2216 // sub SR1, sp, #StackSize
2217 if (!CompareStackPointer && Thumb) {
2218 BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2220 .addReg(ScratchReg1)
2221 .addImm(AlignedStackSize)
2222 .add(predOps(ARMCC::AL));
2223 } else if (!CompareStackPointer) {
2224 BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2226 .addImm(AlignedStackSize)
2227 .add(predOps(ARMCC::AL))
2231 if (Thumb && ST->isThumb1Only()) {
2232 unsigned PCLabelId = ARMFI->createPICLabelUId();
2233 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
2234 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
2235 MachineConstantPool *MCP = MF.getConstantPool();
2236 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, 4);
2238 // ldr SR0, [pc, offset(STACK_LIMIT)]
2239 BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2240 .addConstantPoolIndex(CPI)
2241 .add(predOps(ARMCC::AL));
2244 BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2245 .addReg(ScratchReg0)
2247 .add(predOps(ARMCC::AL));
2249 // Get TLS base address from the coprocessor
2250 // mrc p15, #0, SR0, c13, c0, #3
2251 BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
2257 .add(predOps(ARMCC::AL));
2259 // Use the last tls slot on android and a private field of the TCP on linux.
2260 assert(ST->isTargetAndroid() || ST->isTargetLinux());
2261 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2263 // Get the stack limit from the right offset
2264 // ldr SR0, [sr0, #4 * TlsOffset]
2265 BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
2266 .addReg(ScratchReg0)
2267 .addImm(4 * TlsOffset)
2268 .add(predOps(ARMCC::AL));
2271 // Compare stack limit with stack size requested.
2273 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2274 BuildMI(GetMBB, DL, TII.get(Opcode))
2275 .addReg(ScratchReg0)
2276 .addReg(ScratchReg1)
2277 .add(predOps(ARMCC::AL));
2279 // This jump is taken if StackLimit < SP - stack required.
2280 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2281 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2286 // Calling __morestack(StackSize, Size of stack arguments).
2287 // __morestack knows that the stack size requested is in SR0(r4)
2288 // and amount size of stack arguments is in SR1(r5).
2290 // Pass first argument for the __morestack by Scratch Register #0.
2291 // The amount size of stack required
2293 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2295 .addImm(AlignedStackSize)
2296 .add(predOps(ARMCC::AL));
2298 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2299 .addImm(AlignedStackSize)
2300 .add(predOps(ARMCC::AL))
2303 // Pass second argument for the __morestack by Scratch Register #1.
2304 // The amount size of stack consumed to save function arguments.
2306 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2308 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2309 .add(predOps(ARMCC::AL));
2311 BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2312 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2313 .add(predOps(ARMCC::AL))
2317 // push {lr} - Save return address of this function.
2319 BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2320 .add(predOps(ARMCC::AL))
2323 BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2324 .addReg(ARM::SP, RegState::Define)
2326 .add(predOps(ARMCC::AL))
2330 // Emit the DWARF info about the change in stack as well as where to find the
2331 // previous link register
2333 MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2334 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2335 .addCFIIndex(CFIIndex);
2336 CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2337 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2338 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2339 .addCFIIndex(CFIIndex);
2341 // Call __morestack().
2343 BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2344 .add(predOps(ARMCC::AL))
2345 .addExternalSymbol("__morestack");
2347 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2348 .addExternalSymbol("__morestack");
2351 // pop {lr} - Restore return address of this original function.
2353 if (ST->isThumb1Only()) {
2354 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2355 .add(predOps(ARMCC::AL))
2356 .addReg(ScratchReg0);
2357 BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2358 .addReg(ScratchReg0)
2359 .add(predOps(ARMCC::AL));
2361 BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2362 .addReg(ARM::LR, RegState::Define)
2363 .addReg(ARM::SP, RegState::Define)
2366 .add(predOps(ARMCC::AL));
2369 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2370 .addReg(ARM::SP, RegState::Define)
2372 .add(predOps(ARMCC::AL))
2376 // Restore SR0 and SR1 in case of __morestack() was called.
2377 // __morestack() will skip PostStackMBB block so we need to restore
2378 // scratch registers from here.
2381 BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2382 .add(predOps(ARMCC::AL))
2383 .addReg(ScratchReg0)
2384 .addReg(ScratchReg1);
2386 BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2387 .addReg(ARM::SP, RegState::Define)
2389 .add(predOps(ARMCC::AL))
2390 .addReg(ScratchReg0)
2391 .addReg(ScratchReg1);
2394 // Update the CFA offset now that we've popped
2395 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2396 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2397 .addCFIIndex(CFIIndex);
2399 // bx lr - Return from this function.
2400 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2401 BuildMI(AllocMBB, DL, TII.get(Opcode)).add(predOps(ARMCC::AL));
2403 // Restore SR0 and SR1 in case of __morestack() was not called.
2406 BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2407 .add(predOps(ARMCC::AL))
2408 .addReg(ScratchReg0)
2409 .addReg(ScratchReg1);
2411 BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2412 .addReg(ARM::SP, RegState::Define)
2414 .add(predOps(ARMCC::AL))
2415 .addReg(ScratchReg0)
2416 .addReg(ScratchReg1);
2419 // Update the CFA offset now that we've popped
2420 CFIIndex = MF.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2421 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2422 .addCFIIndex(CFIIndex);
2424 // Tell debuggers that r4 and r5 are now the same as they were in the
2425 // previous function, that they're the "Same Value".
2426 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2427 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2428 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2429 .addCFIIndex(CFIIndex);
2430 CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2431 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2432 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2433 .addCFIIndex(CFIIndex);
2435 // Organizing MBB lists
2436 PostStackMBB->addSuccessor(&PrologueMBB);
2438 AllocMBB->addSuccessor(PostStackMBB);
2440 GetMBB->addSuccessor(PostStackMBB);
2441 GetMBB->addSuccessor(AllocMBB);
2443 McrMBB->addSuccessor(GetMBB);
2445 PrevStackMBB->addSuccessor(McrMBB);
2447 #ifdef EXPENSIVE_CHECKS