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