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