xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Target/ARM/ARMFrameLowering.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===- ARMFrameLowering.cpp - ARM Frame Information -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the ARM implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 // This file contains the ARM implementation of TargetFrameLowering class.
14 //
15 // On ARM, stack frames are structured as follows:
16 //
17 // The stack grows downward.
18 //
19 // All of the individual frame areas on the frame below are optional, i.e. it's
20 // possible to create a function so that the particular area isn't present
21 // in the frame.
22 //
23 // At function entry, the "frame" looks as follows:
24 //
25 // |                                   | Higher address
26 // |-----------------------------------|
27 // |                                   |
28 // | arguments passed on the stack     |
29 // |                                   |
30 // |-----------------------------------| <- sp
31 // |                                   | Lower address
32 //
33 //
34 // After the prologue has run, the frame has the following general structure.
35 // Technically the last frame area (VLAs) doesn't get created until in the
36 // main function body, after the prologue is run. However, it's depicted here
37 // for completeness.
38 //
39 // |                                   | Higher address
40 // |-----------------------------------|
41 // |                                   |
42 // | arguments passed on the stack     |
43 // |                                   |
44 // |-----------------------------------| <- (sp at function entry)
45 // |                                   |
46 // | varargs from registers            |
47 // |                                   |
48 // |-----------------------------------|
49 // |                                   |
50 // | prev_fp, prev_lr                  |
51 // | (a.k.a. "frame record")           |
52 // |                                   |
53 // |- - - - - - - - - - - - - - - - - -| <- fp (r7 or r11)
54 // |                                   |
55 // | callee-saved gpr registers        |
56 // |                                   |
57 // |-----------------------------------|
58 // |                                   |
59 // | callee-saved fp/simd regs         |
60 // |                                   |
61 // |-----------------------------------|
62 // |.empty.space.to.make.part.below....|
63 // |.aligned.in.case.it.needs.more.than| (size of this area is unknown at
64 // |.the.standard.8-byte.alignment.....|  compile time; if present)
65 // |-----------------------------------|
66 // |                                   |
67 // | local variables of fixed size     |
68 // | including spill slots             |
69 // |-----------------------------------| <- base pointer (not defined by ABI,
70 // |.variable-sized.local.variables....|       LLVM chooses r6)
71 // |.(VLAs)............................| (size of this area is unknown at
72 // |...................................|  compile time)
73 // |-----------------------------------| <- sp
74 // |                                   | Lower address
75 //
76 //
77 // To access the data in a frame, at-compile time, a constant offset must be
78 // computable from one of the pointers (fp, bp, sp) to access it. The size
79 // of the areas with a dotted background cannot be computed at compile-time
80 // if they are present, making it required to have all three of fp, bp and
81 // sp to be set up to be able to access all contents in the frame areas,
82 // assuming all of the frame areas are non-empty.
83 //
84 // For most functions, some of the frame areas are empty. For those functions,
85 // it may not be necessary to set up fp or bp:
86 // * A base pointer is definitely needed when there are both VLAs and local
87 //   variables with more-than-default alignment requirements.
88 // * A frame pointer is definitely needed when there are local variables with
89 //   more-than-default alignment requirements.
90 //
91 // In some cases when a base pointer is not strictly needed, it is generated
92 // anyway when offsets from the frame pointer to access local variables become
93 // so large that the offset can't be encoded in the immediate fields of loads
94 // or stores.
95 //
96 // The frame pointer might be chosen to be r7 or r11, depending on the target
97 // architecture and operating system. See ARMSubtarget::useR7AsFramePointer for
98 // details.
99 //
100 // Outgoing function arguments must be at the bottom of the stack frame when
101 // calling another function. If we do not have variable-sized stack objects, we
102 // can allocate a "reserved call frame" area at the bottom of the local
103 // variable area, large enough for all outgoing calls. If we do have VLAs, then
104 // the stack pointer must be decremented and incremented around each call to
105 // make space for the arguments below the VLAs.
106 //
107 //===----------------------------------------------------------------------===//
108 
109 #include "ARMFrameLowering.h"
110 #include "ARMBaseInstrInfo.h"
111 #include "ARMBaseRegisterInfo.h"
112 #include "ARMConstantPoolValue.h"
113 #include "ARMMachineFunctionInfo.h"
114 #include "ARMSubtarget.h"
115 #include "MCTargetDesc/ARMAddressingModes.h"
116 #include "MCTargetDesc/ARMBaseInfo.h"
117 #include "Utils/ARMBaseInfo.h"
118 #include "llvm/ADT/BitVector.h"
119 #include "llvm/ADT/STLExtras.h"
120 #include "llvm/ADT/SmallPtrSet.h"
121 #include "llvm/ADT/SmallVector.h"
122 #include "llvm/CodeGen/MachineBasicBlock.h"
123 #include "llvm/CodeGen/MachineConstantPool.h"
124 #include "llvm/CodeGen/MachineFrameInfo.h"
125 #include "llvm/CodeGen/MachineFunction.h"
126 #include "llvm/CodeGen/MachineInstr.h"
127 #include "llvm/CodeGen/MachineInstrBuilder.h"
128 #include "llvm/CodeGen/MachineJumpTableInfo.h"
129 #include "llvm/CodeGen/MachineModuleInfo.h"
130 #include "llvm/CodeGen/MachineOperand.h"
131 #include "llvm/CodeGen/MachineRegisterInfo.h"
132 #include "llvm/CodeGen/RegisterScavenging.h"
133 #include "llvm/CodeGen/TargetInstrInfo.h"
134 #include "llvm/CodeGen/TargetOpcodes.h"
135 #include "llvm/CodeGen/TargetRegisterInfo.h"
136 #include "llvm/CodeGen/TargetSubtargetInfo.h"
137 #include "llvm/IR/Attributes.h"
138 #include "llvm/IR/CallingConv.h"
139 #include "llvm/IR/DebugLoc.h"
140 #include "llvm/IR/Function.h"
141 #include "llvm/MC/MCContext.h"
142 #include "llvm/MC/MCDwarf.h"
143 #include "llvm/MC/MCInstrDesc.h"
144 #include "llvm/MC/MCRegisterInfo.h"
145 #include "llvm/Support/CodeGen.h"
146 #include "llvm/Support/CommandLine.h"
147 #include "llvm/Support/Compiler.h"
148 #include "llvm/Support/Debug.h"
149 #include "llvm/Support/ErrorHandling.h"
150 #include "llvm/Support/MathExtras.h"
151 #include "llvm/Support/raw_ostream.h"
152 #include "llvm/Target/TargetMachine.h"
153 #include "llvm/Target/TargetOptions.h"
154 #include <algorithm>
155 #include <cassert>
156 #include <cstddef>
157 #include <cstdint>
158 #include <iterator>
159 #include <utility>
160 #include <vector>
161 
162 #define DEBUG_TYPE "arm-frame-lowering"
163 
164 using namespace llvm;
165 
166 static cl::opt<bool>
167 SpillAlignedNEONRegs("align-neon-spills", cl::Hidden, cl::init(true),
168                      cl::desc("Align ARM NEON spills in prolog and epilog"));
169 
170 static MachineBasicBlock::iterator
171 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
172                         unsigned NumAlignedDPRCS2Regs);
173 
ARMFrameLowering(const ARMSubtarget & sti)174 ARMFrameLowering::ARMFrameLowering(const ARMSubtarget &sti)
175     : TargetFrameLowering(StackGrowsDown, sti.getStackAlignment(), 0, Align(4)),
176       STI(sti) {}
177 
keepFramePointer(const MachineFunction & MF) const178 bool ARMFrameLowering::keepFramePointer(const MachineFunction &MF) const {
179   // iOS always has a FP for backtracking, force other targets to keep their FP
180   // when doing FastISel. The emitted code is currently superior, and in cases
181   // like test-suite's lencod FastISel isn't quite correct when FP is eliminated.
182   return MF.getSubtarget<ARMSubtarget>().useFastISel();
183 }
184 
185 /// Returns true if the target can safely skip saving callee-saved registers
186 /// for noreturn nounwind functions.
enableCalleeSaveSkip(const MachineFunction & MF) const187 bool ARMFrameLowering::enableCalleeSaveSkip(const MachineFunction &MF) const {
188   assert(MF.getFunction().hasFnAttribute(Attribute::NoReturn) &&
189          MF.getFunction().hasFnAttribute(Attribute::NoUnwind) &&
190          !MF.getFunction().hasFnAttribute(Attribute::UWTable));
191 
192   // Frame pointer and link register are not treated as normal CSR, thus we
193   // can always skip CSR saves for nonreturning functions.
194   return true;
195 }
196 
197 /// hasFP - Return true if the specified function should have a dedicated frame
198 /// pointer register.  This is true if the function has variable sized allocas
199 /// or if frame pointer elimination is disabled.
hasFP(const MachineFunction & MF) const200 bool ARMFrameLowering::hasFP(const MachineFunction &MF) const {
201   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
202   const MachineFrameInfo &MFI = MF.getFrameInfo();
203 
204   // ABI-required frame pointer.
205   if (MF.getTarget().Options.DisableFramePointerElim(MF))
206     return true;
207 
208   // Frame pointer required for use within this function.
209   return (RegInfo->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
210           MFI.isFrameAddressTaken());
211 }
212 
213 /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
214 /// not required, we reserve argument space for call sites in the function
215 /// immediately on entry to the current function.  This eliminates the need for
216 /// add/sub sp brackets around call sites.  Returns true if the call frame is
217 /// included as part of the stack frame.
hasReservedCallFrame(const MachineFunction & MF) const218 bool ARMFrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
219   const MachineFrameInfo &MFI = MF.getFrameInfo();
220   unsigned CFSize = MFI.getMaxCallFrameSize();
221   // It's not always a good idea to include the call frame as part of the
222   // stack frame. ARM (especially Thumb) has small immediate offset to
223   // address the stack frame. So a large call frame can cause poor codegen
224   // and may even makes it impossible to scavenge a register.
225   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
226     return false;
227 
228   return !MFI.hasVarSizedObjects();
229 }
230 
231 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
232 /// call frame pseudos can be simplified.  Unlike most targets, having a FP
233 /// is not sufficient here since we still may reference some objects via SP
234 /// even when FP is available in Thumb2 mode.
235 bool
canSimplifyCallFramePseudos(const MachineFunction & MF) const236 ARMFrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
237   return hasReservedCallFrame(MF) || MF.getFrameInfo().hasVarSizedObjects();
238 }
239 
emitRegPlusImmediate(bool isARM,MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,const DebugLoc & dl,const ARMBaseInstrInfo & TII,unsigned DestReg,unsigned SrcReg,int NumBytes,unsigned MIFlags=MachineInstr::NoFlags,ARMCC::CondCodes Pred=ARMCC::AL,unsigned PredReg=0)240 static void emitRegPlusImmediate(
241     bool isARM, MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
242     const DebugLoc &dl, const ARMBaseInstrInfo &TII, unsigned DestReg,
243     unsigned SrcReg, int NumBytes, unsigned MIFlags = MachineInstr::NoFlags,
244     ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
245   if (isARM)
246     emitARMRegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
247                             Pred, PredReg, TII, MIFlags);
248   else
249     emitT2RegPlusImmediate(MBB, MBBI, dl, DestReg, SrcReg, NumBytes,
250                            Pred, PredReg, TII, MIFlags);
251 }
252 
emitSPUpdate(bool isARM,MachineBasicBlock & MBB,MachineBasicBlock::iterator & MBBI,const DebugLoc & dl,const ARMBaseInstrInfo & TII,int NumBytes,unsigned MIFlags=MachineInstr::NoFlags,ARMCC::CondCodes Pred=ARMCC::AL,unsigned PredReg=0)253 static void emitSPUpdate(bool isARM, MachineBasicBlock &MBB,
254                          MachineBasicBlock::iterator &MBBI, const DebugLoc &dl,
255                          const ARMBaseInstrInfo &TII, int NumBytes,
256                          unsigned MIFlags = MachineInstr::NoFlags,
257                          ARMCC::CondCodes Pred = ARMCC::AL,
258                          unsigned PredReg = 0) {
259   emitRegPlusImmediate(isARM, MBB, MBBI, dl, TII, ARM::SP, ARM::SP, NumBytes,
260                        MIFlags, Pred, PredReg);
261 }
262 
sizeOfSPAdjustment(const MachineInstr & MI)263 static int sizeOfSPAdjustment(const MachineInstr &MI) {
264   int RegSize;
265   switch (MI.getOpcode()) {
266   case ARM::VSTMDDB_UPD:
267     RegSize = 8;
268     break;
269   case ARM::STMDB_UPD:
270   case ARM::t2STMDB_UPD:
271     RegSize = 4;
272     break;
273   case ARM::t2STR_PRE:
274   case ARM::STR_PRE_IMM:
275     return 4;
276   default:
277     llvm_unreachable("Unknown push or pop like instruction");
278   }
279 
280   int count = 0;
281   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
282   // pred) so the list starts at 4.
283   for (int i = MI.getNumOperands() - 1; i >= 4; --i)
284     count += RegSize;
285   return count;
286 }
287 
WindowsRequiresStackProbe(const MachineFunction & MF,size_t StackSizeInBytes)288 static bool WindowsRequiresStackProbe(const MachineFunction &MF,
289                                       size_t StackSizeInBytes) {
290   const MachineFrameInfo &MFI = MF.getFrameInfo();
291   const Function &F = MF.getFunction();
292   unsigned StackProbeSize = (MFI.getStackProtectorIndex() > 0) ? 4080 : 4096;
293   if (F.hasFnAttribute("stack-probe-size"))
294     F.getFnAttribute("stack-probe-size")
295         .getValueAsString()
296         .getAsInteger(0, StackProbeSize);
297   return (StackSizeInBytes >= StackProbeSize) &&
298          !F.hasFnAttribute("no-stack-arg-probe");
299 }
300 
301 namespace {
302 
303 struct StackAdjustingInsts {
304   struct InstInfo {
305     MachineBasicBlock::iterator I;
306     unsigned SPAdjust;
307     bool BeforeFPSet;
308   };
309 
310   SmallVector<InstInfo, 4> Insts;
311 
addInst__anonc5e3ca320111::StackAdjustingInsts312   void addInst(MachineBasicBlock::iterator I, unsigned SPAdjust,
313                bool BeforeFPSet = false) {
314     InstInfo Info = {I, SPAdjust, BeforeFPSet};
315     Insts.push_back(Info);
316   }
317 
addExtraBytes__anonc5e3ca320111::StackAdjustingInsts318   void addExtraBytes(const MachineBasicBlock::iterator I, unsigned ExtraBytes) {
319     auto Info =
320         llvm::find_if(Insts, [&](InstInfo &Info) { return Info.I == I; });
321     assert(Info != Insts.end() && "invalid sp adjusting instruction");
322     Info->SPAdjust += ExtraBytes;
323   }
324 
emitDefCFAOffsets__anonc5e3ca320111::StackAdjustingInsts325   void emitDefCFAOffsets(MachineBasicBlock &MBB, const DebugLoc &dl,
326                          const ARMBaseInstrInfo &TII, bool HasFP) {
327     MachineFunction &MF = *MBB.getParent();
328     unsigned CFAOffset = 0;
329     for (auto &Info : Insts) {
330       if (HasFP && !Info.BeforeFPSet)
331         return;
332 
333       CFAOffset += Info.SPAdjust;
334       unsigned CFIIndex = MF.addFrameInst(
335           MCCFIInstruction::cfiDefCfaOffset(nullptr, CFAOffset));
336       BuildMI(MBB, std::next(Info.I), dl,
337               TII.get(TargetOpcode::CFI_INSTRUCTION))
338               .addCFIIndex(CFIIndex)
339               .setMIFlags(MachineInstr::FrameSetup);
340     }
341   }
342 };
343 
344 } // end anonymous namespace
345 
346 /// Emit an instruction sequence that will align the address in
347 /// register Reg by zero-ing out the lower bits.  For versions of the
348 /// architecture that support Neon, this must be done in a single
349 /// instruction, since skipAlignedDPRCS2Spills assumes it is done in a
350 /// single instruction. That function only gets called when optimizing
351 /// spilling of D registers on a core with the Neon instruction set
352 /// present.
emitAligningInstructions(MachineFunction & MF,ARMFunctionInfo * AFI,const TargetInstrInfo & TII,MachineBasicBlock & MBB,MachineBasicBlock::iterator MBBI,const DebugLoc & DL,const unsigned Reg,const Align Alignment,const bool MustBeSingleInstruction)353 static void emitAligningInstructions(MachineFunction &MF, ARMFunctionInfo *AFI,
354                                      const TargetInstrInfo &TII,
355                                      MachineBasicBlock &MBB,
356                                      MachineBasicBlock::iterator MBBI,
357                                      const DebugLoc &DL, const unsigned Reg,
358                                      const Align Alignment,
359                                      const bool MustBeSingleInstruction) {
360   const ARMSubtarget &AST =
361       static_cast<const ARMSubtarget &>(MF.getSubtarget());
362   const bool CanUseBFC = AST.hasV6T2Ops() || AST.hasV7Ops();
363   const unsigned AlignMask = Alignment.value() - 1U;
364   const unsigned NrBitsToZero = Log2(Alignment);
365   assert(!AFI->isThumb1OnlyFunction() && "Thumb1 not supported");
366   if (!AFI->isThumbFunction()) {
367     // if the BFC instruction is available, use that to zero the lower
368     // bits:
369     //   bfc Reg, #0, log2(Alignment)
370     // otherwise use BIC, if the mask to zero the required number of bits
371     // can be encoded in the bic immediate field
372     //   bic Reg, Reg, Alignment-1
373     // otherwise, emit
374     //   lsr Reg, Reg, log2(Alignment)
375     //   lsl Reg, Reg, log2(Alignment)
376     if (CanUseBFC) {
377       BuildMI(MBB, MBBI, DL, TII.get(ARM::BFC), Reg)
378           .addReg(Reg, RegState::Kill)
379           .addImm(~AlignMask)
380           .add(predOps(ARMCC::AL));
381     } else if (AlignMask <= 255) {
382       BuildMI(MBB, MBBI, DL, TII.get(ARM::BICri), Reg)
383           .addReg(Reg, RegState::Kill)
384           .addImm(AlignMask)
385           .add(predOps(ARMCC::AL))
386           .add(condCodeOp());
387     } else {
388       assert(!MustBeSingleInstruction &&
389              "Shouldn't call emitAligningInstructions demanding a single "
390              "instruction to be emitted for large stack alignment for a target "
391              "without BFC.");
392       BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
393           .addReg(Reg, RegState::Kill)
394           .addImm(ARM_AM::getSORegOpc(ARM_AM::lsr, NrBitsToZero))
395           .add(predOps(ARMCC::AL))
396           .add(condCodeOp());
397       BuildMI(MBB, MBBI, DL, TII.get(ARM::MOVsi), Reg)
398           .addReg(Reg, RegState::Kill)
399           .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, NrBitsToZero))
400           .add(predOps(ARMCC::AL))
401           .add(condCodeOp());
402     }
403   } else {
404     // Since this is only reached for Thumb-2 targets, the BFC instruction
405     // should always be available.
406     assert(CanUseBFC);
407     BuildMI(MBB, MBBI, DL, TII.get(ARM::t2BFC), Reg)
408         .addReg(Reg, RegState::Kill)
409         .addImm(~AlignMask)
410         .add(predOps(ARMCC::AL));
411   }
412 }
413 
414 /// We need the offset of the frame pointer relative to other MachineFrameInfo
415 /// offsets which are encoded relative to SP at function begin.
416 /// See also emitPrologue() for how the FP is set up.
417 /// Unfortunately we cannot determine this value in determineCalleeSaves() yet
418 /// as assignCalleeSavedSpillSlots() hasn't run at this point. Instead we use
419 /// this to produce a conservative estimate that we check in an assert() later.
getMaxFPOffset(const ARMSubtarget & STI,const ARMFunctionInfo & AFI)420 static int getMaxFPOffset(const ARMSubtarget &STI, const ARMFunctionInfo &AFI) {
421   // For Thumb1, push.w isn't available, so the first push will always push
422   // r7 and lr onto the stack first.
423   if (AFI.isThumb1OnlyFunction())
424     return -AFI.getArgRegsSaveSize() - (2 * 4);
425   // This is a conservative estimation: Assume the frame pointer being r7 and
426   // pc("r15") up to r8 getting spilled before (= 8 registers).
427   int FPCXTSaveSize = (STI.hasV8_1MMainlineOps() && AFI.isCmseNSEntryFunction()) ? 4 : 0;
428   return - FPCXTSaveSize - AFI.getArgRegsSaveSize() - (8 * 4);
429 }
430 
emitPrologue(MachineFunction & MF,MachineBasicBlock & MBB) const431 void ARMFrameLowering::emitPrologue(MachineFunction &MF,
432                                     MachineBasicBlock &MBB) const {
433   MachineBasicBlock::iterator MBBI = MBB.begin();
434   MachineFrameInfo  &MFI = MF.getFrameInfo();
435   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
436   MachineModuleInfo &MMI = MF.getMMI();
437   MCContext &Context = MMI.getContext();
438   const TargetMachine &TM = MF.getTarget();
439   const MCRegisterInfo *MRI = Context.getRegisterInfo();
440   const ARMBaseRegisterInfo *RegInfo = STI.getRegisterInfo();
441   const ARMBaseInstrInfo &TII = *STI.getInstrInfo();
442   assert(!AFI->isThumb1OnlyFunction() &&
443          "This emitPrologue does not support Thumb1!");
444   bool isARM = !AFI->isThumbFunction();
445   Align Alignment = STI.getFrameLowering()->getStackAlign();
446   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
447   unsigned NumBytes = MFI.getStackSize();
448   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
449   int FPCXTSaveSize = 0;
450 
451   // Debug location must be unknown since the first debug location is used
452   // to determine the end of the prologue.
453   DebugLoc dl;
454 
455   Register FramePtr = RegInfo->getFrameRegister(MF);
456 
457   // Determine the sizes of each callee-save spill areas and record which frame
458   // belongs to which callee-save spill areas.
459   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
460   int FramePtrSpillFI = 0;
461   int D8SpillFI = 0;
462 
463   // All calls are tail calls in GHC calling conv, and functions have no
464   // prologue/epilogue.
465   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
466     return;
467 
468   StackAdjustingInsts DefCFAOffsetCandidates;
469   bool HasFP = hasFP(MF);
470 
471   // Allocate the vararg register save area.
472   if (ArgRegsSaveSize) {
473     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -ArgRegsSaveSize,
474                  MachineInstr::FrameSetup);
475     DefCFAOffsetCandidates.addInst(std::prev(MBBI), ArgRegsSaveSize, true);
476   }
477 
478   if (!AFI->hasStackFrame() &&
479       (!STI.isTargetWindows() || !WindowsRequiresStackProbe(MF, NumBytes))) {
480     if (NumBytes - ArgRegsSaveSize != 0) {
481       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -(NumBytes - ArgRegsSaveSize),
482                    MachineInstr::FrameSetup);
483       DefCFAOffsetCandidates.addInst(std::prev(MBBI),
484                                      NumBytes - ArgRegsSaveSize, true);
485     }
486     DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
487     return;
488   }
489 
490   // Determine spill area sizes.
491   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
492     unsigned Reg = CSI[i].getReg();
493     int FI = CSI[i].getFrameIdx();
494     switch (Reg) {
495     case ARM::R8:
496     case ARM::R9:
497     case ARM::R10:
498     case ARM::R11:
499     case ARM::R12:
500       if (STI.splitFramePushPop(MF)) {
501         GPRCS2Size += 4;
502         break;
503       }
504       LLVM_FALLTHROUGH;
505     case ARM::R0:
506     case ARM::R1:
507     case ARM::R2:
508     case ARM::R3:
509     case ARM::R4:
510     case ARM::R5:
511     case ARM::R6:
512     case ARM::R7:
513     case ARM::LR:
514       if (Reg == FramePtr)
515         FramePtrSpillFI = FI;
516       GPRCS1Size += 4;
517       break;
518     case ARM::FPCXTNS:
519       FPCXTSaveSize = 4;
520       break;
521     default:
522       // This is a DPR. Exclude the aligned DPRCS2 spills.
523       if (Reg == ARM::D8)
524         D8SpillFI = FI;
525       if (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())
526         DPRCSSize += 8;
527     }
528   }
529 
530   // Move past FPCXT area.
531   MachineBasicBlock::iterator LastPush = MBB.end(), GPRCS1Push, GPRCS2Push;
532   if (FPCXTSaveSize > 0) {
533     LastPush = MBBI++;
534     DefCFAOffsetCandidates.addInst(LastPush, FPCXTSaveSize, true);
535   }
536 
537   // Move past area 1.
538   if (GPRCS1Size > 0) {
539     GPRCS1Push = LastPush = MBBI++;
540     DefCFAOffsetCandidates.addInst(LastPush, GPRCS1Size, true);
541   }
542 
543   // Determine starting offsets of spill areas.
544   unsigned FPCXTOffset = NumBytes - ArgRegsSaveSize - FPCXTSaveSize;
545   unsigned GPRCS1Offset = FPCXTOffset - GPRCS1Size;
546   unsigned GPRCS2Offset = GPRCS1Offset - GPRCS2Size;
547   Align DPRAlign = DPRCSSize ? std::min(Align(8), Alignment) : Align(4);
548   unsigned DPRGapSize =
549       (GPRCS1Size + GPRCS2Size + FPCXTSaveSize + ArgRegsSaveSize) %
550       DPRAlign.value();
551 
552   unsigned DPRCSOffset = GPRCS2Offset - DPRGapSize - DPRCSSize;
553   int FramePtrOffsetInPush = 0;
554   if (HasFP) {
555     int FPOffset = MFI.getObjectOffset(FramePtrSpillFI);
556     assert(getMaxFPOffset(STI, *AFI) <= FPOffset &&
557            "Max FP estimation is wrong");
558     FramePtrOffsetInPush = FPOffset + ArgRegsSaveSize + FPCXTSaveSize;
559     AFI->setFramePtrSpillOffset(MFI.getObjectOffset(FramePtrSpillFI) +
560                                 NumBytes);
561   }
562   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
563   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
564   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
565 
566   // Move past area 2.
567   if (GPRCS2Size > 0) {
568     GPRCS2Push = LastPush = MBBI++;
569     DefCFAOffsetCandidates.addInst(LastPush, GPRCS2Size);
570   }
571 
572   // Prolog/epilog inserter assumes we correctly align DPRs on the stack, so our
573   // .cfi_offset operations will reflect that.
574   if (DPRGapSize) {
575     assert(DPRGapSize == 4 && "unexpected alignment requirements for DPRs");
576     if (LastPush != MBB.end() &&
577         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, DPRGapSize))
578       DefCFAOffsetCandidates.addExtraBytes(LastPush, DPRGapSize);
579     else {
580       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRGapSize,
581                    MachineInstr::FrameSetup);
582       DefCFAOffsetCandidates.addInst(std::prev(MBBI), DPRGapSize);
583     }
584   }
585 
586   // Move past area 3.
587   if (DPRCSSize > 0) {
588     // Since vpush register list cannot have gaps, there may be multiple vpush
589     // instructions in the prologue.
590     while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VSTMDDB_UPD) {
591       DefCFAOffsetCandidates.addInst(MBBI, sizeOfSPAdjustment(*MBBI));
592       LastPush = MBBI++;
593     }
594   }
595 
596   // Move past the aligned DPRCS2 area.
597   if (AFI->getNumAlignedDPRCS2Regs() > 0) {
598     MBBI = skipAlignedDPRCS2Spills(MBBI, AFI->getNumAlignedDPRCS2Regs());
599     // The code inserted by emitAlignedDPRCS2Spills realigns the stack, and
600     // leaves the stack pointer pointing to the DPRCS2 area.
601     //
602     // Adjust NumBytes to represent the stack slots below the DPRCS2 area.
603     NumBytes += MFI.getObjectOffset(D8SpillFI);
604   } else
605     NumBytes = DPRCSOffset;
606 
607   if (STI.isTargetWindows() && WindowsRequiresStackProbe(MF, NumBytes)) {
608     uint32_t NumWords = NumBytes >> 2;
609 
610     if (NumWords < 65536)
611       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi16), ARM::R4)
612           .addImm(NumWords)
613           .setMIFlags(MachineInstr::FrameSetup)
614           .add(predOps(ARMCC::AL));
615     else
616       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R4)
617         .addImm(NumWords)
618         .setMIFlags(MachineInstr::FrameSetup);
619 
620     switch (TM.getCodeModel()) {
621     case CodeModel::Tiny:
622       llvm_unreachable("Tiny code model not available on ARM.");
623     case CodeModel::Small:
624     case CodeModel::Medium:
625     case CodeModel::Kernel:
626       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBL))
627           .add(predOps(ARMCC::AL))
628           .addExternalSymbol("__chkstk")
629           .addReg(ARM::R4, RegState::Implicit)
630           .setMIFlags(MachineInstr::FrameSetup);
631       break;
632     case CodeModel::Large:
633       BuildMI(MBB, MBBI, dl, TII.get(ARM::t2MOVi32imm), ARM::R12)
634         .addExternalSymbol("__chkstk")
635         .setMIFlags(MachineInstr::FrameSetup);
636 
637       BuildMI(MBB, MBBI, dl, TII.get(ARM::tBLXr))
638           .add(predOps(ARMCC::AL))
639           .addReg(ARM::R12, RegState::Kill)
640           .addReg(ARM::R4, RegState::Implicit)
641           .setMIFlags(MachineInstr::FrameSetup);
642       break;
643     }
644 
645     BuildMI(MBB, MBBI, dl, TII.get(ARM::t2SUBrr), ARM::SP)
646         .addReg(ARM::SP, RegState::Kill)
647         .addReg(ARM::R4, RegState::Kill)
648         .setMIFlags(MachineInstr::FrameSetup)
649         .add(predOps(ARMCC::AL))
650         .add(condCodeOp());
651     NumBytes = 0;
652   }
653 
654   if (NumBytes) {
655     // Adjust SP after all the callee-save spills.
656     if (AFI->getNumAlignedDPRCS2Regs() == 0 &&
657         tryFoldSPUpdateIntoPushPop(STI, MF, &*LastPush, NumBytes))
658       DefCFAOffsetCandidates.addExtraBytes(LastPush, NumBytes);
659     else {
660       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes,
661                    MachineInstr::FrameSetup);
662       DefCFAOffsetCandidates.addInst(std::prev(MBBI), NumBytes);
663     }
664 
665     if (HasFP && isARM)
666       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
667       // Note it's not safe to do this in Thumb2 mode because it would have
668       // taken two instructions:
669       // mov sp, r7
670       // sub sp, #24
671       // If an interrupt is taken between the two instructions, then sp is in
672       // an inconsistent state (pointing to the middle of callee-saved area).
673       // The interrupt handler can end up clobbering the registers.
674       AFI->setShouldRestoreSPFromFP(true);
675   }
676 
677   // Set FP to point to the stack slot that contains the previous FP.
678   // For iOS, FP is R7, which has now been stored in spill area 1.
679   // Otherwise, if this is not iOS, all the callee-saved registers go
680   // into spill area 1, including the FP in R11.  In either case, it
681   // is in area one and the adjustment needs to take place just after
682   // that push.
683   if (HasFP) {
684     MachineBasicBlock::iterator AfterPush = std::next(GPRCS1Push);
685     unsigned PushSize = sizeOfSPAdjustment(*GPRCS1Push);
686     emitRegPlusImmediate(!AFI->isThumbFunction(), MBB, AfterPush,
687                          dl, TII, FramePtr, ARM::SP,
688                          PushSize + FramePtrOffsetInPush,
689                          MachineInstr::FrameSetup);
690     if (FramePtrOffsetInPush + PushSize != 0) {
691       unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfa(
692           nullptr, MRI->getDwarfRegNum(FramePtr, true),
693           FPCXTSaveSize + ArgRegsSaveSize - FramePtrOffsetInPush));
694       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
695           .addCFIIndex(CFIIndex)
696           .setMIFlags(MachineInstr::FrameSetup);
697     } else {
698       unsigned CFIIndex =
699           MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(
700               nullptr, MRI->getDwarfRegNum(FramePtr, true)));
701       BuildMI(MBB, AfterPush, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
702           .addCFIIndex(CFIIndex)
703           .setMIFlags(MachineInstr::FrameSetup);
704     }
705   }
706 
707   // Now that the prologue's actual instructions are finalised, we can insert
708   // the necessary DWARF cf instructions to describe the situation. Start by
709   // recording where each register ended up:
710   if (GPRCS1Size > 0) {
711     MachineBasicBlock::iterator Pos = std::next(GPRCS1Push);
712     int CFIIndex;
713     for (const auto &Entry : CSI) {
714       unsigned Reg = Entry.getReg();
715       int FI = Entry.getFrameIdx();
716       switch (Reg) {
717       case ARM::R8:
718       case ARM::R9:
719       case ARM::R10:
720       case ARM::R11:
721       case ARM::R12:
722         if (STI.splitFramePushPop(MF))
723           break;
724         LLVM_FALLTHROUGH;
725       case ARM::R0:
726       case ARM::R1:
727       case ARM::R2:
728       case ARM::R3:
729       case ARM::R4:
730       case ARM::R5:
731       case ARM::R6:
732       case ARM::R7:
733       case ARM::LR:
734         CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
735             nullptr, MRI->getDwarfRegNum(Reg, true), MFI.getObjectOffset(FI)));
736         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
737             .addCFIIndex(CFIIndex)
738             .setMIFlags(MachineInstr::FrameSetup);
739         break;
740       }
741     }
742   }
743 
744   if (GPRCS2Size > 0) {
745     MachineBasicBlock::iterator Pos = std::next(GPRCS2Push);
746     for (const auto &Entry : CSI) {
747       unsigned Reg = Entry.getReg();
748       int FI = Entry.getFrameIdx();
749       switch (Reg) {
750       case ARM::R8:
751       case ARM::R9:
752       case ARM::R10:
753       case ARM::R11:
754       case ARM::R12:
755         if (STI.splitFramePushPop(MF)) {
756           unsigned DwarfReg =  MRI->getDwarfRegNum(Reg, true);
757           unsigned Offset = MFI.getObjectOffset(FI);
758           unsigned CFIIndex = MF.addFrameInst(
759               MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
760           BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
761               .addCFIIndex(CFIIndex)
762               .setMIFlags(MachineInstr::FrameSetup);
763         }
764         break;
765       }
766     }
767   }
768 
769   if (DPRCSSize > 0) {
770     // Since vpush register list cannot have gaps, there may be multiple vpush
771     // instructions in the prologue.
772     MachineBasicBlock::iterator Pos = std::next(LastPush);
773     for (const auto &Entry : CSI) {
774       unsigned Reg = Entry.getReg();
775       int FI = Entry.getFrameIdx();
776       if ((Reg >= ARM::D0 && Reg <= ARM::D31) &&
777           (Reg < ARM::D8 || Reg >= ARM::D8 + AFI->getNumAlignedDPRCS2Regs())) {
778         unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
779         unsigned Offset = MFI.getObjectOffset(FI);
780         unsigned CFIIndex = MF.addFrameInst(
781             MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
782         BuildMI(MBB, Pos, dl, TII.get(TargetOpcode::CFI_INSTRUCTION))
783             .addCFIIndex(CFIIndex)
784             .setMIFlags(MachineInstr::FrameSetup);
785       }
786     }
787   }
788 
789   // Now we can emit descriptions of where the canonical frame address was
790   // throughout the process. If we have a frame pointer, it takes over the job
791   // half-way through, so only the first few .cfi_def_cfa_offset instructions
792   // actually get emitted.
793   DefCFAOffsetCandidates.emitDefCFAOffsets(MBB, dl, TII, HasFP);
794 
795   if (STI.isTargetELF() && hasFP(MF))
796     MFI.setOffsetAdjustment(MFI.getOffsetAdjustment() -
797                             AFI->getFramePtrSpillOffset());
798 
799   AFI->setFPCXTSaveAreaSize(FPCXTSaveSize);
800   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
801   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
802   AFI->setDPRCalleeSavedGapSize(DPRGapSize);
803   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
804 
805   // If we need dynamic stack realignment, do it here. Be paranoid and make
806   // sure if we also have VLAs, we have a base pointer for frame access.
807   // If aligned NEON registers were spilled, the stack has already been
808   // realigned.
809   if (!AFI->getNumAlignedDPRCS2Regs() && RegInfo->hasStackRealignment(MF)) {
810     Align MaxAlign = MFI.getMaxAlign();
811     assert(!AFI->isThumb1OnlyFunction());
812     if (!AFI->isThumbFunction()) {
813       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::SP, MaxAlign,
814                                false);
815     } else {
816       // We cannot use sp as source/dest register here, thus we're using r4 to
817       // perform the calculations. We're emitting the following sequence:
818       // mov r4, sp
819       // -- use emitAligningInstructions to produce best sequence to zero
820       // -- out lower bits in r4
821       // mov sp, r4
822       // FIXME: It will be better just to find spare register here.
823       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::R4)
824           .addReg(ARM::SP, RegState::Kill)
825           .add(predOps(ARMCC::AL));
826       emitAligningInstructions(MF, AFI, TII, MBB, MBBI, dl, ARM::R4, MaxAlign,
827                                false);
828       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
829           .addReg(ARM::R4, RegState::Kill)
830           .add(predOps(ARMCC::AL));
831     }
832 
833     AFI->setShouldRestoreSPFromFP(true);
834   }
835 
836   // If we need a base pointer, set it up here. It's whatever the value
837   // of the stack pointer is at this point. Any variable size objects
838   // will be allocated after this, so we can still use the base pointer
839   // to reference locals.
840   // FIXME: Clarify FrameSetup flags here.
841   if (RegInfo->hasBasePointer(MF)) {
842     if (isARM)
843       BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), RegInfo->getBaseRegister())
844           .addReg(ARM::SP)
845           .add(predOps(ARMCC::AL))
846           .add(condCodeOp());
847     else
848       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), RegInfo->getBaseRegister())
849           .addReg(ARM::SP)
850           .add(predOps(ARMCC::AL));
851   }
852 
853   // If the frame has variable sized objects then the epilogue must restore
854   // the sp from fp. We can assume there's an FP here since hasFP already
855   // checks for hasVarSizedObjects.
856   if (MFI.hasVarSizedObjects())
857     AFI->setShouldRestoreSPFromFP(true);
858 }
859 
emitEpilogue(MachineFunction & MF,MachineBasicBlock & MBB) const860 void ARMFrameLowering::emitEpilogue(MachineFunction &MF,
861                                     MachineBasicBlock &MBB) const {
862   MachineFrameInfo &MFI = MF.getFrameInfo();
863   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
864   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
865   const ARMBaseInstrInfo &TII =
866       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
867   assert(!AFI->isThumb1OnlyFunction() &&
868          "This emitEpilogue does not support Thumb1!");
869   bool isARM = !AFI->isThumbFunction();
870 
871   unsigned ArgRegsSaveSize = AFI->getArgRegsSaveSize();
872   int NumBytes = (int)MFI.getStackSize();
873   Register FramePtr = RegInfo->getFrameRegister(MF);
874 
875   // All calls are tail calls in GHC calling conv, and functions have no
876   // prologue/epilogue.
877   if (MF.getFunction().getCallingConv() == CallingConv::GHC)
878     return;
879 
880   // First put ourselves on the first (from top) terminator instructions.
881   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
882   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
883 
884   if (!AFI->hasStackFrame()) {
885     if (NumBytes - ArgRegsSaveSize != 0)
886       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes - ArgRegsSaveSize,
887                    MachineInstr::FrameDestroy);
888   } else {
889     // Unwind MBBI to point to first LDR / VLDRD.
890     if (MBBI != MBB.begin()) {
891       do {
892         --MBBI;
893       } while (MBBI != MBB.begin() &&
894                MBBI->getFlag(MachineInstr::FrameDestroy));
895       if (!MBBI->getFlag(MachineInstr::FrameDestroy))
896         ++MBBI;
897     }
898 
899     // Move SP to start of FP callee save spill area.
900     NumBytes -= (ArgRegsSaveSize +
901                  AFI->getFPCXTSaveAreaSize() +
902                  AFI->getGPRCalleeSavedArea1Size() +
903                  AFI->getGPRCalleeSavedArea2Size() +
904                  AFI->getDPRCalleeSavedGapSize() +
905                  AFI->getDPRCalleeSavedAreaSize());
906 
907     // Reset SP based on frame pointer only if the stack frame extends beyond
908     // frame pointer stack slot or target is ELF and the function has FP.
909     if (AFI->shouldRestoreSPFromFP()) {
910       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
911       if (NumBytes) {
912         if (isARM)
913           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
914                                   ARMCC::AL, 0, TII,
915                                   MachineInstr::FrameDestroy);
916         else {
917           // It's not possible to restore SP from FP in a single instruction.
918           // For iOS, this looks like:
919           // mov sp, r7
920           // sub sp, #24
921           // This is bad, if an interrupt is taken after the mov, sp is in an
922           // inconsistent state.
923           // Use the first callee-saved register as a scratch register.
924           assert(!MFI.getPristineRegs(MF).test(ARM::R4) &&
925                  "No scratch register to restore SP from FP!");
926           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
927                                  ARMCC::AL, 0, TII, MachineInstr::FrameDestroy);
928           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
929               .addReg(ARM::R4)
930               .add(predOps(ARMCC::AL))
931               .setMIFlag(MachineInstr::FrameDestroy);
932         }
933       } else {
934         // Thumb2 or ARM.
935         if (isARM)
936           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
937               .addReg(FramePtr)
938               .add(predOps(ARMCC::AL))
939               .add(condCodeOp())
940               .setMIFlag(MachineInstr::FrameDestroy);
941         else
942           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVr), ARM::SP)
943               .addReg(FramePtr)
944               .add(predOps(ARMCC::AL))
945               .setMIFlag(MachineInstr::FrameDestroy);
946       }
947     } else if (NumBytes &&
948                !tryFoldSPUpdateIntoPushPop(STI, MF, &*MBBI, NumBytes))
949       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes,
950                    MachineInstr::FrameDestroy);
951 
952     // Increment past our save areas.
953     if (MBBI != MBB.end() && AFI->getDPRCalleeSavedAreaSize()) {
954       MBBI++;
955       // Since vpop register list cannot have gaps, there may be multiple vpop
956       // instructions in the epilogue.
957       while (MBBI != MBB.end() && MBBI->getOpcode() == ARM::VLDMDIA_UPD)
958         MBBI++;
959     }
960     if (AFI->getDPRCalleeSavedGapSize()) {
961       assert(AFI->getDPRCalleeSavedGapSize() == 4 &&
962              "unexpected DPR alignment gap");
963       emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedGapSize(),
964                    MachineInstr::FrameDestroy);
965     }
966 
967     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
968     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
969     if (AFI->getFPCXTSaveAreaSize()) MBBI++;
970   }
971 
972   if (ArgRegsSaveSize)
973     emitSPUpdate(isARM, MBB, MBBI, dl, TII, ArgRegsSaveSize,
974                  MachineInstr::FrameDestroy);
975 }
976 
977 /// getFrameIndexReference - Provide a base+offset reference to an FI slot for
978 /// debug info.  It's the same as what we use for resolving the code-gen
979 /// references for now.  FIXME: This can go wrong when references are
980 /// SP-relative and simple call frames aren't used.
getFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg) const981 StackOffset ARMFrameLowering::getFrameIndexReference(const MachineFunction &MF,
982                                                      int FI,
983                                                      Register &FrameReg) const {
984   return StackOffset::getFixed(ResolveFrameIndexReference(MF, FI, FrameReg, 0));
985 }
986 
ResolveFrameIndexReference(const MachineFunction & MF,int FI,Register & FrameReg,int SPAdj) const987 int ARMFrameLowering::ResolveFrameIndexReference(const MachineFunction &MF,
988                                                  int FI, Register &FrameReg,
989                                                  int SPAdj) const {
990   const MachineFrameInfo &MFI = MF.getFrameInfo();
991   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
992       MF.getSubtarget().getRegisterInfo());
993   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
994   int Offset = MFI.getObjectOffset(FI) + MFI.getStackSize();
995   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
996   bool isFixed = MFI.isFixedObjectIndex(FI);
997 
998   FrameReg = ARM::SP;
999   Offset += SPAdj;
1000 
1001   // SP can move around if there are allocas.  We may also lose track of SP
1002   // when emergency spilling inside a non-reserved call frame setup.
1003   bool hasMovingSP = !hasReservedCallFrame(MF);
1004 
1005   // When dynamically realigning the stack, use the frame pointer for
1006   // parameters, and the stack/base pointer for locals.
1007   if (RegInfo->hasStackRealignment(MF)) {
1008     assert(hasFP(MF) && "dynamic stack realignment without a FP!");
1009     if (isFixed) {
1010       FrameReg = RegInfo->getFrameRegister(MF);
1011       Offset = FPOffset;
1012     } else if (hasMovingSP) {
1013       assert(RegInfo->hasBasePointer(MF) &&
1014              "VLAs and dynamic stack alignment, but missing base pointer!");
1015       FrameReg = RegInfo->getBaseRegister();
1016       Offset -= SPAdj;
1017     }
1018     return Offset;
1019   }
1020 
1021   // If there is a frame pointer, use it when we can.
1022   if (hasFP(MF) && AFI->hasStackFrame()) {
1023     // Use frame pointer to reference fixed objects. Use it for locals if
1024     // there are VLAs (and thus the SP isn't reliable as a base).
1025     if (isFixed || (hasMovingSP && !RegInfo->hasBasePointer(MF))) {
1026       FrameReg = RegInfo->getFrameRegister(MF);
1027       return FPOffset;
1028     } else if (hasMovingSP) {
1029       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
1030       if (AFI->isThumb2Function()) {
1031         // Try to use the frame pointer if we can, else use the base pointer
1032         // since it's available. This is handy for the emergency spill slot, in
1033         // particular.
1034         if (FPOffset >= -255 && FPOffset < 0) {
1035           FrameReg = RegInfo->getFrameRegister(MF);
1036           return FPOffset;
1037         }
1038       }
1039     } else if (AFI->isThumbFunction()) {
1040       // Prefer SP to base pointer, if the offset is suitably aligned and in
1041       // range as the effective range of the immediate offset is bigger when
1042       // basing off SP.
1043       // Use  add <rd>, sp, #<imm8>
1044       //      ldr <rd>, [sp, #<imm8>]
1045       if (Offset >= 0 && (Offset & 3) == 0 && Offset <= 1020)
1046         return Offset;
1047       // In Thumb2 mode, the negative offset is very limited. Try to avoid
1048       // out of range references. ldr <rt>,[<rn>, #-<imm8>]
1049       if (AFI->isThumb2Function() && FPOffset >= -255 && FPOffset < 0) {
1050         FrameReg = RegInfo->getFrameRegister(MF);
1051         return FPOffset;
1052       }
1053     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
1054       // Otherwise, use SP or FP, whichever is closer to the stack slot.
1055       FrameReg = RegInfo->getFrameRegister(MF);
1056       return FPOffset;
1057     }
1058   }
1059   // Use the base pointer if we have one.
1060   // FIXME: Maybe prefer sp on Thumb1 if it's legal and the offset is cheaper?
1061   // That can happen if we forced a base pointer for a large call frame.
1062   if (RegInfo->hasBasePointer(MF)) {
1063     FrameReg = RegInfo->getBaseRegister();
1064     Offset -= SPAdj;
1065   }
1066   return Offset;
1067 }
1068 
emitPushInst(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,ArrayRef<CalleeSavedInfo> CSI,unsigned StmOpc,unsigned StrOpc,bool NoGap,bool (* Func)(unsigned,bool),unsigned NumAlignedDPRCS2Regs,unsigned MIFlags) const1069 void ARMFrameLowering::emitPushInst(MachineBasicBlock &MBB,
1070                                     MachineBasicBlock::iterator MI,
1071                                     ArrayRef<CalleeSavedInfo> CSI,
1072                                     unsigned StmOpc, unsigned StrOpc,
1073                                     bool NoGap, bool (*Func)(unsigned, bool),
1074                                     unsigned NumAlignedDPRCS2Regs,
1075                                     unsigned MIFlags) const {
1076   MachineFunction &MF = *MBB.getParent();
1077   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1078   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1079 
1080   DebugLoc DL;
1081 
1082   using RegAndKill = std::pair<unsigned, bool>;
1083 
1084   SmallVector<RegAndKill, 4> Regs;
1085   unsigned i = CSI.size();
1086   while (i != 0) {
1087     unsigned LastReg = 0;
1088     for (; i != 0; --i) {
1089       unsigned Reg = CSI[i-1].getReg();
1090       if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
1091 
1092       // D-registers in the aligned area DPRCS2 are NOT spilled here.
1093       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1094         continue;
1095 
1096       const MachineRegisterInfo &MRI = MF.getRegInfo();
1097       bool isLiveIn = MRI.isLiveIn(Reg);
1098       if (!isLiveIn && !MRI.isReserved(Reg))
1099         MBB.addLiveIn(Reg);
1100       // If NoGap is true, push consecutive registers and then leave the rest
1101       // for other instructions. e.g.
1102       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
1103       if (NoGap && LastReg && LastReg != Reg-1)
1104         break;
1105       LastReg = Reg;
1106       // Do not set a kill flag on values that are also marked as live-in. This
1107       // happens with the @llvm-returnaddress intrinsic and with arguments
1108       // passed in callee saved registers.
1109       // Omitting the kill flags is conservatively correct even if the live-in
1110       // is not used after all.
1111       Regs.push_back(std::make_pair(Reg, /*isKill=*/!isLiveIn));
1112     }
1113 
1114     if (Regs.empty())
1115       continue;
1116 
1117     llvm::sort(Regs, [&](const RegAndKill &LHS, const RegAndKill &RHS) {
1118       return TRI.getEncodingValue(LHS.first) < TRI.getEncodingValue(RHS.first);
1119     });
1120 
1121     if (Regs.size() > 1 || StrOpc== 0) {
1122       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
1123                                     .addReg(ARM::SP)
1124                                     .setMIFlags(MIFlags)
1125                                     .add(predOps(ARMCC::AL));
1126       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1127         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
1128     } else if (Regs.size() == 1) {
1129       BuildMI(MBB, MI, DL, TII.get(StrOpc), ARM::SP)
1130           .addReg(Regs[0].first, getKillRegState(Regs[0].second))
1131           .addReg(ARM::SP)
1132           .setMIFlags(MIFlags)
1133           .addImm(-4)
1134           .add(predOps(ARMCC::AL));
1135     }
1136     Regs.clear();
1137 
1138     // Put any subsequent vpush instructions before this one: they will refer to
1139     // higher register numbers so need to be pushed first in order to preserve
1140     // monotonicity.
1141     if (MI != MBB.begin())
1142       --MI;
1143   }
1144 }
1145 
emitPopInst(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,MutableArrayRef<CalleeSavedInfo> CSI,unsigned LdmOpc,unsigned LdrOpc,bool isVarArg,bool NoGap,bool (* Func)(unsigned,bool),unsigned NumAlignedDPRCS2Regs) const1146 void ARMFrameLowering::emitPopInst(MachineBasicBlock &MBB,
1147                                    MachineBasicBlock::iterator MI,
1148                                    MutableArrayRef<CalleeSavedInfo> CSI,
1149                                    unsigned LdmOpc, unsigned LdrOpc,
1150                                    bool isVarArg, bool NoGap,
1151                                    bool (*Func)(unsigned, bool),
1152                                    unsigned NumAlignedDPRCS2Regs) const {
1153   MachineFunction &MF = *MBB.getParent();
1154   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1155   const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
1156   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1157   DebugLoc DL;
1158   bool isTailCall = false;
1159   bool isInterrupt = false;
1160   bool isTrap = false;
1161   bool isCmseEntry = false;
1162   if (MBB.end() != MI) {
1163     DL = MI->getDebugLoc();
1164     unsigned RetOpcode = MI->getOpcode();
1165     isTailCall = (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNri);
1166     isInterrupt =
1167         RetOpcode == ARM::SUBS_PC_LR || RetOpcode == ARM::t2SUBS_PC_LR;
1168     isTrap =
1169         RetOpcode == ARM::TRAP || RetOpcode == ARM::TRAPNaCl ||
1170         RetOpcode == ARM::tTRAP;
1171     isCmseEntry = (RetOpcode == ARM::tBXNS || RetOpcode == ARM::tBXNS_RET);
1172   }
1173 
1174   SmallVector<unsigned, 4> Regs;
1175   unsigned i = CSI.size();
1176   while (i != 0) {
1177     unsigned LastReg = 0;
1178     bool DeleteRet = false;
1179     for (; i != 0; --i) {
1180       CalleeSavedInfo &Info = CSI[i-1];
1181       unsigned Reg = Info.getReg();
1182       if (!(Func)(Reg, STI.splitFramePushPop(MF))) continue;
1183 
1184       // The aligned reloads from area DPRCS2 are not inserted here.
1185       if (Reg >= ARM::D8 && Reg < ARM::D8 + NumAlignedDPRCS2Regs)
1186         continue;
1187 
1188       if (Reg == ARM::LR && !isTailCall && !isVarArg && !isInterrupt &&
1189           !isCmseEntry && !isTrap && STI.hasV5TOps()) {
1190         if (MBB.succ_empty()) {
1191           Reg = ARM::PC;
1192           // Fold the return instruction into the LDM.
1193           DeleteRet = true;
1194           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
1195           // We 'restore' LR into PC so it is not live out of the return block:
1196           // Clear Restored bit.
1197           Info.setRestored(false);
1198         } else
1199           LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1200       }
1201 
1202       // If NoGap is true, pop consecutive registers and then leave the rest
1203       // for other instructions. e.g.
1204       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
1205       if (NoGap && LastReg && LastReg != Reg-1)
1206         break;
1207 
1208       LastReg = Reg;
1209       Regs.push_back(Reg);
1210     }
1211 
1212     if (Regs.empty())
1213       continue;
1214 
1215     llvm::sort(Regs, [&](unsigned LHS, unsigned RHS) {
1216       return TRI.getEncodingValue(LHS) < TRI.getEncodingValue(RHS);
1217     });
1218 
1219     if (Regs.size() > 1 || LdrOpc == 0) {
1220       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
1221                                     .addReg(ARM::SP)
1222                                     .add(predOps(ARMCC::AL))
1223                                     .setMIFlags(MachineInstr::FrameDestroy);
1224       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
1225         MIB.addReg(Regs[i], getDefRegState(true));
1226       if (DeleteRet) {
1227         if (MI != MBB.end()) {
1228           MIB.copyImplicitOps(*MI);
1229           MI->eraseFromParent();
1230         }
1231       }
1232       MI = MIB;
1233     } else if (Regs.size() == 1) {
1234       // If we adjusted the reg to PC from LR above, switch it back here. We
1235       // only do that for LDM.
1236       if (Regs[0] == ARM::PC)
1237         Regs[0] = ARM::LR;
1238       MachineInstrBuilder MIB =
1239         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
1240           .addReg(ARM::SP, RegState::Define)
1241           .addReg(ARM::SP)
1242           .setMIFlags(MachineInstr::FrameDestroy);
1243       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
1244       // that refactoring is complete (eventually).
1245       if (LdrOpc == ARM::LDR_POST_REG || LdrOpc == ARM::LDR_POST_IMM) {
1246         MIB.addReg(0);
1247         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
1248       } else
1249         MIB.addImm(4);
1250       MIB.add(predOps(ARMCC::AL));
1251     }
1252     Regs.clear();
1253 
1254     // Put any subsequent vpop instructions after this one: they will refer to
1255     // higher register numbers so need to be popped afterwards.
1256     if (MI != MBB.end())
1257       ++MI;
1258   }
1259 }
1260 
1261 /// Emit aligned spill instructions for NumAlignedDPRCS2Regs D-registers
1262 /// starting from d8.  Also insert stack realignment code and leave the stack
1263 /// pointer pointing to the d8 spill slot.
emitAlignedDPRCS2Spills(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned NumAlignedDPRCS2Regs,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI)1264 static void emitAlignedDPRCS2Spills(MachineBasicBlock &MBB,
1265                                     MachineBasicBlock::iterator MI,
1266                                     unsigned NumAlignedDPRCS2Regs,
1267                                     ArrayRef<CalleeSavedInfo> CSI,
1268                                     const TargetRegisterInfo *TRI) {
1269   MachineFunction &MF = *MBB.getParent();
1270   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1271   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1272   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1273   MachineFrameInfo &MFI = MF.getFrameInfo();
1274 
1275   // Mark the D-register spill slots as properly aligned.  Since MFI computes
1276   // stack slot layout backwards, this can actually mean that the d-reg stack
1277   // slot offsets can be wrong. The offset for d8 will always be correct.
1278   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1279     unsigned DNum = CSI[i].getReg() - ARM::D8;
1280     if (DNum > NumAlignedDPRCS2Regs - 1)
1281       continue;
1282     int FI = CSI[i].getFrameIdx();
1283     // The even-numbered registers will be 16-byte aligned, the odd-numbered
1284     // registers will be 8-byte aligned.
1285     MFI.setObjectAlignment(FI, DNum % 2 ? Align(8) : Align(16));
1286 
1287     // The stack slot for D8 needs to be maximally aligned because this is
1288     // actually the point where we align the stack pointer.  MachineFrameInfo
1289     // computes all offsets relative to the incoming stack pointer which is a
1290     // bit weird when realigning the stack.  Any extra padding for this
1291     // over-alignment is not realized because the code inserted below adjusts
1292     // the stack pointer by numregs * 8 before aligning the stack pointer.
1293     if (DNum == 0)
1294       MFI.setObjectAlignment(FI, MFI.getMaxAlign());
1295   }
1296 
1297   // Move the stack pointer to the d8 spill slot, and align it at the same
1298   // time. Leave the stack slot address in the scratch register r4.
1299   //
1300   //   sub r4, sp, #numregs * 8
1301   //   bic r4, r4, #align - 1
1302   //   mov sp, r4
1303   //
1304   bool isThumb = AFI->isThumbFunction();
1305   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1306   AFI->setShouldRestoreSPFromFP(true);
1307 
1308   // sub r4, sp, #numregs * 8
1309   // The immediate is <= 64, so it doesn't need any special encoding.
1310   unsigned Opc = isThumb ? ARM::t2SUBri : ARM::SUBri;
1311   BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1312       .addReg(ARM::SP)
1313       .addImm(8 * NumAlignedDPRCS2Regs)
1314       .add(predOps(ARMCC::AL))
1315       .add(condCodeOp());
1316 
1317   Align MaxAlign = MF.getFrameInfo().getMaxAlign();
1318   // We must set parameter MustBeSingleInstruction to true, since
1319   // skipAlignedDPRCS2Spills expects exactly 3 instructions to perform
1320   // stack alignment.  Luckily, this can always be done since all ARM
1321   // architecture versions that support Neon also support the BFC
1322   // instruction.
1323   emitAligningInstructions(MF, AFI, TII, MBB, MI, DL, ARM::R4, MaxAlign, true);
1324 
1325   // mov sp, r4
1326   // The stack pointer must be adjusted before spilling anything, otherwise
1327   // the stack slots could be clobbered by an interrupt handler.
1328   // Leave r4 live, it is used below.
1329   Opc = isThumb ? ARM::tMOVr : ARM::MOVr;
1330   MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(Opc), ARM::SP)
1331                                 .addReg(ARM::R4)
1332                                 .add(predOps(ARMCC::AL));
1333   if (!isThumb)
1334     MIB.add(condCodeOp());
1335 
1336   // Now spill NumAlignedDPRCS2Regs registers starting from d8.
1337   // r4 holds the stack slot address.
1338   unsigned NextReg = ARM::D8;
1339 
1340   // 16-byte aligned vst1.64 with 4 d-regs and address writeback.
1341   // The writeback is only needed when emitting two vst1.64 instructions.
1342   if (NumAlignedDPRCS2Regs >= 6) {
1343     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1344                                                &ARM::QQPRRegClass);
1345     MBB.addLiveIn(SupReg);
1346     BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Qwb_fixed), ARM::R4)
1347         .addReg(ARM::R4, RegState::Kill)
1348         .addImm(16)
1349         .addReg(NextReg)
1350         .addReg(SupReg, RegState::ImplicitKill)
1351         .add(predOps(ARMCC::AL));
1352     NextReg += 4;
1353     NumAlignedDPRCS2Regs -= 4;
1354   }
1355 
1356   // We won't modify r4 beyond this point.  It currently points to the next
1357   // register to be spilled.
1358   unsigned R4BaseReg = NextReg;
1359 
1360   // 16-byte aligned vst1.64 with 4 d-regs, no writeback.
1361   if (NumAlignedDPRCS2Regs >= 4) {
1362     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1363                                                &ARM::QQPRRegClass);
1364     MBB.addLiveIn(SupReg);
1365     BuildMI(MBB, MI, DL, TII.get(ARM::VST1d64Q))
1366         .addReg(ARM::R4)
1367         .addImm(16)
1368         .addReg(NextReg)
1369         .addReg(SupReg, RegState::ImplicitKill)
1370         .add(predOps(ARMCC::AL));
1371     NextReg += 4;
1372     NumAlignedDPRCS2Regs -= 4;
1373   }
1374 
1375   // 16-byte aligned vst1.64 with 2 d-regs.
1376   if (NumAlignedDPRCS2Regs >= 2) {
1377     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1378                                                &ARM::QPRRegClass);
1379     MBB.addLiveIn(SupReg);
1380     BuildMI(MBB, MI, DL, TII.get(ARM::VST1q64))
1381         .addReg(ARM::R4)
1382         .addImm(16)
1383         .addReg(SupReg)
1384         .add(predOps(ARMCC::AL));
1385     NextReg += 2;
1386     NumAlignedDPRCS2Regs -= 2;
1387   }
1388 
1389   // Finally, use a vanilla vstr.64 for the odd last register.
1390   if (NumAlignedDPRCS2Regs) {
1391     MBB.addLiveIn(NextReg);
1392     // vstr.64 uses addrmode5 which has an offset scale of 4.
1393     BuildMI(MBB, MI, DL, TII.get(ARM::VSTRD))
1394         .addReg(NextReg)
1395         .addReg(ARM::R4)
1396         .addImm((NextReg - R4BaseReg) * 2)
1397         .add(predOps(ARMCC::AL));
1398   }
1399 
1400   // The last spill instruction inserted should kill the scratch register r4.
1401   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1402 }
1403 
1404 /// Skip past the code inserted by emitAlignedDPRCS2Spills, and return an
1405 /// iterator to the following instruction.
1406 static MachineBasicBlock::iterator
skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,unsigned NumAlignedDPRCS2Regs)1407 skipAlignedDPRCS2Spills(MachineBasicBlock::iterator MI,
1408                         unsigned NumAlignedDPRCS2Regs) {
1409   //   sub r4, sp, #numregs * 8
1410   //   bic r4, r4, #align - 1
1411   //   mov sp, r4
1412   ++MI; ++MI; ++MI;
1413   assert(MI->mayStore() && "Expecting spill instruction");
1414 
1415   // These switches all fall through.
1416   switch(NumAlignedDPRCS2Regs) {
1417   case 7:
1418     ++MI;
1419     assert(MI->mayStore() && "Expecting spill instruction");
1420     LLVM_FALLTHROUGH;
1421   default:
1422     ++MI;
1423     assert(MI->mayStore() && "Expecting spill instruction");
1424     LLVM_FALLTHROUGH;
1425   case 1:
1426   case 2:
1427   case 4:
1428     assert(MI->killsRegister(ARM::R4) && "Missed kill flag");
1429     ++MI;
1430   }
1431   return MI;
1432 }
1433 
1434 /// Emit aligned reload instructions for NumAlignedDPRCS2Regs D-registers
1435 /// starting from d8.  These instructions are assumed to execute while the
1436 /// stack is still aligned, unlike the code inserted by emitPopInst.
emitAlignedDPRCS2Restores(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned NumAlignedDPRCS2Regs,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI)1437 static void emitAlignedDPRCS2Restores(MachineBasicBlock &MBB,
1438                                       MachineBasicBlock::iterator MI,
1439                                       unsigned NumAlignedDPRCS2Regs,
1440                                       ArrayRef<CalleeSavedInfo> CSI,
1441                                       const TargetRegisterInfo *TRI) {
1442   MachineFunction &MF = *MBB.getParent();
1443   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1444   DebugLoc DL = MI != MBB.end() ? MI->getDebugLoc() : DebugLoc();
1445   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1446 
1447   // Find the frame index assigned to d8.
1448   int D8SpillFI = 0;
1449   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
1450     if (CSI[i].getReg() == ARM::D8) {
1451       D8SpillFI = CSI[i].getFrameIdx();
1452       break;
1453     }
1454 
1455   // Materialize the address of the d8 spill slot into the scratch register r4.
1456   // This can be fairly complicated if the stack frame is large, so just use
1457   // the normal frame index elimination mechanism to do it.  This code runs as
1458   // the initial part of the epilog where the stack and base pointers haven't
1459   // been changed yet.
1460   bool isThumb = AFI->isThumbFunction();
1461   assert(!AFI->isThumb1OnlyFunction() && "Can't realign stack for thumb1");
1462 
1463   unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
1464   BuildMI(MBB, MI, DL, TII.get(Opc), ARM::R4)
1465       .addFrameIndex(D8SpillFI)
1466       .addImm(0)
1467       .add(predOps(ARMCC::AL))
1468       .add(condCodeOp());
1469 
1470   // Now restore NumAlignedDPRCS2Regs registers starting from d8.
1471   unsigned NextReg = ARM::D8;
1472 
1473   // 16-byte aligned vld1.64 with 4 d-regs and writeback.
1474   if (NumAlignedDPRCS2Regs >= 6) {
1475     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1476                                                &ARM::QQPRRegClass);
1477     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Qwb_fixed), NextReg)
1478         .addReg(ARM::R4, RegState::Define)
1479         .addReg(ARM::R4, RegState::Kill)
1480         .addImm(16)
1481         .addReg(SupReg, RegState::ImplicitDefine)
1482         .add(predOps(ARMCC::AL));
1483     NextReg += 4;
1484     NumAlignedDPRCS2Regs -= 4;
1485   }
1486 
1487   // We won't modify r4 beyond this point.  It currently points to the next
1488   // register to be spilled.
1489   unsigned R4BaseReg = NextReg;
1490 
1491   // 16-byte aligned vld1.64 with 4 d-regs, no writeback.
1492   if (NumAlignedDPRCS2Regs >= 4) {
1493     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1494                                                &ARM::QQPRRegClass);
1495     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1d64Q), NextReg)
1496         .addReg(ARM::R4)
1497         .addImm(16)
1498         .addReg(SupReg, RegState::ImplicitDefine)
1499         .add(predOps(ARMCC::AL));
1500     NextReg += 4;
1501     NumAlignedDPRCS2Regs -= 4;
1502   }
1503 
1504   // 16-byte aligned vld1.64 with 2 d-regs.
1505   if (NumAlignedDPRCS2Regs >= 2) {
1506     unsigned SupReg = TRI->getMatchingSuperReg(NextReg, ARM::dsub_0,
1507                                                &ARM::QPRRegClass);
1508     BuildMI(MBB, MI, DL, TII.get(ARM::VLD1q64), SupReg)
1509         .addReg(ARM::R4)
1510         .addImm(16)
1511         .add(predOps(ARMCC::AL));
1512     NextReg += 2;
1513     NumAlignedDPRCS2Regs -= 2;
1514   }
1515 
1516   // Finally, use a vanilla vldr.64 for the remaining odd register.
1517   if (NumAlignedDPRCS2Regs)
1518     BuildMI(MBB, MI, DL, TII.get(ARM::VLDRD), NextReg)
1519         .addReg(ARM::R4)
1520         .addImm(2 * (NextReg - R4BaseReg))
1521         .add(predOps(ARMCC::AL));
1522 
1523   // Last store kills r4.
1524   std::prev(MI)->addRegisterKilled(ARM::R4, TRI);
1525 }
1526 
spillCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,ArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const1527 bool ARMFrameLowering::spillCalleeSavedRegisters(
1528     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1529     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1530   if (CSI.empty())
1531     return false;
1532 
1533   MachineFunction &MF = *MBB.getParent();
1534   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1535 
1536   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
1537   unsigned PushOneOpc = AFI->isThumbFunction() ?
1538     ARM::t2STR_PRE : ARM::STR_PRE_IMM;
1539   unsigned FltOpc = ARM::VSTMDDB_UPD;
1540   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1541   // Save the non-secure floating point context.
1542   if (llvm::any_of(CSI, [](const CalleeSavedInfo &C) {
1543         return C.getReg() == ARM::FPCXTNS;
1544       })) {
1545     BuildMI(MBB, MI, DebugLoc(), STI.getInstrInfo()->get(ARM::VSTR_FPCXTNS_pre),
1546             ARM::SP)
1547         .addReg(ARM::SP)
1548         .addImm(-4)
1549         .add(predOps(ARMCC::AL));
1550   }
1551   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register, 0,
1552                MachineInstr::FrameSetup);
1553   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register, 0,
1554                MachineInstr::FrameSetup);
1555   emitPushInst(MBB, MI, CSI, FltOpc, 0, true, &isARMArea3Register,
1556                NumAlignedDPRCS2Regs, MachineInstr::FrameSetup);
1557 
1558   // The code above does not insert spill code for the aligned DPRCS2 registers.
1559   // The stack realignment code will be inserted between the push instructions
1560   // and these spills.
1561   if (NumAlignedDPRCS2Regs)
1562     emitAlignedDPRCS2Spills(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1563 
1564   return true;
1565 }
1566 
restoreCalleeSavedRegisters(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,MutableArrayRef<CalleeSavedInfo> CSI,const TargetRegisterInfo * TRI) const1567 bool ARMFrameLowering::restoreCalleeSavedRegisters(
1568     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1569     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
1570   if (CSI.empty())
1571     return false;
1572 
1573   MachineFunction &MF = *MBB.getParent();
1574   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1575   bool isVarArg = AFI->getArgRegsSaveSize() > 0;
1576   unsigned NumAlignedDPRCS2Regs = AFI->getNumAlignedDPRCS2Regs();
1577 
1578   // The emitPopInst calls below do not insert reloads for the aligned DPRCS2
1579   // registers. Do that here instead.
1580   if (NumAlignedDPRCS2Regs)
1581     emitAlignedDPRCS2Restores(MBB, MI, NumAlignedDPRCS2Regs, CSI, TRI);
1582 
1583   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
1584   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST :ARM::LDR_POST_IMM;
1585   unsigned FltOpc = ARM::VLDMDIA_UPD;
1586   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true, &isARMArea3Register,
1587               NumAlignedDPRCS2Regs);
1588   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1589               &isARMArea2Register, 0);
1590   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
1591               &isARMArea1Register, 0);
1592 
1593   return true;
1594 }
1595 
1596 // FIXME: Make generic?
EstimateFunctionSizeInBytes(const MachineFunction & MF,const ARMBaseInstrInfo & TII)1597 static unsigned EstimateFunctionSizeInBytes(const MachineFunction &MF,
1598                                             const ARMBaseInstrInfo &TII) {
1599   unsigned FnSize = 0;
1600   for (auto &MBB : MF) {
1601     for (auto &MI : MBB)
1602       FnSize += TII.getInstSizeInBytes(MI);
1603   }
1604   if (MF.getJumpTableInfo())
1605     for (auto &Table: MF.getJumpTableInfo()->getJumpTables())
1606       FnSize += Table.MBBs.size() * 4;
1607   FnSize += MF.getConstantPool()->getConstants().size() * 4;
1608   return FnSize;
1609 }
1610 
1611 /// estimateRSStackSizeLimit - Look at each instruction that references stack
1612 /// frames and return the stack size limit beyond which some of these
1613 /// instructions will require a scratch register during their expansion later.
1614 // FIXME: Move to TII?
estimateRSStackSizeLimit(MachineFunction & MF,const TargetFrameLowering * TFI,bool & HasNonSPFrameIndex)1615 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
1616                                          const TargetFrameLowering *TFI,
1617                                          bool &HasNonSPFrameIndex) {
1618   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1619   const ARMBaseInstrInfo &TII =
1620       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1621   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1622   unsigned Limit = (1 << 12) - 1;
1623   for (auto &MBB : MF) {
1624     for (auto &MI : MBB) {
1625       if (MI.isDebugInstr())
1626         continue;
1627       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1628         if (!MI.getOperand(i).isFI())
1629           continue;
1630 
1631         // When using ADDri to get the address of a stack object, 255 is the
1632         // largest offset guaranteed to fit in the immediate offset.
1633         if (MI.getOpcode() == ARM::ADDri) {
1634           Limit = std::min(Limit, (1U << 8) - 1);
1635           break;
1636         }
1637         // t2ADDri will not require an extra register, it can reuse the
1638         // destination.
1639         if (MI.getOpcode() == ARM::t2ADDri || MI.getOpcode() == ARM::t2ADDri12)
1640           break;
1641 
1642         const MCInstrDesc &MCID = MI.getDesc();
1643         const TargetRegisterClass *RegClass = TII.getRegClass(MCID, i, TRI, MF);
1644         if (RegClass && !RegClass->contains(ARM::SP))
1645           HasNonSPFrameIndex = true;
1646 
1647         // Otherwise check the addressing mode.
1648         switch (MI.getDesc().TSFlags & ARMII::AddrModeMask) {
1649         case ARMII::AddrMode_i12:
1650         case ARMII::AddrMode2:
1651           // Default 12 bit limit.
1652           break;
1653         case ARMII::AddrMode3:
1654         case ARMII::AddrModeT2_i8:
1655           Limit = std::min(Limit, (1U << 8) - 1);
1656           break;
1657         case ARMII::AddrMode5FP16:
1658           Limit = std::min(Limit, ((1U << 8) - 1) * 2);
1659           break;
1660         case ARMII::AddrMode5:
1661         case ARMII::AddrModeT2_i8s4:
1662         case ARMII::AddrModeT2_ldrex:
1663           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
1664           break;
1665         case ARMII::AddrModeT2_i12:
1666           // i12 supports only positive offset so these will be converted to
1667           // i8 opcodes. See llvm::rewriteT2FrameIndex.
1668           if (TFI->hasFP(MF) && AFI->hasStackFrame())
1669             Limit = std::min(Limit, (1U << 8) - 1);
1670           break;
1671         case ARMII::AddrMode4:
1672         case ARMII::AddrMode6:
1673           // Addressing modes 4 & 6 (load/store) instructions can't encode an
1674           // immediate offset for stack references.
1675           return 0;
1676         case ARMII::AddrModeT2_i7:
1677           Limit = std::min(Limit, ((1U << 7) - 1) * 1);
1678           break;
1679         case ARMII::AddrModeT2_i7s2:
1680           Limit = std::min(Limit, ((1U << 7) - 1) * 2);
1681           break;
1682         case ARMII::AddrModeT2_i7s4:
1683           Limit = std::min(Limit, ((1U << 7) - 1) * 4);
1684           break;
1685         default:
1686           llvm_unreachable("Unhandled addressing mode in stack size limit calculation");
1687         }
1688         break; // At most one FI per instruction
1689       }
1690     }
1691   }
1692 
1693   return Limit;
1694 }
1695 
1696 // In functions that realign the stack, it can be an advantage to spill the
1697 // callee-saved vector registers after realigning the stack. The vst1 and vld1
1698 // instructions take alignment hints that can improve performance.
1699 static void
checkNumAlignedDPRCS2Regs(MachineFunction & MF,BitVector & SavedRegs)1700 checkNumAlignedDPRCS2Regs(MachineFunction &MF, BitVector &SavedRegs) {
1701   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(0);
1702   if (!SpillAlignedNEONRegs)
1703     return;
1704 
1705   // Naked functions don't spill callee-saved registers.
1706   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
1707     return;
1708 
1709   // We are planning to use NEON instructions vst1 / vld1.
1710   if (!static_cast<const ARMSubtarget &>(MF.getSubtarget()).hasNEON())
1711     return;
1712 
1713   // Don't bother if the default stack alignment is sufficiently high.
1714   if (MF.getSubtarget().getFrameLowering()->getStackAlign() >= Align(8))
1715     return;
1716 
1717   // Aligned spills require stack realignment.
1718   if (!static_cast<const ARMBaseRegisterInfo *>(
1719            MF.getSubtarget().getRegisterInfo())->canRealignStack(MF))
1720     return;
1721 
1722   // We always spill contiguous d-registers starting from d8. Count how many
1723   // needs spilling.  The register allocator will almost always use the
1724   // callee-saved registers in order, but it can happen that there are holes in
1725   // the range.  Registers above the hole will be spilled to the standard DPRCS
1726   // area.
1727   unsigned NumSpills = 0;
1728   for (; NumSpills < 8; ++NumSpills)
1729     if (!SavedRegs.test(ARM::D8 + NumSpills))
1730       break;
1731 
1732   // Don't do this for just one d-register. It's not worth it.
1733   if (NumSpills < 2)
1734     return;
1735 
1736   // Spill the first NumSpills D-registers after realigning the stack.
1737   MF.getInfo<ARMFunctionInfo>()->setNumAlignedDPRCS2Regs(NumSpills);
1738 
1739   // A scratch register is required for the vst1 / vld1 instructions.
1740   SavedRegs.set(ARM::R4);
1741 }
1742 
enableShrinkWrapping(const MachineFunction & MF) const1743 bool ARMFrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
1744   // For CMSE entry functions, we want to save the FPCXT_NS immediately
1745   // upon function entry (resp. restore it immmediately before return)
1746   if (STI.hasV8_1MMainlineOps() &&
1747       MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction())
1748     return false;
1749 
1750   return true;
1751 }
1752 
determineCalleeSaves(MachineFunction & MF,BitVector & SavedRegs,RegScavenger * RS) const1753 void ARMFrameLowering::determineCalleeSaves(MachineFunction &MF,
1754                                             BitVector &SavedRegs,
1755                                             RegScavenger *RS) const {
1756   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1757   // This tells PEI to spill the FP as if it is any other callee-save register
1758   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1759   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1760   // to combine multiple loads / stores.
1761   bool CanEliminateFrame = true;
1762   bool CS1Spilled = false;
1763   bool LRSpilled = false;
1764   unsigned NumGPRSpills = 0;
1765   unsigned NumFPRSpills = 0;
1766   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1767   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1768   const ARMBaseRegisterInfo *RegInfo = static_cast<const ARMBaseRegisterInfo *>(
1769       MF.getSubtarget().getRegisterInfo());
1770   const ARMBaseInstrInfo &TII =
1771       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
1772   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1773   MachineFrameInfo &MFI = MF.getFrameInfo();
1774   MachineRegisterInfo &MRI = MF.getRegInfo();
1775   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1776   (void)TRI;  // Silence unused warning in non-assert builds.
1777   Register FramePtr = RegInfo->getFrameRegister(MF);
1778 
1779   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
1780   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
1781   // since it's not always possible to restore sp from fp in a single
1782   // instruction.
1783   // FIXME: It will be better just to find spare register here.
1784   if (AFI->isThumb2Function() &&
1785       (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF)))
1786     SavedRegs.set(ARM::R4);
1787 
1788   // If a stack probe will be emitted, spill R4 and LR, since they are
1789   // clobbered by the stack probe call.
1790   // This estimate should be a safe, conservative estimate. The actual
1791   // stack probe is enabled based on the size of the local objects;
1792   // this estimate also includes the varargs store size.
1793   if (STI.isTargetWindows() &&
1794       WindowsRequiresStackProbe(MF, MFI.estimateStackSize(MF))) {
1795     SavedRegs.set(ARM::R4);
1796     SavedRegs.set(ARM::LR);
1797   }
1798 
1799   if (AFI->isThumb1OnlyFunction()) {
1800     // Spill LR if Thumb1 function uses variable length argument lists.
1801     if (AFI->getArgRegsSaveSize() > 0)
1802       SavedRegs.set(ARM::LR);
1803 
1804     // Spill R4 if Thumb1 epilogue has to restore SP from FP or the function
1805     // requires stack alignment.  We don't know for sure what the stack size
1806     // will be, but for this, an estimate is good enough. If there anything
1807     // changes it, it'll be a spill, which implies we've used all the registers
1808     // and so R4 is already used, so not marking it here will be OK.
1809     // FIXME: It will be better just to find spare register here.
1810     if (MFI.hasVarSizedObjects() || RegInfo->hasStackRealignment(MF) ||
1811         MFI.estimateStackSize(MF) > 508)
1812       SavedRegs.set(ARM::R4);
1813   }
1814 
1815   // See if we can spill vector registers to aligned stack.
1816   checkNumAlignedDPRCS2Regs(MF, SavedRegs);
1817 
1818   // Spill the BasePtr if it's used.
1819   if (RegInfo->hasBasePointer(MF))
1820     SavedRegs.set(RegInfo->getBaseRegister());
1821 
1822   // On v8.1-M.Main CMSE entry functions save/restore FPCXT.
1823   if (STI.hasV8_1MMainlineOps() && AFI->isCmseNSEntryFunction())
1824     CanEliminateFrame = false;
1825 
1826   // Don't spill FP if the frame can be eliminated. This is determined
1827   // by scanning the callee-save registers to see if any is modified.
1828   const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&MF);
1829   for (unsigned i = 0; CSRegs[i]; ++i) {
1830     unsigned Reg = CSRegs[i];
1831     bool Spilled = false;
1832     if (SavedRegs.test(Reg)) {
1833       Spilled = true;
1834       CanEliminateFrame = false;
1835     }
1836 
1837     if (!ARM::GPRRegClass.contains(Reg)) {
1838       if (Spilled) {
1839         if (ARM::SPRRegClass.contains(Reg))
1840           NumFPRSpills++;
1841         else if (ARM::DPRRegClass.contains(Reg))
1842           NumFPRSpills += 2;
1843         else if (ARM::QPRRegClass.contains(Reg))
1844           NumFPRSpills += 4;
1845       }
1846       continue;
1847     }
1848 
1849     if (Spilled) {
1850       NumGPRSpills++;
1851 
1852       if (!STI.splitFramePushPop(MF)) {
1853         if (Reg == ARM::LR)
1854           LRSpilled = true;
1855         CS1Spilled = true;
1856         continue;
1857       }
1858 
1859       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1860       switch (Reg) {
1861       case ARM::LR:
1862         LRSpilled = true;
1863         LLVM_FALLTHROUGH;
1864       case ARM::R0: case ARM::R1:
1865       case ARM::R2: case ARM::R3:
1866       case ARM::R4: case ARM::R5:
1867       case ARM::R6: case ARM::R7:
1868         CS1Spilled = true;
1869         break;
1870       default:
1871         break;
1872       }
1873     } else {
1874       if (!STI.splitFramePushPop(MF)) {
1875         UnspilledCS1GPRs.push_back(Reg);
1876         continue;
1877       }
1878 
1879       switch (Reg) {
1880       case ARM::R0: case ARM::R1:
1881       case ARM::R2: case ARM::R3:
1882       case ARM::R4: case ARM::R5:
1883       case ARM::R6: case ARM::R7:
1884       case ARM::LR:
1885         UnspilledCS1GPRs.push_back(Reg);
1886         break;
1887       default:
1888         UnspilledCS2GPRs.push_back(Reg);
1889         break;
1890       }
1891     }
1892   }
1893 
1894   bool ForceLRSpill = false;
1895   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
1896     unsigned FnSize = EstimateFunctionSizeInBytes(MF, TII);
1897     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1898     // use of BL to implement far jump.
1899     if (FnSize >= (1 << 11)) {
1900       CanEliminateFrame = false;
1901       ForceLRSpill = true;
1902     }
1903   }
1904 
1905   // If any of the stack slot references may be out of range of an immediate
1906   // offset, make sure a register (or a spill slot) is available for the
1907   // register scavenger. Note that if we're indexing off the frame pointer, the
1908   // effective stack size is 4 bytes larger since the FP points to the stack
1909   // slot of the previous FP. Also, if we have variable sized objects in the
1910   // function, stack slot references will often be negative, and some of
1911   // our instructions are positive-offset only, so conservatively consider
1912   // that case to want a spill slot (or register) as well. Similarly, if
1913   // the function adjusts the stack pointer during execution and the
1914   // adjustments aren't already part of our stack size estimate, our offset
1915   // calculations may be off, so be conservative.
1916   // FIXME: We could add logic to be more precise about negative offsets
1917   //        and which instructions will need a scratch register for them. Is it
1918   //        worth the effort and added fragility?
1919   unsigned EstimatedStackSize =
1920       MFI.estimateStackSize(MF) + 4 * (NumGPRSpills + NumFPRSpills);
1921 
1922   // Determine biggest (positive) SP offset in MachineFrameInfo.
1923   int MaxFixedOffset = 0;
1924   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I) {
1925     int MaxObjectOffset = MFI.getObjectOffset(I) + MFI.getObjectSize(I);
1926     MaxFixedOffset = std::max(MaxFixedOffset, MaxObjectOffset);
1927   }
1928 
1929   bool HasFP = hasFP(MF);
1930   if (HasFP) {
1931     if (AFI->hasStackFrame())
1932       EstimatedStackSize += 4;
1933   } else {
1934     // If FP is not used, SP will be used to access arguments, so count the
1935     // size of arguments into the estimation.
1936     EstimatedStackSize += MaxFixedOffset;
1937   }
1938   EstimatedStackSize += 16; // For possible paddings.
1939 
1940   unsigned EstimatedRSStackSizeLimit, EstimatedRSFixedSizeLimit;
1941   bool HasNonSPFrameIndex = false;
1942   if (AFI->isThumb1OnlyFunction()) {
1943     // For Thumb1, don't bother to iterate over the function. The only
1944     // instruction that requires an emergency spill slot is a store to a
1945     // frame index.
1946     //
1947     // tSTRspi, which is used for sp-relative accesses, has an 8-bit unsigned
1948     // immediate. tSTRi, which is used for bp- and fp-relative accesses, has
1949     // a 5-bit unsigned immediate.
1950     //
1951     // We could try to check if the function actually contains a tSTRspi
1952     // that might need the spill slot, but it's not really important.
1953     // Functions with VLAs or extremely large call frames are rare, and
1954     // if a function is allocating more than 1KB of stack, an extra 4-byte
1955     // slot probably isn't relevant.
1956     if (RegInfo->hasBasePointer(MF))
1957       EstimatedRSStackSizeLimit = (1U << 5) * 4;
1958     else
1959       EstimatedRSStackSizeLimit = (1U << 8) * 4;
1960     EstimatedRSFixedSizeLimit = (1U << 5) * 4;
1961   } else {
1962     EstimatedRSStackSizeLimit =
1963         estimateRSStackSizeLimit(MF, this, HasNonSPFrameIndex);
1964     EstimatedRSFixedSizeLimit = EstimatedRSStackSizeLimit;
1965   }
1966   // Final estimate of whether sp or bp-relative accesses might require
1967   // scavenging.
1968   bool HasLargeStack = EstimatedStackSize > EstimatedRSStackSizeLimit;
1969 
1970   // If the stack pointer moves and we don't have a base pointer, the
1971   // estimate logic doesn't work. The actual offsets might be larger when
1972   // we're constructing a call frame, or we might need to use negative
1973   // offsets from fp.
1974   bool HasMovingSP = MFI.hasVarSizedObjects() ||
1975     (MFI.adjustsStack() && !canSimplifyCallFramePseudos(MF));
1976   bool HasBPOrFixedSP = RegInfo->hasBasePointer(MF) || !HasMovingSP;
1977 
1978   // If we have a frame pointer, we assume arguments will be accessed
1979   // relative to the frame pointer. Check whether fp-relative accesses to
1980   // arguments require scavenging.
1981   //
1982   // We could do slightly better on Thumb1; in some cases, an sp-relative
1983   // offset would be legal even though an fp-relative offset is not.
1984   int MaxFPOffset = getMaxFPOffset(STI, *AFI);
1985   bool HasLargeArgumentList =
1986       HasFP && (MaxFixedOffset - MaxFPOffset) > (int)EstimatedRSFixedSizeLimit;
1987 
1988   bool BigFrameOffsets = HasLargeStack || !HasBPOrFixedSP ||
1989                          HasLargeArgumentList || HasNonSPFrameIndex;
1990   LLVM_DEBUG(dbgs() << "EstimatedLimit: " << EstimatedRSStackSizeLimit
1991                     << "; EstimatedStack: " << EstimatedStackSize
1992                     << "; EstimatedFPStack: " << MaxFixedOffset - MaxFPOffset
1993                     << "; BigFrameOffsets: " << BigFrameOffsets << "\n");
1994   if (BigFrameOffsets ||
1995       !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
1996     AFI->setHasStackFrame(true);
1997 
1998     if (HasFP) {
1999       SavedRegs.set(FramePtr);
2000       // If the frame pointer is required by the ABI, also spill LR so that we
2001       // emit a complete frame record.
2002       if (MF.getTarget().Options.DisableFramePointerElim(MF) && !LRSpilled) {
2003         SavedRegs.set(ARM::LR);
2004         LRSpilled = true;
2005         NumGPRSpills++;
2006         auto LRPos = llvm::find(UnspilledCS1GPRs, ARM::LR);
2007         if (LRPos != UnspilledCS1GPRs.end())
2008           UnspilledCS1GPRs.erase(LRPos);
2009       }
2010       auto FPPos = llvm::find(UnspilledCS1GPRs, FramePtr);
2011       if (FPPos != UnspilledCS1GPRs.end())
2012         UnspilledCS1GPRs.erase(FPPos);
2013       NumGPRSpills++;
2014       if (FramePtr == ARM::R7)
2015         CS1Spilled = true;
2016     }
2017 
2018     // This is true when we inserted a spill for a callee-save GPR which is
2019     // not otherwise used by the function. This guaranteees it is possible
2020     // to scavenge a register to hold the address of a stack slot. On Thumb1,
2021     // the register must be a valid operand to tSTRi, i.e. r4-r7. For other
2022     // subtargets, this is any GPR, i.e. r4-r11 or lr.
2023     //
2024     // If we don't insert a spill, we instead allocate an emergency spill
2025     // slot, which can be used by scavenging to spill an arbitrary register.
2026     //
2027     // We currently don't try to figure out whether any specific instruction
2028     // requires scavening an additional register.
2029     bool ExtraCSSpill = false;
2030 
2031     if (AFI->isThumb1OnlyFunction()) {
2032       // For Thumb1-only targets, we need some low registers when we save and
2033       // restore the high registers (which aren't allocatable, but could be
2034       // used by inline assembly) because the push/pop instructions can not
2035       // access high registers. If necessary, we might need to push more low
2036       // registers to ensure that there is at least one free that can be used
2037       // for the saving & restoring, and preferably we should ensure that as
2038       // many as are needed are available so that fewer push/pop instructions
2039       // are required.
2040 
2041       // Low registers which are not currently pushed, but could be (r4-r7).
2042       SmallVector<unsigned, 4> AvailableRegs;
2043 
2044       // Unused argument registers (r0-r3) can be clobbered in the prologue for
2045       // free.
2046       int EntryRegDeficit = 0;
2047       for (unsigned Reg : {ARM::R0, ARM::R1, ARM::R2, ARM::R3}) {
2048         if (!MF.getRegInfo().isLiveIn(Reg)) {
2049           --EntryRegDeficit;
2050           LLVM_DEBUG(dbgs()
2051                      << printReg(Reg, TRI)
2052                      << " is unused argument register, EntryRegDeficit = "
2053                      << EntryRegDeficit << "\n");
2054         }
2055       }
2056 
2057       // Unused return registers can be clobbered in the epilogue for free.
2058       int ExitRegDeficit = AFI->getReturnRegsCount() - 4;
2059       LLVM_DEBUG(dbgs() << AFI->getReturnRegsCount()
2060                         << " return regs used, ExitRegDeficit = "
2061                         << ExitRegDeficit << "\n");
2062 
2063       int RegDeficit = std::max(EntryRegDeficit, ExitRegDeficit);
2064       LLVM_DEBUG(dbgs() << "RegDeficit = " << RegDeficit << "\n");
2065 
2066       // r4-r6 can be used in the prologue if they are pushed by the first push
2067       // instruction.
2068       for (unsigned Reg : {ARM::R4, ARM::R5, ARM::R6}) {
2069         if (SavedRegs.test(Reg)) {
2070           --RegDeficit;
2071           LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
2072                             << " is saved low register, RegDeficit = "
2073                             << RegDeficit << "\n");
2074         } else {
2075           AvailableRegs.push_back(Reg);
2076           LLVM_DEBUG(
2077               dbgs()
2078               << printReg(Reg, TRI)
2079               << " is non-saved low register, adding to AvailableRegs\n");
2080         }
2081       }
2082 
2083       // r7 can be used if it is not being used as the frame pointer.
2084       if (!HasFP) {
2085         if (SavedRegs.test(ARM::R7)) {
2086           --RegDeficit;
2087           LLVM_DEBUG(dbgs() << "%r7 is saved low register, RegDeficit = "
2088                             << RegDeficit << "\n");
2089         } else {
2090           AvailableRegs.push_back(ARM::R7);
2091           LLVM_DEBUG(
2092               dbgs()
2093               << "%r7 is non-saved low register, adding to AvailableRegs\n");
2094         }
2095       }
2096 
2097       // Each of r8-r11 needs to be copied to a low register, then pushed.
2098       for (unsigned Reg : {ARM::R8, ARM::R9, ARM::R10, ARM::R11}) {
2099         if (SavedRegs.test(Reg)) {
2100           ++RegDeficit;
2101           LLVM_DEBUG(dbgs() << printReg(Reg, TRI)
2102                             << " is saved high register, RegDeficit = "
2103                             << RegDeficit << "\n");
2104         }
2105       }
2106 
2107       // LR can only be used by PUSH, not POP, and can't be used at all if the
2108       // llvm.returnaddress intrinsic is used. This is only worth doing if we
2109       // are more limited at function entry than exit.
2110       if ((EntryRegDeficit > ExitRegDeficit) &&
2111           !(MF.getRegInfo().isLiveIn(ARM::LR) &&
2112             MF.getFrameInfo().isReturnAddressTaken())) {
2113         if (SavedRegs.test(ARM::LR)) {
2114           --RegDeficit;
2115           LLVM_DEBUG(dbgs() << "%lr is saved register, RegDeficit = "
2116                             << RegDeficit << "\n");
2117         } else {
2118           AvailableRegs.push_back(ARM::LR);
2119           LLVM_DEBUG(dbgs() << "%lr is not saved, adding to AvailableRegs\n");
2120         }
2121       }
2122 
2123       // If there are more high registers that need pushing than low registers
2124       // available, push some more low registers so that we can use fewer push
2125       // instructions. This might not reduce RegDeficit all the way to zero,
2126       // because we can only guarantee that r4-r6 are available, but r8-r11 may
2127       // need saving.
2128       LLVM_DEBUG(dbgs() << "Final RegDeficit = " << RegDeficit << "\n");
2129       for (; RegDeficit > 0 && !AvailableRegs.empty(); --RegDeficit) {
2130         unsigned Reg = AvailableRegs.pop_back_val();
2131         LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2132                           << " to make up reg deficit\n");
2133         SavedRegs.set(Reg);
2134         NumGPRSpills++;
2135         CS1Spilled = true;
2136         assert(!MRI.isReserved(Reg) && "Should not be reserved");
2137         if (Reg != ARM::LR && !MRI.isPhysRegUsed(Reg))
2138           ExtraCSSpill = true;
2139         UnspilledCS1GPRs.erase(llvm::find(UnspilledCS1GPRs, Reg));
2140         if (Reg == ARM::LR)
2141           LRSpilled = true;
2142       }
2143       LLVM_DEBUG(dbgs() << "After adding spills, RegDeficit = " << RegDeficit
2144                         << "\n");
2145     }
2146 
2147     // Avoid spilling LR in Thumb1 if there's a tail call: it's expensive to
2148     // restore LR in that case.
2149     bool ExpensiveLRRestore = AFI->isThumb1OnlyFunction() && MFI.hasTailCall();
2150 
2151     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
2152     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
2153     if (!LRSpilled && CS1Spilled && !ExpensiveLRRestore) {
2154       SavedRegs.set(ARM::LR);
2155       NumGPRSpills++;
2156       SmallVectorImpl<unsigned>::iterator LRPos;
2157       LRPos = llvm::find(UnspilledCS1GPRs, (unsigned)ARM::LR);
2158       if (LRPos != UnspilledCS1GPRs.end())
2159         UnspilledCS1GPRs.erase(LRPos);
2160 
2161       ForceLRSpill = false;
2162       if (!MRI.isReserved(ARM::LR) && !MRI.isPhysRegUsed(ARM::LR) &&
2163           !AFI->isThumb1OnlyFunction())
2164         ExtraCSSpill = true;
2165     }
2166 
2167     // If stack and double are 8-byte aligned and we are spilling an odd number
2168     // of GPRs, spill one extra callee save GPR so we won't have to pad between
2169     // the integer and double callee save areas.
2170     LLVM_DEBUG(dbgs() << "NumGPRSpills = " << NumGPRSpills << "\n");
2171     const Align TargetAlign = getStackAlign();
2172     if (TargetAlign >= Align(8) && (NumGPRSpills & 1)) {
2173       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
2174         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
2175           unsigned Reg = UnspilledCS1GPRs[i];
2176           // Don't spill high register if the function is thumb.  In the case of
2177           // Windows on ARM, accept R11 (frame pointer)
2178           if (!AFI->isThumbFunction() ||
2179               (STI.isTargetWindows() && Reg == ARM::R11) ||
2180               isARMLowRegister(Reg) ||
2181               (Reg == ARM::LR && !ExpensiveLRRestore)) {
2182             SavedRegs.set(Reg);
2183             LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2184                               << " to make up alignment\n");
2185             if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg) &&
2186                 !(Reg == ARM::LR && AFI->isThumb1OnlyFunction()))
2187               ExtraCSSpill = true;
2188             break;
2189           }
2190         }
2191       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
2192         unsigned Reg = UnspilledCS2GPRs.front();
2193         SavedRegs.set(Reg);
2194         LLVM_DEBUG(dbgs() << "Spilling " << printReg(Reg, TRI)
2195                           << " to make up alignment\n");
2196         if (!MRI.isReserved(Reg) && !MRI.isPhysRegUsed(Reg))
2197           ExtraCSSpill = true;
2198       }
2199     }
2200 
2201     // Estimate if we might need to scavenge a register at some point in order
2202     // to materialize a stack offset. If so, either spill one additional
2203     // callee-saved register or reserve a special spill slot to facilitate
2204     // register scavenging. Thumb1 needs a spill slot for stack pointer
2205     // adjustments also, even when the frame itself is small.
2206     if (BigFrameOffsets && !ExtraCSSpill) {
2207       // If any non-reserved CS register isn't spilled, just spill one or two
2208       // extra. That should take care of it!
2209       unsigned NumExtras = TargetAlign.value() / 4;
2210       SmallVector<unsigned, 2> Extras;
2211       while (NumExtras && !UnspilledCS1GPRs.empty()) {
2212         unsigned Reg = UnspilledCS1GPRs.pop_back_val();
2213         if (!MRI.isReserved(Reg) &&
2214             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg))) {
2215           Extras.push_back(Reg);
2216           NumExtras--;
2217         }
2218       }
2219       // For non-Thumb1 functions, also check for hi-reg CS registers
2220       if (!AFI->isThumb1OnlyFunction()) {
2221         while (NumExtras && !UnspilledCS2GPRs.empty()) {
2222           unsigned Reg = UnspilledCS2GPRs.pop_back_val();
2223           if (!MRI.isReserved(Reg)) {
2224             Extras.push_back(Reg);
2225             NumExtras--;
2226           }
2227         }
2228       }
2229       if (NumExtras == 0) {
2230         for (unsigned Reg : Extras) {
2231           SavedRegs.set(Reg);
2232           if (!MRI.isPhysRegUsed(Reg))
2233             ExtraCSSpill = true;
2234         }
2235       }
2236       if (!ExtraCSSpill && RS) {
2237         // Reserve a slot closest to SP or frame pointer.
2238         LLVM_DEBUG(dbgs() << "Reserving emergency spill slot\n");
2239         const TargetRegisterClass &RC = ARM::GPRRegClass;
2240         unsigned Size = TRI->getSpillSize(RC);
2241         Align Alignment = TRI->getSpillAlign(RC);
2242         RS->addScavengingFrameIndex(
2243             MFI.CreateStackObject(Size, Alignment, false));
2244       }
2245     }
2246   }
2247 
2248   if (ForceLRSpill)
2249     SavedRegs.set(ARM::LR);
2250   AFI->setLRIsSpilled(SavedRegs.test(ARM::LR));
2251 }
2252 
getCalleeSaves(const MachineFunction & MF,BitVector & SavedRegs) const2253 void ARMFrameLowering::getCalleeSaves(const MachineFunction &MF,
2254                                       BitVector &SavedRegs) const {
2255   TargetFrameLowering::getCalleeSaves(MF, SavedRegs);
2256 
2257   // If we have the "returned" parameter attribute which guarantees that we
2258   // return the value which was passed in r0 unmodified (e.g. C++ 'structors),
2259   // record that fact for IPRA.
2260   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2261   if (AFI->getPreservesR0())
2262     SavedRegs.set(ARM::R0);
2263 }
2264 
assignCalleeSavedSpillSlots(MachineFunction & MF,const TargetRegisterInfo * TRI,std::vector<CalleeSavedInfo> & CSI) const2265 bool ARMFrameLowering::assignCalleeSavedSpillSlots(
2266     MachineFunction &MF, const TargetRegisterInfo *TRI,
2267     std::vector<CalleeSavedInfo> &CSI) const {
2268   // For CMSE entry functions, handle floating-point context as if it was a
2269   // callee-saved register.
2270   if (STI.hasV8_1MMainlineOps() &&
2271       MF.getInfo<ARMFunctionInfo>()->isCmseNSEntryFunction()) {
2272     CSI.emplace_back(ARM::FPCXTNS);
2273     CSI.back().setRestored(false);
2274   }
2275 
2276   return false;
2277 }
2278 
2279 const TargetFrameLowering::SpillSlot *
getCalleeSavedSpillSlots(unsigned & NumEntries) const2280 ARMFrameLowering::getCalleeSavedSpillSlots(unsigned &NumEntries) const {
2281   static const SpillSlot FixedSpillOffsets[] = {{ARM::FPCXTNS, -4}};
2282   NumEntries = array_lengthof(FixedSpillOffsets);
2283   return FixedSpillOffsets;
2284 }
2285 
eliminateCallFramePseudoInstr(MachineFunction & MF,MachineBasicBlock & MBB,MachineBasicBlock::iterator I) const2286 MachineBasicBlock::iterator ARMFrameLowering::eliminateCallFramePseudoInstr(
2287     MachineFunction &MF, MachineBasicBlock &MBB,
2288     MachineBasicBlock::iterator I) const {
2289   const ARMBaseInstrInfo &TII =
2290       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2291   if (!hasReservedCallFrame(MF)) {
2292     // If we have alloca, convert as follows:
2293     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
2294     // ADJCALLSTACKUP   -> add, sp, sp, amount
2295     MachineInstr &Old = *I;
2296     DebugLoc dl = Old.getDebugLoc();
2297     unsigned Amount = TII.getFrameSize(Old);
2298     if (Amount != 0) {
2299       // We need to keep the stack aligned properly.  To do this, we round the
2300       // amount of space needed for the outgoing arguments up to the next
2301       // alignment boundary.
2302       Amount = alignSPAdjust(Amount);
2303 
2304       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305       assert(!AFI->isThumb1OnlyFunction() &&
2306              "This eliminateCallFramePseudoInstr does not support Thumb1!");
2307       bool isARM = !AFI->isThumbFunction();
2308 
2309       // Replace the pseudo instruction with a new instruction...
2310       unsigned Opc = Old.getOpcode();
2311       int PIdx = Old.findFirstPredOperandIdx();
2312       ARMCC::CondCodes Pred =
2313           (PIdx == -1) ? ARMCC::AL
2314                        : (ARMCC::CondCodes)Old.getOperand(PIdx).getImm();
2315       unsigned PredReg = TII.getFramePred(Old);
2316       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
2317         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, MachineInstr::NoFlags,
2318                      Pred, PredReg);
2319       } else {
2320         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
2321         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, MachineInstr::NoFlags,
2322                      Pred, PredReg);
2323       }
2324     }
2325   }
2326   return MBB.erase(I);
2327 }
2328 
2329 /// Get the minimum constant for ARM that is greater than or equal to the
2330 /// argument. In ARM, constants can have any value that can be produced by
2331 /// rotating an 8-bit value to the right by an even number of bits within a
2332 /// 32-bit word.
alignToARMConstant(uint32_t Value)2333 static uint32_t alignToARMConstant(uint32_t Value) {
2334   unsigned Shifted = 0;
2335 
2336   if (Value == 0)
2337       return 0;
2338 
2339   while (!(Value & 0xC0000000)) {
2340       Value = Value << 2;
2341       Shifted += 2;
2342   }
2343 
2344   bool Carry = (Value & 0x00FFFFFF);
2345   Value = ((Value & 0xFF000000) >> 24) + Carry;
2346 
2347   if (Value & 0x0000100)
2348       Value = Value & 0x000001FC;
2349 
2350   if (Shifted > 24)
2351       Value = Value >> (Shifted - 24);
2352   else
2353       Value = Value << (24 - Shifted);
2354 
2355   return Value;
2356 }
2357 
2358 // The stack limit in the TCB is set to this many bytes above the actual
2359 // stack limit.
2360 static const uint64_t kSplitStackAvailable = 256;
2361 
2362 // Adjust the function prologue to enable split stacks. This currently only
2363 // supports android and linux.
2364 //
2365 // The ABI of the segmented stack prologue is a little arbitrarily chosen, but
2366 // must be well defined in order to allow for consistent implementations of the
2367 // __morestack helper function. The ABI is also not a normal ABI in that it
2368 // doesn't follow the normal calling conventions because this allows the
2369 // prologue of each function to be optimized further.
2370 //
2371 // Currently, the ABI looks like (when calling __morestack)
2372 //
2373 //  * r4 holds the minimum stack size requested for this function call
2374 //  * r5 holds the stack size of the arguments to the function
2375 //  * the beginning of the function is 3 instructions after the call to
2376 //    __morestack
2377 //
2378 // Implementations of __morestack should use r4 to allocate a new stack, r5 to
2379 // place the arguments on to the new stack, and the 3-instruction knowledge to
2380 // jump directly to the body of the function when working on the new stack.
2381 //
2382 // An old (and possibly no longer compatible) implementation of __morestack for
2383 // ARM can be found at [1].
2384 //
2385 // [1] - https://github.com/mozilla/rust/blob/86efd9/src/rt/arch/arm/morestack.S
adjustForSegmentedStacks(MachineFunction & MF,MachineBasicBlock & PrologueMBB) const2386 void ARMFrameLowering::adjustForSegmentedStacks(
2387     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2388   unsigned Opcode;
2389   unsigned CFIIndex;
2390   const ARMSubtarget *ST = &MF.getSubtarget<ARMSubtarget>();
2391   bool Thumb = ST->isThumb();
2392 
2393   // Sadly, this currently doesn't support varargs, platforms other than
2394   // android/linux. Note that thumb1/thumb2 are support for android/linux.
2395   if (MF.getFunction().isVarArg())
2396     report_fatal_error("Segmented stacks do not support vararg functions.");
2397   if (!ST->isTargetAndroid() && !ST->isTargetLinux())
2398     report_fatal_error("Segmented stacks not supported on this platform.");
2399 
2400   MachineFrameInfo &MFI = MF.getFrameInfo();
2401   MachineModuleInfo &MMI = MF.getMMI();
2402   MCContext &Context = MMI.getContext();
2403   const MCRegisterInfo *MRI = Context.getRegisterInfo();
2404   const ARMBaseInstrInfo &TII =
2405       *static_cast<const ARMBaseInstrInfo *>(MF.getSubtarget().getInstrInfo());
2406   ARMFunctionInfo *ARMFI = MF.getInfo<ARMFunctionInfo>();
2407   DebugLoc DL;
2408 
2409   uint64_t StackSize = MFI.getStackSize();
2410 
2411   // Do not generate a prologue for leaf functions with a stack of size zero.
2412   // For non-leaf functions we have to allow for the possibility that the
2413   // callis to a non-split function, as in PR37807. This function could also
2414   // take the address of a non-split function. When the linker tries to adjust
2415   // its non-existent prologue, it would fail with an error. Mark the object
2416   // file so that such failures are not errors. See this Go language bug-report
2417   // https://go-review.googlesource.com/c/go/+/148819/
2418   if (StackSize == 0 && !MFI.hasTailCall()) {
2419     MF.getMMI().setHasNosplitStack(true);
2420     return;
2421   }
2422 
2423   // Use R4 and R5 as scratch registers.
2424   // We save R4 and R5 before use and restore them before leaving the function.
2425   unsigned ScratchReg0 = ARM::R4;
2426   unsigned ScratchReg1 = ARM::R5;
2427   uint64_t AlignedStackSize;
2428 
2429   MachineBasicBlock *PrevStackMBB = MF.CreateMachineBasicBlock();
2430   MachineBasicBlock *PostStackMBB = MF.CreateMachineBasicBlock();
2431   MachineBasicBlock *AllocMBB = MF.CreateMachineBasicBlock();
2432   MachineBasicBlock *GetMBB = MF.CreateMachineBasicBlock();
2433   MachineBasicBlock *McrMBB = MF.CreateMachineBasicBlock();
2434 
2435   // Grab everything that reaches PrologueMBB to update there liveness as well.
2436   SmallPtrSet<MachineBasicBlock *, 8> BeforePrologueRegion;
2437   SmallVector<MachineBasicBlock *, 2> WalkList;
2438   WalkList.push_back(&PrologueMBB);
2439 
2440   do {
2441     MachineBasicBlock *CurMBB = WalkList.pop_back_val();
2442     for (MachineBasicBlock *PredBB : CurMBB->predecessors()) {
2443       if (BeforePrologueRegion.insert(PredBB).second)
2444         WalkList.push_back(PredBB);
2445     }
2446   } while (!WalkList.empty());
2447 
2448   // The order in that list is important.
2449   // The blocks will all be inserted before PrologueMBB using that order.
2450   // Therefore the block that should appear first in the CFG should appear
2451   // first in the list.
2452   MachineBasicBlock *AddedBlocks[] = {PrevStackMBB, McrMBB, GetMBB, AllocMBB,
2453                                       PostStackMBB};
2454 
2455   for (MachineBasicBlock *B : AddedBlocks)
2456     BeforePrologueRegion.insert(B);
2457 
2458   for (const auto &LI : PrologueMBB.liveins()) {
2459     for (MachineBasicBlock *PredBB : BeforePrologueRegion)
2460       PredBB->addLiveIn(LI);
2461   }
2462 
2463   // Remove the newly added blocks from the list, since we know
2464   // we do not have to do the following updates for them.
2465   for (MachineBasicBlock *B : AddedBlocks) {
2466     BeforePrologueRegion.erase(B);
2467     MF.insert(PrologueMBB.getIterator(), B);
2468   }
2469 
2470   for (MachineBasicBlock *MBB : BeforePrologueRegion) {
2471     // Make sure the LiveIns are still sorted and unique.
2472     MBB->sortUniqueLiveIns();
2473     // Replace the edges to PrologueMBB by edges to the sequences
2474     // we are about to add.
2475     MBB->ReplaceUsesOfBlockWith(&PrologueMBB, AddedBlocks[0]);
2476   }
2477 
2478   // The required stack size that is aligned to ARM constant criterion.
2479   AlignedStackSize = alignToARMConstant(StackSize);
2480 
2481   // When the frame size is less than 256 we just compare the stack
2482   // boundary directly to the value of the stack pointer, per gcc.
2483   bool CompareStackPointer = AlignedStackSize < kSplitStackAvailable;
2484 
2485   // We will use two of the callee save registers as scratch registers so we
2486   // need to save those registers onto the stack.
2487   // We will use SR0 to hold stack limit and SR1 to hold the stack size
2488   // requested and arguments for __morestack().
2489   // SR0: Scratch Register #0
2490   // SR1: Scratch Register #1
2491   // push {SR0, SR1}
2492   if (Thumb) {
2493     BuildMI(PrevStackMBB, DL, TII.get(ARM::tPUSH))
2494         .add(predOps(ARMCC::AL))
2495         .addReg(ScratchReg0)
2496         .addReg(ScratchReg1);
2497   } else {
2498     BuildMI(PrevStackMBB, DL, TII.get(ARM::STMDB_UPD))
2499         .addReg(ARM::SP, RegState::Define)
2500         .addReg(ARM::SP)
2501         .add(predOps(ARMCC::AL))
2502         .addReg(ScratchReg0)
2503         .addReg(ScratchReg1);
2504   }
2505 
2506   // Emit the relevant DWARF information about the change in stack pointer as
2507   // well as where to find both r4 and r5 (the callee-save registers)
2508   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 8));
2509   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2510       .addCFIIndex(CFIIndex);
2511   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2512       nullptr, MRI->getDwarfRegNum(ScratchReg1, true), -4));
2513   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2514       .addCFIIndex(CFIIndex);
2515   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2516       nullptr, MRI->getDwarfRegNum(ScratchReg0, true), -8));
2517   BuildMI(PrevStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2518       .addCFIIndex(CFIIndex);
2519 
2520   // mov SR1, sp
2521   if (Thumb) {
2522     BuildMI(McrMBB, DL, TII.get(ARM::tMOVr), ScratchReg1)
2523         .addReg(ARM::SP)
2524         .add(predOps(ARMCC::AL));
2525   } else if (CompareStackPointer) {
2526     BuildMI(McrMBB, DL, TII.get(ARM::MOVr), ScratchReg1)
2527         .addReg(ARM::SP)
2528         .add(predOps(ARMCC::AL))
2529         .add(condCodeOp());
2530   }
2531 
2532   // sub SR1, sp, #StackSize
2533   if (!CompareStackPointer && Thumb) {
2534     BuildMI(McrMBB, DL, TII.get(ARM::tSUBi8), ScratchReg1)
2535         .add(condCodeOp())
2536         .addReg(ScratchReg1)
2537         .addImm(AlignedStackSize)
2538         .add(predOps(ARMCC::AL));
2539   } else if (!CompareStackPointer) {
2540     BuildMI(McrMBB, DL, TII.get(ARM::SUBri), ScratchReg1)
2541         .addReg(ARM::SP)
2542         .addImm(AlignedStackSize)
2543         .add(predOps(ARMCC::AL))
2544         .add(condCodeOp());
2545   }
2546 
2547   if (Thumb && ST->isThumb1Only()) {
2548     unsigned PCLabelId = ARMFI->createPICLabelUId();
2549     ARMConstantPoolValue *NewCPV = ARMConstantPoolSymbol::Create(
2550         MF.getFunction().getContext(), "__STACK_LIMIT", PCLabelId, 0);
2551     MachineConstantPool *MCP = MF.getConstantPool();
2552     unsigned CPI = MCP->getConstantPoolIndex(NewCPV, Align(4));
2553 
2554     // ldr SR0, [pc, offset(STACK_LIMIT)]
2555     BuildMI(GetMBB, DL, TII.get(ARM::tLDRpci), ScratchReg0)
2556         .addConstantPoolIndex(CPI)
2557         .add(predOps(ARMCC::AL));
2558 
2559     // ldr SR0, [SR0]
2560     BuildMI(GetMBB, DL, TII.get(ARM::tLDRi), ScratchReg0)
2561         .addReg(ScratchReg0)
2562         .addImm(0)
2563         .add(predOps(ARMCC::AL));
2564   } else {
2565     // Get TLS base address from the coprocessor
2566     // mrc p15, #0, SR0, c13, c0, #3
2567     BuildMI(McrMBB, DL, TII.get(Thumb ? ARM::t2MRC : ARM::MRC),
2568             ScratchReg0)
2569         .addImm(15)
2570         .addImm(0)
2571         .addImm(13)
2572         .addImm(0)
2573         .addImm(3)
2574         .add(predOps(ARMCC::AL));
2575 
2576     // Use the last tls slot on android and a private field of the TCP on linux.
2577     assert(ST->isTargetAndroid() || ST->isTargetLinux());
2578     unsigned TlsOffset = ST->isTargetAndroid() ? 63 : 1;
2579 
2580     // Get the stack limit from the right offset
2581     // ldr SR0, [sr0, #4 * TlsOffset]
2582     BuildMI(GetMBB, DL, TII.get(Thumb ? ARM::t2LDRi12 : ARM::LDRi12),
2583             ScratchReg0)
2584         .addReg(ScratchReg0)
2585         .addImm(4 * TlsOffset)
2586         .add(predOps(ARMCC::AL));
2587   }
2588 
2589   // Compare stack limit with stack size requested.
2590   // cmp SR0, SR1
2591   Opcode = Thumb ? ARM::tCMPr : ARM::CMPrr;
2592   BuildMI(GetMBB, DL, TII.get(Opcode))
2593       .addReg(ScratchReg0)
2594       .addReg(ScratchReg1)
2595       .add(predOps(ARMCC::AL));
2596 
2597   // This jump is taken if StackLimit < SP - stack required.
2598   Opcode = Thumb ? ARM::tBcc : ARM::Bcc;
2599   BuildMI(GetMBB, DL, TII.get(Opcode)).addMBB(PostStackMBB)
2600        .addImm(ARMCC::LO)
2601        .addReg(ARM::CPSR);
2602 
2603 
2604   // Calling __morestack(StackSize, Size of stack arguments).
2605   // __morestack knows that the stack size requested is in SR0(r4)
2606   // and amount size of stack arguments is in SR1(r5).
2607 
2608   // Pass first argument for the __morestack by Scratch Register #0.
2609   //   The amount size of stack required
2610   if (Thumb) {
2611     BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg0)
2612         .add(condCodeOp())
2613         .addImm(AlignedStackSize)
2614         .add(predOps(ARMCC::AL));
2615   } else {
2616     BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg0)
2617         .addImm(AlignedStackSize)
2618         .add(predOps(ARMCC::AL))
2619         .add(condCodeOp());
2620   }
2621   // Pass second argument for the __morestack by Scratch Register #1.
2622   //   The amount size of stack consumed to save function arguments.
2623   if (Thumb) {
2624     BuildMI(AllocMBB, DL, TII.get(ARM::tMOVi8), ScratchReg1)
2625         .add(condCodeOp())
2626         .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2627         .add(predOps(ARMCC::AL));
2628   } else {
2629     BuildMI(AllocMBB, DL, TII.get(ARM::MOVi), ScratchReg1)
2630         .addImm(alignToARMConstant(ARMFI->getArgumentStackSize()))
2631         .add(predOps(ARMCC::AL))
2632         .add(condCodeOp());
2633   }
2634 
2635   // push {lr} - Save return address of this function.
2636   if (Thumb) {
2637     BuildMI(AllocMBB, DL, TII.get(ARM::tPUSH))
2638         .add(predOps(ARMCC::AL))
2639         .addReg(ARM::LR);
2640   } else {
2641     BuildMI(AllocMBB, DL, TII.get(ARM::STMDB_UPD))
2642         .addReg(ARM::SP, RegState::Define)
2643         .addReg(ARM::SP)
2644         .add(predOps(ARMCC::AL))
2645         .addReg(ARM::LR);
2646   }
2647 
2648   // Emit the DWARF info about the change in stack as well as where to find the
2649   // previous link register
2650   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 12));
2651   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2652       .addCFIIndex(CFIIndex);
2653   CFIIndex = MF.addFrameInst(MCCFIInstruction::createOffset(
2654         nullptr, MRI->getDwarfRegNum(ARM::LR, true), -12));
2655   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2656       .addCFIIndex(CFIIndex);
2657 
2658   // Call __morestack().
2659   if (Thumb) {
2660     BuildMI(AllocMBB, DL, TII.get(ARM::tBL))
2661         .add(predOps(ARMCC::AL))
2662         .addExternalSymbol("__morestack");
2663   } else {
2664     BuildMI(AllocMBB, DL, TII.get(ARM::BL))
2665         .addExternalSymbol("__morestack");
2666   }
2667 
2668   // pop {lr} - Restore return address of this original function.
2669   if (Thumb) {
2670     if (ST->isThumb1Only()) {
2671       BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2672           .add(predOps(ARMCC::AL))
2673           .addReg(ScratchReg0);
2674       BuildMI(AllocMBB, DL, TII.get(ARM::tMOVr), ARM::LR)
2675           .addReg(ScratchReg0)
2676           .add(predOps(ARMCC::AL));
2677     } else {
2678       BuildMI(AllocMBB, DL, TII.get(ARM::t2LDR_POST))
2679           .addReg(ARM::LR, RegState::Define)
2680           .addReg(ARM::SP, RegState::Define)
2681           .addReg(ARM::SP)
2682           .addImm(4)
2683           .add(predOps(ARMCC::AL));
2684     }
2685   } else {
2686     BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2687         .addReg(ARM::SP, RegState::Define)
2688         .addReg(ARM::SP)
2689         .add(predOps(ARMCC::AL))
2690         .addReg(ARM::LR);
2691   }
2692 
2693   // Restore SR0 and SR1 in case of __morestack() was called.
2694   // __morestack() will skip PostStackMBB block so we need to restore
2695   // scratch registers from here.
2696   // pop {SR0, SR1}
2697   if (Thumb) {
2698     BuildMI(AllocMBB, DL, TII.get(ARM::tPOP))
2699         .add(predOps(ARMCC::AL))
2700         .addReg(ScratchReg0)
2701         .addReg(ScratchReg1);
2702   } else {
2703     BuildMI(AllocMBB, DL, TII.get(ARM::LDMIA_UPD))
2704         .addReg(ARM::SP, RegState::Define)
2705         .addReg(ARM::SP)
2706         .add(predOps(ARMCC::AL))
2707         .addReg(ScratchReg0)
2708         .addReg(ScratchReg1);
2709   }
2710 
2711   // Update the CFA offset now that we've popped
2712   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
2713   BuildMI(AllocMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2714       .addCFIIndex(CFIIndex);
2715 
2716   // Return from this function.
2717   BuildMI(AllocMBB, DL, TII.get(ST->getReturnOpcode())).add(predOps(ARMCC::AL));
2718 
2719   // Restore SR0 and SR1 in case of __morestack() was not called.
2720   // pop {SR0, SR1}
2721   if (Thumb) {
2722     BuildMI(PostStackMBB, DL, TII.get(ARM::tPOP))
2723         .add(predOps(ARMCC::AL))
2724         .addReg(ScratchReg0)
2725         .addReg(ScratchReg1);
2726   } else {
2727     BuildMI(PostStackMBB, DL, TII.get(ARM::LDMIA_UPD))
2728         .addReg(ARM::SP, RegState::Define)
2729         .addReg(ARM::SP)
2730         .add(predOps(ARMCC::AL))
2731         .addReg(ScratchReg0)
2732         .addReg(ScratchReg1);
2733   }
2734 
2735   // Update the CFA offset now that we've popped
2736   CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 0));
2737   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2738       .addCFIIndex(CFIIndex);
2739 
2740   // Tell debuggers that r4 and r5 are now the same as they were in the
2741   // previous function, that they're the "Same Value".
2742   CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2743       nullptr, MRI->getDwarfRegNum(ScratchReg0, true)));
2744   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2745       .addCFIIndex(CFIIndex);
2746   CFIIndex = MF.addFrameInst(MCCFIInstruction::createSameValue(
2747       nullptr, MRI->getDwarfRegNum(ScratchReg1, true)));
2748   BuildMI(PostStackMBB, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
2749       .addCFIIndex(CFIIndex);
2750 
2751   // Organizing MBB lists
2752   PostStackMBB->addSuccessor(&PrologueMBB);
2753 
2754   AllocMBB->addSuccessor(PostStackMBB);
2755 
2756   GetMBB->addSuccessor(PostStackMBB);
2757   GetMBB->addSuccessor(AllocMBB);
2758 
2759   McrMBB->addSuccessor(GetMBB);
2760 
2761   PrevStackMBB->addSuccessor(McrMBB);
2762 
2763 #ifdef EXPENSIVE_CHECKS
2764   MF.verify();
2765 #endif
2766 }
2767