1 //===-- ARMFrameLowering.cpp - ARM Frame Information ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the ARM implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARMFrameLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "MCTargetDesc/ARMAddressingModes.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Target/TargetOptions.h"
35 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
36 cl::desc("Align ARM NEON spills in prolog and epilog"));
38 static MachineBasicBlock::iterator
39 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
40 unsigned NumAlignedDPRCS2Regs);
42 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
43 : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, 4),
46 /// hasFP - Return true if the specified function should have a dedicated frame
47 /// pointer register. This is true if the function has variable sized allocas
48 /// or if frame pointer elimination is disabled.
49 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
50 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
52 // iOS requires FP not to be clobbered for backtracing purpose.
53 if (STI.isTargetIOS())
56 const MachineFrameInfo *MFI = MF.getFrameInfo();
57 // Always eliminate non-leaf frame pointers.
58 return ((MF.getTarget().Options.DisableFramePointerElim(MF) &&
60 RegInfo->needsStackRealignment(MF) ||
61 MFI->hasVarSizedObjects() ||
62 MFI->isFrameAddressTaken());
65 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
66 /// not required, we reserve argument space for call sites in the function
67 /// immediately on entry to the current function. This eliminates the need for
68 /// add/sub sp brackets around call sites. Returns true if the call frame is
69 /// included as part of the stack frame.
70 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
71 const MachineFrameInfo *FFI = MF.getFrameInfo();
72 unsigned CFSize = FFI->getMaxCallFrameSize();
73 // It's not always a good idea to include the call frame as part of the
74 // stack frame. ARM (especially Thumb) has small immediate offset to
75 // address the stack frame. So a large call frame can cause poor codegen
76 // and may even makes it impossible to scavenge a register.
77 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
80 return !MF.getFrameInfo()->hasVarSizedObjects();
83 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
84 /// call frame pseudos can be simplified. Unlike most targets, having a FP
85 /// is not sufficient here since we still may reference some objects via SP
86 /// even when FP is available in Thumb2 mode.
88 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
89 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
92 static bool isCSRestore(MachineInstr *MI,
93 const ARMBaseInstrInfo &TII,
94 const MCPhysReg *CSRegs) {
95 // Integer spill area is handled with "pop".
96 if (isPopOpcode(MI->getOpcode())) {
97 // The first two operands are predicates. The last two are
98 // imp-def and imp-use of SP. Check everything in between.
99 for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
100 if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
104 if ((MI->getOpcode() == ARM::LDR_POST_IMM ||
105 MI->getOpcode() == ARM::LDR_POST_REG ||
106 MI->getOpcode() == ARM::t2LDR_POST) &&
107 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs) &&
108 MI->getOperand(1).getReg() == ARM::SP)
114 static void emitRegPlusImmediate(bool isARM, MachineBasicBlock &MBB,
115 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
116 const ARMBaseInstrInfo &TII, unsigned DestReg,
117 unsigned SrcReg, int NumBytes,
118 unsigned MIFlags = MachineInstr::NoFlags,
119 ARMCC::CondCodes Pred = ARMCC::AL,
120 unsigned PredReg = 0) {
122 emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
123 Pred, PredReg, TII, MIFlags);
125 emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
126 Pred, PredReg, TII, MIFlags);
129 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
130 MachineBasicBlock::iterator &MBBI, DebugLoc dl,
131 const ARMBaseInstrInfo &TII, int NumBytes,
132 unsigned MIFlags = MachineInstr::NoFlags,
133 ARMCC::CondCodes Pred = ARMCC::AL,
134 unsigned PredReg = 0) {
135 emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
136 MIFlags, Pred, PredReg);
139 static int sizeOfSPAdjustment(const MachineInstr *MI) {
141 switch (MI->getOpcode()) {
142 case ARM::VSTMDDB_UPD:
146 case ARM::t2STMDB_UPD:
150 case ARM::STR_PRE_IMM:
153 llvm_unreachable("Unknown push or pop like instruction");
157 // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
158 // pred) so the list starts at 4.
159 for (int i = MI->getNumOperands() - 1; i >= 4; --i)
164 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
165 size_t StackSizeInBytes) {
166 const MachineFrameInfo *MFI = MF.getFrameInfo();
167 if (MFI->getStackProtectorIndex() > 0)
168 return StackSizeInBytes >= 4080;
169 return StackSizeInBytes >= 4096;
173 struct StackAdjustingInsts {
175 MachineBasicBlock::iterator I;
180 SmallVector<InstInfo, 4> Insts;
182 void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
183 bool BeforeFPSet = false) {
184 InstInfo Info = {I, SPAdjust, BeforeFPSet};
185 Insts.push_back(Info);
188 void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
189 auto Info = std::find_if(Insts.begin(), Insts.end(),
190 [&](InstInfo &Info) { return Info.I == I; });
191 assert(Info != Insts.end() && "invalid sp adjusting instruction");
192 Info->SPAdjust += ExtraBytes;
195 void emitDefCFAOffsets(MachineModuleInfo &MMI, MachineBasicBlock &MBB,
196 DebugLoc dl, const ARMBaseInstrInfo &TII, bool HasFP) {
197 unsigned CFAOffset = 0;
198 for (auto &Info : Insts) {
199 if (HasFP && !Info.BeforeFPSet)
202 CFAOffset -= Info.SPAdjust;
203 unsigned CFIIndex = MMI.addFrameInst(
204 MCCFIInstruction::createDefCfaOffset(nullptr, CFAOffset));
205 BuildMI(MBB, std::next(Info.I), dl,
206 TII.get(TargetOpcode::CFI_INSTRUCTION)).addCFIIndex(CFIIndex);
212 void ARMFrameLowering::emitPrologue(MachineFunction &MF) const {
213 MachineBasicBlock &MBB = MF.front();
214 MachineBasicBlock::iterator MBBI = MBB.begin();
215 MachineFrameInfo *MFI = MF.getFrameInfo();
216 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
217 MachineModuleInfo &MMI = MF.getMMI();
218 MCContext &Context = MMI.getContext();
219 const TargetMachine &TM = MF.getTarget();
220 const MCRegisterInfo *MRI = Context.getRegisterInfo();
221 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
222 TM.getSubtargetImpl()->getRegisterInfo());
223 const ARMBaseInstrInfo &TII = *static_cast<const ARMBaseInstrInfo *>(
224 TM.getSubtargetImpl()->getInstrInfo());
225 assert(!AFI->isThumb1OnlyFunction() &&
226 "This emitPrologue does not support Thumb1!");
227 bool isARM = !AFI->isThumbFunction();
229 TM.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
230 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
231 unsigned NumBytes = MFI->getStackSize();
232 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
233 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
234 unsigned FramePtr = RegInfo->getFrameRegister(MF);
236 // Determine the sizes of each callee-save spill areas and record which frame
237 // belongs to which callee-save spill areas.
238 unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
239 int FramePtrSpillFI = 0;
242 // All calls are tail calls in GHC calling conv, and functions have no
243 // prologue/epilogue.
244 if (MF.getFunction()->getCallingConv() == CallingConv::GHC)
247 StackAdjustingInsts DefCFAOffsetCandidates;
249 // Allocate the vararg register save area.
250 if (ArgRegsSaveSize) {
251 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
252 MachineInstr::FrameSetup);
253 DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
256 if (!AFI->hasStackFrame() &&
257 (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
258 if (NumBytes - ArgRegsSaveSize != 0) {
259 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
260 MachineInstr::FrameSetup);
261 DefCFAOffsetCandidates.addInst(std::prev(MBBI),
262 NumBytes - ArgRegsSaveSize, true);
267 // Determine spill area sizes.
268 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
269 unsigned Reg = CSI[i].getReg();
270 int FI = CSI[i].getFrameIdx();
277 if (STI.isTargetDarwin()) {
292 FramePtrSpillFI = FI;
296 // This is a DPR. Exclude the aligned DPRCS2 spills.
299 if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
305 MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
306 if (GPRCS1Size > 0) {
307 GPRCS1Push = LastPush = MBBI++;
308 DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
311 // Determine starting offsets of spill areas.
312 bool HasFP = hasFP(MF);
313 unsigned GPRCS1Offset = NumBytes - ArgRegsSaveSize - GPRCS1Size;
314 unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
315 unsigned DPRAlign = DPRCSSize ? std::min(8U, Align) : 4U;
316 unsigned DPRGapSize = (GPRCS1Size + GPRCS2Size + ArgRegsSaveSize) % DPRAlign;
317 unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
318 int FramePtrOffsetInPush = 0;
320 FramePtrOffsetInPush =
321 MFI->getObjectOffset(FramePtrSpillFI) + ArgRegsSaveSize;
322 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
325 AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
326 AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
327 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
330 if (GPRCS2Size > 0) {
331 GPRCS2Push = LastPush = MBBI++;
332 DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
335 // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
336 // .cfi_offset operations will reflect that.
338 assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
339 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, DPRGapSize))
340 DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
342 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
343 MachineInstr::FrameSetup);
344 DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
350 // Since vpush register list cannot have gaps, there may be multiple vpush
351 // instructions in the prologue.
352 while (MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
353 DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(MBBI));
358 // Move past the aligned DPRCS2 area.
359 if (AFI->getNumAlignedDPRCS2Regs() > 0) {
360 MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
361 // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
362 // leaves the stack pointer pointing to the DPRCS2 area.
364 // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
365 NumBytes += MFI->getObjectOffset(D8SpillFI);
367 NumBytes = DPRCSOffset;
369 if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
370 uint32_t NumWords = NumBytes >> 2;
372 if (NumWords < 65536)
373 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
375 .setMIFlags(MachineInstr::FrameSetup));
377 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
379 .setMIFlags(MachineInstr::FrameSetup);
381 switch (TM.getCodeModel()) {
382 case CodeModel::Small:
383 case CodeModel::Medium:
384 case CodeModel::Default:
385 case CodeModel::Kernel:
386 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
387 .addImm((unsigned)ARMCC::AL).addReg(0)
388 .addExternalSymbol("__chkstk")
389 .addReg(ARM::R4, RegState::Implicit)
390 .setMIFlags(MachineInstr::FrameSetup);
392 case CodeModel::Large:
393 case CodeModel::JITDefault:
394 BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
395 .addExternalSymbol("__chkstk")
396 .setMIFlags(MachineInstr::FrameSetup);
398 BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
399 .addImm((unsigned)ARMCC::AL).addReg(0)
400 .addReg(ARM::R12, RegState::Kill)
401 .addReg(ARM::R4, RegState::Implicit)
402 .setMIFlags(MachineInstr::FrameSetup);
406 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr),
408 .addReg(ARM::SP, RegState::Define)
409 .addReg(ARM::R4, RegState::Kill)
410 .setMIFlags(MachineInstr::FrameSetup)));
415 // Adjust SP after all the callee-save spills.
416 if (tryFoldSPUpdateIntoPushPop(STI, MF, LastPush, NumBytes))
417 DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
419 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
420 MachineInstr::FrameSetup);
421 DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
425 // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
426 // Note it's not safe to do this in Thumb2 mode because it would have
427 // taken two instructions:
430 // If an interrupt is taken between the two instructions, then sp is in
431 // an inconsistent state (pointing to the middle of callee-saved area).
432 // The interrupt handler can end up clobbering the registers.
433 AFI->setShouldRestoreSPFromFP(true);
436 // Set FP to point to the stack slot that contains the previous FP.
437 // For iOS, FP is R7, which has now been stored in spill area 1.
438 // Otherwise, if this is not iOS, all the callee-saved registers go
439 // into spill area 1, including the FP in R11. In either case, it
440 // is in area one and the adjustment needs to take place just after
443 MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
444 unsigned PushSize = sizeOfSPAdjustment(GPRCS1Push);
445 emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
446 dl, TII, FramePtr, ARM::SP,
447 PushSize + FramePtrOffsetInPush,
448 MachineInstr::FrameSetup);
449 if (FramePtrOffsetInPush + PushSize != 0) {
450 unsigned CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfa(
451 nullptr, MRI->getDwarfRegNum(FramePtr, true),
452 -(ArgRegsSaveSize - FramePtrOffsetInPush)));
453 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
454 .addCFIIndex(CFIIndex);
457 MMI.addFrameInst(MCCFIInstruction::createDefCfaRegister(
458 nullptr, MRI->getDwarfRegNum(FramePtr, true)));
459 BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
460 .addCFIIndex(CFIIndex);
464 // Now that the prologue's actual instructions are finalised, we can insert
465 // the necessary DWARF cf instructions to describe the situation. Start by
466 // recording where each register ended up:
467 if (GPRCS1Size > 0) {
468 MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
470 for (const auto &Entry : CSI) {
471 unsigned Reg = Entry.getReg();
472 int FI = Entry.getFrameIdx();
479 if (STI.isTargetDarwin())
491 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
492 nullptr, MRI->getDwarfRegNum(Reg, true), MFI->getObjectOffset(FI)));
493 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
494 .addCFIIndex(CFIIndex);
500 if (GPRCS2Size > 0) {
501 MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
502 for (const auto &Entry : CSI) {
503 unsigned Reg = Entry.getReg();
504 int FI = Entry.getFrameIdx();
511 if (STI.isTargetDarwin()) {
512 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
513 unsigned Offset = MFI->getObjectOffset(FI);
514 unsigned CFIIndex = MMI.addFrameInst(
515 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
516 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
517 .addCFIIndex(CFIIndex);
525 // Since vpush register list cannot have gaps, there may be multiple vpush
526 // instructions in the prologue.
527 MachineBasicBlock::iterator Pos = std::next(LastPush);
528 for (const auto &Entry : CSI) {
529 unsigned Reg = Entry.getReg();
530 int FI = Entry.getFrameIdx();
531 if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
532 (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
533 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
534 unsigned Offset = MFI->getObjectOffset(FI);
535 unsigned CFIIndex = MMI.addFrameInst(
536 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
537 BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
538 .addCFIIndex(CFIIndex);
543 // Now we can emit descriptions of where the canonical frame address was
544 // throughout the process. If we have a frame pointer, it takes over the job
545 // half-way through, so only the first few .cfi_def_cfa_offset instructions
546 // actually get emitted.
547 DefCFAOffsetCandidates.emitDefCFAOffsets(MMI, MBB, dl, TII, HasFP);
549 if (STI.isTargetELF() && hasFP(MF))
550 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
551 AFI->getFramePtrSpillOffset());
553 AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
554 AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
555 AFI->setDPRCalleeSavedGapSize(DPRGapSize);
556 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
558 // If we need dynamic stack realignment, do it here. Be paranoid and make
559 // sure if we also have VLAs, we have a base pointer for frame access.
560 // If aligned NEON registers were spilled, the stack has already been
562 if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->needsStackRealignment(MF)) {
563 unsigned MaxAlign = MFI->getMaxAlignment();
564 assert (!AFI->isThumb1OnlyFunction());
565 if (!AFI->isThumbFunction()) {
566 // Emit bic sp, sp, MaxAlign
567 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
568 TII.get(ARM::BICri), ARM::SP)
569 .addReg(ARM::SP, RegState::Kill)
570 .addImm(MaxAlign-1)));
572 // We cannot use sp as source/dest register here, thus we're emitting the
573 // following sequence:
575 // bic r4, r4, MaxAlign
577 // FIXME: It will be better just to find spare register here.
578 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
579 .addReg(ARM::SP, RegState::Kill));
580 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
581 TII.get(ARM::t2BICri), ARM::R4)
582 .addReg(ARM::R4, RegState::Kill)
583 .addImm(MaxAlign-1)));
584 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
585 .addReg(ARM::R4, RegState::Kill));
588 AFI->setShouldRestoreSPFromFP(true);
591 // If we need a base pointer, set it up here. It's whatever the value
592 // of the stack pointer is at this point. Any variable size objects
593 // will be allocated after this, so we can still use the base pointer
594 // to reference locals.
595 // FIXME: Clarify FrameSetup flags here.
596 if (RegInfo->hasBasePointer(MF)) {
598 BuildMI(MBB, MBBI, dl,
599 TII.get(ARM::MOVr), RegInfo->getBaseRegister())
601 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
603 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
604 RegInfo->getBaseRegister())
608 // If the frame has variable sized objects then the epilogue must restore
609 // the sp from fp. We can assume there's an FP here since hasFP already
610 // checks for hasVarSizedObjects.
611 if (MFI->hasVarSizedObjects())
612 AFI->setShouldRestoreSPFromFP(true);
615 // Resolve TCReturn pseudo-instruction
616 void ARMFrameLowering::fixTCReturn(MachineFunction &MF,
617 MachineBasicBlock &MBB) const {
618 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
619 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
620 unsigned RetOpcode = MBBI->getOpcode();
621 DebugLoc dl = MBBI->getDebugLoc();
622 const ARMBaseInstrInfo &TII =
623 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
625 if (!(RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri))
628 // Tail call return: adjust the stack pointer and jump to callee.
629 MBBI = MBB.getLastNonDebugInstr();
630 MachineOperand &JumpTarget = MBBI->getOperand(0);
632 // Jump to label or value in register.
633 if (RetOpcode == ARM::TCRETURNdi) {
634 unsigned TCOpcode = STI.isThumb() ?
635 (STI.isTargetMachO() ? ARM::tTAILJMPd : ARM::tTAILJMPdND) :
637 MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
638 if (JumpTarget.isGlobal())
639 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
640 JumpTarget.getTargetFlags());
642 assert(JumpTarget.isSymbol());
643 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
644 JumpTarget.getTargetFlags());
647 // Add the default predicate in Thumb mode.
648 if (STI.isThumb()) MIB.addImm(ARMCC::AL).addReg(0);
649 } else if (RetOpcode == ARM::TCRETURNri) {
650 BuildMI(MBB, MBBI, dl,
651 TII.get(STI.isThumb() ? ARM::tTAILJMPr : ARM::TAILJMPr)).
652 addReg(JumpTarget.getReg(), RegState::Kill);
655 MachineInstr *NewMI = std::prev(MBBI);
656 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
657 NewMI->addOperand(MBBI->getOperand(i));
659 // Delete the pseudo instruction TCRETURN.
664 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
665 MachineBasicBlock &MBB) const {
666 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
667 assert(MBBI->isReturn() && "Can only insert epilog into returning blocks");
668 DebugLoc dl = MBBI->getDebugLoc();
669 MachineFrameInfo *MFI = MF.getFrameInfo();
670 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
671 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
672 const ARMBaseInstrInfo &TII =
673 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
674 assert(!AFI->isThumb1OnlyFunction() &&
675 "This emitEpilogue does not support Thumb1!");
676 bool isARM = !AFI->isThumbFunction();
678 unsigned Align = MF.getTarget()
681 ->getStackAlignment();
682 unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize(Align);
683 int NumBytes = (int)MFI->getStackSize();
684 unsigned FramePtr = RegInfo->getFrameRegister(MF);
686 // All calls are tail calls in GHC calling conv, and functions have no
687 // prologue/epilogue.
688 if (MF.getFunction()->getCallingConv() == CallingConv::GHC) {
689 fixTCReturn(MF, MBB);
693 if (!AFI->hasStackFrame()) {
694 if (NumBytes - ArgRegsSaveSize != 0)
695 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize);
697 // Unwind MBBI to point to first LDR / VLDRD.
698 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
699 if (MBBI != MBB.begin()) {
702 } while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
703 if (!isCSRestore(MBBI, TII, CSRegs))
707 // Move SP to start of FP callee save spill area.
708 NumBytes -= (ArgRegsSaveSize +
709 AFI->getGPRCalleeSavedArea1Size() +
710 AFI->getGPRCalleeSavedArea2Size() +
711 AFI->getDPRCalleeSavedGapSize() +
712 AFI->getDPRCalleeSavedAreaSize());
714 // Reset SP based on frame pointer only if the stack frame extends beyond
715 // frame pointer stack slot or target is ELF and the function has FP.
716 if (AFI->shouldRestoreSPFromFP()) {
717 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
720 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
723 // It's not possible to restore SP from FP in a single instruction.
724 // For iOS, this looks like:
727 // This is bad, if an interrupt is taken after the mov, sp is in an
728 // inconsistent state.
729 // Use the first callee-saved register as a scratch register.
730 assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
731 "No scratch register to restore SP from FP!");
732 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
734 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
741 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
742 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
744 AddDefaultPred(BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr),
748 } else if (NumBytes &&
749 !tryFoldSPUpdateIntoPushPop(STI, MF, MBBI, NumBytes))
750 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
752 // Increment past our save areas.
753 if (AFI->getDPRCalleeSavedAreaSize()) {
755 // Since vpop register list cannot have gaps, there may be multiple vpop
756 // instructions in the epilogue.
757 while (MBBI->getOpcode() == ARM::VLDMDIA_UPD)
760 if (AFI->getDPRCalleeSavedGapSize()) {
761 assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
762 "unexpected DPR alignment gap");
763 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize());
766 if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
767 if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
770 fixTCReturn(MF, MBB);
773 emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize);
776 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
777 /// debug info. It's the same as what we use for resolving the code-gen
778 /// references for now. FIXME: This can go wrong when references are
779 /// SP-relative and simple call frames aren't used.
781 ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
782 unsigned &FrameReg) const {
783 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
787 ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
788 int FI, unsigned &FrameReg,
790 const MachineFrameInfo *MFI = MF.getFrameInfo();
791 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
792 MF.getSubtarget().getRegisterInfo());
793 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
794 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
795 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
796 bool isFixed = MFI->isFixedObjectIndex(FI);
801 // SP can move around if there are allocas. We may also lose track of SP
802 // when emergency spilling inside a non-reserved call frame setup.
803 bool hasMovingSP = !hasReservedCallFrame(MF);
805 // When dynamically realigning the stack, use the frame pointer for
806 // parameters, and the stack/base pointer for locals.
807 if (RegInfo->needsStackRealignment(MF)) {
808 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
810 FrameReg = RegInfo->getFrameRegister(MF);
812 } else if (hasMovingSP) {
813 assert(RegInfo->hasBasePointer(MF) &&
814 "VLAs and dynamic stack alignment, but missing base pointer!");
815 FrameReg = RegInfo->getBaseRegister();
820 // If there is a frame pointer, use it when we can.
821 if (hasFP(MF) && AFI->hasStackFrame()) {
822 // Use frame pointer to reference fixed objects. Use it for locals if
823 // there are VLAs (and thus the SP isn't reliable as a base).
824 if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
825 FrameReg = RegInfo->getFrameRegister(MF);
827 } else if (hasMovingSP) {
828 assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
829 if (AFI->isThumb2Function()) {
830 // Try to use the frame pointer if we can, else use the base pointer
831 // since it's available. This is handy for the emergency spill slot, in
833 if (FPOffset >= -255 && FPOffset < 0) {
834 FrameReg = RegInfo->getFrameRegister(MF);
838 } else if (AFI->isThumb2Function()) {
839 // Use add <rd>, sp, #<imm8>
840 // ldr <rd>, [sp, #<imm8>]
841 // if at all possible to save space.
842 if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
844 // In Thumb2 mode, the negative offset is very limited. Try to avoid
845 // out of range references. ldr <rt>,[<rn>, #-<imm8>]
846 if (FPOffset >= -255 && FPOffset < 0) {
847 FrameReg = RegInfo->getFrameRegister(MF);
850 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
851 // Otherwise, use SP or FP, whichever is closer to the stack slot.
852 FrameReg = RegInfo->getFrameRegister(MF);
856 // Use the base pointer if we have one.
857 if (RegInfo->hasBasePointer(MF))
858 FrameReg = RegInfo->getBaseRegister();
862 int ARMFrameLowering::getFrameIndexOffset(const MachineFunction &MF,
865 return getFrameIndexReference(MF, FI, FrameReg);
868 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
869 MachineBasicBlock::iterator MI,
870 const std::vector<CalleeSavedInfo> &CSI,
871 unsigned StmOpc, unsigned StrOpc,
873 bool(*Func)(unsigned, bool),
874 unsigned NumAlignedDPRCS2Regs,
875 unsigned MIFlags) const {
876 MachineFunction &MF = *MBB.getParent();
877 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
880 if (MI != MBB.end()) DL = MI->getDebugLoc();
882 SmallVector<std::pair<unsigned,bool>, 4> Regs;
883 unsigned i = CSI.size();
885 unsigned LastReg = 0;
886 for (; i != 0; --i) {
887 unsigned Reg = CSI[i-1].getReg();
888 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
890 // D-registers in the aligned area DPRCS2 are NOT spilled here.
891 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
894 // Add the callee-saved register as live-in unless it's LR and
895 // @llvm.returnaddress is called. If LR is returned for
896 // @llvm.returnaddress then it's already added to the function and
897 // entry block live-in sets.
899 if (Reg == ARM::LR) {
900 if (MF.getFrameInfo()->isReturnAddressTaken() &&
901 MF.getRegInfo().isLiveIn(Reg))
908 // If NoGap is true, push consecutive registers and then leave the rest
909 // for other instructions. e.g.
910 // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
911 if (NoGap && LastReg && LastReg != Reg-1)
914 Regs.push_back(std::make_pair(Reg, isKill));
919 if (Regs.size() > 1 || StrOpc== 0) {
920 MachineInstrBuilder MIB =
921 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
922 .addReg(ARM::SP).setMIFlags(MIFlags));
923 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
924 MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
925 } else if (Regs.size() == 1) {
926 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
928 .addReg(Regs[0].first, getKillRegState(Regs[0].second))
929 .addReg(ARM::SP).setMIFlags(MIFlags)
935 // Put any subsequent vpush instructions before this one: they will refer to
936 // higher register numbers so need to be pushed first in order to preserve
942 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
943 MachineBasicBlock::iterator MI,
944 const std::vector<CalleeSavedInfo> &CSI,
945 unsigned LdmOpc, unsigned LdrOpc,
946 bool isVarArg, bool NoGap,
947 bool(*Func)(unsigned, bool),
948 unsigned NumAlignedDPRCS2Regs) const {
949 MachineFunction &MF = *MBB.getParent();
950 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
951 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
952 DebugLoc DL = MI->getDebugLoc();
953 unsigned RetOpcode = MI->getOpcode();
954 bool isTailCall = (RetOpcode == ARM::TCRETURNdi ||
955 RetOpcode == ARM::TCRETURNri);
957 RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
959 SmallVector<unsigned, 4> Regs;
960 unsigned i = CSI.size();
962 unsigned LastReg = 0;
963 bool DeleteRet = false;
964 for (; i != 0; --i) {
965 unsigned Reg = CSI[i-1].getReg();
966 if (!(Func)(Reg, STI.isTargetDarwin())) continue;
968 // The aligned reloads from area DPRCS2 are not inserted here.
969 if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
972 if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
975 LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
976 // Fold the return instruction into the LDM.
980 // If NoGap is true, pop consecutive registers and then leave the rest
981 // for other instructions. e.g.
982 // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
983 if (NoGap && LastReg && LastReg != Reg-1)
992 if (Regs.size() > 1 || LdrOpc == 0) {
993 MachineInstrBuilder MIB =
994 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
996 for (unsigned i = 0, e = Regs.size(); i < e; ++i)
997 MIB.addReg(Regs[i], getDefRegState(true));
999 MIB.copyImplicitOps(&*MI);
1000 MI->eraseFromParent();
1003 } else if (Regs.size() == 1) {
1004 // If we adjusted the reg to PC from LR above, switch it back here. We
1005 // only do that for LDM.
1006 if (Regs[0] == ARM::PC)
1008 MachineInstrBuilder MIB =
1009 BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1010 .addReg(ARM::SP, RegState::Define)
1012 // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1013 // that refactoring is complete (eventually).
1014 if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1016 MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1019 AddDefaultPred(MIB);
1023 // Put any subsequent vpop instructions after this one: they will refer to
1024 // higher register numbers so need to be popped afterwards.
1029 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1030 /// starting from d8. Also insert stack realignment code and leave the stack
1031 /// pointer pointing to the d8 spill slot.
1032 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1033 MachineBasicBlock::iterator MI,
1034 unsigned NumAlignedDPRCS2Regs,
1035 const std::vector<CalleeSavedInfo> &CSI,
1036 const TargetRegisterInfo *TRI) {
1037 MachineFunction &MF = *MBB.getParent();
1038 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1039 DebugLoc DL = MI->getDebugLoc();
1040 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1041 MachineFrameInfo &MFI = *MF.getFrameInfo();
1043 // Mark the D-register spill slots as properly aligned. Since MFI computes
1044 // stack slot layout backwards, this can actually mean that the d-reg stack
1045 // slot offsets can be wrong. The offset for d8 will always be correct.
1046 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1047 unsigned DNum = CSI[i].getReg() - ARM::D8;
1050 int FI = CSI[i].getFrameIdx();
1051 // The even-numbered registers will be 16-byte aligned, the odd-numbered
1052 // registers will be 8-byte aligned.
1053 MFI.setObjectAlignment(FI, DNum % 2 ? 8 : 16);
1055 // The stack slot for D8 needs to be maximally aligned because this is
1056 // actually the point where we align the stack pointer. MachineFrameInfo
1057 // computes all offsets relative to the incoming stack pointer which is a
1058 // bit weird when realigning the stack. Any extra padding for this
1059 // over-alignment is not realized because the code inserted below adjusts
1060 // the stack pointer by numregs * 8 before aligning the stack pointer.
1062 MFI.setObjectAlignment(FI, MFI.getMaxAlignment());
1065 // Move the stack pointer to the d8 spill slot, and align it at the same
1066 // time. Leave the stack slot address in the scratch register r4.
1068 // sub r4, sp, #numregs * 8
1069 // bic r4, r4, #align - 1
1072 bool isThumb = AFI->isThumbFunction();
1073 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1074 AFI->setShouldRestoreSPFromFP(true);
1076 // sub r4, sp, #numregs * 8
1077 // The immediate is <= 64, so it doesn't need any special encoding.
1078 unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1079 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1081 .addImm(8 * NumAlignedDPRCS2Regs)));
1083 // bic r4, r4, #align-1
1084 Opc = isThumb ? ARM::t2BICri : ARM::BICri;
1085 unsigned MaxAlign = MF.getFrameInfo()->getMaxAlignment();
1086 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1087 .addReg(ARM::R4, RegState::Kill)
1088 .addImm(MaxAlign - 1)));
1091 // The stack pointer must be adjusted before spilling anything, otherwise
1092 // the stack slots could be clobbered by an interrupt handler.
1093 // Leave r4 live, it is used below.
1094 Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1095 MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1097 MIB = AddDefaultPred(MIB);
1101 // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1102 // r4 holds the stack slot address.
1103 unsigned NextReg = ARM::D8;
1105 // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1106 // The writeback is only needed when emitting two vst1.64 instructions.
1107 if (NumAlignedDPRCS2Regs >= 6) {
1108 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1109 &ARM::QQPRRegClass);
1110 MBB.addLiveIn(SupReg);
1111 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed),
1113 .addReg(ARM::R4, RegState::Kill).addImm(16)
1115 .addReg(SupReg, RegState::ImplicitKill));
1117 NumAlignedDPRCS2Regs -= 4;
1120 // We won't modify r4 beyond this point. It currently points to the next
1121 // register to be spilled.
1122 unsigned R4BaseReg = NextReg;
1124 // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1125 if (NumAlignedDPRCS2Regs >= 4) {
1126 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1127 &ARM::QQPRRegClass);
1128 MBB.addLiveIn(SupReg);
1129 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1130 .addReg(ARM::R4).addImm(16).addReg(NextReg)
1131 .addReg(SupReg, RegState::ImplicitKill));
1133 NumAlignedDPRCS2Regs -= 4;
1136 // 16-byte aligned vst1.64 with 2 d-regs.
1137 if (NumAlignedDPRCS2Regs >= 2) {
1138 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1140 MBB.addLiveIn(SupReg);
1141 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1142 .addReg(ARM::R4).addImm(16).addReg(SupReg));
1144 NumAlignedDPRCS2Regs -= 2;
1147 // Finally, use a vanilla vstr.64 for the odd last register.
1148 if (NumAlignedDPRCS2Regs) {
1149 MBB.addLiveIn(NextReg);
1150 // vstr.64 uses addrmode5 which has an offset scale of 4.
1151 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1153 .addReg(ARM::R4).addImm((NextReg-R4BaseReg)*2));
1156 // The last spill instruction inserted should kill the scratch register r4.
1157 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1160 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1161 /// iterator to the following instruction.
1162 static MachineBasicBlock::iterator
1163 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1164 unsigned NumAlignedDPRCS2Regs) {
1165 // sub r4, sp, #numregs * 8
1166 // bic r4, r4, #align - 1
1169 assert(MI->mayStore() && "Expecting spill instruction");
1171 // These switches all fall through.
1172 switch(NumAlignedDPRCS2Regs) {
1175 assert(MI->mayStore() && "Expecting spill instruction");
1178 assert(MI->mayStore() && "Expecting spill instruction");
1182 assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1188 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1189 /// starting from d8. These instructions are assumed to execute while the
1190 /// stack is still aligned, unlike the code inserted by emitPopInst.
1191 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1192 MachineBasicBlock::iterator MI,
1193 unsigned NumAlignedDPRCS2Regs,
1194 const std::vector<CalleeSavedInfo> &CSI,
1195 const TargetRegisterInfo *TRI) {
1196 MachineFunction &MF = *MBB.getParent();
1197 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1198 DebugLoc DL = MI->getDebugLoc();
1199 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1201 // Find the frame index assigned to d8.
1203 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1204 if (CSI[i].getReg() == ARM::D8) {
1205 D8SpillFI = CSI[i].getFrameIdx();
1209 // Materialize the address of the d8 spill slot into the scratch register r4.
1210 // This can be fairly complicated if the stack frame is large, so just use
1211 // the normal frame index elimination mechanism to do it. This code runs as
1212 // the initial part of the epilog where the stack and base pointers haven't
1213 // been changed yet.
1214 bool isThumb = AFI->isThumbFunction();
1215 assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1217 unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1218 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1219 .addFrameIndex(D8SpillFI).addImm(0)));
1221 // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1222 unsigned NextReg = ARM::D8;
1224 // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1225 if (NumAlignedDPRCS2Regs >= 6) {
1226 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1227 &ARM::QQPRRegClass);
1228 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1229 .addReg(ARM::R4, RegState::Define)
1230 .addReg(ARM::R4, RegState::Kill).addImm(16)
1231 .addReg(SupReg, RegState::ImplicitDefine));
1233 NumAlignedDPRCS2Regs -= 4;
1236 // We won't modify r4 beyond this point. It currently points to the next
1237 // register to be spilled.
1238 unsigned R4BaseReg = NextReg;
1240 // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1241 if (NumAlignedDPRCS2Regs >= 4) {
1242 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1243 &ARM::QQPRRegClass);
1244 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1245 .addReg(ARM::R4).addImm(16)
1246 .addReg(SupReg, RegState::ImplicitDefine));
1248 NumAlignedDPRCS2Regs -= 4;
1251 // 16-byte aligned vld1.64 with 2 d-regs.
1252 if (NumAlignedDPRCS2Regs >= 2) {
1253 unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1255 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1256 .addReg(ARM::R4).addImm(16));
1258 NumAlignedDPRCS2Regs -= 2;
1261 // Finally, use a vanilla vldr.64 for the remaining odd register.
1262 if (NumAlignedDPRCS2Regs)
1263 AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1264 .addReg(ARM::R4).addImm(2*(NextReg-R4BaseReg)));
1266 // Last store kills r4.
1267 std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1270 bool ARMFrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1271 MachineBasicBlock::iterator MI,
1272 const std::vector<CalleeSavedInfo> &CSI,
1273 const TargetRegisterInfo *TRI) const {
1277 MachineFunction &MF = *MBB.getParent();
1278 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1280 unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1281 unsigned PushOneOpc = AFI->isThumbFunction() ?
1282 ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1283 unsigned FltOpc = ARM::VSTMDDB_UPD;
1284 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1285 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1286 MachineInstr::FrameSetup);
1287 emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1288 MachineInstr::FrameSetup);
1289 emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1290 NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1292 // The code above does not insert spill code for the aligned DPRCS2 registers.
1293 // The stack realignment code will be inserted between the push instructions
1294 // and these spills.
1295 if (NumAlignedDPRCS2Regs)
1296 emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1301 bool ARMFrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1302 MachineBasicBlock::iterator MI,
1303 const std::vector<CalleeSavedInfo> &CSI,
1304 const TargetRegisterInfo *TRI) const {
1308 MachineFunction &MF = *MBB.getParent();
1309 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1310 bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1311 unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1313 // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1314 // registers. Do that here instead.
1315 if (NumAlignedDPRCS2Regs)
1316 emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1318 unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1319 unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1320 unsigned FltOpc = ARM::VLDMDIA_UPD;
1321 emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1322 NumAlignedDPRCS2Regs);
1323 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1324 &isARMArea2Register, 0);
1325 emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1326 &isARMArea1Register, 0);
1331 // FIXME: Make generic?
1332 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
1333 const ARMBaseInstrInfo &TII) {
1334 unsigned FnSize = 0;
1335 for (auto &MBB : MF) {
1336 for (auto &MI : MBB)
1337 FnSize += TII.GetInstSizeInBytes(&MI);
1342 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1343 /// frames and return the stack size limit beyond which some of these
1344 /// instructions will require a scratch register during their expansion later.
1345 // FIXME: Move to TII?
1346 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1347 const TargetFrameLowering *TFI) {
1348 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1349 unsigned Limit = (1 << 12) - 1;
1350 for (auto &MBB : MF) {
1351 for (auto &MI : MBB) {
1352 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1353 if (!MI.getOperand(i).isFI())
1356 // When using ADDri to get the address of a stack object, 255 is the
1357 // largest offset guaranteed to fit in the immediate offset.
1358 if (MI.getOpcode() == ARM::ADDri) {
1359 Limit = std::min(Limit, (1U << 8) - 1);
1363 // Otherwise check the addressing mode.
1364 switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1365 case ARMII::AddrMode3:
1366 case ARMII::AddrModeT2_i8:
1367 Limit = std::min(Limit, (1U << 8) - 1);
1369 case ARMII::AddrMode5:
1370 case ARMII::AddrModeT2_i8s4:
1371 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1373 case ARMII::AddrModeT2_i12:
1374 // i12 supports only positive offset so these will be converted to
1375 // i8 opcodes. See llvm::rewriteT2FrameIndex.
1376 if (TFI->hasFP(MF) && AFI->hasStackFrame())
1377 Limit = std::min(Limit, (1U << 8) - 1);
1379 case ARMII::AddrMode4:
1380 case ARMII::AddrMode6:
1381 // Addressing modes 4 & 6 (load/store) instructions can't encode an
1382 // immediate offset for stack references.
1387 break; // At most one FI per instruction
1395 // In functions that realign the stack, it can be an advantage to spill the
1396 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1397 // instructions take alignment hints that can improve performance.
1399 static void checkNumAlignedDPRCS2Regs(MachineFunction &MF) {
1400 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1401 if (!SpillAlignedNEONRegs)
1404 // Naked functions don't spill callee-saved registers.
1405 if (MF.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1409 // We are planning to use NEON instructions vst1 / vld1.
1410 if (!MF.getTarget().getSubtarget<ARMSubtarget>().hasNEON())
1413 // Don't bother if the default stack alignment is sufficiently high.
1416 ->getFrameLowering()
1417 ->getStackAlignment() >= 8)
1420 // Aligned spills require stack realignment.
1421 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1422 MF.getSubtarget().getRegisterInfo());
1423 if (!RegInfo->canRealignStack(MF))
1426 // We always spill contiguous d-registers starting from d8. Count how many
1427 // needs spilling. The register allocator will almost always use the
1428 // callee-saved registers in order, but it can happen that there are holes in
1429 // the range. Registers above the hole will be spilled to the standard DPRCS
1431 MachineRegisterInfo &MRI = MF.getRegInfo();
1432 unsigned NumSpills = 0;
1433 for (; NumSpills < 8; ++NumSpills)
1434 if (!MRI.isPhysRegUsed(ARM::D8 + NumSpills))
1437 // Don't do this for just one d-register. It's not worth it.
1441 // Spill the first NumSpills D-registers after realigning the stack.
1442 MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1444 // A scratch register is required for the vst1 / vld1 instructions.
1445 MF.getRegInfo().setPhysRegUsed(ARM::R4);
1449 ARMFrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1450 RegScavenger *RS) const {
1451 // This tells PEI to spill the FP as if it is any other callee-save register
1452 // to take advantage the eliminateFrameIndex machinery. This also ensures it
1453 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1454 // to combine multiple loads / stores.
1455 bool CanEliminateFrame = true;
1456 bool CS1Spilled = false;
1457 bool LRSpilled = false;
1458 unsigned NumGPRSpills = 0;
1459 SmallVector<unsigned, 4> UnspilledCS1GPRs;
1460 SmallVector<unsigned, 4> UnspilledCS2GPRs;
1461 const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1462 MF.getSubtarget().getRegisterInfo());
1463 const ARMBaseInstrInfo &TII =
1464 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1465 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1466 MachineFrameInfo *MFI = MF.getFrameInfo();
1467 MachineRegisterInfo &MRI = MF.getRegInfo();
1468 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1470 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1471 // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1472 // since it's not always possible to restore sp from fp in a single
1474 // FIXME: It will be better just to find spare register here.
1475 if (AFI->isThumb2Function() &&
1476 (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
1477 MRI.setPhysRegUsed(ARM::R4);
1479 if (AFI->isThumb1OnlyFunction()) {
1480 // Spill LR if Thumb1 function uses variable length argument lists.
1481 if (AFI->getArgRegsSaveSize() > 0)
1482 MRI.setPhysRegUsed(ARM::LR);
1484 // Spill R4 if Thumb1 epilogue has to restore SP from FP. We don't know
1485 // for sure what the stack size will be, but for this, an estimate is good
1486 // enough. If there anything changes it, it'll be a spill, which implies
1487 // we've used all the registers and so R4 is already used, so not marking
1488 // it here will be OK.
1489 // FIXME: It will be better just to find spare register here.
1490 unsigned StackSize = MFI->estimateStackSize(MF);
1491 if (MFI->hasVarSizedObjects() || StackSize > 508)
1492 MRI.setPhysRegUsed(ARM::R4);
1495 // See if we can spill vector registers to aligned stack.
1496 checkNumAlignedDPRCS2Regs(MF);
1498 // Spill the BasePtr if it's used.
1499 if (RegInfo->hasBasePointer(MF))
1500 MRI.setPhysRegUsed(RegInfo->getBaseRegister());
1502 // Don't spill FP if the frame can be eliminated. This is determined
1503 // by scanning the callee-save registers to see if any is used.
1504 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1505 for (unsigned i = 0; CSRegs[i]; ++i) {
1506 unsigned Reg = CSRegs[i];
1507 bool Spilled = false;
1508 if (MRI.isPhysRegUsed(Reg)) {
1510 CanEliminateFrame = false;
1513 if (!ARM::GPRRegClass.contains(Reg))
1519 if (!STI.isTargetDarwin()) {
1526 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1531 case ARM::R0: case ARM::R1:
1532 case ARM::R2: case ARM::R3:
1533 case ARM::R4: case ARM::R5:
1534 case ARM::R6: case ARM::R7:
1541 if (!STI.isTargetDarwin()) {
1542 UnspilledCS1GPRs.push_back(Reg);
1547 case ARM::R0: case ARM::R1:
1548 case ARM::R2: case ARM::R3:
1549 case ARM::R4: case ARM::R5:
1550 case ARM::R6: case ARM::R7:
1552 UnspilledCS1GPRs.push_back(Reg);
1555 UnspilledCS2GPRs.push_back(Reg);
1561 bool ForceLRSpill = false;
1562 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1563 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
1564 // Force LR to be spilled if the Thumb function size is > 2048. This enables
1565 // use of BL to implement far jump. If it turns out that it's not needed
1566 // then the branch fix up path will undo it.
1567 if (FnSize >= (1 << 11)) {
1568 CanEliminateFrame = false;
1569 ForceLRSpill = true;
1573 // If any of the stack slot references may be out of range of an immediate
1574 // offset, make sure a register (or a spill slot) is available for the
1575 // register scavenger. Note that if we're indexing off the frame pointer, the
1576 // effective stack size is 4 bytes larger since the FP points to the stack
1577 // slot of the previous FP. Also, if we have variable sized objects in the
1578 // function, stack slot references will often be negative, and some of
1579 // our instructions are positive-offset only, so conservatively consider
1580 // that case to want a spill slot (or register) as well. Similarly, if
1581 // the function adjusts the stack pointer during execution and the
1582 // adjustments aren't already part of our stack size estimate, our offset
1583 // calculations may be off, so be conservative.
1584 // FIXME: We could add logic to be more precise about negative offsets
1585 // and which instructions will need a scratch register for them. Is it
1586 // worth the effort and added fragility?
1589 (MFI->estimateStackSize(MF) +
1590 ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
1591 estimateRSStackSizeLimit(MF, this)))
1592 || MFI->hasVarSizedObjects()
1593 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
1595 bool ExtraCSSpill = false;
1596 if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1597 AFI->setHasStackFrame(true);
1599 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1600 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1601 if (!LRSpilled && CS1Spilled) {
1602 MRI.setPhysRegUsed(ARM::LR);
1604 SmallVectorImpl<unsigned>::iterator LRPos;
1605 LRPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1607 if (LRPos != UnspilledCS1GPRs.end())
1608 UnspilledCS1GPRs.erase(LRPos);
1610 ForceLRSpill = false;
1611 ExtraCSSpill = true;
1615 MRI.setPhysRegUsed(FramePtr);
1616 auto FPPos = std::find(UnspilledCS1GPRs.begin(), UnspilledCS1GPRs.end(),
1618 if (FPPos != UnspilledCS1GPRs.end())
1619 UnspilledCS1GPRs.erase(FPPos);
1623 // If stack and double are 8-byte aligned and we are spilling an odd number
1624 // of GPRs, spill one extra callee save GPR so we won't have to pad between
1625 // the integer and double callee save areas.
1626 unsigned TargetAlign = getStackAlignment();
1627 if (TargetAlign >= 8 && (NumGPRSpills & 1)) {
1628 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1629 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1630 unsigned Reg = UnspilledCS1GPRs[i];
1631 // Don't spill high register if the function is thumb1
1632 if (!AFI->isThumb1OnlyFunction() ||
1633 isARMLowRegister(Reg) || Reg == ARM::LR) {
1634 MRI.setPhysRegUsed(Reg);
1635 if (!MRI.isReserved(Reg))
1636 ExtraCSSpill = true;
1640 } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
1641 unsigned Reg = UnspilledCS2GPRs.front();
1642 MRI.setPhysRegUsed(Reg);
1643 if (!MRI.isReserved(Reg))
1644 ExtraCSSpill = true;
1648 // Estimate if we might need to scavenge a register at some point in order
1649 // to materialize a stack offset. If so, either spill one additional
1650 // callee-saved register or reserve a special spill slot to facilitate
1651 // register scavenging. Thumb1 needs a spill slot for stack pointer
1652 // adjustments also, even when the frame itself is small.
1653 if (BigStack && !ExtraCSSpill) {
1654 // If any non-reserved CS register isn't spilled, just spill one or two
1655 // extra. That should take care of it!
1656 unsigned NumExtras = TargetAlign / 4;
1657 SmallVector<unsigned, 2> Extras;
1658 while (NumExtras && !UnspilledCS1GPRs.empty()) {
1659 unsigned Reg = UnspilledCS1GPRs.back();
1660 UnspilledCS1GPRs.pop_back();
1661 if (!MRI.isReserved(Reg) &&
1662 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
1664 Extras.push_back(Reg);
1668 // For non-Thumb1 functions, also check for hi-reg CS registers
1669 if (!AFI->isThumb1OnlyFunction()) {
1670 while (NumExtras && !UnspilledCS2GPRs.empty()) {
1671 unsigned Reg = UnspilledCS2GPRs.back();
1672 UnspilledCS2GPRs.pop_back();
1673 if (!MRI.isReserved(Reg)) {
1674 Extras.push_back(Reg);
1679 if (Extras.size() && NumExtras == 0) {
1680 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1681 MRI.setPhysRegUsed(Extras[i]);
1683 } else if (!AFI->isThumb1OnlyFunction()) {
1684 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
1685 // closest to SP or frame pointer.
1686 const TargetRegisterClass *RC = &ARM::GPRRegClass;
1687 RS->addScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1695 MRI.setPhysRegUsed(ARM::LR);
1696 AFI->setLRIsSpilledForFarJump(true);
1701 void ARMFrameLowering::
1702 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1703 MachineBasicBlock::iterator I) const {
1704 const ARMBaseInstrInfo &TII =
1705 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1706 if (!hasReservedCallFrame(MF)) {
1707 // If we have alloca, convert as follows:
1708 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1709 // ADJCALLSTACKUP -> add, sp, sp, amount
1710 MachineInstr *Old = I;
1711 DebugLoc dl = Old->getDebugLoc();
1712 unsigned Amount = Old->getOperand(0).getImm();
1714 // We need to keep the stack aligned properly. To do this, we round the
1715 // amount of space needed for the outgoing arguments up to the next
1716 // alignment boundary.
1717 unsigned Align = getStackAlignment();
1718 Amount = (Amount+Align-1)/Align*Align;
1720 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1721 assert(!AFI->isThumb1OnlyFunction() &&
1722 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1723 bool isARM = !AFI->isThumbFunction();
1725 // Replace the pseudo instruction with a new instruction...
1726 unsigned Opc = Old->getOpcode();
1727 int PIdx = Old->findFirstPredOperandIdx();
1728 ARMCC::CondCodes Pred = (PIdx == -1)
1729 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1730 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1731 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1732 unsigned PredReg = Old->getOperand(2).getReg();
1733 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
1736 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1737 unsigned PredReg = Old->getOperand(3).getReg();
1738 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1739 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
1747 /// Get the minimum constant for ARM that is greater than or equal to the
1748 /// argument. In ARM, constants can have any value that can be produced by
1749 /// rotating an 8-bit value to the right by an even number of bits within a
1751 static uint32_t alignToARMConstant(uint32_t Value) {
1752 unsigned Shifted = 0;
1757 while (!(Value & 0xC0000000)) {
1762 bool Carry = (Value & 0x00FFFFFF);
1763 Value = ((Value & 0xFF000000) >> 24) + Carry;
1765 if (Value & 0x0000100)
1766 Value = Value & 0x000001FC;
1769 Value = Value >> (Shifted - 24);
1771 Value = Value << (24 - Shifted);
1776 // The stack limit in the TCB is set to this many bytes above the actual
1778 static const uint64_t kSplitStackAvailable = 256;
1780 // Adjust the function prologue to enable split stacks. This currently only
1781 // supports android and linux.
1783 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
1784 // must be well defined in order to allow for consistent implementations of the
1785 // __morestack helper function. The ABI is also not a normal ABI in that it
1786 // doesn't follow the normal calling conventions because this allows the
1787 // prologue of each function to be optimized further.
1789 // Currently, the ABI looks like (when calling __morestack)
1791 // * r4 holds the minimum stack size requested for this function call
1792 // * r5 holds the stack size of the arguments to the function
1793 // * the beginning of the function is 3 instructions after the call to
1796 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
1797 // place the arguments on to the new stack, and the 3-instruction knowledge to
1798 // jump directly to the body of the function when working on the new stack.
1800 // An old (and possibly no longer compatible) implementation of __morestack for
1801 // ARM can be found at [1].
1803 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
1804 void ARMFrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1807 const ARMSubtarget *ST = &MF.getTarget().getSubtarget<ARMSubtarget>();
1808 bool Thumb = ST->isThumb();
1810 // Sadly, this currently doesn't support varargs, platforms other than
1811 // android/linux. Note that thumb1/thumb2 are support for android/linux.
1812 if (MF.getFunction()->isVarArg())
1813 report_fatal_error("Segmented stacks do not support vararg functions.");
1814 if (!ST->isTargetAndroid() && !ST->isTargetLinux())
1815 report_fatal_error("Segmented stacks not supported on this platform.");
1817 MachineBasicBlock &prologueMBB = MF.front();
1818 MachineFrameInfo *MFI = MF.getFrameInfo();
1819 MachineModuleInfo &MMI = MF.getMMI();
1820 MCContext &Context = MMI.getContext();
1821 const MCRegisterInfo *MRI = Context.getRegisterInfo();
1822 const ARMBaseInstrInfo &TII =
1823 *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1824 ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
1827 uint64_t StackSize = MFI->getStackSize();
1829 // Do not generate a prologue for functions with a stack of size zero
1833 // Use R4 and R5 as scratch registers.
1834 // We save R4 and R5 before use and restore them before leaving the function.
1835 unsigned ScratchReg0 = ARM::R4;
1836 unsigned ScratchReg1 = ARM::R5;
1837 uint64_t AlignedStackSize;
1839 MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
1840 MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
1841 MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
1842 MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
1843 MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
1845 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1846 e = prologueMBB.livein_end();
1848 AllocMBB->addLiveIn(*i);
1849 GetMBB->addLiveIn(*i);
1850 McrMBB->addLiveIn(*i);
1851 PrevStackMBB->addLiveIn(*i);
1852 PostStackMBB->addLiveIn(*i);
1855 MF.push_front(PostStackMBB);
1856 MF.push_front(AllocMBB);
1857 MF.push_front(GetMBB);
1858 MF.push_front(McrMBB);
1859 MF.push_front(PrevStackMBB);
1861 // The required stack size that is aligned to ARM constant criterion.
1862 AlignedStackSize = alignToARMConstant(StackSize);
1864 // When the frame size is less than 256 we just compare the stack
1865 // boundary directly to the value of the stack pointer, per gcc.
1866 bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
1868 // We will use two of the callee save registers as scratch registers so we
1869 // need to save those registers onto the stack.
1870 // We will use SR0 to hold stack limit and SR1 to hold the stack size
1871 // requested and arguments for __morestack().
1872 // SR0: Scratch Register #0
1873 // SR1: Scratch Register #1
1876 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH)))
1877 .addReg(ScratchReg0).addReg(ScratchReg1);
1879 AddDefaultPred(BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
1880 .addReg(ARM::SP, RegState::Define).addReg(ARM::SP))
1881 .addReg(ScratchReg0).addReg(ScratchReg1);
1884 // Emit the relevant DWARF information about the change in stack pointer as
1885 // well as where to find both r4 and r5 (the callee-save registers)
1887 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -8));
1888 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1889 .addCFIIndex(CFIIndex);
1890 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1891 nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
1892 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1893 .addCFIIndex(CFIIndex);
1894 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
1895 nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
1896 BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
1897 .addCFIIndex(CFIIndex);
1901 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
1903 } else if (CompareStackPointer) {
1904 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
1905 .addReg(ARM::SP)).addReg(0);
1908 // sub SR1, sp, #StackSize
1909 if (!CompareStackPointer && Thumb) {
1911 AddDefaultCC(BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1))
1912 .addReg(ScratchReg1).addImm(AlignedStackSize));
1913 } else if (!CompareStackPointer) {
1914 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
1915 .addReg(ARM::SP).addImm(AlignedStackSize)).addReg(0);
1918 if (Thumb && ST->isThumb1Only()) {
1919 unsigned PCLabelId = ARMFI->createPICLabelUId();
1920 ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
1921 MF.getFunction()->getContext(), "__STACK_LIMIT", PCLabelId, 0);
1922 MachineConstantPool *MCP = MF.getConstantPool();
1923 unsigned CPI = MCP->getConstantPoolIndex(NewCPV, MF.getAlignment());
1925 // ldr SR0, [pc, offset(STACK_LIMIT)]
1926 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
1927 .addConstantPoolIndex(CPI));
1930 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
1931 .addReg(ScratchReg0).addImm(0));
1933 // Get TLS base address from the coprocessor
1934 // mrc p15, #0, SR0, c13, c0, #3
1935 AddDefaultPred(BuildMI(McrMBB, DL, TII.get(ARM::MRC), ScratchReg0)
1942 // Use the last tls slot on android and a private field of the TCP on linux.
1943 assert(ST->isTargetAndroid() || ST->isTargetLinux());
1944 unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
1946 // Get the stack limit from the right offset
1947 // ldr SR0, [sr0, #4 * TlsOffset]
1948 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(ARM::LDRi12), ScratchReg0)
1949 .addReg(ScratchReg0).addImm(4 * TlsOffset));
1952 // Compare stack limit with stack size requested.
1954 Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
1955 AddDefaultPred(BuildMI(GetMBB, DL, TII.get(Opcode))
1956 .addReg(ScratchReg0)
1957 .addReg(ScratchReg1));
1959 // This jump is taken if StackLimit < SP - stack required.
1960 Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
1961 BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
1966 // Calling __morestack(StackSize, Size of stack arguments).
1967 // __morestack knows that the stack size requested is in SR0(r4)
1968 // and amount size of stack arguments is in SR1(r5).
1970 // Pass first argument for the __morestack by Scratch Register #0.
1971 // The amount size of stack required
1973 AddDefaultPred(AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8),
1974 ScratchReg0)).addImm(AlignedStackSize));
1976 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
1977 .addImm(AlignedStackSize)).addReg(0);
1979 // Pass second argument for the __morestack by Scratch Register #1.
1980 // The amount size of stack consumed to save function arguments.
1983 AddDefaultCC(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1))
1984 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())));
1986 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
1987 .addImm(alignToARMConstant(ARMFI->getArgumentStackSize())))
1991 // push {lr} - Save return address of this function.
1993 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH)))
1996 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
1997 .addReg(ARM::SP, RegState::Define)
2002 // Emit the DWARF info about the change in stack as well as where to find the
2003 // previous link register
2005 MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, -12));
2006 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2007 .addCFIIndex(CFIIndex);
2008 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createOffset(
2009 nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2010 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2011 .addCFIIndex(CFIIndex);
2013 // Call __morestack().
2015 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tBL)))
2016 .addExternalSymbol("__morestack");
2018 BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2019 .addExternalSymbol("__morestack");
2022 // pop {lr} - Restore return address of this original function.
2024 if (ST->isThumb1Only()) {
2025 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2026 .addReg(ScratchReg0);
2027 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2028 .addReg(ScratchReg0));
2030 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2031 .addReg(ARM::LR, RegState::Define)
2032 .addReg(ARM::SP, RegState::Define)
2037 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2038 .addReg(ARM::SP, RegState::Define)
2043 // Restore SR0 and SR1 in case of __morestack() was called.
2044 // __morestack() will skip PostStackMBB block so we need to restore
2045 // scratch registers from here.
2048 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::tPOP)))
2049 .addReg(ScratchReg0)
2050 .addReg(ScratchReg1);
2052 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2053 .addReg(ARM::SP, RegState::Define)
2055 .addReg(ScratchReg0)
2056 .addReg(ScratchReg1);
2059 // Update the CFA offset now that we've popped
2060 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2061 BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2062 .addCFIIndex(CFIIndex);
2064 // bx lr - Return from this function.
2065 Opcode = Thumb ? ARM::tBX_RET : ARM::BX_RET;
2066 AddDefaultPred(BuildMI(AllocMBB, DL, TII.get(Opcode)));
2068 // Restore SR0 and SR1 in case of __morestack() was not called.
2071 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP)))
2072 .addReg(ScratchReg0)
2073 .addReg(ScratchReg1);
2075 AddDefaultPred(BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2076 .addReg(ARM::SP, RegState::Define)
2078 .addReg(ScratchReg0)
2079 .addReg(ScratchReg1);
2082 // Update the CFA offset now that we've popped
2083 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createDefCfaOffset(nullptr, 0));
2084 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2085 .addCFIIndex(CFIIndex);
2087 // Tell debuggers that r4 and r5 are now the same as they were in the
2088 // previous function, that they're the "Same Value".
2089 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2090 nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2091 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2092 .addCFIIndex(CFIIndex);
2093 CFIIndex = MMI.addFrameInst(MCCFIInstruction::createSameValue(
2094 nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2095 BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2096 .addCFIIndex(CFIIndex);
2098 // Organizing MBB lists
2099 PostStackMBB->addSuccessor(&prologueMBB);
2101 AllocMBB->addSuccessor(PostStackMBB);
2103 GetMBB->addSuccessor(PostStackMBB);
2104 GetMBB->addSuccessor(AllocMBB);
2106 McrMBB->addSuccessor(GetMBB);
2108 PrevStackMBB->addSuccessor(McrMBB);