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