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