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