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