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