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