71b60794f32fc5f5a291eddd500eb300af177335
[oota-llvm.git] / lib / Target / ARM / ARMFrameInfo.cpp
1 //=======- ARMFrameInfo.cpp - ARM Frame Information ------------*- C++ -*-====//
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 TargetFrameInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMFrameInfo.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/RegisterScavenging.h"
23 #include "llvm/Target/TargetOptions.h"
24
25 using namespace llvm;
26
27 /// hasFP - Return true if the specified function should have a dedicated frame
28 /// pointer register.  This is true if the function has variable sized allocas
29 /// or if frame pointer elimination is disabled.
30 ///
31 bool ARMFrameInfo::hasFP(const MachineFunction &MF) const {
32   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
33
34   // Mac OS X requires FP not to be clobbered for backtracing purpose.
35   if (STI.isTargetDarwin())
36     return true;
37
38   const MachineFrameInfo *MFI = MF.getFrameInfo();
39   // Always eliminate non-leaf frame pointers.
40   return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
41           RegInfo->needsStackRealignment(MF) ||
42           MFI->hasVarSizedObjects() ||
43           MFI->isFrameAddressTaken());
44 }
45
46 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
47 // not required, we reserve argument space for call sites in the function
48 // immediately on entry to the current function. This eliminates the need for
49 // add/sub sp brackets around call sites. Returns true if the call frame is
50 // included as part of the stack frame.
51 bool ARMFrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
52   const MachineFrameInfo *FFI = MF.getFrameInfo();
53   unsigned CFSize = FFI->getMaxCallFrameSize();
54   // It's not always a good idea to include the call frame as part of the
55   // stack frame. ARM (especially Thumb) has small immediate offset to
56   // address the stack frame. So a large call frame can cause poor codegen
57   // and may even makes it impossible to scavenge a register.
58   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
59     return false;
60
61   return !MF.getFrameInfo()->hasVarSizedObjects();
62 }
63
64 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
65 // call frame pseudos can be simplified. Unlike most targets, having a FP
66 // is not sufficient here since we still may reference some objects via SP
67 // even when FP is available in Thumb2 mode.
68 bool ARMFrameInfo::canSimplifyCallFramePseudos(const MachineFunction &MF)const {
69   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
70 }
71
72 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
73   for (unsigned i = 0; CSRegs[i]; ++i)
74     if (Reg == CSRegs[i])
75       return true;
76   return false;
77 }
78
79 static bool isCSRestore(MachineInstr *MI,
80                         const ARMBaseInstrInfo &TII,
81                         const unsigned *CSRegs) {
82   // Integer spill area is handled with "pop".
83   if (MI->getOpcode() == ARM::LDMIA_RET ||
84       MI->getOpcode() == ARM::t2LDMIA_RET ||
85       MI->getOpcode() == ARM::LDMIA_UPD ||
86       MI->getOpcode() == ARM::t2LDMIA_UPD ||
87       MI->getOpcode() == ARM::VLDMDIA_UPD) {
88     // The first two operands are predicates. The last two are
89     // imp-def and imp-use of SP. Check everything in between.
90     for (int i = 5, e = MI->getNumOperands(); i != e; ++i)
91       if (!isCalleeSavedRegister(MI->getOperand(i).getReg(), CSRegs))
92         return false;
93     return true;
94   }
95
96   return false;
97 }
98
99 static void
100 emitSPUpdate(bool isARM,
101              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
102              DebugLoc dl, const ARMBaseInstrInfo &TII,
103              int NumBytes,
104              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
105   if (isARM)
106     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
107                             Pred, PredReg, TII);
108   else
109     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
110                            Pred, PredReg, TII);
111 }
112
113 void ARMFrameInfo::emitPrologue(MachineFunction &MF) const {
114   MachineBasicBlock &MBB = MF.front();
115   MachineBasicBlock::iterator MBBI = MBB.begin();
116   MachineFrameInfo  *MFI = MF.getFrameInfo();
117   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
118   const ARMBaseRegisterInfo *RegInfo =
119     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
120   const ARMBaseInstrInfo &TII =
121     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
122   assert(!AFI->isThumb1OnlyFunction() &&
123          "This emitPrologue does not support Thumb1!");
124   bool isARM = !AFI->isThumbFunction();
125   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
126   unsigned NumBytes = MFI->getStackSize();
127   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
128   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
129   unsigned FramePtr = RegInfo->getFrameRegister(MF);
130
131   // Determine the sizes of each callee-save spill areas and record which frame
132   // belongs to which callee-save spill areas.
133   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
134   int FramePtrSpillFI = 0;
135
136   // Allocate the vararg register save area. This is not counted in NumBytes.
137   if (VARegSaveSize)
138     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
139
140   if (!AFI->hasStackFrame()) {
141     if (NumBytes != 0)
142       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
143     return;
144   }
145
146   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
147     unsigned Reg = CSI[i].getReg();
148     int FI = CSI[i].getFrameIdx();
149     switch (Reg) {
150     case ARM::R4:
151     case ARM::R5:
152     case ARM::R6:
153     case ARM::R7:
154     case ARM::LR:
155       if (Reg == FramePtr)
156         FramePtrSpillFI = FI;
157       AFI->addGPRCalleeSavedArea1Frame(FI);
158       GPRCS1Size += 4;
159       break;
160     case ARM::R8:
161     case ARM::R9:
162     case ARM::R10:
163     case ARM::R11:
164       if (Reg == FramePtr)
165         FramePtrSpillFI = FI;
166       if (STI.isTargetDarwin()) {
167         AFI->addGPRCalleeSavedArea2Frame(FI);
168         GPRCS2Size += 4;
169       } else {
170         AFI->addGPRCalleeSavedArea1Frame(FI);
171         GPRCS1Size += 4;
172       }
173       break;
174     default:
175       AFI->addDPRCalleeSavedAreaFrame(FI);
176       DPRCSSize += 8;
177     }
178   }
179
180   // Move past area 1.
181   if (GPRCS1Size > 0) MBBI++;
182
183   // Set FP to point to the stack slot that contains the previous FP.
184   // For Darwin, FP is R7, which has now been stored in spill area 1.
185   // Otherwise, if this is not Darwin, all the callee-saved registers go
186   // into spill area 1, including the FP in R11.  In either case, it is
187   // now safe to emit this assignment.
188   bool HasFP = hasFP(MF);
189   if (HasFP) {
190     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
191     MachineInstrBuilder MIB =
192       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
193       .addFrameIndex(FramePtrSpillFI).addImm(0);
194     AddDefaultCC(AddDefaultPred(MIB));
195   }
196
197   // Move past area 2.
198   if (GPRCS2Size > 0) MBBI++;
199
200   // Determine starting offsets of spill areas.
201   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
202   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
203   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
204   if (HasFP)
205     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
206                                 NumBytes);
207   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
208   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
209   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
210
211   // Move past area 3.
212   if (DPRCSSize > 0) MBBI++;
213
214   NumBytes = DPRCSOffset;
215   if (NumBytes) {
216     // Adjust SP after all the callee-save spills.
217     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
218     if (HasFP && isARM)
219       // Restore from fp only in ARM mode: e.g. sub sp, r7, #24
220       // Note it's not safe to do this in Thumb2 mode because it would have
221       // taken two instructions:
222       // mov sp, r7
223       // sub sp, #24
224       // If an interrupt is taken between the two instructions, then sp is in
225       // an inconsistent state (pointing to the middle of callee-saved area).
226       // The interrupt handler can end up clobbering the registers.
227       AFI->setShouldRestoreSPFromFP(true);
228   }
229
230   if (STI.isTargetELF() && hasFP(MF))
231     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
232                              AFI->getFramePtrSpillOffset());
233
234   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
235   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
236   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
237
238   // If we need dynamic stack realignment, do it here. Be paranoid and make
239   // sure if we also have VLAs, we have a base pointer for frame access.
240   if (RegInfo->needsStackRealignment(MF)) {
241     unsigned MaxAlign = MFI->getMaxAlignment();
242     assert (!AFI->isThumb1OnlyFunction());
243     if (!AFI->isThumbFunction()) {
244       // Emit bic sp, sp, MaxAlign
245       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
246                                           TII.get(ARM::BICri), ARM::SP)
247                                   .addReg(ARM::SP, RegState::Kill)
248                                   .addImm(MaxAlign-1)));
249     } else {
250       // We cannot use sp as source/dest register here, thus we're emitting the
251       // following sequence:
252       // mov r4, sp
253       // bic r4, r4, MaxAlign
254       // mov sp, r4
255       // FIXME: It will be better just to find spare register here.
256       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
257         .addReg(ARM::SP, RegState::Kill);
258       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
259                                           TII.get(ARM::t2BICri), ARM::R4)
260                                   .addReg(ARM::R4, RegState::Kill)
261                                   .addImm(MaxAlign-1)));
262       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
263         .addReg(ARM::R4, RegState::Kill);
264     }
265
266     AFI->setShouldRestoreSPFromFP(true);
267   }
268
269   // If we need a base pointer, set it up here. It's whatever the value
270   // of the stack pointer is at this point. Any variable size objects
271   // will be allocated after this, so we can still use the base pointer
272   // to reference locals.
273   if (RegInfo->hasBasePointer(MF)) {
274     if (isARM)
275       BuildMI(MBB, MBBI, dl,
276               TII.get(ARM::MOVr), RegInfo->getBaseRegister())
277         .addReg(ARM::SP)
278         .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
279     else
280       BuildMI(MBB, MBBI, dl,
281               TII.get(ARM::tMOVgpr2gpr), RegInfo->getBaseRegister())
282         .addReg(ARM::SP);
283   }
284
285   // If the frame has variable sized objects then the epilogue must restore
286   // the sp from fp.
287   if (MFI->hasVarSizedObjects())
288     AFI->setShouldRestoreSPFromFP(true);
289 }
290
291 void ARMFrameInfo::emitEpilogue(MachineFunction &MF,
292                                 MachineBasicBlock &MBB) const {
293   MachineBasicBlock::iterator MBBI = prior(MBB.end());
294   assert(MBBI->getDesc().isReturn() &&
295          "Can only insert epilog into returning blocks");
296   unsigned RetOpcode = MBBI->getOpcode();
297   DebugLoc dl = MBBI->getDebugLoc();
298   MachineFrameInfo *MFI = MF.getFrameInfo();
299   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
300   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
301   const ARMBaseInstrInfo &TII =
302     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
303   assert(!AFI->isThumb1OnlyFunction() &&
304          "This emitEpilogue does not support Thumb1!");
305   bool isARM = !AFI->isThumbFunction();
306
307   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
308   int NumBytes = (int)MFI->getStackSize();
309   unsigned FramePtr = RegInfo->getFrameRegister(MF);
310
311   if (!AFI->hasStackFrame()) {
312     if (NumBytes != 0)
313       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
314   } else {
315     // Unwind MBBI to point to first LDR / VLDRD.
316     const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
317     if (MBBI != MBB.begin()) {
318       do
319         --MBBI;
320       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
321       if (!isCSRestore(MBBI, TII, CSRegs))
322         ++MBBI;
323     }
324
325     // Move SP to start of FP callee save spill area.
326     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
327                  AFI->getGPRCalleeSavedArea2Size() +
328                  AFI->getDPRCalleeSavedAreaSize());
329
330     // Reset SP based on frame pointer only if the stack frame extends beyond
331     // frame pointer stack slot or target is ELF and the function has FP.
332     if (AFI->shouldRestoreSPFromFP()) {
333       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
334       if (NumBytes) {
335         if (isARM)
336           emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
337                                   ARMCC::AL, 0, TII);
338         else {
339           // It's not possible to restore SP from FP in a single instruction.
340           // For Darwin, this looks like:
341           // mov sp, r7
342           // sub sp, #24
343           // This is bad, if an interrupt is taken after the mov, sp is in an
344           // inconsistent state.
345           // Use the first callee-saved register as a scratch register.
346           assert(MF.getRegInfo().isPhysRegUsed(ARM::R4) &&
347                  "No scratch register to restore SP from FP!");
348           emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::R4, FramePtr, -NumBytes,
349                                  ARMCC::AL, 0, TII);
350           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
351             .addReg(ARM::R4);
352         }
353       } else {
354         // Thumb2 or ARM.
355         if (isARM)
356           BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
357             .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
358         else
359           BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
360             .addReg(FramePtr);
361       }
362     } else if (NumBytes)
363       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
364
365     // Increment past our save areas.
366     if (AFI->getDPRCalleeSavedAreaSize()) MBBI++;
367     if (AFI->getGPRCalleeSavedArea2Size()) MBBI++;
368     if (AFI->getGPRCalleeSavedArea1Size()) MBBI++;
369   }
370
371   if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
372       RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
373     // Tail call return: adjust the stack pointer and jump to callee.
374     MBBI = prior(MBB.end());
375     MachineOperand &JumpTarget = MBBI->getOperand(0);
376
377     // Jump to label or value in register.
378     if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND) {
379       unsigned TCOpcode = (RetOpcode == ARM::TCRETURNdi)
380         ? (STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)
381         : (STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND);
382       MachineInstrBuilder MIB = BuildMI(MBB, MBBI, dl, TII.get(TCOpcode));
383       if (JumpTarget.isGlobal())
384         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
385                              JumpTarget.getTargetFlags());
386       else {
387         assert(JumpTarget.isSymbol());
388         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
389                               JumpTarget.getTargetFlags());
390       }
391     } else if (RetOpcode == ARM::TCRETURNri) {
392       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
393         addReg(JumpTarget.getReg(), RegState::Kill);
394     } else if (RetOpcode == ARM::TCRETURNriND) {
395       BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
396         addReg(JumpTarget.getReg(), RegState::Kill);
397     }
398
399     MachineInstr *NewMI = prior(MBBI);
400     for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
401       NewMI->addOperand(MBBI->getOperand(i));
402
403     // Delete the pseudo instruction TCRETURN.
404     MBB.erase(MBBI);
405   }
406
407   if (VARegSaveSize)
408     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
409 }
410
411 // Provide a base+offset reference to an FI slot for debug info. It's the
412 // same as what we use for resolving the code-gen references for now.
413 // FIXME: This can go wrong when references are SP-relative and simple call
414 //        frames aren't used.
415 int
416 ARMFrameInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
417                                      unsigned &FrameReg) const {
418   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
419 }
420
421 int
422 ARMFrameInfo::ResolveFrameIndexReference(const MachineFunction &MF,
423                                          int FI,
424                                          unsigned &FrameReg,
425                                          int SPAdj) const {
426   const MachineFrameInfo *MFI = MF.getFrameInfo();
427   const ARMBaseRegisterInfo *RegInfo =
428     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
429   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
430   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
431   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
432   bool isFixed = MFI->isFixedObjectIndex(FI);
433
434   FrameReg = ARM::SP;
435   Offset += SPAdj;
436   if (AFI->isGPRCalleeSavedArea1Frame(FI))
437     return Offset - AFI->getGPRCalleeSavedArea1Offset();
438   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
439     return Offset - AFI->getGPRCalleeSavedArea2Offset();
440   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
441     return Offset - AFI->getDPRCalleeSavedAreaOffset();
442
443   // When dynamically realigning the stack, use the frame pointer for
444   // parameters, and the stack/base pointer for locals.
445   if (RegInfo->needsStackRealignment(MF)) {
446     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
447     if (isFixed) {
448       FrameReg = RegInfo->getFrameRegister(MF);
449       Offset = FPOffset;
450     } else if (MFI->hasVarSizedObjects()) {
451       assert(RegInfo->hasBasePointer(MF) &&
452              "VLAs and dynamic stack alignment, but missing base pointer!");
453       FrameReg = RegInfo->getBaseRegister();
454     }
455     return Offset;
456   }
457
458   // If there is a frame pointer, use it when we can.
459   if (hasFP(MF) && AFI->hasStackFrame()) {
460     // Use frame pointer to reference fixed objects. Use it for locals if
461     // there are VLAs (and thus the SP isn't reliable as a base).
462     if (isFixed || (MFI->hasVarSizedObjects() &&
463                     !RegInfo->hasBasePointer(MF))) {
464       FrameReg = RegInfo->getFrameRegister(MF);
465       return FPOffset;
466     } else if (MFI->hasVarSizedObjects()) {
467       assert(RegInfo->hasBasePointer(MF) && "missing base pointer!");
468       // Try to use the frame pointer if we can, else use the base pointer
469       // since it's available. This is handy for the emergency spill slot, in
470       // particular.
471       if (AFI->isThumb2Function()) {
472         if (FPOffset >= -255 && FPOffset < 0) {
473           FrameReg = RegInfo->getFrameRegister(MF);
474           return FPOffset;
475         }
476       } else
477         FrameReg = RegInfo->getBaseRegister();
478     } else if (AFI->isThumb2Function()) {
479       // In Thumb2 mode, the negative offset is very limited. Try to avoid
480       // out of range references.
481       if (FPOffset >= -255 && FPOffset < 0) {
482         FrameReg = RegInfo->getFrameRegister(MF);
483         return FPOffset;
484       }
485     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
486       // Otherwise, use SP or FP, whichever is closer to the stack slot.
487       FrameReg = RegInfo->getFrameRegister(MF);
488       return FPOffset;
489     }
490   }
491   // Use the base pointer if we have one.
492   if (RegInfo->hasBasePointer(MF))
493     FrameReg = RegInfo->getBaseRegister();
494   return Offset;
495 }
496
497 int ARMFrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
498   unsigned FrameReg;
499   return getFrameIndexReference(MF, FI, FrameReg);
500 }
501
502 void ARMFrameInfo::emitPushInst(MachineBasicBlock &MBB,
503                                 MachineBasicBlock::iterator MI,
504                                 const std::vector<CalleeSavedInfo> &CSI,
505                                 unsigned StmOpc, unsigned StrOpc, bool NoGap,
506                                 bool(*Func)(unsigned, bool)) const {
507   MachineFunction &MF = *MBB.getParent();
508   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
509
510   DebugLoc DL;
511   if (MI != MBB.end()) DL = MI->getDebugLoc();
512
513   SmallVector<std::pair<unsigned,bool>, 4> Regs;
514   unsigned i = CSI.size();
515   while (i != 0) {
516     unsigned LastReg = 0;
517     for (; i != 0; --i) {
518       unsigned Reg = CSI[i-1].getReg();
519       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
520
521       // Add the callee-saved register as live-in unless it's LR and
522       // @llvm.returnaddress is called. If LR is returned for
523       // @llvm.returnaddress then it's already added to the function and
524       // entry block live-in sets.
525       bool isKill = true;
526       if (Reg == ARM::LR) {
527         if (MF.getFrameInfo()->isReturnAddressTaken() &&
528             MF.getRegInfo().isLiveIn(Reg))
529           isKill = false;
530       }
531
532       if (isKill)
533         MBB.addLiveIn(Reg);
534
535       // If NoGap is true, push consecutive registers and then leave the rest
536       // for other instructions. e.g.
537       // vpush {d8, d10, d11} -> vpush {d8}, vpush {d10, d11}
538       if (NoGap && LastReg && LastReg != Reg-1)
539         break;
540       LastReg = Reg;
541       Regs.push_back(std::make_pair(Reg, isKill));
542     }
543
544     if (Regs.empty())
545       continue;
546     if (Regs.size() > 1 || StrOpc== 0) {
547       MachineInstrBuilder MIB =
548         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(StmOpc), ARM::SP)
549                        .addReg(ARM::SP));
550       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
551         MIB.addReg(Regs[i].first, getKillRegState(Regs[i].second));
552     } else if (Regs.size() == 1) {
553       MachineInstrBuilder MIB = BuildMI(MBB, MI, DL, TII.get(StrOpc),
554                                         ARM::SP)
555         .addReg(Regs[0].first, getKillRegState(Regs[0].second))
556         .addReg(ARM::SP);
557       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
558       // that refactoring is complete (eventually).
559       if (StrOpc == ARM::STR_PRE) {
560         MIB.addReg(0);
561         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::sub, 4, ARM_AM::no_shift));
562       } else
563         MIB.addImm(-4);
564       AddDefaultPred(MIB);
565     }
566     Regs.clear();
567   }
568 }
569
570 void ARMFrameInfo::emitPopInst(MachineBasicBlock &MBB,
571                                MachineBasicBlock::iterator MI,
572                                const std::vector<CalleeSavedInfo> &CSI,
573                                unsigned LdmOpc, unsigned LdrOpc,
574                                bool isVarArg, bool NoGap,
575                                bool(*Func)(unsigned, bool)) const {
576   MachineFunction &MF = *MBB.getParent();
577   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
578   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
579   DebugLoc DL = MI->getDebugLoc();
580
581   SmallVector<unsigned, 4> Regs;
582   unsigned i = CSI.size();
583   while (i != 0) {
584     unsigned LastReg = 0;
585     bool DeleteRet = false;
586     for (; i != 0; --i) {
587       unsigned Reg = CSI[i-1].getReg();
588       if (!(Func)(Reg, STI.isTargetDarwin())) continue;
589
590       if (Reg == ARM::LR && !isVarArg) {
591         Reg = ARM::PC;
592         LdmOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_RET : ARM::LDMIA_RET;
593         // Fold the return instruction into the LDM.
594         DeleteRet = true;
595       }
596
597       // If NoGap is true, pop consecutive registers and then leave the rest
598       // for other instructions. e.g.
599       // vpop {d8, d10, d11} -> vpop {d8}, vpop {d10, d11}
600       if (NoGap && LastReg && LastReg != Reg-1)
601         break;
602
603       LastReg = Reg;
604       Regs.push_back(Reg);
605     }
606
607     if (Regs.empty())
608       continue;
609     if (Regs.size() > 1 || LdrOpc == 0) {
610       MachineInstrBuilder MIB =
611         AddDefaultPred(BuildMI(MBB, MI, DL, TII.get(LdmOpc), ARM::SP)
612                        .addReg(ARM::SP));
613       for (unsigned i = 0, e = Regs.size(); i < e; ++i)
614         MIB.addReg(Regs[i], getDefRegState(true));
615       if (DeleteRet)
616         MI->eraseFromParent();
617       MI = MIB;
618     } else if (Regs.size() == 1) {
619       // If we adjusted the reg to PC from LR above, switch it back here. We
620       // only do that for LDM.
621       if (Regs[0] == ARM::PC)
622         Regs[0] = ARM::LR;
623       MachineInstrBuilder MIB =
624         BuildMI(MBB, MI, DL, TII.get(LdrOpc), Regs[0])
625           .addReg(ARM::SP, RegState::Define)
626           .addReg(ARM::SP);
627       // ARM mode needs an extra reg0 here due to addrmode2. Will go away once
628       // that refactoring is complete (eventually).
629       if (LdrOpc == ARM::LDR_POST) {
630         MIB.addReg(0);
631         MIB.addImm(ARM_AM::getAM2Opc(ARM_AM::add, 4, ARM_AM::no_shift));
632       } else
633         MIB.addImm(4);
634       AddDefaultPred(MIB);
635     }
636     Regs.clear();
637   }
638 }
639
640 bool ARMFrameInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
641                                              MachineBasicBlock::iterator MI,
642                                        const std::vector<CalleeSavedInfo> &CSI,
643                                        const TargetRegisterInfo *TRI) const {
644   if (CSI.empty())
645     return false;
646
647   MachineFunction &MF = *MBB.getParent();
648   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
649   DebugLoc DL = MI->getDebugLoc();
650
651   unsigned PushOpc = AFI->isThumbFunction() ? ARM::t2STMDB_UPD : ARM::STMDB_UPD;
652   unsigned PushOneOpc = AFI->isThumbFunction() ? ARM::t2STR_PRE : ARM::STR_PRE;
653   unsigned FltOpc = ARM::VSTMDDB_UPD;
654   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea1Register);
655   emitPushInst(MBB, MI, CSI, PushOpc, PushOneOpc, false, &isARMArea2Register);
656   emitPushInst(MBB, MI, CSI, FltOpc,  0, true,  &isARMArea3Register);
657
658   return true;
659 }
660
661 bool ARMFrameInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
662                                                MachineBasicBlock::iterator MI,
663                                        const std::vector<CalleeSavedInfo> &CSI,
664                                          const TargetRegisterInfo *TRI) const {
665   if (CSI.empty())
666     return false;
667
668   MachineFunction &MF = *MBB.getParent();
669   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
670   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
671   DebugLoc DL = MI->getDebugLoc();
672
673   unsigned PopOpc = AFI->isThumbFunction() ? ARM::t2LDMIA_UPD : ARM::LDMIA_UPD;
674   unsigned LdrOpc = AFI->isThumbFunction() ? ARM::t2LDR_POST : ARM::LDR_POST;
675   unsigned FltOpc = ARM::VLDMDIA_UPD;
676   emitPopInst(MBB, MI, CSI, FltOpc, 0, isVarArg, true,  &isARMArea3Register);
677   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
678               &isARMArea2Register);
679   emitPopInst(MBB, MI, CSI, PopOpc, LdrOpc, isVarArg, false,
680               &isARMArea1Register);
681
682   return true;
683 }
684
685 // FIXME: Make generic?
686 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
687                                        const ARMBaseInstrInfo &TII) {
688   unsigned FnSize = 0;
689   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
690        MBBI != E; ++MBBI) {
691     const MachineBasicBlock &MBB = *MBBI;
692     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
693          I != E; ++I)
694       FnSize += TII.GetInstSizeInBytes(I);
695   }
696   return FnSize;
697 }
698
699 /// estimateStackSize - Estimate and return the size of the frame.
700 /// FIXME: Make generic?
701 static unsigned estimateStackSize(MachineFunction &MF) {
702   const MachineFrameInfo *FFI = MF.getFrameInfo();
703   int Offset = 0;
704   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
705     int FixedOff = -FFI->getObjectOffset(i);
706     if (FixedOff > Offset) Offset = FixedOff;
707   }
708   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
709     if (FFI->isDeadObjectIndex(i))
710       continue;
711     Offset += FFI->getObjectSize(i);
712     unsigned Align = FFI->getObjectAlignment(i);
713     // Adjust to alignment boundary
714     Offset = (Offset+Align-1)/Align*Align;
715   }
716   return (unsigned)Offset;
717 }
718
719 /// estimateRSStackSizeLimit - Look at each instruction that references stack
720 /// frames and return the stack size limit beyond which some of these
721 /// instructions will require a scratch register during their expansion later.
722 // FIXME: Move to TII?
723 static unsigned estimateRSStackSizeLimit(MachineFunction &MF,
724                                          const TargetFrameInfo *TFI) {
725   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
726   unsigned Limit = (1 << 12) - 1;
727   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
728     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
729          I != E; ++I) {
730       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
731         if (!I->getOperand(i).isFI()) continue;
732
733         // When using ADDri to get the address of a stack object, 255 is the
734         // largest offset guaranteed to fit in the immediate offset.
735         if (I->getOpcode() == ARM::ADDri) {
736           Limit = std::min(Limit, (1U << 8) - 1);
737           break;
738         }
739
740         // Otherwise check the addressing mode.
741         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
742         case ARMII::AddrMode3:
743         case ARMII::AddrModeT2_i8:
744           Limit = std::min(Limit, (1U << 8) - 1);
745           break;
746         case ARMII::AddrMode5:
747         case ARMII::AddrModeT2_i8s4:
748           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
749           break;
750         case ARMII::AddrModeT2_i12:
751           // i12 supports only positive offset so these will be converted to
752           // i8 opcodes. See llvm::rewriteT2FrameIndex.
753           if (TFI->hasFP(MF) && AFI->hasStackFrame())
754             Limit = std::min(Limit, (1U << 8) - 1);
755           break;
756         case ARMII::AddrMode4:
757         case ARMII::AddrMode6:
758           // Addressing modes 4 & 6 (load/store) instructions can't encode an
759           // immediate offset for stack references.
760           return 0;
761         default:
762           break;
763         }
764         break; // At most one FI per instruction
765       }
766     }
767   }
768
769   return Limit;
770 }
771
772 void
773 ARMFrameInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
774                                                    RegScavenger *RS) const {
775   // This tells PEI to spill the FP as if it is any other callee-save register
776   // to take advantage the eliminateFrameIndex machinery. This also ensures it
777   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
778   // to combine multiple loads / stores.
779   bool CanEliminateFrame = true;
780   bool CS1Spilled = false;
781   bool LRSpilled = false;
782   unsigned NumGPRSpills = 0;
783   SmallVector<unsigned, 4> UnspilledCS1GPRs;
784   SmallVector<unsigned, 4> UnspilledCS2GPRs;
785   const ARMBaseRegisterInfo *RegInfo =
786     static_cast<const ARMBaseRegisterInfo*>(MF.getTarget().getRegisterInfo());
787   const ARMBaseInstrInfo &TII =
788     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
789   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
790   MachineFrameInfo *MFI = MF.getFrameInfo();
791   unsigned FramePtr = RegInfo->getFrameRegister(MF);
792
793   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
794   // scratch register. Also spill R4 if Thumb2 function has varsized objects,
795   // since it's always posible to restore sp from fp in a single instruction.
796   // FIXME: It will be better just to find spare register here.
797   if (AFI->isThumb2Function() &&
798       (MFI->hasVarSizedObjects() || RegInfo->needsStackRealignment(MF)))
799     MF.getRegInfo().setPhysRegUsed(ARM::R4);
800
801   // Spill LR if Thumb1 function uses variable length argument lists.
802   if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
803     MF.getRegInfo().setPhysRegUsed(ARM::LR);
804
805   // Spill the BasePtr if it's used.
806   if (RegInfo->hasBasePointer(MF))
807     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
808
809   // Don't spill FP if the frame can be eliminated. This is determined
810   // by scanning the callee-save registers to see if any is used.
811   const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
812   for (unsigned i = 0; CSRegs[i]; ++i) {
813     unsigned Reg = CSRegs[i];
814     bool Spilled = false;
815     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
816       AFI->setCSRegisterIsSpilled(Reg);
817       Spilled = true;
818       CanEliminateFrame = false;
819     } else {
820       // Check alias registers too.
821       for (const unsigned *Aliases =
822              RegInfo->getAliasSet(Reg); *Aliases; ++Aliases) {
823         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
824           Spilled = true;
825           CanEliminateFrame = false;
826         }
827       }
828     }
829
830     if (!ARM::GPRRegisterClass->contains(Reg))
831       continue;
832
833     if (Spilled) {
834       NumGPRSpills++;
835
836       if (!STI.isTargetDarwin()) {
837         if (Reg == ARM::LR)
838           LRSpilled = true;
839         CS1Spilled = true;
840         continue;
841       }
842
843       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
844       switch (Reg) {
845       case ARM::LR:
846         LRSpilled = true;
847         // Fallthrough
848       case ARM::R4: case ARM::R5:
849       case ARM::R6: case ARM::R7:
850         CS1Spilled = true;
851         break;
852       default:
853         break;
854       }
855     } else {
856       if (!STI.isTargetDarwin()) {
857         UnspilledCS1GPRs.push_back(Reg);
858         continue;
859       }
860
861       switch (Reg) {
862       case ARM::R4: case ARM::R5:
863       case ARM::R6: case ARM::R7:
864       case ARM::LR:
865         UnspilledCS1GPRs.push_back(Reg);
866         break;
867       default:
868         UnspilledCS2GPRs.push_back(Reg);
869         break;
870       }
871     }
872   }
873
874   bool ForceLRSpill = false;
875   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
876     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
877     // Force LR to be spilled if the Thumb function size is > 2048. This enables
878     // use of BL to implement far jump. If it turns out that it's not needed
879     // then the branch fix up path will undo it.
880     if (FnSize >= (1 << 11)) {
881       CanEliminateFrame = false;
882       ForceLRSpill = true;
883     }
884   }
885
886   // If any of the stack slot references may be out of range of an immediate
887   // offset, make sure a register (or a spill slot) is available for the
888   // register scavenger. Note that if we're indexing off the frame pointer, the
889   // effective stack size is 4 bytes larger since the FP points to the stack
890   // slot of the previous FP. Also, if we have variable sized objects in the
891   // function, stack slot references will often be negative, and some of
892   // our instructions are positive-offset only, so conservatively consider
893   // that case to want a spill slot (or register) as well. Similarly, if
894   // the function adjusts the stack pointer during execution and the
895   // adjustments aren't already part of our stack size estimate, our offset
896   // calculations may be off, so be conservative.
897   // FIXME: We could add logic to be more precise about negative offsets
898   //        and which instructions will need a scratch register for them. Is it
899   //        worth the effort and added fragility?
900   bool BigStack =
901     (RS &&
902      (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
903       estimateRSStackSizeLimit(MF, this)))
904     || MFI->hasVarSizedObjects()
905     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
906
907   bool ExtraCSSpill = false;
908   if (BigStack || !CanEliminateFrame || RegInfo->cannotEliminateFrame(MF)) {
909     AFI->setHasStackFrame(true);
910
911     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
912     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
913     if (!LRSpilled && CS1Spilled) {
914       MF.getRegInfo().setPhysRegUsed(ARM::LR);
915       AFI->setCSRegisterIsSpilled(ARM::LR);
916       NumGPRSpills++;
917       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
918                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
919       ForceLRSpill = false;
920       ExtraCSSpill = true;
921     }
922
923     if (hasFP(MF)) {
924       MF.getRegInfo().setPhysRegUsed(FramePtr);
925       NumGPRSpills++;
926     }
927
928     // If stack and double are 8-byte aligned and we are spilling an odd number
929     // of GPRs, spill one extra callee save GPR so we won't have to pad between
930     // the integer and double callee save areas.
931     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
932     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
933       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
934         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
935           unsigned Reg = UnspilledCS1GPRs[i];
936           // Don't spill high register if the function is thumb1
937           if (!AFI->isThumb1OnlyFunction() ||
938               isARMLowRegister(Reg) || Reg == ARM::LR) {
939             MF.getRegInfo().setPhysRegUsed(Reg);
940             AFI->setCSRegisterIsSpilled(Reg);
941             if (!RegInfo->isReservedReg(MF, Reg))
942               ExtraCSSpill = true;
943             break;
944           }
945         }
946       } else if (!UnspilledCS2GPRs.empty() && !AFI->isThumb1OnlyFunction()) {
947         unsigned Reg = UnspilledCS2GPRs.front();
948         MF.getRegInfo().setPhysRegUsed(Reg);
949         AFI->setCSRegisterIsSpilled(Reg);
950         if (!RegInfo->isReservedReg(MF, Reg))
951           ExtraCSSpill = true;
952       }
953     }
954
955     // Estimate if we might need to scavenge a register at some point in order
956     // to materialize a stack offset. If so, either spill one additional
957     // callee-saved register or reserve a special spill slot to facilitate
958     // register scavenging. Thumb1 needs a spill slot for stack pointer
959     // adjustments also, even when the frame itself is small.
960     if (BigStack && !ExtraCSSpill) {
961       // If any non-reserved CS register isn't spilled, just spill one or two
962       // extra. That should take care of it!
963       unsigned NumExtras = TargetAlign / 4;
964       SmallVector<unsigned, 2> Extras;
965       while (NumExtras && !UnspilledCS1GPRs.empty()) {
966         unsigned Reg = UnspilledCS1GPRs.back();
967         UnspilledCS1GPRs.pop_back();
968         if (!RegInfo->isReservedReg(MF, Reg) &&
969             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
970              Reg == ARM::LR)) {
971           Extras.push_back(Reg);
972           NumExtras--;
973         }
974       }
975       // For non-Thumb1 functions, also check for hi-reg CS registers
976       if (!AFI->isThumb1OnlyFunction()) {
977         while (NumExtras && !UnspilledCS2GPRs.empty()) {
978           unsigned Reg = UnspilledCS2GPRs.back();
979           UnspilledCS2GPRs.pop_back();
980           if (!RegInfo->isReservedReg(MF, Reg)) {
981             Extras.push_back(Reg);
982             NumExtras--;
983           }
984         }
985       }
986       if (Extras.size() && NumExtras == 0) {
987         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
988           MF.getRegInfo().setPhysRegUsed(Extras[i]);
989           AFI->setCSRegisterIsSpilled(Extras[i]);
990         }
991       } else if (!AFI->isThumb1OnlyFunction()) {
992         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
993         // closest to SP or frame pointer.
994         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
995         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
996                                                            RC->getAlignment(),
997                                                            false));
998       }
999     }
1000   }
1001
1002   if (ForceLRSpill) {
1003     MF.getRegInfo().setPhysRegUsed(ARM::LR);
1004     AFI->setCSRegisterIsSpilled(ARM::LR);
1005     AFI->setLRIsSpilledForFarJump(true);
1006   }
1007 }