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