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