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