1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the ARM implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARMFrameLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "MCTargetDesc/ARMAddressingModes.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Target/TargetOptions.h"
35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36 cl::desc("Align ARM NEON spills in prolog and epilog"));
38 static MachineBasicBlock::iterator
39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
42 /// hasFP - Return true if the specified function should have a dedicated frame
43 /// pointer register. This is true if the function has variable sized allocas
44 /// or if frame pointer elimination is disabled.
45 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
46 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
48 // iOS requires FP not to be clobbered for backtracing purpose.
49 if (STI.isTargetIOS())
52 const MachineFrameInfo *MFI = MF.getFrameInfo();
53 // Always eliminate non-leaf frame pointers.
54 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
56 RegInfo->needsStackRealignment(MF) ||
57 MFI->hasVarSizedObjects() ||
58 MFI->isFrameAddressTaken());
61 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
62 /// not required, we reserve argument space for call sites in the function
63 /// immediately on entry to the current function. This eliminates the need for
64 /// add/sub sp brackets around call sites. Returns true if the call frame is
65 /// included as part of the stack frame.
66 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
67 const MachineFrameInfo *FFI = MF.getFrameInfo();
68 unsigned CFSize = FFI->getMaxCallFrameSize();
69 // It's not always a good idea to include the call frame as part of the
70 // stack frame. ARM (especially Thumb) has small immediate offset to
71 // address the stack frame. So a large call frame can cause poor codegen
72 // and may even makes it impossible to scavenge a register.
73 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
76 return !MF.getFrameInfo()->hasVarSizedObjects();
79 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
80 /// call frame pseudos can be simplified. Unlike most targets, having a FP
81 /// is not sufficient here since we still may reference some objects via SP
82 /// even when FP is available in Thumb2 mode.
84 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
85 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
88 static bool isCSRestore(MachineInstr *MI,
89 const ARMBaseInstrInfo &TII,
90 const MCPhysReg *CSRegs) {
91 // Integer spill area is handled with "pop".
92 if (isPopOpcode(MI->getOpcode())) {
93 // The first two operands are predicates. The last two are
94 // imp-def and imp-use of SP. Check everything in between.
95 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
96 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
100 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
101 MI->getOpcode() == ARM::LDR_POST_REG ||
102 MI->getOpcode() == ARM::t2LDR_POST) &&
103 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
104 MI->getOperand(1).getReg() == ARM::SP)
110 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
111 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
112 const ARMBaseInstrInfo &TII, unsigned DestReg,
113 unsigned SrcReg, int NumBytes,
114 unsigned MIFlags = MachineInstr::NoFlags,
115 ARMCC::CondCodes Pred = ARMCC::AL,
116 unsigned PredReg = 0) {
118 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
119 Pred, PredReg, TII, MIFlags);
121 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
122 Pred, PredReg, TII, MIFlags);
125 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
126 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
127 const ARMBaseInstrInfo &TII, int NumBytes,
128 unsigned MIFlags = MachineInstr::NoFlags,
129 ARMCC::CondCodes Pred = ARMCC::AL,
130 unsigned PredReg = 0) {
131 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
132 MIFlags, Pred, PredReg);
135 static int sizeOfSPAdjustment(const MachineInstr *MI) {
136 assert(MI->getOpcode() == ARM::VSTMDDB_UPD);
138 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
139 // pred) so the list starts at 4.
140 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
145 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
146 size_t StackSizeInBytes) {
147 const MachineFrameInfo *MFI = MF.getFrameInfo();
148 if (MFI->getStackProtectorIndex() > 0)
149 return StackSizeInBytes >= 4080;
150 return StackSizeInBytes >= 4096;
153 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
154 MachineBasicBlock &MBB = MF.front();
155 MachineBasicBlock::iterator MBBI = MBB.begin();
156 MachineFrameInfo *MFI = MF.getFrameInfo();
157 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
158 MachineModuleInfo &MMI = MF.getMMI();
159 MCContext &Context = MMI.getContext();
160 const TargetMachine &TM = MF.getTarget();
161 const MCRegisterInfo *MRI = Context.getRegisterInfo();
162 const ARMBaseRegisterInfo *RegInfo =
163 static_cast<const ARMBaseRegisterInfo*>(TM.getRegisterInfo());
164 const ARMBaseInstrInfo &TII =
165 *static_cast<const ARMBaseInstrInfo*>(TM.getInstrInfo());
166 assert(!AFI->isThumb1OnlyFunction() &&
167 "This emitPrologue does not support Thumb1!");
168 bool isARM = !AFI->isThumbFunction();
169 unsigned Align = TM.getFrameLowering()->getStackAlignment();
170 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
171 unsigned NumBytes = MFI->getStackSize();
172 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
173 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
174 unsigned FramePtr = RegInfo->getFrameRegister(MF);
177 // Determine the sizes of each callee-save spill areas and record which frame
178 // belongs to which callee-save spill areas.
179 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
180 int FramePtrSpillFI = 0;
183 // All calls are tail calls in GHC calling conv, and functions have no
184 // prologue/epilogue.
185 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
188 // Allocate the vararg register save area.
189 if (ArgRegsSaveSize) {
190 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
191 MachineInstr::FrameSetup);
192 CFAOffset -= ArgRegsSaveSize;
193 unsigned CFIIndex = MMI.addFrameInst(
194 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
195 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
196 .addCFIIndex(CFIIndex);
199 if (!AFI->hasStackFrame() &&
200 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
201 if (NumBytes - ArgRegsSaveSize != 0) {
202 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
203 MachineInstr::FrameSetup);
204 CFAOffset -= NumBytes - ArgRegsSaveSize;
205 unsigned CFIIndex = MMI.addFrameInst(
206 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
207 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
208 .addCFIIndex(CFIIndex);
213 // Determine spill area sizes.
214 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
215 unsigned Reg = CSI[i].getReg();
216 int FI = CSI[i].getFrameIdx();
223 if (STI.isTargetMachO()) {
238 FramePtrSpillFI = FI;
242 // This is a DPR. Exclude the aligned DPRCS2 spills.
245 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
251 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push,
254 GPRCS1Push = LastPush = MBBI++;
256 // Determine starting offsets of spill areas.
257 bool HasFP = hasFP(MF);
258 unsigned DPRCSOffset = NumBytes - (ArgRegsSaveSize + GPRCS1Size
259 + GPRCS2Size + DPRCSSize);
260 unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
261 unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
262 int FramePtrOffsetInPush = 0;
264 FramePtrOffsetInPush = MFI->getObjectOffset(FramePtrSpillFI)
265 + GPRCS1Size + ArgRegsSaveSize;
266 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
269 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
270 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
271 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
275 GPRCS2Push = LastPush = MBBI++;
280 // Since vpush register list cannot have gaps, there may be multiple vpush
281 // instructions in the prologue.
282 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD)
286 // Move past the aligned DPRCS2 area.
287 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
288 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
289 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
290 // leaves the stack pointer pointing to the DPRCS2 area.
292 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
293 NumBytes += MFI->getObjectOffset(D8SpillFI);
295 NumBytes = DPRCSOffset;
297 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
298 uint32_t NumWords = NumBytes >> 2;
300 if (NumWords < 65536)
301 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
304 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
307 switch (TM.getCodeModel()) {
308 case CodeModel::Small:
309 case CodeModel::Medium:
310 case CodeModel::Default:
311 case CodeModel::Kernel:
312 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
313 .addImm((unsigned)ARMCC::AL).addReg(0)
314 .addExternalSymbol("__chkstk")
315 .addReg(ARM::R4, RegState::Implicit);
317 case CodeModel::Large:
318 case CodeModel::JITDefault:
319 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
320 .addExternalSymbol("__chkstk");
322 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
323 .addImm((unsigned)ARMCC::AL).addReg(0)
324 .addReg(ARM::R12, RegState::Kill)
325 .addReg(ARM::R4, RegState::Implicit);
329 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
331 .addReg(ARM::SP, RegState::Define)
332 .addReg(ARM::R4, RegState::Kill)
333 .setMIFlags(MachineInstr::FrameSetup)));
337 unsigned adjustedGPRCS1Size = GPRCS1Size;
339 // Adjust SP after all the callee-save spills.
340 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes)) {
341 if (LastPush == GPRCS1Push) {
342 FramePtrOffsetInPush += NumBytes;
343 adjustedGPRCS1Size += NumBytes;
347 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
348 MachineInstr::FrameSetup);
351 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
352 // Note it's not safe to do this in Thumb2 mode because it would have
353 // taken two instructions:
356 // If an interrupt is taken between the two instructions, then sp is in
357 // an inconsistent state (pointing to the middle of callee-saved area).
358 // The interrupt handler can end up clobbering the registers.
359 AFI->setShouldRestoreSPFromFP(true);
362 if (adjustedGPRCS1Size > 0) {
363 CFAOffset -= adjustedGPRCS1Size;
364 unsigned CFIIndex = MMI.addFrameInst(
365 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
366 MachineBasicBlock::iterator Pos = ++GPRCS1Push;
367 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
368 .addCFIIndex(CFIIndex);
369 for (const auto &Entry : CSI) {
370 unsigned Reg = Entry.getReg();
371 int FI = Entry.getFrameIdx();
378 if (STI.isTargetMachO())
390 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
391 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
392 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
393 .addCFIIndex(CFIIndex);
399 // Set FP to point to the stack slot that contains the previous FP.
400 // For iOS, FP is R7, which has now been stored in spill area 1.
401 // Otherwise, if this is not iOS, all the callee-saved registers go
402 // into spill area 1, including the FP in R11. In either case, it
403 // is in area one and the adjustment needs to take place just after
406 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, GPRCS1Push, dl, TII,
407 FramePtr, ARM::SP, FramePtrOffsetInPush,
408 MachineInstr::FrameSetup);
409 if (FramePtrOffsetInPush) {
410 CFAOffset += FramePtrOffsetInPush;
411 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
412 nullptr, MRI->getDwarfRegNum(FramePtr, true), CFAOffset));
413 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
414 .addCFIIndex(CFIIndex);
418 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
419 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
420 BuildMI(MBB, GPRCS1Push, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
421 .addCFIIndex(CFIIndex);
425 if (GPRCS2Size > 0) {
426 MachineBasicBlock::iterator Pos = ++GPRCS2Push;
428 CFAOffset -= GPRCS2Size;
429 unsigned CFIIndex = MMI.addFrameInst(
430 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
431 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
432 .addCFIIndex(CFIIndex);
434 for (const auto &Entry : CSI) {
435 unsigned Reg = Entry.getReg();
436 int FI = Entry.getFrameIdx();
443 if (STI.isTargetMachO()) {
444 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
445 unsigned Offset = MFI->getObjectOffset(FI);
446 unsigned CFIIndex = MMI.addFrameInst(
447 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
448 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
449 .addCFIIndex(CFIIndex);
457 // Since vpush register list cannot have gaps, there may be multiple vpush
458 // instructions in the prologue.
460 MachineBasicBlock::iterator Push = DPRCSPush++;
462 CFAOffset -= sizeOfSPAdjustment(Push);
463 unsigned CFIIndex = MMI.addFrameInst(
464 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
465 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
466 .addCFIIndex(CFIIndex);
468 } while (DPRCSPush->getOpcode() == ARM::VSTMDDB_UPD);
470 for (const auto &Entry : CSI) {
471 unsigned Reg = Entry.getReg();
472 int FI = Entry.getFrameIdx();
473 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
474 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
475 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
476 unsigned Offset = MFI->getObjectOffset(FI);
477 unsigned CFIIndex = MMI.addFrameInst(
478 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
479 BuildMI(MBB, DPRCSPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
480 .addCFIIndex(CFIIndex);
487 CFAOffset -= NumBytes;
488 unsigned CFIIndex = MMI.addFrameInst(
489 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
490 BuildMI(MBB, MBBI, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
491 .addCFIIndex(CFIIndex);
495 if (STI.isTargetELF() && hasFP(MF))
496 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
497 AFI->getFramePtrSpillOffset());
499 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
500 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
501 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
503 // If we need dynamic stack realignment, do it here. Be paranoid and make
504 // sure if we also have VLAs, we have a base pointer for frame access.
505 // If aligned NEON registers were spilled, the stack has already been
507 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
508 unsigned MaxAlign = MFI->getMaxAlignment();
509 assert (!AFI->isThumb1OnlyFunction());
510 if (!AFI->isThumbFunction()) {
511 // Emit bic sp, sp, MaxAlign
512 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
513 TII.get(ARM::BICri), ARM::SP)
514 .addReg(ARM::SP, RegState::Kill)
515 .addImm(MaxAlign-1)));
517 // We cannot use sp as source/dest register here, thus we're emitting the
518 // following sequence:
520 // bic r4, r4, MaxAlign
522 // FIXME: It will be better just to find spare register here.
523 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
524 .addReg(ARM::SP, RegState::Kill));
525 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
526 TII.get(ARM::t2BICri), ARM::R4)
527 .addReg(ARM::R4, RegState::Kill)
528 .addImm(MaxAlign-1)));
529 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
530 .addReg(ARM::R4, RegState::Kill));
533 AFI->setShouldRestoreSPFromFP(true);
536 // If we need a base pointer, set it up here. It's whatever the value
537 // of the stack pointer is at this point. Any variable size objects
538 // will be allocated after this, so we can still use the base pointer
539 // to reference locals.
540 // FIXME: Clarify FrameSetup flags here.
541 if (RegInfo->hasBasePointer(MF)) {
543 BuildMI(MBB, MBBI, dl,
544 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
546 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
548 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
549 RegInfo->getBaseRegister())
553 // If the frame has variable sized objects then the epilogue must restore
554 // the sp from fp. We can assume there's an FP here since hasFP already
555 // checks for hasVarSizedObjects.
556 if (MFI->hasVarSizedObjects())
557 AFI->setShouldRestoreSPFromFP(true);
560 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
561 MachineBasicBlock &MBB) const {
562 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
563 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
564 unsigned RetOpcode = MBBI->getOpcode();
565 DebugLoc dl = MBBI->getDebugLoc();
566 MachineFrameInfo *MFI = MF.getFrameInfo();
567 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
568 const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
569 const ARMBaseInstrInfo &TII =
570 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
571 assert(!AFI->isThumb1OnlyFunction() &&
572 "This emitEpilogue does not support Thumb1!");
573 bool isARM = !AFI->isThumbFunction();
575 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
576 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
577 int NumBytes = (int)MFI->getStackSize();
578 unsigned FramePtr = RegInfo->getFrameRegister(MF);
580 // All calls are tail calls in GHC calling conv, and functions have no
581 // prologue/epilogue.
582 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
585 if (!AFI->hasStackFrame()) {
586 if (NumBytes - ArgRegsSaveSize != 0)
587 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
589 // Unwind MBBI to point to first LDR / VLDRD.
590 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
591 if (MBBI != MBB.begin()) {
594 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
595 if (!isCSRestore(MBBI, TII, CSRegs))
599 // Move SP to start of FP callee save spill area.
600 NumBytes -= (ArgRegsSaveSize +
601 AFI->getGPRCalleeSavedArea1Size() +
602 AFI->getGPRCalleeSavedArea2Size() +
603 AFI->getDPRCalleeSavedAreaSize());
605 // Reset SP based on frame pointer only if the stack frame extends beyond
606 // frame pointer stack slot or target is ELF and the function has FP.
607 if (AFI->shouldRestoreSPFromFP()) {
608 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
611 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
614 // It's not possible to restore SP from FP in a single instruction.
615 // For iOS, this looks like:
618 // This is bad, if an interrupt is taken after the mov, sp is in an
619 // inconsistent state.
620 // Use the first callee-saved register as a scratch register.
621 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
622 "No scratch register to restore SP from FP!");
623 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
625 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
632 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
633 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
635 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
639 } else if (NumBytes &&
640 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
641 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
643 // Increment past our save areas.
644 if (AFI->getDPRCalleeSavedAreaSize()) {
646 // Since vpop register list cannot have gaps, there may be multiple vpop
647 // instructions in the epilogue.
648 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
651 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
652 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
655 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri) {
656 // Tail call return: adjust the stack pointer and jump to callee.
657 MBBI = MBB.getLastNonDebugInstr();
658 MachineOperand &JumpTarget = MBBI->getOperand(0);
660 // Jump to label or value in register.
661 if (RetOpcode == ARM::TCRETURNdi) {
662 unsigned TCOpcode = STI.isThumb() ?
663 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
665 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
666 if (JumpTarget.isGlobal())
667 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
668 JumpTarget.getTargetFlags());
670 assert(JumpTarget.isSymbol());
671 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
672 JumpTarget.getTargetFlags());
675 // Add the default predicate in Thumb mode.
676 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
677 } else if (RetOpcode == ARM::TCRETURNri) {
678 BuildMI(MBB, MBBI, dl,
679 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
680 addReg(JumpTarget.getReg(), RegState::Kill);
683 MachineInstr *NewMI = std::prev(MBBI);
684 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
685 NewMI->addOperand(MBBI->getOperand(i));
687 // Delete the pseudo instruction TCRETURN.
693 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
696 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
697 /// debug info. It's the same as what we use for resolving the code-gen
698 /// references for now. FIXME: This can go wrong when references are
699 /// SP-relative and simple call frames aren't used.
701 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
702 unsigned &FrameReg) const {
703 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
707 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
708 int FI, unsigned &FrameReg,
710 const MachineFrameInfo *MFI = MF.getFrameInfo();
711 const ARMBaseRegisterInfo *RegInfo =
712 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
713 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
714 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
715 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
716 bool isFixed = MFI->isFixedObjectIndex(FI);
721 // SP can move around if there are allocas. We may also lose track of SP
722 // when emergency spilling inside a non-reserved call frame setup.
723 bool hasMovingSP = !hasReservedCallFrame(MF);
725 // When dynamically realigning the stack, use the frame pointer for
726 // parameters, and the stack/base pointer for locals.
727 if (RegInfo->needsStackRealignment(MF)) {
728 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
730 FrameReg = RegInfo->getFrameRegister(MF);
732 } else if (hasMovingSP) {
733 assert(RegInfo->hasBasePointer(MF) &&
734 "VLAs and dynamic stack alignment, but missing base pointer!");
735 FrameReg = RegInfo->getBaseRegister();
740 // If there is a frame pointer, use it when we can.
741 if (hasFP(MF) && AFI->hasStackFrame()) {
742 // Use frame pointer to reference fixed objects. Use it for locals if
743 // there are VLAs (and thus the SP isn't reliable as a base).
744 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
745 FrameReg = RegInfo->getFrameRegister(MF);
747 } else if (hasMovingSP) {
748 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
749 if (AFI->isThumb2Function()) {
750 // Try to use the frame pointer if we can, else use the base pointer
751 // since it's available. This is handy for the emergency spill slot, in
753 if (FPOffset >= -255 && FPOffset < 0) {
754 FrameReg = RegInfo->getFrameRegister(MF);
758 } else if (AFI->isThumb2Function()) {
759 // Use add <rd>, sp, #<imm8>
760 // ldr <rd>, [sp, #<imm8>]
761 // if at all possible to save space.
762 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
764 // In Thumb2 mode, the negative offset is very limited. Try to avoid
765 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
766 if (FPOffset >= -255 && FPOffset < 0) {
767 FrameReg = RegInfo->getFrameRegister(MF);
770 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
771 // Otherwise, use SP or FP, whichever is closer to the stack slot.
772 FrameReg = RegInfo->getFrameRegister(MF);
776 // Use the base pointer if we have one.
777 if (RegInfo->hasBasePointer(MF))
778 FrameReg = RegInfo->getBaseRegister();
782 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
785 return getFrameIndexReference(MF, FI, FrameReg);
788 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
789 MachineBasicBlock::iterator MI,
790 const std::vector<CalleeSavedInfo> &CSI,
791 unsigned StmOpc, unsigned StrOpc,
793 bool(*Func)(unsigned, bool),
794 unsigned NumAlignedDPRCS2Regs,
795 unsigned MIFlags) const {
796 MachineFunction &MF = *MBB.getParent();
797 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
800 if (MI != MBB.end()) DL = MI->getDebugLoc();
802 SmallVector<std::pair<unsigned,bool>, 4> Regs;
803 unsigned i = CSI.size();
805 unsigned LastReg = 0;
806 for (; i != 0; --i) {
807 unsigned Reg = CSI[i-1].getReg();
808 if (!(Func)(Reg, STI.isTargetMachO())) continue;
810 // D-registers in the aligned area DPRCS2 are NOT spilled here.
811 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
814 // Add the callee-saved register as live-in unless it's LR and
815 // @llvm.returnaddress is called. If LR is returned for
816 // @llvm.returnaddress then it's already added to the function and
817 // entry block live-in sets.
819 if (Reg == ARM::LR) {
820 if (MF.getFrameInfo()->isReturnAddressTaken() &&
821 MF.getRegInfo().isLiveIn(Reg))
828 // If NoGap is true, push consecutive registers and then leave the rest
829 // for other instructions. e.g.
830 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
831 if (NoGap && LastReg && LastReg != Reg-1)
834 Regs.push_back(std::make_pair(Reg, isKill));
839 if (Regs.size() > 1 || StrOpc== 0) {
840 MachineInstrBuilder MIB =
841 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
842 .addReg(ARM::SP).setMIFlags(MIFlags));
843 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
844 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
845 } else if (Regs.size() == 1) {
846 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
848 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
849 .addReg(ARM::SP).setMIFlags(MIFlags)
855 // Put any subsequent vpush instructions before this one: they will refer to
856 // higher register numbers so need to be pushed first in order to preserve
862 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
863 MachineBasicBlock::iterator MI,
864 const std::vector<CalleeSavedInfo> &CSI,
865 unsigned LdmOpc, unsigned LdrOpc,
866 bool isVarArg, bool NoGap,
867 bool(*Func)(unsigned, bool),
868 unsigned NumAlignedDPRCS2Regs) const {
869 MachineFunction &MF = *MBB.getParent();
870 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
871 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
872 DebugLoc DL = MI->getDebugLoc();
873 unsigned RetOpcode = MI->getOpcode();
874 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
875 RetOpcode == ARM::TCRETURNri);
877 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
879 SmallVector<unsigned, 4> Regs;
880 unsigned i = CSI.size();
882 unsigned LastReg = 0;
883 bool DeleteRet = false;
884 for (; i != 0; --i) {
885 unsigned Reg = CSI[i-1].getReg();
886 if (!(Func)(Reg, STI.isTargetMachO())) continue;
888 // The aligned reloads from area DPRCS2 are not inserted here.
889 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
892 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
895 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
896 // Fold the return instruction into the LDM.
900 // If NoGap is true, pop consecutive registers and then leave the rest
901 // for other instructions. e.g.
902 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
903 if (NoGap && LastReg && LastReg != Reg-1)
912 if (Regs.size() > 1 || LdrOpc == 0) {
913 MachineInstrBuilder MIB =
914 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
916 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
917 MIB.addReg(Regs[i], getDefRegState(true));
919 MIB.copyImplicitOps(&*MI);
920 MI->eraseFromParent();
923 } else if (Regs.size() == 1) {
924 // If we adjusted the reg to PC from LR above, switch it back here. We
925 // only do that for LDM.
926 if (Regs[0] == ARM::PC)
928 MachineInstrBuilder MIB =
929 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
930 .addReg(ARM::SP, RegState::Define)
932 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
933 // that refactoring is complete (eventually).
934 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
936 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
943 // Put any subsequent vpop instructions after this one: they will refer to
944 // higher register numbers so need to be popped afterwards.
949 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
950 /// starting from d8. Also insert stack realignment code and leave the stack
951 /// pointer pointing to the d8 spill slot.
952 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
953 MachineBasicBlock::iterator MI,
954 unsigned NumAlignedDPRCS2Regs,
955 const std::vector<CalleeSavedInfo> &CSI,
956 const TargetRegisterInfo *TRI) {
957 MachineFunction &MF = *MBB.getParent();
958 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
959 DebugLoc DL = MI->getDebugLoc();
960 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
961 MachineFrameInfo &MFI = *MF.getFrameInfo();
963 // Mark the D-register spill slots as properly aligned. Since MFI computes
964 // stack slot layout backwards, this can actually mean that the d-reg stack
965 // slot offsets can be wrong. The offset for d8 will always be correct.
966 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
967 unsigned DNum = CSI[i].getReg() - ARM::D8;
970 int FI = CSI[i].getFrameIdx();
971 // The even-numbered registers will be 16-byte aligned, the odd-numbered
972 // registers will be 8-byte aligned.
973 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
975 // The stack slot for D8 needs to be maximally aligned because this is
976 // actually the point where we align the stack pointer. MachineFrameInfo
977 // computes all offsets relative to the incoming stack pointer which is a
978 // bit weird when realigning the stack. Any extra padding for this
979 // over-alignment is not realized because the code inserted below adjusts
980 // the stack pointer by numregs * 8 before aligning the stack pointer.
982 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
985 // Move the stack pointer to the d8 spill slot, and align it at the same
986 // time. Leave the stack slot address in the scratch register r4.
988 // sub r4, sp, #numregs * 8
989 // bic r4, r4, #align - 1
992 bool isThumb = AFI->isThumbFunction();
993 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
994 AFI->setShouldRestoreSPFromFP(true);
996 // sub r4, sp, #numregs * 8
997 // The immediate is <= 64, so it doesn't need any special encoding.
998 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
999 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1001 .addImm(8 * NumAlignedDPRCS2Regs)));
1003 // bic r4, r4, #align-1
1004 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1005 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1006 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1007 .addReg(ARM::R4, RegState::Kill)
1008 .addImm(MaxAlign - 1)));
1011 // The stack pointer must be adjusted before spilling anything, otherwise
1012 // the stack slots could be clobbered by an interrupt handler.
1013 // Leave r4 live, it is used below.
1014 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1015 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1017 MIB = AddDefaultPred(MIB);
1021 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1022 // r4 holds the stack slot address.
1023 unsigned NextReg = ARM::D8;
1025 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1026 // The writeback is only needed when emitting two vst1.64 instructions.
1027 if (NumAlignedDPRCS2Regs >= 6) {
1028 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1029 &ARM::QQPRRegClass);
1030 MBB.addLiveIn(SupReg);
1031 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1033 .addReg(ARM::R4, RegState::Kill).addImm(16)
1035 .addReg(SupReg, RegState::ImplicitKill));
1037 NumAlignedDPRCS2Regs -= 4;
1040 // We won't modify r4 beyond this point. It currently points to the next
1041 // register to be spilled.
1042 unsigned R4BaseReg = NextReg;
1044 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1045 if (NumAlignedDPRCS2Regs >= 4) {
1046 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1047 &ARM::QQPRRegClass);
1048 MBB.addLiveIn(SupReg);
1049 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1050 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1051 .addReg(SupReg, RegState::ImplicitKill));
1053 NumAlignedDPRCS2Regs -= 4;
1056 // 16-byte aligned vst1.64 with 2 d-regs.
1057 if (NumAlignedDPRCS2Regs >= 2) {
1058 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1060 MBB.addLiveIn(SupReg);
1061 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1062 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1064 NumAlignedDPRCS2Regs -= 2;
1067 // Finally, use a vanilla vstr.64 for the odd last register.
1068 if (NumAlignedDPRCS2Regs) {
1069 MBB.addLiveIn(NextReg);
1070 // vstr.64 uses addrmode5 which has an offset scale of 4.
1071 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1073 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1076 // The last spill instruction inserted should kill the scratch register r4.
1077 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1080 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1081 /// iterator to the following instruction.
1082 static MachineBasicBlock::iterator
1083 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1084 unsigned NumAlignedDPRCS2Regs) {
1085 // sub r4, sp, #numregs * 8
1086 // bic r4, r4, #align - 1
1089 assert(MI->mayStore() && "Expecting spill instruction");
1091 // These switches all fall through.
1092 switch(NumAlignedDPRCS2Regs) {
1095 assert(MI->mayStore() && "Expecting spill instruction");
1098 assert(MI->mayStore() && "Expecting spill instruction");
1102 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1108 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1109 /// starting from d8. These instructions are assumed to execute while the
1110 /// stack is still aligned, unlike the code inserted by emitPopInst.
1111 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1112 MachineBasicBlock::iterator MI,
1113 unsigned NumAlignedDPRCS2Regs,
1114 const std::vector<CalleeSavedInfo> &CSI,
1115 const TargetRegisterInfo *TRI) {
1116 MachineFunction &MF = *MBB.getParent();
1117 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1118 DebugLoc DL = MI->getDebugLoc();
1119 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1121 // Find the frame index assigned to d8.
1123 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1124 if (CSI[i].getReg() == ARM::D8) {
1125 D8SpillFI = CSI[i].getFrameIdx();
1129 // Materialize the address of the d8 spill slot into the scratch register r4.
1130 // This can be fairly complicated if the stack frame is large, so just use
1131 // the normal frame index elimination mechanism to do it. This code runs as
1132 // the initial part of the epilog where the stack and base pointers haven't
1133 // been changed yet.
1134 bool isThumb = AFI->isThumbFunction();
1135 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1137 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1138 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1139 .addFrameIndex(D8SpillFI).addImm(0)));
1141 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1142 unsigned NextReg = ARM::D8;
1144 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1145 if (NumAlignedDPRCS2Regs >= 6) {
1146 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1147 &ARM::QQPRRegClass);
1148 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1149 .addReg(ARM::R4, RegState::Define)
1150 .addReg(ARM::R4, RegState::Kill).addImm(16)
1151 .addReg(SupReg, RegState::ImplicitDefine));
1153 NumAlignedDPRCS2Regs -= 4;
1156 // We won't modify r4 beyond this point. It currently points to the next
1157 // register to be spilled.
1158 unsigned R4BaseReg = NextReg;
1160 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1161 if (NumAlignedDPRCS2Regs >= 4) {
1162 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1163 &ARM::QQPRRegClass);
1164 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1165 .addReg(ARM::R4).addImm(16)
1166 .addReg(SupReg, RegState::ImplicitDefine));
1168 NumAlignedDPRCS2Regs -= 4;
1171 // 16-byte aligned vld1.64 with 2 d-regs.
1172 if (NumAlignedDPRCS2Regs >= 2) {
1173 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1175 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1176 .addReg(ARM::R4).addImm(16));
1178 NumAlignedDPRCS2Regs -= 2;
1181 // Finally, use a vanilla vldr.64 for the remaining odd register.
1182 if (NumAlignedDPRCS2Regs)
1183 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1184 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1186 // Last store kills r4.
1187 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1190 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1191 MachineBasicBlock::iterator MI,
1192 const std::vector<CalleeSavedInfo> &CSI,
1193 const TargetRegisterInfo *TRI) const {
1197 MachineFunction &MF = *MBB.getParent();
1198 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1200 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1201 unsigned PushOneOpc = AFI->isThumbFunction() ?
1202 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1203 unsigned FltOpc = ARM::VSTMDDB_UPD;
1204 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1205 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1206 MachineInstr::FrameSetup);
1207 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1208 MachineInstr::FrameSetup);
1209 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1210 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1212 // The code above does not insert spill code for the aligned DPRCS2 registers.
1213 // The stack realignment code will be inserted between the push instructions
1214 // and these spills.
1215 if (NumAlignedDPRCS2Regs)
1216 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1221 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1222 MachineBasicBlock::iterator MI,
1223 const std::vector<CalleeSavedInfo> &CSI,
1224 const TargetRegisterInfo *TRI) const {
1228 MachineFunction &MF = *MBB.getParent();
1229 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1230 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1231 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1233 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1234 // registers. Do that here instead.
1235 if (NumAlignedDPRCS2Regs)
1236 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1238 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1239 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1240 unsigned FltOpc = ARM::VLDMDIA_UPD;
1241 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1242 NumAlignedDPRCS2Regs);
1243 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1244 &isARMArea2Register, 0);
1245 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1246 &isARMArea1Register, 0);
1251 // FIXME: Make generic?
1252 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1253 const ARMBaseInstrInfo &TII) {
1254 unsigned FnSize = 0;
1255 for (auto &MBB : MF) {
1256 for (auto &MI : MBB)
1257 FnSize += TII.GetInstSizeInBytes(&MI);
1262 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1263 /// frames and return the stack size limit beyond which some of these
1264 /// instructions will require a scratch register during their expansion later.
1265 // FIXME: Move to TII?
1266 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1267 const TargetFrameLowering *TFI) {
1268 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1269 unsigned Limit = (1 << 12) - 1;
1270 for (auto &MBB : MF) {
1271 for (auto &MI : MBB) {
1272 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1273 if (!MI.getOperand(i).isFI())
1276 // When using ADDri to get the address of a stack object, 255 is the
1277 // largest offset guaranteed to fit in the immediate offset.
1278 if (MI.getOpcode() == ARM::ADDri) {
1279 Limit = std::min(Limit, (1U << 8) - 1);
1283 // Otherwise check the addressing mode.
1284 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1285 case ARMII::AddrMode3:
1286 case ARMII::AddrModeT2_i8:
1287 Limit = std::min(Limit, (1U << 8) - 1);
1289 case ARMII::AddrMode5:
1290 case ARMII::AddrModeT2_i8s4:
1291 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1293 case ARMII::AddrModeT2_i12:
1294 // i12 supports only positive offset so these will be converted to
1295 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1296 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1297 Limit = std::min(Limit, (1U << 8) - 1);
1299 case ARMII::AddrMode4:
1300 case ARMII::AddrMode6:
1301 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1302 // immediate offset for stack references.
1307 break; // At most one FI per instruction
1315 // In functions that realign the stack, it can be an advantage to spill the
1316 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1317 // instructions take alignment hints that can improve performance.
1319 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1320 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1321 if (!SpillAlignedNEONRegs)
1324 // Naked functions don't spill callee-saved registers.
1325 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1329 // We are planning to use NEON instructions vst1 / vld1.
1330 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1333 // Don't bother if the default stack alignment is sufficiently high.
1334 if (MF.getTarget().getFrameLowering()->getStackAlignment() >= 8)
1337 // Aligned spills require stack realignment.
1338 const ARMBaseRegisterInfo *RegInfo =
1339 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1340 if (!RegInfo->canRealignStack(MF))
1343 // We always spill contiguous d-registers starting from d8. Count how many
1344 // needs spilling. The register allocator will almost always use the
1345 // callee-saved registers in order, but it can happen that there are holes in
1346 // the range. Registers above the hole will be spilled to the standard DPRCS
1348 MachineRegisterInfo &MRI = MF.getRegInfo();
1349 unsigned NumSpills = 0;
1350 for (; NumSpills < 8; ++NumSpills)
1351 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1354 // Don't do this for just one d-register. It's not worth it.
1358 // Spill the first NumSpills D-registers after realigning the stack.
1359 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1361 // A scratch register is required for the vst1 / vld1 instructions.
1362 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1366 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1367 RegScavenger *RS) const {
1368 // This tells PEI to spill the FP as if it is any other callee-save register
1369 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1370 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1371 // to combine multiple loads / stores.
1372 bool CanEliminateFrame = true;
1373 bool CS1Spilled = false;
1374 bool LRSpilled = false;
1375 unsigned NumGPRSpills = 0;
1376 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1377 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1378 const ARMBaseRegisterInfo *RegInfo =
1379 static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
1380 const ARMBaseInstrInfo &TII =
1381 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1382 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1383 MachineFrameInfo *MFI = MF.getFrameInfo();
1384 MachineRegisterInfo &MRI = MF.getRegInfo();
1385 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1387 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1388 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1389 // since it's not always possible to restore sp from fp in a single
1391 // FIXME: It will be better just to find spare register here.
1392 if (AFI->isThumb2Function() &&
1393 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1394 MRI.setPhysRegUsed(ARM::R4);
1396 if (AFI->isThumb1OnlyFunction()) {
1397 // Spill LR if Thumb1 function uses variable length argument lists.
1398 if (AFI->getArgRegsSaveSize() > 0)
1399 MRI.setPhysRegUsed(ARM::LR);
1401 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1402 // for sure what the stack size will be, but for this, an estimate is good
1403 // enough. If there anything changes it, it'll be a spill, which implies
1404 // we've used all the registers and so R4 is already used, so not marking
1405 // it here will be OK.
1406 // FIXME: It will be better just to find spare register here.
1407 unsigned StackSize = MFI->estimateStackSize(MF);
1408 if (MFI->hasVarSizedObjects() || StackSize > 508)
1409 MRI.setPhysRegUsed(ARM::R4);
1412 // See if we can spill vector registers to aligned stack.
1413 checkNumAlignedDPRCS2Regs(MF);
1415 // Spill the BasePtr if it's used.
1416 if (RegInfo->hasBasePointer(MF))
1417 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1419 // Don't spill FP if the frame can be eliminated. This is determined
1420 // by scanning the callee-save registers to see if any is used.
1421 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1422 for (unsigned i = 0; CSRegs[i]; ++i) {
1423 unsigned Reg = CSRegs[i];
1424 bool Spilled = false;
1425 if (MRI.isPhysRegUsed(Reg)) {
1427 CanEliminateFrame = false;
1430 if (!ARM::GPRRegClass.contains(Reg))
1436 if (!STI.isTargetMachO()) {
1443 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1448 case ARM::R0: case ARM::R1:
1449 case ARM::R2: case ARM::R3:
1450 case ARM::R4: case ARM::R5:
1451 case ARM::R6: case ARM::R7:
1458 if (!STI.isTargetMachO()) {
1459 UnspilledCS1GPRs.push_back(Reg);
1464 case ARM::R0: case ARM::R1:
1465 case ARM::R2: case ARM::R3:
1466 case ARM::R4: case ARM::R5:
1467 case ARM::R6: case ARM::R7:
1469 UnspilledCS1GPRs.push_back(Reg);
1472 UnspilledCS2GPRs.push_back(Reg);
1478 bool ForceLRSpill = false;
1479 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1480 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1481 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1482 // use of BL to implement far jump. If it turns out that it's not needed
1483 // then the branch fix up path will undo it.
1484 if (FnSize >= (1 << 11)) {
1485 CanEliminateFrame = false;
1486 ForceLRSpill = true;
1490 // If any of the stack slot references may be out of range of an immediate
1491 // offset, make sure a register (or a spill slot) is available for the
1492 // register scavenger. Note that if we're indexing off the frame pointer, the
1493 // effective stack size is 4 bytes larger since the FP points to the stack
1494 // slot of the previous FP. Also, if we have variable sized objects in the
1495 // function, stack slot references will often be negative, and some of
1496 // our instructions are positive-offset only, so conservatively consider
1497 // that case to want a spill slot (or register) as well. Similarly, if
1498 // the function adjusts the stack pointer during execution and the
1499 // adjustments aren't already part of our stack size estimate, our offset
1500 // calculations may be off, so be conservative.
1501 // FIXME: We could add logic to be more precise about negative offsets
1502 // and which instructions will need a scratch register for them. Is it
1503 // worth the effort and added fragility?
1506 (MFI->estimateStackSize(MF) +
1507 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1508 estimateRSStackSizeLimit(MF, this)))
1509 || MFI->hasVarSizedObjects()
1510 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1512 bool ExtraCSSpill = false;
1513 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1514 AFI->setHasStackFrame(true);
1516 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1517 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1518 if (!LRSpilled && CS1Spilled) {
1519 MRI.setPhysRegUsed(ARM::LR);
1521 SmallVectorImpl<unsigned>::iterator LRPos;
1522 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1524 if (LRPos != UnspilledCS1GPRs.end())
1525 UnspilledCS1GPRs.erase(LRPos);
1527 ForceLRSpill = false;
1528 ExtraCSSpill = true;
1532 MRI.setPhysRegUsed(FramePtr);
1533 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1535 if (FPPos != UnspilledCS1GPRs.end())
1536 UnspilledCS1GPRs.erase(FPPos);
1540 // If stack and double are 8-byte aligned and we are spilling an odd number
1541 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1542 // the integer and double callee save areas.
1543 unsigned TargetAlign = getStackAlignment();
1544 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1545 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1546 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1547 unsigned Reg = UnspilledCS1GPRs[i];
1548 // Don't spill high register if the function is thumb1
1549 if (!AFI->isThumb1OnlyFunction() ||
1550 isARMLowRegister(Reg) || Reg == ARM::LR) {
1551 MRI.setPhysRegUsed(Reg);
1552 if (!MRI.isReserved(Reg))
1553 ExtraCSSpill = true;
1557 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1558 unsigned Reg = UnspilledCS2GPRs.front();
1559 MRI.setPhysRegUsed(Reg);
1560 if (!MRI.isReserved(Reg))
1561 ExtraCSSpill = true;
1565 // Estimate if we might need to scavenge a register at some point in order
1566 // to materialize a stack offset. If so, either spill one additional
1567 // callee-saved register or reserve a special spill slot to facilitate
1568 // register scavenging. Thumb1 needs a spill slot for stack pointer
1569 // adjustments also, even when the frame itself is small.
1570 if (BigStack && !ExtraCSSpill) {
1571 // If any non-reserved CS register isn't spilled, just spill one or two
1572 // extra. That should take care of it!
1573 unsigned NumExtras = TargetAlign / 4;
1574 SmallVector<unsigned, 2> Extras;
1575 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1576 unsigned Reg = UnspilledCS1GPRs.back();
1577 UnspilledCS1GPRs.pop_back();
1578 if (!MRI.isReserved(Reg) &&
1579 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1581 Extras.push_back(Reg);
1585 // For non-Thumb1 functions, also check for hi-reg CS registers
1586 if (!AFI->isThumb1OnlyFunction()) {
1587 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1588 unsigned Reg = UnspilledCS2GPRs.back();
1589 UnspilledCS2GPRs.pop_back();
1590 if (!MRI.isReserved(Reg)) {
1591 Extras.push_back(Reg);
1596 if (Extras.size() && NumExtras == 0) {
1597 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1598 MRI.setPhysRegUsed(Extras[i]);
1600 } else if (!AFI->isThumb1OnlyFunction()) {
1601 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1602 // closest to SP or frame pointer.
1603 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1604 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1612 MRI.setPhysRegUsed(ARM::LR);
1613 AFI->setLRIsSpilledForFarJump(true);
1618 void ARMFrameLowering::
1619 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1620 MachineBasicBlock::iterator I) const {
1621 const ARMBaseInstrInfo &TII =
1622 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1623 if (!hasReservedCallFrame(MF)) {
1624 // If we have alloca, convert as follows:
1625 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1626 // ADJCALLSTACKUP -> add, sp, sp, amount
1627 MachineInstr *Old = I;
1628 DebugLoc dl = Old->getDebugLoc();
1629 unsigned Amount = Old->getOperand(0).getImm();
1631 // We need to keep the stack aligned properly. To do this, we round the
1632 // amount of space needed for the outgoing arguments up to the next
1633 // alignment boundary.
1634 unsigned Align = getStackAlignment();
1635 Amount = (Amount+Align-1)/Align*Align;
1637 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1638 assert(!AFI->isThumb1OnlyFunction() &&
1639 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1640 bool isARM = !AFI->isThumbFunction();
1642 // Replace the pseudo instruction with a new instruction...
1643 unsigned Opc = Old->getOpcode();
1644 int PIdx = Old->findFirstPredOperandIdx();
1645 ARMCC::CondCodes Pred = (PIdx == -1)
1646 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1647 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1648 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1649 unsigned PredReg = Old->getOperand(2).getReg();
1650 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1653 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1654 unsigned PredReg = Old->getOperand(3).getReg();
1655 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1656 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1664 /// Get the minimum constant for ARM that is greater than or equal to the
1665 /// argument. In ARM, constants can have any value that can be produced by
1666 /// rotating an 8-bit value to the right by an even number of bits within a
1668 static uint32_t alignToARMConstant(uint32_t Value) {
1669 unsigned Shifted = 0;
1674 while (!(Value & 0xC0000000)) {
1679 bool Carry = (Value & 0x00FFFFFF);
1680 Value = ((Value & 0xFF000000) >> 24) + Carry;
1682 if (Value & 0x0000100)
1683 Value = Value & 0x000001FC;
1686 Value = Value >> (Shifted - 24);
1688 Value = Value << (24 - Shifted);
1693 // The stack limit in the TCB is set to this many bytes above the actual
1695 static const uint64_t kSplitStackAvailable = 256;
1697 // Adjust the function prologue to enable split stacks. This currently only
1698 // supports android and linux.
1700 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1701 // must be well defined in order to allow for consistent implementations of the
1702 // __morestack helper function. The ABI is also not a normal ABI in that it
1703 // doesn't follow the normal calling conventions because this allows the
1704 // prologue of each function to be optimized further.
1706 // Currently, the ABI looks like (when calling __morestack)
1708 // * r4 holds the minimum stack size requested for this function call
1709 // * r5 holds the stack size of the arguments to the function
1710 // * the beginning of the function is 3 instructions after the call to
1713 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1714 // place the arguments on to the new stack, and the 3-instruction knowledge to
1715 // jump directly to the body of the function when working on the new stack.
1717 // An old (and possibly no longer compatible) implementation of __morestack for
1718 // ARM can be found at [1].
1720 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1721 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1724 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1725 bool Thumb = ST->isThumb();
1727 // Sadly, this currently doesn't support varargs, platforms other than
1728 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1729 if (MF.getFunction()->isVarArg())
1730 report_fatal_error("Segmented stacks do not support vararg functions.");
1731 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1732 report_fatal_error("Segmented stacks not supported on this platform.");
1734 MachineBasicBlock &prologueMBB = MF.front();
1735 MachineFrameInfo *MFI = MF.getFrameInfo();
1736 MachineModuleInfo &MMI = MF.getMMI();
1737 MCContext &Context = MMI.getContext();
1738 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1739 const ARMBaseInstrInfo &TII =
1740 *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
1741 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1744 // Use R4 and R5 as scratch registers.
1745 // We save R4 and R5 before use and restore them before leaving the function.
1746 unsigned ScratchReg0 = ARM::R4;
1747 unsigned ScratchReg1 = ARM::R5;
1748 uint64_t AlignedStackSize;
1750 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1751 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1752 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1753 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1754 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1756 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1757 e = prologueMBB.livein_end();
1759 AllocMBB->addLiveIn(*i);
1760 GetMBB->addLiveIn(*i);
1761 McrMBB->addLiveIn(*i);
1762 PrevStackMBB->addLiveIn(*i);
1763 PostStackMBB->addLiveIn(*i);
1766 MF.push_front(PostStackMBB);
1767 MF.push_front(AllocMBB);
1768 MF.push_front(GetMBB);
1769 MF.push_front(McrMBB);
1770 MF.push_front(PrevStackMBB);
1772 // The required stack size that is aligned to ARM constant criterion.
1773 uint64_t StackSize = MFI->getStackSize();
1775 AlignedStackSize = alignToARMConstant(StackSize);
1777 // When the frame size is less than 256 we just compare the stack
1778 // boundary directly to the value of the stack pointer, per gcc.
1779 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1781 // We will use two of the callee save registers as scratch registers so we
1782 // need to save those registers onto the stack.
1783 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1784 // requested and arguments for __morestack().
1785 // SR0: Scratch Register #0
1786 // SR1: Scratch Register #1
1789 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1790 .addReg(ScratchReg0).addReg(ScratchReg1);
1792 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1793 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1794 .addReg(ScratchReg0).addReg(ScratchReg1);
1797 // Emit the relevant DWARF information about the change in stack pointer as
1798 // well as where to find both r4 and r5 (the callee-save registers)
1800 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1801 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1802 .addCFIIndex(CFIIndex);
1803 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1804 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1805 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1806 .addCFIIndex(CFIIndex);
1807 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1808 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1809 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1810 .addCFIIndex(CFIIndex);
1814 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1816 } else if (CompareStackPointer) {
1817 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1818 .addReg(ARM::SP)).addReg(0);
1821 // sub SR1, sp, #StackSize
1822 if (!CompareStackPointer && Thumb) {
1824 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1825 .addReg(ScratchReg1).addImm(AlignedStackSize));
1826 } else if (!CompareStackPointer) {
1827 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1828 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1831 if (Thumb && ST->isThumb1Only()) {
1832 unsigned PCLabelId = ARMFI->createPICLabelUId();
1833 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1834 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1835 MachineConstantPool *MCP = MF.getConstantPool();
1836 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1838 // ldr SR0, [pc, offset(STACK_LIMIT)]
1839 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1840 .addConstantPoolIndex(CPI));
1843 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1844 .addReg(ScratchReg0).addImm(0));
1846 // Get TLS base address from the coprocessor
1847 // mrc p15, #0, SR0, c13, c0, #3
1848 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1855 // Use the last tls slot on android and a private field of the TCP on linux.
1856 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1857 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1859 // Get the stack limit from the right offset
1860 // ldr SR0, [sr0, #4 * TlsOffset]
1861 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1862 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1865 // Compare stack limit with stack size requested.
1867 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1868 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1869 .addReg(ScratchReg0)
1870 .addReg(ScratchReg1));
1872 // This jump is taken if StackLimit < SP - stack required.
1873 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1874 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1879 // Calling __morestack(StackSize, Size of stack arguments).
1880 // __morestack knows that the stack size requested is in SR0(r4)
1881 // and amount size of stack arguments is in SR1(r5).
1883 // Pass first argument for the __morestack by Scratch Register #0.
1884 // The amount size of stack required
1886 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1887 ScratchReg0)).addImm(AlignedStackSize));
1889 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1890 .addImm(AlignedStackSize)).addReg(0);
1892 // Pass second argument for the __morestack by Scratch Register #1.
1893 // The amount size of stack consumed to save function arguments.
1896 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1897 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1899 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1900 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1904 // push {lr} - Save return address of this function.
1906 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1909 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1910 .addReg(ARM::SP, RegState::Define)
1915 // Emit the DWARF info about the change in stack as well as where to find the
1916 // previous link register
1918 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
1919 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1920 .addCFIIndex(CFIIndex);
1921 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1922 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
1923 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1924 .addCFIIndex(CFIIndex);
1926 // Call __morestack().
1928 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
1929 .addExternalSymbol("__morestack");
1931 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
1932 .addExternalSymbol("__morestack");
1935 // pop {lr} - Restore return address of this original function.
1937 if (ST->isThumb1Only()) {
1938 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1939 .addReg(ScratchReg0);
1940 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
1941 .addReg(ScratchReg0));
1943 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
1944 .addReg(ARM::LR, RegState::Define)
1945 .addReg(ARM::SP, RegState::Define)
1950 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1951 .addReg(ARM::SP, RegState::Define)
1956 // Restore SR0 and SR1 in case of __morestack() was called.
1957 // __morestack() will skip PostStackMBB block so we need to restore
1958 // scratch registers from here.
1961 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
1962 .addReg(ScratchReg0)
1963 .addReg(ScratchReg1);
1965 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
1966 .addReg(ARM::SP, RegState::Define)
1968 .addReg(ScratchReg0)
1969 .addReg(ScratchReg1);
1972 // Update the CFA offset now that we've popped
1973 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1974 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1975 .addCFIIndex(CFIIndex);
1977 // bx lr - Return from this function.
1978 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
1979 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
1981 // Restore SR0 and SR1 in case of __morestack() was not called.
1984 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
1985 .addReg(ScratchReg0)
1986 .addReg(ScratchReg1);
1988 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
1989 .addReg(ARM::SP, RegState::Define)
1991 .addReg(ScratchReg0)
1992 .addReg(ScratchReg1);
1995 // Update the CFA offset now that we've popped
1996 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
1997 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1998 .addCFIIndex(CFIIndex);
2000 // Tell debuggers that r4 and r5 are now the same as they were in the
2001 // previous function, that they're the "Same Value".
2002 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2003 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2004 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2005 .addCFIIndex(CFIIndex);
2006 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2007 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2008 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2009 .addCFIIndex(CFIIndex);
2011 // Organizing MBB lists
2012 PostStackMBB->addSuccessor(&prologueMBB);
2014 AllocMBB->addSuccessor(PostStackMBB);
2016 GetMBB->addSuccessor(PostStackMBB);
2017 GetMBB->addSuccessor(AllocMBB);
2019 McrMBB->addSuccessor(GetMBB);
2021 PrevStackMBB->addSuccessor(McrMBB);