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