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