Remove redundant foldMemoryOperand variants and other code clean up.
[oota-llvm.git] / lib / Target / ARM / ARMRegisterInfo.cpp
1 //===- ARMRegisterInfo.cpp - ARM Register Information -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the "Instituto Nokia de Tecnologia" and
6 // is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains the ARM implementation of the MRegisterInfo class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMInstrInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineLocation.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 static cl::opt<bool> ThumbRegScavenging("enable-thumb-reg-scavenging",
40                                cl::Hidden,
41                                cl::desc("Enable register scavenging on Thumb"));
42
43 unsigned ARMRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
44   using namespace ARM;
45   switch (RegEnum) {
46   case R0:  case S0:  case D0:  return 0;
47   case R1:  case S1:  case D1:  return 1;
48   case R2:  case S2:  case D2:  return 2;
49   case R3:  case S3:  case D3:  return 3;
50   case R4:  case S4:  case D4:  return 4;
51   case R5:  case S5:  case D5:  return 5;
52   case R6:  case S6:  case D6:  return 6;
53   case R7:  case S7:  case D7:  return 7;
54   case R8:  case S8:  case D8:  return 8;
55   case R9:  case S9:  case D9:  return 9;
56   case R10: case S10: case D10: return 10;
57   case R11: case S11: case D11: return 11;
58   case R12: case S12: case D12: return 12;
59   case SP:  case S13: case D13: return 13;
60   case LR:  case S14: case D14: return 14;
61   case PC:  case S15: case D15: return 15;
62   case S16: return 16;
63   case S17: return 17;
64   case S18: return 18;
65   case S19: return 19;
66   case S20: return 20;
67   case S21: return 21;
68   case S22: return 22;
69   case S23: return 23;
70   case S24: return 24;
71   case S25: return 25;
72   case S26: return 26;
73   case S27: return 27;
74   case S28: return 28;
75   case S29: return 29;
76   case S30: return 30;
77   case S31: return 31;
78   default:
79     assert(0 && "Unknown ARM register!");
80     abort();
81   }
82 }
83
84 ARMRegisterInfo::ARMRegisterInfo(const TargetInstrInfo &tii,
85                                  const ARMSubtarget &sti)
86   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
87     TII(tii), STI(sti),
88     FramePtr((STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
89 }
90
91 bool ARMRegisterInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
92                                                 MachineBasicBlock::iterator MI,
93                                 const std::vector<CalleeSavedInfo> &CSI) const {
94   MachineFunction &MF = *MBB.getParent();
95   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
96   if (!AFI->isThumbFunction() || CSI.empty())
97     return false;
98
99   MachineInstrBuilder MIB = BuildMI(MBB, MI, TII.get(ARM::tPUSH));
100   for (unsigned i = CSI.size(); i != 0; --i) {
101     unsigned Reg = CSI[i-1].getReg();
102     // Add the callee-saved register as live-in. It's killed at the spill.
103     MBB.addLiveIn(Reg);
104     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
105   }
106   return true;
107 }
108
109 bool ARMRegisterInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
110                                                  MachineBasicBlock::iterator MI,
111                                 const std::vector<CalleeSavedInfo> &CSI) const {
112   MachineFunction &MF = *MBB.getParent();
113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
114   if (!AFI->isThumbFunction() || CSI.empty())
115     return false;
116
117   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
118   MachineInstr *PopMI = new MachineInstr(TII.get(ARM::tPOP));
119   MBB.insert(MI, PopMI);
120   for (unsigned i = CSI.size(); i != 0; --i) {
121     unsigned Reg = CSI[i-1].getReg();
122     if (Reg == ARM::LR) {
123       // Special epilogue for vararg functions. See emitEpilogue
124       if (isVarArg)
125         continue;
126       Reg = ARM::PC;
127       PopMI->setInstrDescriptor(TII.get(ARM::tPOP_RET));
128       MBB.erase(MI);
129     }
130     PopMI->addRegOperand(Reg, true);
131   }
132   return true;
133 }
134
135 static inline
136 const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
137   return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
138 }
139
140 static inline
141 const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
142   return MIB.addReg(0);
143 }
144
145 static const MachineInstrBuilder &ARMInstrAddOperand(MachineInstrBuilder &MIB,
146                                                      MachineOperand &MO) {
147   if (MO.isRegister())
148     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit());
149   else if (MO.isImmediate())
150     MIB = MIB.addImm(MO.getImm());
151   else if (MO.isFrameIndex())
152     MIB = MIB.addFrameIndex(MO.getFrameIndex());
153   else
154     assert(0 && "Unknown operand for ARMInstrAddOperand!");
155
156   return MIB;
157 }
158
159 void ARMRegisterInfo::
160 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
161                     unsigned SrcReg, int FI,
162                     const TargetRegisterClass *RC) const {
163   if (RC == ARM::GPRRegisterClass) {
164     MachineFunction &MF = *MBB.getParent();
165     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
166     if (AFI->isThumbFunction())
167       BuildMI(MBB, I, TII.get(ARM::tSpill)).addReg(SrcReg, false, false, true)
168         .addFrameIndex(FI).addImm(0);
169     else
170       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::STR))
171                      .addReg(SrcReg, false, false, true)
172                      .addFrameIndex(FI).addReg(0).addImm(0));
173   } else if (RC == ARM::DPRRegisterClass) {
174     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTD))
175                    .addReg(SrcReg, false, false, true)
176                    .addFrameIndex(FI).addImm(0));
177   } else {
178     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
179     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTS))
180                    .addReg(SrcReg, false, false, true)
181                    .addFrameIndex(FI).addImm(0));
182   }
183 }
184
185 void ARMRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
186                                      SmallVectorImpl<MachineOperand> &Addr,
187                                      const TargetRegisterClass *RC,
188                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
189   unsigned Opc = 0;
190   if (RC == ARM::GPRRegisterClass) {
191     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
192     if (AFI->isThumbFunction()) {
193       Opc = Addr[0].isFrameIndex() ? ARM::tSpill : ARM::tSTR;
194       MachineInstrBuilder MIB = 
195         BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, true);
196       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
197         MIB = ARMInstrAddOperand(MIB, Addr[i]);
198       NewMIs.push_back(MIB);
199       return;
200     }
201     Opc = ARM::STR;
202   } else if (RC == ARM::DPRRegisterClass) {
203     Opc = ARM::FSTD;
204   } else {
205     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
206     Opc = ARM::FSTS;
207   }
208
209   MachineInstrBuilder MIB = 
210     BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, true);
211   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
212     MIB = ARMInstrAddOperand(MIB, Addr[i]);
213   AddDefaultPred(MIB);
214   NewMIs.push_back(MIB);
215   return;
216 }
217
218 void ARMRegisterInfo::
219 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
220                      unsigned DestReg, int FI,
221                      const TargetRegisterClass *RC) const {
222   if (RC == ARM::GPRRegisterClass) {
223     MachineFunction &MF = *MBB.getParent();
224     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
225     if (AFI->isThumbFunction())
226       BuildMI(MBB, I, TII.get(ARM::tRestore), DestReg)
227         .addFrameIndex(FI).addImm(0);
228     else
229       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::LDR), DestReg)
230                      .addFrameIndex(FI).addReg(0).addImm(0));
231   } else if (RC == ARM::DPRRegisterClass) {
232     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDD), DestReg)
233                    .addFrameIndex(FI).addImm(0));
234   } else {
235     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
236     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDS), DestReg)
237                    .addFrameIndex(FI).addImm(0));
238   }
239 }
240
241 void ARMRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
242                                       SmallVectorImpl<MachineOperand> &Addr,
243                                       const TargetRegisterClass *RC,
244                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
245   unsigned Opc = 0;
246   if (RC == ARM::GPRRegisterClass) {
247     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
248     if (AFI->isThumbFunction()) {
249       Opc = Addr[0].isFrameIndex() ? ARM::tRestore : ARM::tLDR;
250       MachineInstrBuilder MIB = BuildMI(TII.get(Opc), DestReg);
251       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
252         MIB = ARMInstrAddOperand(MIB, Addr[i]);
253       NewMIs.push_back(MIB);
254       return;
255     }
256     Opc = ARM::LDR;
257   } else if (RC == ARM::DPRRegisterClass) {
258     Opc = ARM::FLDD;
259   } else {
260     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
261     Opc = ARM::FLDS;
262   }
263
264   MachineInstrBuilder MIB =  BuildMI(TII.get(Opc), DestReg);
265   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
266     MIB = ARMInstrAddOperand(MIB, Addr[i]);
267   AddDefaultPred(MIB);
268   NewMIs.push_back(MIB);
269   return;
270 }
271
272 void ARMRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
273                                    MachineBasicBlock::iterator I,
274                                    unsigned DestReg, unsigned SrcReg,
275                                    const TargetRegisterClass *DestRC,
276                                    const TargetRegisterClass *SrcRC) const {
277   if (DestRC != SrcRC) {
278     cerr << "Not yet supported!";
279     abort();
280   }
281
282   if (DestRC == ARM::GPRRegisterClass) {
283     MachineFunction &MF = *MBB.getParent();
284     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
285     if (AFI->isThumbFunction())
286       BuildMI(MBB, I, TII.get(ARM::tMOVr), DestReg).addReg(SrcReg);
287     else
288       AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::MOVr), DestReg)
289                                   .addReg(SrcReg)));
290   } else if (DestRC == ARM::SPRRegisterClass)
291     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FCPYS), DestReg)
292                    .addReg(SrcReg));
293   else if (DestRC == ARM::DPRRegisterClass)
294     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FCPYD), DestReg)
295                    .addReg(SrcReg));
296   else
297     abort();
298 }
299
300 /// emitLoadConstPool - Emits a load from constpool to materialize the
301 /// specified immediate.
302 static void emitLoadConstPool(MachineBasicBlock &MBB,
303                               MachineBasicBlock::iterator &MBBI,
304                               unsigned DestReg, int Val,
305                               ARMCC::CondCodes Pred, unsigned PredReg,
306                               const TargetInstrInfo &TII, bool isThumb) {
307   MachineFunction &MF = *MBB.getParent();
308   MachineConstantPool *ConstantPool = MF.getConstantPool();
309   Constant *C = ConstantInt::get(Type::Int32Ty, Val);
310   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 2);
311   if (isThumb)
312     BuildMI(MBB, MBBI, TII.get(ARM::tLDRcp), DestReg).addConstantPoolIndex(Idx);
313   else
314     BuildMI(MBB, MBBI, TII.get(ARM::LDRcp), DestReg).addConstantPoolIndex(Idx)
315       .addReg(0).addImm(0).addImm((unsigned)Pred).addReg(PredReg);
316 }
317
318 void ARMRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
319                                     MachineBasicBlock::iterator I,
320                                     unsigned DestReg,
321                                     const MachineInstr *Orig) const {
322   if (Orig->getOpcode() == ARM::MOVi2pieces) {
323     emitLoadConstPool(MBB, I, DestReg,
324                       Orig->getOperand(1).getImmedValue(),
325                       (ARMCC::CondCodes)Orig->getOperand(2).getImmedValue(),
326                       Orig->getOperand(3).getReg(),
327                       TII, false);
328     return;
329   }
330
331   MachineInstr *MI = Orig->clone();
332   MI->getOperand(0).setReg(DestReg);
333   MBB.insert(I, MI);
334 }
335
336 /// isLowRegister - Returns true if the register is low register r0-r7.
337 ///
338 static bool isLowRegister(unsigned Reg) {
339   using namespace ARM;
340   switch (Reg) {
341   case R0:  case R1:  case R2:  case R3:
342   case R4:  case R5:  case R6:  case R7:
343     return true;
344   default:
345     return false;
346   }
347 }
348
349 MachineInstr *ARMRegisterInfo::foldMemoryOperand(MachineInstr *MI,
350                                                  SmallVectorImpl<unsigned> &Ops,
351                                                  int FI) const {
352   if (Ops.size() != 1) return NULL;
353
354   unsigned OpNum = Ops[0];
355   unsigned Opc = MI->getOpcode();
356   MachineInstr *NewMI = NULL;
357   switch (Opc) {
358   default: break;
359   case ARM::MOVr: {
360     if (MI->getOperand(4).getReg() == ARM::CPSR)
361       // If it is updating CPSR, then it cannot be foled.
362       break;
363     unsigned Pred = MI->getOperand(2).getImmedValue();
364     unsigned PredReg = MI->getOperand(3).getReg();
365     if (OpNum == 0) { // move -> store
366       unsigned SrcReg = MI->getOperand(1).getReg();
367       NewMI = BuildMI(TII.get(ARM::STR)).addReg(SrcReg).addFrameIndex(FI)
368         .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
369     } else {          // move -> load
370       unsigned DstReg = MI->getOperand(0).getReg();
371       NewMI = BuildMI(TII.get(ARM::LDR), DstReg).addFrameIndex(FI).addReg(0)
372         .addImm(0).addImm(Pred).addReg(PredReg);
373     }
374     break;
375   }
376   case ARM::tMOVr: {
377     if (OpNum == 0) { // move -> store
378       unsigned SrcReg = MI->getOperand(1).getReg();
379       if (isPhysicalRegister(SrcReg) && !isLowRegister(SrcReg))
380         // tSpill cannot take a high register operand.
381         break;
382       NewMI = BuildMI(TII.get(ARM::tSpill)).addReg(SrcReg).addFrameIndex(FI)
383         .addImm(0);
384     } else {          // move -> load
385       unsigned DstReg = MI->getOperand(0).getReg();
386       if (isPhysicalRegister(DstReg) && !isLowRegister(DstReg))
387         // tRestore cannot target a high register operand.
388         break;
389       NewMI = BuildMI(TII.get(ARM::tRestore), DstReg).addFrameIndex(FI)
390         .addImm(0);
391     }
392     break;
393   }
394   case ARM::FCPYS: {
395     unsigned Pred = MI->getOperand(2).getImmedValue();
396     unsigned PredReg = MI->getOperand(3).getReg();
397     if (OpNum == 0) { // move -> store
398       unsigned SrcReg = MI->getOperand(1).getReg();
399       NewMI = BuildMI(TII.get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
400         .addImm(0).addImm(Pred).addReg(PredReg);
401     } else {          // move -> load
402       unsigned DstReg = MI->getOperand(0).getReg();
403       NewMI = BuildMI(TII.get(ARM::FLDS), DstReg).addFrameIndex(FI)
404         .addImm(0).addImm(Pred).addReg(PredReg);
405     }
406     break;
407   }
408   case ARM::FCPYD: {
409     unsigned Pred = MI->getOperand(2).getImmedValue();
410     unsigned PredReg = MI->getOperand(3).getReg();
411     if (OpNum == 0) { // move -> store
412       unsigned SrcReg = MI->getOperand(1).getReg();
413       NewMI = BuildMI(TII.get(ARM::FSTD)).addReg(SrcReg).addFrameIndex(FI)
414         .addImm(0).addImm(Pred).addReg(PredReg);
415     } else {          // move -> load
416       unsigned DstReg = MI->getOperand(0).getReg();
417       NewMI = BuildMI(TII.get(ARM::FLDD), DstReg).addFrameIndex(FI)
418         .addImm(0).addImm(Pred).addReg(PredReg);
419     }
420     break;
421   }
422   }
423
424   if (NewMI)
425     NewMI->copyKillDeadInfo(MI);
426   return NewMI;
427 }
428
429 const unsigned*
430 ARMRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
431   static const unsigned CalleeSavedRegs[] = {
432     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
433     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
434
435     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
436     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
437     0
438   };
439
440   static const unsigned DarwinCalleeSavedRegs[] = {
441     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
442     ARM::R11, ARM::R10, ARM::R9, ARM::R8,
443
444     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
445     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
446     0
447   };
448   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
449 }
450
451 const TargetRegisterClass* const *
452 ARMRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
453   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
454     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
455     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
456     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
457
458     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
459     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
460     0
461   };
462   return CalleeSavedRegClasses;
463 }
464
465 BitVector ARMRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
466   // FIXME: avoid re-calculating this everytime.
467   BitVector Reserved(getNumRegs());
468   Reserved.set(ARM::SP);
469   Reserved.set(ARM::PC);
470   if (STI.isTargetDarwin() || hasFP(MF))
471     Reserved.set(FramePtr);
472   // Some targets reserve R9.
473   if (STI.isR9Reserved())
474     Reserved.set(ARM::R9);
475   return Reserved;
476 }
477
478 bool
479 ARMRegisterInfo::isReservedReg(const MachineFunction &MF, unsigned Reg) const {
480   switch (Reg) {
481   default: break;
482   case ARM::SP:
483   case ARM::PC:
484     return true;
485   case ARM::R7:
486   case ARM::R11:
487     if (FramePtr == Reg && (STI.isTargetDarwin() || hasFP(MF)))
488       return true;
489     break;
490   case ARM::R9:
491     return STI.isR9Reserved();
492   }
493
494   return false;
495 }
496
497 bool
498 ARMRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
499   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
500   return ThumbRegScavenging || !AFI->isThumbFunction();
501 }
502
503 /// hasFP - Return true if the specified function should have a dedicated frame
504 /// pointer register.  This is true if the function has variable sized allocas
505 /// or if frame pointer elimination is disabled.
506 ///
507 bool ARMRegisterInfo::hasFP(const MachineFunction &MF) const {
508   return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
509 }
510
511 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
512 // not required, we reserve argument space for call sites in the function
513 // immediately on entry to the current function. This eliminates the need for
514 // add/sub sp brackets around call sites. Returns true if the call frame is
515 // included as part of the stack frame.
516 bool ARMRegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
517   const MachineFrameInfo *FFI = MF.getFrameInfo();
518   unsigned CFSize = FFI->getMaxCallFrameSize();
519   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
520   // It's not always a good idea to include the call frame as part of the
521   // stack frame. ARM (especially Thumb) has small immediate offset to
522   // address the stack frame. So a large call frame can cause poor codegen
523   // and may even makes it impossible to scavenge a register.
524   if (AFI->isThumbFunction()) {
525     if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
526       return false;
527   } else {
528     if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
529       return false;
530   }
531   return !MF.getFrameInfo()->hasVarSizedObjects();
532 }
533
534 /// emitARMRegPlusImmediate - Emits a series of instructions to materialize
535 /// a destreg = basereg + immediate in ARM code.
536 static
537 void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
538                              MachineBasicBlock::iterator &MBBI,
539                              unsigned DestReg, unsigned BaseReg, int NumBytes,
540                              ARMCC::CondCodes Pred, unsigned PredReg,
541                              const TargetInstrInfo &TII) {
542   bool isSub = NumBytes < 0;
543   if (isSub) NumBytes = -NumBytes;
544
545   while (NumBytes) {
546     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
547     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
548     assert(ThisVal && "Didn't extract field correctly");
549     
550     // We will handle these bits from offset, clear them.
551     NumBytes &= ~ThisVal;
552     
553     // Get the properly encoded SOImmVal field.
554     int SOImmVal = ARM_AM::getSOImmVal(ThisVal);
555     assert(SOImmVal != -1 && "Bit extraction didn't work?");
556     
557     // Build the new ADD / SUB.
558     BuildMI(MBB, MBBI, TII.get(isSub ? ARM::SUBri : ARM::ADDri), DestReg)
559       .addReg(BaseReg, false, false, true).addImm(SOImmVal)
560       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
561     BaseReg = DestReg;
562   }
563 }
564
565 /// calcNumMI - Returns the number of instructions required to materialize
566 /// the specific add / sub r, c instruction.
567 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
568                           unsigned NumBits, unsigned Scale) {
569   unsigned NumMIs = 0;
570   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
571
572   if (Opc == ARM::tADDrSPi) {
573     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
574     Bytes -= ThisVal;
575     NumMIs++;
576     NumBits = 8;
577     Scale = 1;  // Followed by a number of tADDi8.
578     Chunk = ((1 << NumBits) - 1) * Scale;
579   }
580
581   NumMIs += Bytes / Chunk;
582   if ((Bytes % Chunk) != 0)
583     NumMIs++;
584   if (ExtraOpc)
585     NumMIs++;
586   return NumMIs;
587 }
588
589 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
590 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
591 /// in a register using mov / mvn sequences or load the immediate from a
592 /// constpool entry.
593 static
594 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
595                                MachineBasicBlock::iterator &MBBI,
596                                unsigned DestReg, unsigned BaseReg,
597                                int NumBytes, bool CanChangeCC,
598                                const TargetInstrInfo &TII) {
599     bool isHigh = !isLowRegister(DestReg) ||
600                   (BaseReg != 0 && !isLowRegister(BaseReg));
601     bool isSub = false;
602     // Subtract doesn't have high register version. Load the negative value
603     // if either base or dest register is a high register. Also, if do not
604     // issue sub as part of the sequence if condition register is to be
605     // preserved.
606     if (NumBytes < 0 && !isHigh && CanChangeCC) {
607       isSub = true;
608       NumBytes = -NumBytes;
609     }
610     unsigned LdReg = DestReg;
611     if (DestReg == ARM::SP) {
612       assert(BaseReg == ARM::SP && "Unexpected!");
613       LdReg = ARM::R3;
614       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R12)
615         .addReg(ARM::R3, false, false, true);
616     }
617
618     if (NumBytes <= 255 && NumBytes >= 0)
619       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
620     else if (NumBytes < 0 && NumBytes >= -255) {
621       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
622       BuildMI(MBB, MBBI, TII.get(ARM::tNEG), LdReg)
623         .addReg(LdReg, false, false, true);
624     } else
625       emitLoadConstPool(MBB, MBBI, LdReg, NumBytes, ARMCC::AL, 0, TII, true);
626
627     // Emit add / sub.
628     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
629     const MachineInstrBuilder MIB = BuildMI(MBB, MBBI, TII.get(Opc), DestReg);
630     if (DestReg == ARM::SP || isSub)
631       MIB.addReg(BaseReg).addReg(LdReg, false, false, true);
632     else
633       MIB.addReg(LdReg).addReg(BaseReg, false, false, true);
634     if (DestReg == ARM::SP)
635       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R3)
636         .addReg(ARM::R12, false, false, true);
637 }
638
639 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
640 /// a destreg = basereg + immediate in Thumb code.
641 static
642 void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
643                                MachineBasicBlock::iterator &MBBI,
644                                unsigned DestReg, unsigned BaseReg,
645                                int NumBytes, const TargetInstrInfo &TII) {
646   bool isSub = NumBytes < 0;
647   unsigned Bytes = (unsigned)NumBytes;
648   if (isSub) Bytes = -NumBytes;
649   bool isMul4 = (Bytes & 3) == 0;
650   bool isTwoAddr = false;
651   bool DstNotEqBase = false;
652   unsigned NumBits = 1;
653   unsigned Scale = 1;
654   int Opc = 0;
655   int ExtraOpc = 0;
656
657   if (DestReg == BaseReg && BaseReg == ARM::SP) {
658     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
659     NumBits = 7;
660     Scale = 4;
661     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
662     isTwoAddr = true;
663   } else if (!isSub && BaseReg == ARM::SP) {
664     // r1 = add sp, 403
665     // =>
666     // r1 = add sp, 100 * 4
667     // r1 = add r1, 3
668     if (!isMul4) {
669       Bytes &= ~3;
670       ExtraOpc = ARM::tADDi3;
671     }
672     NumBits = 8;
673     Scale = 4;
674     Opc = ARM::tADDrSPi;
675   } else {
676     // sp = sub sp, c
677     // r1 = sub sp, c
678     // r8 = sub sp, c
679     if (DestReg != BaseReg)
680       DstNotEqBase = true;
681     NumBits = 8;
682     Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
683     isTwoAddr = true;
684   }
685
686   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
687   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
688   if (NumMIs > Threshold) {
689     // This will expand into too many instructions. Load the immediate from a
690     // constpool entry.
691     emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII);
692     return;
693   }
694
695   if (DstNotEqBase) {
696     if (isLowRegister(DestReg) && isLowRegister(BaseReg)) {
697       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
698       unsigned Chunk = (1 << 3) - 1;
699       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
700       Bytes -= ThisVal;
701       BuildMI(MBB, MBBI, TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3), DestReg)
702         .addReg(BaseReg, false, false, true).addImm(ThisVal);
703     } else {
704       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), DestReg)
705         .addReg(BaseReg, false, false, true);
706     }
707     BaseReg = DestReg;
708   }
709
710   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
711   while (Bytes) {
712     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
713     Bytes -= ThisVal;
714     ThisVal /= Scale;
715     // Build the new tADD / tSUB.
716     if (isTwoAddr)
717       BuildMI(MBB, MBBI, TII.get(Opc), DestReg).addReg(DestReg).addImm(ThisVal);
718     else {
719       bool isKill = BaseReg != ARM::SP;
720       BuildMI(MBB, MBBI, TII.get(Opc), DestReg)
721         .addReg(BaseReg, false, false, isKill).addImm(ThisVal);
722       BaseReg = DestReg;
723
724       if (Opc == ARM::tADDrSPi) {
725         // r4 = add sp, imm
726         // r4 = add r4, imm
727         // ...
728         NumBits = 8;
729         Scale = 1;
730         Chunk = ((1 << NumBits) - 1) * Scale;
731         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
732         isTwoAddr = true;
733       }
734     }
735   }
736
737   if (ExtraOpc)
738     BuildMI(MBB, MBBI, TII.get(ExtraOpc), DestReg)
739       .addReg(DestReg, false, false, true)
740       .addImm(((unsigned)NumBytes) & 3);
741 }
742
743 static
744 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
745                   int NumBytes, ARMCC::CondCodes Pred, unsigned PredReg,
746                   bool isThumb, const TargetInstrInfo &TII) {
747   if (isThumb)
748     emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII);
749   else
750     emitARMRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes,
751                             Pred, PredReg, TII);
752 }
753
754 void ARMRegisterInfo::
755 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
756                               MachineBasicBlock::iterator I) const {
757   if (!hasReservedCallFrame(MF)) {
758     // If we have alloca, convert as follows:
759     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
760     // ADJCALLSTACKUP   -> add, sp, sp, amount
761     MachineInstr *Old = I;
762     unsigned Amount = Old->getOperand(0).getImmedValue();
763     if (Amount != 0) {
764       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
765       // We need to keep the stack aligned properly.  To do this, we round the
766       // amount of space needed for the outgoing arguments up to the next
767       // alignment boundary.
768       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
769       Amount = (Amount+Align-1)/Align*Align;
770
771       // Replace the pseudo instruction with a new instruction...
772       unsigned Opc = Old->getOpcode();
773       bool isThumb = AFI->isThumbFunction();
774       ARMCC::CondCodes Pred = isThumb
775         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(1).getImmedValue();
776       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
777         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
778         unsigned PredReg = isThumb ? 0 : Old->getOperand(2).getReg();
779         emitSPUpdate(MBB, I, -Amount, Pred, PredReg, isThumb, TII);
780       } else {
781         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
782         unsigned PredReg = isThumb ? 0 : Old->getOperand(3).getReg();
783         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
784         emitSPUpdate(MBB, I, Amount, Pred, PredReg, isThumb, TII);
785       }
786     }
787   }
788   MBB.erase(I);
789 }
790
791 /// emitThumbConstant - Emit a series of instructions to materialize a
792 /// constant.
793 static void emitThumbConstant(MachineBasicBlock &MBB,
794                               MachineBasicBlock::iterator &MBBI,
795                               unsigned DestReg, int Imm,
796                               const TargetInstrInfo &TII) {
797   bool isSub = Imm < 0;
798   if (isSub) Imm = -Imm;
799
800   int Chunk = (1 << 8) - 1;
801   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
802   Imm -= ThisVal;
803   BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), DestReg).addImm(ThisVal);
804   if (Imm > 0) 
805     emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII);
806   if (isSub)
807     BuildMI(MBB, MBBI, TII.get(ARM::tNEG), DestReg)
808       .addReg(DestReg, false, false, true);
809 }
810
811 /// findScratchRegister - Find a 'free' ARM register. If register scavenger
812 /// is not being used, R12 is available. Otherwise, try for a call-clobbered
813 /// register first and then a spilled callee-saved register if that fails.
814 static
815 unsigned findScratchRegister(RegScavenger *RS, const TargetRegisterClass *RC,
816                              ARMFunctionInfo *AFI) {
817   unsigned Reg = RS ? RS->FindUnusedReg(RC, true) : (unsigned) ARM::R12;
818   if (Reg == 0)
819     // Try a already spilled CS register.
820     Reg = RS->FindUnusedReg(RC, AFI->getSpilledCSRegisters());
821
822   return Reg;
823 }
824
825 void ARMRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
826                                           int SPAdj, RegScavenger *RS) const{
827   unsigned i = 0;
828   MachineInstr &MI = *II;
829   MachineBasicBlock &MBB = *MI.getParent();
830   MachineFunction &MF = *MBB.getParent();
831   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
832   bool isThumb = AFI->isThumbFunction();
833
834   while (!MI.getOperand(i).isFrameIndex()) {
835     ++i;
836     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
837   }
838   
839   unsigned FrameReg = ARM::SP;
840   int FrameIndex = MI.getOperand(i).getFrameIndex();
841   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) + 
842                MF.getFrameInfo()->getStackSize() + SPAdj;
843
844   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
845     Offset -= AFI->getGPRCalleeSavedArea1Offset();
846   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
847     Offset -= AFI->getGPRCalleeSavedArea2Offset();
848   else if (AFI->isDPRCalleeSavedAreaFrame(FrameIndex))
849     Offset -= AFI->getDPRCalleeSavedAreaOffset();
850   else if (hasFP(MF)) {
851     assert(SPAdj == 0 && "Unexpected");
852     // There is alloca()'s in this function, must reference off the frame
853     // pointer instead.
854     FrameReg = getFrameRegister(MF);
855     Offset -= AFI->getFramePtrSpillOffset();
856   }
857
858   unsigned Opcode = MI.getOpcode();
859   const TargetInstrDescriptor &Desc = TII.get(Opcode);
860   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
861   bool isSub = false;
862
863   if (Opcode == ARM::ADDri) {
864     Offset += MI.getOperand(i+1).getImm();
865     if (Offset == 0) {
866       // Turn it into a move.
867       MI.setInstrDescriptor(TII.get(ARM::MOVr));
868       MI.getOperand(i).ChangeToRegister(FrameReg, false);
869       MI.RemoveOperand(i+1);
870       return;
871     } else if (Offset < 0) {
872       Offset = -Offset;
873       isSub = true;
874       MI.setInstrDescriptor(TII.get(ARM::SUBri));
875     }
876
877     // Common case: small offset, fits into instruction.
878     int ImmedOffset = ARM_AM::getSOImmVal(Offset);
879     if (ImmedOffset != -1) {
880       // Replace the FrameIndex with sp / fp
881       MI.getOperand(i).ChangeToRegister(FrameReg, false);
882       MI.getOperand(i+1).ChangeToImmediate(ImmedOffset);
883       return;
884     }
885     
886     // Otherwise, we fallback to common code below to form the imm offset with
887     // a sequence of ADDri instructions.  First though, pull as much of the imm
888     // into this ADDri as possible.
889     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
890     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
891     
892     // We will handle these bits from offset, clear them.
893     Offset &= ~ThisImmVal;
894     
895     // Get the properly encoded SOImmVal field.
896     int ThisSOImmVal = ARM_AM::getSOImmVal(ThisImmVal);
897     assert(ThisSOImmVal != -1 && "Bit extraction didn't work?");    
898     MI.getOperand(i+1).ChangeToImmediate(ThisSOImmVal);
899   } else if (Opcode == ARM::tADDrSPi) {
900     Offset += MI.getOperand(i+1).getImm();
901
902     // Can't use tADDrSPi if it's based off the frame pointer.
903     unsigned NumBits = 0;
904     unsigned Scale = 1;
905     if (FrameReg != ARM::SP) {
906       Opcode = ARM::tADDi3;
907       MI.setInstrDescriptor(TII.get(ARM::tADDi3));
908       NumBits = 3;
909     } else {
910       NumBits = 8;
911       Scale = 4;
912       assert((Offset & 3) == 0 &&
913              "Thumb add/sub sp, #imm immediate must be multiple of 4!");
914     }
915
916     if (Offset == 0) {
917       // Turn it into a move.
918       MI.setInstrDescriptor(TII.get(ARM::tMOVr));
919       MI.getOperand(i).ChangeToRegister(FrameReg, false);
920       MI.RemoveOperand(i+1);
921       return;
922     }
923
924     // Common case: small offset, fits into instruction.
925     unsigned Mask = (1 << NumBits) - 1;
926     if (((Offset / Scale) & ~Mask) == 0) {
927       // Replace the FrameIndex with sp / fp
928       MI.getOperand(i).ChangeToRegister(FrameReg, false);
929       MI.getOperand(i+1).ChangeToImmediate(Offset / Scale);
930       return;
931     }
932
933     unsigned DestReg = MI.getOperand(0).getReg();
934     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
935     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
936     // MI would expand into a large number of instructions. Don't try to
937     // simplify the immediate.
938     if (NumMIs > 2) {
939       emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII);
940       MBB.erase(II);
941       return;
942     }
943
944     if (Offset > 0) {
945       // Translate r0 = add sp, imm to
946       // r0 = add sp, 255*4
947       // r0 = add r0, (imm - 255*4)
948       MI.getOperand(i).ChangeToRegister(FrameReg, false);
949       MI.getOperand(i+1).ChangeToImmediate(Mask);
950       Offset = (Offset - Mask * Scale);
951       MachineBasicBlock::iterator NII = next(II);
952       emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII);
953     } else {
954       // Translate r0 = add sp, -imm to
955       // r0 = -imm (this is then translated into a series of instructons)
956       // r0 = add r0, sp
957       emitThumbConstant(MBB, II, DestReg, Offset, TII);
958       MI.setInstrDescriptor(TII.get(ARM::tADDhirr));
959       MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
960       MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
961     }
962     return;
963   } else {
964     unsigned ImmIdx = 0;
965     int InstrOffs = 0;
966     unsigned NumBits = 0;
967     unsigned Scale = 1;
968     switch (AddrMode) {
969     case ARMII::AddrMode2: {
970       ImmIdx = i+2;
971       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
972       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
973         InstrOffs *= -1;
974       NumBits = 12;
975       break;
976     }
977     case ARMII::AddrMode3: {
978       ImmIdx = i+2;
979       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
980       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
981         InstrOffs *= -1;
982       NumBits = 8;
983       break;
984     }
985     case ARMII::AddrMode5: {
986       ImmIdx = i+1;
987       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
988       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
989         InstrOffs *= -1;
990       NumBits = 8;
991       Scale = 4;
992       break;
993     }
994     case ARMII::AddrModeTs: {
995       ImmIdx = i+1;
996       InstrOffs = MI.getOperand(ImmIdx).getImm();
997       NumBits = (FrameReg == ARM::SP) ? 8 : 5;
998       Scale = 4;
999       break;
1000     }
1001     default:
1002       assert(0 && "Unsupported addressing mode!");
1003       abort();
1004       break;
1005     }
1006
1007     Offset += InstrOffs * Scale;
1008     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1009     if (Offset < 0 && !isThumb) {
1010       Offset = -Offset;
1011       isSub = true;
1012     }
1013
1014     // Common case: small offset, fits into instruction.
1015     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1016     int ImmedOffset = Offset / Scale;
1017     unsigned Mask = (1 << NumBits) - 1;
1018     if ((unsigned)Offset <= Mask * Scale) {
1019       // Replace the FrameIndex with sp
1020       MI.getOperand(i).ChangeToRegister(FrameReg, false);
1021       if (isSub)
1022         ImmedOffset |= 1 << NumBits;
1023       ImmOp.ChangeToImmediate(ImmedOffset);
1024       return;
1025     }
1026
1027     bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
1028     if (AddrMode == ARMII::AddrModeTs) {
1029       // Thumb tLDRspi, tSTRspi. These will change to instructions that use
1030       // a different base register.
1031       NumBits = 5;
1032       Mask = (1 << NumBits) - 1;
1033     }
1034     // If this is a thumb spill / restore, we will be using a constpool load to
1035     // materialize the offset.
1036     if (AddrMode == ARMII::AddrModeTs && isThumSpillRestore)
1037       ImmOp.ChangeToImmediate(0);
1038     else {
1039       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1040       ImmedOffset = ImmedOffset & Mask;
1041       if (isSub)
1042         ImmedOffset |= 1 << NumBits;
1043       ImmOp.ChangeToImmediate(ImmedOffset);
1044       Offset &= ~(Mask*Scale);
1045     }
1046   }
1047   
1048   // If we get here, the immediate doesn't fit into the instruction.  We folded
1049   // as much as possible above, handle the rest, providing a register that is
1050   // SP+LargeImm.
1051   assert(Offset && "This code isn't needed if offset already handled!");
1052
1053   if (isThumb) {
1054     if (TII.isLoad(Opcode)) {
1055       // Use the destination register to materialize sp + offset.
1056       unsigned TmpReg = MI.getOperand(0).getReg();
1057       bool UseRR = false;
1058       if (Opcode == ARM::tRestore) {
1059         if (FrameReg == ARM::SP)
1060           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1061         else {
1062           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1063           UseRR = true;
1064         }
1065       } else
1066         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1067       MI.setInstrDescriptor(TII.get(ARM::tLDR));
1068       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1069       if (UseRR)
1070         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
1071       else
1072         MI.addRegOperand(0, false); // tLDR has an extra register operand.
1073     } else if (TII.isStore(Opcode)) {
1074       // FIXME! This is horrific!!! We need register scavenging.
1075       // Our temporary workaround has marked r3 unavailable. Of course, r3 is
1076       // also a ABI register so it's possible that is is the register that is
1077       // being storing here. If that's the case, we do the following:
1078       // r12 = r2
1079       // Use r2 to materialize sp + offset
1080       // str r3, r2
1081       // r2 = r12
1082       unsigned ValReg = MI.getOperand(0).getReg();
1083       unsigned TmpReg = ARM::R3;
1084       bool UseRR = false;
1085       if (ValReg == ARM::R3) {
1086         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1087           .addReg(ARM::R2, false, false, true);
1088         TmpReg = ARM::R2;
1089       }
1090       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1091         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1092           .addReg(ARM::R3, false, false, true);
1093       if (Opcode == ARM::tSpill) {
1094         if (FrameReg == ARM::SP)
1095           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1096         else {
1097           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1098           UseRR = true;
1099         }
1100       } else
1101         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1102       MI.setInstrDescriptor(TII.get(ARM::tSTR));
1103       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1104       if (UseRR)
1105         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
1106       else
1107         MI.addRegOperand(0, false); // tSTR has an extra register operand.
1108
1109       MachineBasicBlock::iterator NII = next(II);
1110       if (ValReg == ARM::R3)
1111         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R2)
1112           .addReg(ARM::R12, false, false, true);
1113       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1114         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R3)
1115           .addReg(ARM::R12, false, false, true);
1116     } else
1117       assert(false && "Unexpected opcode!");
1118   } else {
1119     // Insert a set of r12 with the full address: r12 = sp + offset
1120     // If the offset we have is too large to fit into the instruction, we need
1121     // to form it with a series of ADDri's.  Do this by taking 8-bit chunks
1122     // out of 'Offset'.
1123     unsigned ScratchReg = findScratchRegister(RS, &ARM::GPRRegClass, AFI);
1124     if (ScratchReg == 0)
1125       // No register is "free". Scavenge a register.
1126       ScratchReg = RS->scavengeRegister(&ARM::GPRRegClass, II, SPAdj);
1127     int PIdx = MI.findFirstPredOperandIdx();
1128     ARMCC::CondCodes Pred = (PIdx == -1)
1129       ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImmedValue();
1130     unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1131     emitARMRegPlusImmediate(MBB, II, ScratchReg, FrameReg,
1132                             isSub ? -Offset : Offset, Pred, PredReg, TII);
1133     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1134   }
1135 }
1136
1137 static unsigned estimateStackSize(MachineFunction &MF, MachineFrameInfo *MFI) {
1138   const MachineFrameInfo *FFI = MF.getFrameInfo();
1139   int Offset = 0;
1140   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
1141     int FixedOff = -FFI->getObjectOffset(i);
1142     if (FixedOff > Offset) Offset = FixedOff;
1143   }
1144   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
1145     Offset += FFI->getObjectSize(i);
1146     unsigned Align = FFI->getObjectAlignment(i);
1147     // Adjust to alignment boundary
1148     Offset = (Offset+Align-1)/Align*Align;
1149   }
1150   return (unsigned)Offset;
1151 }
1152
1153 void
1154 ARMRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1155                                                       RegScavenger *RS) const {
1156   // This tells PEI to spill the FP as if it is any other callee-save register
1157   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1158   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1159   // to combine multiple loads / stores.
1160   bool CanEliminateFrame = true;
1161   bool CS1Spilled = false;
1162   bool LRSpilled = false;
1163   unsigned NumGPRSpills = 0;
1164   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1165   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1166   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1167
1168   // Don't spill FP if the frame can be eliminated. This is determined
1169   // by scanning the callee-save registers to see if any is used.
1170   const unsigned *CSRegs = getCalleeSavedRegs();
1171   const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
1172   for (unsigned i = 0; CSRegs[i]; ++i) {
1173     unsigned Reg = CSRegs[i];
1174     bool Spilled = false;
1175     if (MF.isPhysRegUsed(Reg)) {
1176       AFI->setCSRegisterIsSpilled(Reg);
1177       Spilled = true;
1178       CanEliminateFrame = false;
1179     } else {
1180       // Check alias registers too.
1181       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
1182         if (MF.isPhysRegUsed(*Aliases)) {
1183           Spilled = true;
1184           CanEliminateFrame = false;
1185         }
1186       }
1187     }
1188
1189     if (CSRegClasses[i] == &ARM::GPRRegClass) {
1190       if (Spilled) {
1191         NumGPRSpills++;
1192
1193         if (!STI.isTargetDarwin()) {
1194           if (Reg == ARM::LR)
1195             LRSpilled = true;
1196           CS1Spilled = true;
1197           continue;
1198         }
1199
1200         // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1201         switch (Reg) {
1202         case ARM::LR:
1203           LRSpilled = true;
1204           // Fallthrough
1205         case ARM::R4:
1206         case ARM::R5:
1207         case ARM::R6:
1208         case ARM::R7:
1209           CS1Spilled = true;
1210           break;
1211         default:
1212           break;
1213         }
1214       } else { 
1215         if (!STI.isTargetDarwin()) {
1216           UnspilledCS1GPRs.push_back(Reg);
1217           continue;
1218         }
1219
1220         switch (Reg) {
1221         case ARM::R4:
1222         case ARM::R5:
1223         case ARM::R6:
1224         case ARM::R7:
1225         case ARM::LR:
1226           UnspilledCS1GPRs.push_back(Reg);
1227           break;
1228         default:
1229           UnspilledCS2GPRs.push_back(Reg);
1230           break;
1231         }
1232       }
1233     }
1234   }
1235
1236   bool ForceLRSpill = false;
1237   if (!LRSpilled && AFI->isThumbFunction()) {
1238     unsigned FnSize = ARM::GetFunctionSize(MF);
1239     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1240     // use of BL to implement far jump. If it turns out that it's not needed
1241     // then the branch fix up path will undo it.
1242     if (FnSize >= (1 << 11)) {
1243       CanEliminateFrame = false;
1244       ForceLRSpill = true;
1245     }
1246   }
1247
1248   bool ExtraCSSpill = false;
1249   if (!CanEliminateFrame || hasFP(MF)) {
1250     AFI->setHasStackFrame(true);
1251
1252     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1253     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1254     if (!LRSpilled && CS1Spilled) {
1255       MF.setPhysRegUsed(ARM::LR);
1256       AFI->setCSRegisterIsSpilled(ARM::LR);
1257       NumGPRSpills++;
1258       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1259                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1260       ForceLRSpill = false;
1261       ExtraCSSpill = true;
1262     }
1263
1264     // Darwin ABI requires FP to point to the stack slot that contains the
1265     // previous FP.
1266     if (STI.isTargetDarwin() || hasFP(MF)) {
1267       MF.setPhysRegUsed(FramePtr);
1268       NumGPRSpills++;
1269     }
1270
1271     // If stack and double are 8-byte aligned and we are spilling an odd number
1272     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
1273     // the integer and double callee save areas.
1274     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1275     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1276       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1277         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1278           unsigned Reg = UnspilledCS1GPRs[i];
1279           // Don't spiil high register if the function is thumb
1280           if (!AFI->isThumbFunction() || isLowRegister(Reg) || Reg == ARM::LR) {
1281             MF.setPhysRegUsed(Reg);
1282             AFI->setCSRegisterIsSpilled(Reg);
1283             if (!isReservedReg(MF, Reg))
1284               ExtraCSSpill = true;
1285             break;
1286           }
1287         }
1288       } else if (!UnspilledCS2GPRs.empty() &&
1289                  !AFI->isThumbFunction()) {
1290         unsigned Reg = UnspilledCS2GPRs.front();
1291         MF.setPhysRegUsed(Reg);
1292         AFI->setCSRegisterIsSpilled(Reg);
1293         if (!isReservedReg(MF, Reg))
1294           ExtraCSSpill = true;
1295       }
1296     }
1297
1298     // Estimate if we might need to scavenge a register at some point in order
1299     // to materialize a stack offset. If so, either spill one additiona
1300     // callee-saved register or reserve a special spill slot to facilitate
1301     // register scavenging.
1302     if (RS && !ExtraCSSpill && !AFI->isThumbFunction()) {
1303       MachineFrameInfo  *MFI = MF.getFrameInfo();
1304       unsigned Size = estimateStackSize(MF, MFI);
1305       unsigned Limit = (1 << 12) - 1;
1306       for (MachineFunction::iterator BB = MF.begin(),E = MF.end();BB != E; ++BB)
1307         for (MachineBasicBlock::iterator I= BB->begin(); I != BB->end(); ++I) {
1308           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1309             if (I->getOperand(i).isFrameIndex()) {
1310               unsigned Opcode = I->getOpcode();
1311               const TargetInstrDescriptor &Desc = TII.get(Opcode);
1312               unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1313               if (AddrMode == ARMII::AddrMode3) {
1314                 Limit = (1 << 8) - 1;
1315                 goto DoneEstimating;
1316               } else if (AddrMode == ARMII::AddrMode5) {
1317                 unsigned ThisLimit = ((1 << 8) - 1) * 4;
1318                 if (ThisLimit < Limit)
1319                   Limit = ThisLimit;
1320               }
1321             }
1322         }
1323     DoneEstimating:
1324       if (Size >= Limit) {
1325         // If any non-reserved CS register isn't spilled, just spill one or two
1326         // extra. That should take care of it!
1327         unsigned NumExtras = TargetAlign / 4;
1328         SmallVector<unsigned, 2> Extras;
1329         while (NumExtras && !UnspilledCS1GPRs.empty()) {
1330           unsigned Reg = UnspilledCS1GPRs.back();
1331           UnspilledCS1GPRs.pop_back();
1332           if (!isReservedReg(MF, Reg)) {
1333             Extras.push_back(Reg);
1334             NumExtras--;
1335           }
1336         }
1337         while (NumExtras && !UnspilledCS2GPRs.empty()) {
1338           unsigned Reg = UnspilledCS2GPRs.back();
1339           UnspilledCS2GPRs.pop_back();
1340           if (!isReservedReg(MF, Reg)) {
1341             Extras.push_back(Reg);
1342             NumExtras--;
1343           }
1344         }
1345         if (Extras.size() && NumExtras == 0) {
1346           for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1347             MF.setPhysRegUsed(Extras[i]);
1348             AFI->setCSRegisterIsSpilled(Extras[i]);
1349           }
1350         } else {
1351           // Reserve a slot closest to SP or frame pointer.
1352           const TargetRegisterClass *RC = &ARM::GPRRegClass;
1353           RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1354                                                            RC->getAlignment()));
1355         }
1356       }
1357     }
1358   }
1359
1360   if (ForceLRSpill) {
1361     MF.setPhysRegUsed(ARM::LR);
1362     AFI->setCSRegisterIsSpilled(ARM::LR);
1363     AFI->setLRIsSpilledForFarJump(true);
1364   }
1365 }
1366
1367 /// Move iterator pass the next bunch of callee save load / store ops for
1368 /// the particular spill area (1: integer area 1, 2: integer area 2,
1369 /// 3: fp area, 0: don't care).
1370 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1371                                    MachineBasicBlock::iterator &MBBI,
1372                                    int Opc, unsigned Area,
1373                                    const ARMSubtarget &STI) {
1374   while (MBBI != MBB.end() &&
1375          MBBI->getOpcode() == Opc && MBBI->getOperand(1).isFrameIndex()) {
1376     if (Area != 0) {
1377       bool Done = false;
1378       unsigned Category = 0;
1379       switch (MBBI->getOperand(0).getReg()) {
1380       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1381       case ARM::LR:
1382         Category = 1;
1383         break;
1384       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1385         Category = STI.isTargetDarwin() ? 2 : 1;
1386         break;
1387       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1388       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1389         Category = 3;
1390         break;
1391       default:
1392         Done = true;
1393         break;
1394       }
1395       if (Done || Category != Area)
1396         break;
1397     }
1398
1399     ++MBBI;
1400   }
1401 }
1402
1403 void ARMRegisterInfo::emitPrologue(MachineFunction &MF) const {
1404   MachineBasicBlock &MBB = MF.front();
1405   MachineBasicBlock::iterator MBBI = MBB.begin();
1406   MachineFrameInfo  *MFI = MF.getFrameInfo();
1407   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1408   bool isThumb = AFI->isThumbFunction();
1409   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1410   unsigned NumBytes = MFI->getStackSize();
1411   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1412
1413   if (isThumb) {
1414     // Check if R3 is live in. It might have to be used as a scratch register.
1415     for (MachineFunction::livein_iterator I=MF.livein_begin(),E=MF.livein_end();
1416          I != E; ++I) {
1417       if ((*I).first == ARM::R3) {
1418         AFI->setR3IsLiveIn(true);
1419         break;
1420       }
1421     }
1422
1423     // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
1424     NumBytes = (NumBytes + 3) & ~3;
1425     MFI->setStackSize(NumBytes);
1426   }
1427
1428   // Determine the sizes of each callee-save spill areas and record which frame
1429   // belongs to which callee-save spill areas.
1430   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1431   int FramePtrSpillFI = 0;
1432
1433   if (VARegSaveSize)
1434     emitSPUpdate(MBB, MBBI, -VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1435
1436   if (!AFI->hasStackFrame()) {
1437     if (NumBytes != 0)
1438       emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1439     return;
1440   }
1441
1442   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1443     unsigned Reg = CSI[i].getReg();
1444     int FI = CSI[i].getFrameIdx();
1445     switch (Reg) {
1446     case ARM::R4:
1447     case ARM::R5:
1448     case ARM::R6:
1449     case ARM::R7:
1450     case ARM::LR:
1451       if (Reg == FramePtr)
1452         FramePtrSpillFI = FI;
1453       AFI->addGPRCalleeSavedArea1Frame(FI);
1454       GPRCS1Size += 4;
1455       break;
1456     case ARM::R8:
1457     case ARM::R9:
1458     case ARM::R10:
1459     case ARM::R11:
1460       if (Reg == FramePtr)
1461         FramePtrSpillFI = FI;
1462       if (STI.isTargetDarwin()) {
1463         AFI->addGPRCalleeSavedArea2Frame(FI);
1464         GPRCS2Size += 4;
1465       } else {
1466         AFI->addGPRCalleeSavedArea1Frame(FI);
1467         GPRCS1Size += 4;
1468       }
1469       break;
1470     default:
1471       AFI->addDPRCalleeSavedAreaFrame(FI);
1472       DPRCSSize += 8;
1473     }
1474   }
1475
1476   if (!isThumb) {
1477     // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1478     emitSPUpdate(MBB, MBBI, -GPRCS1Size, ARMCC::AL, 0, isThumb, TII);
1479     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 1, STI);
1480   } else if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH)
1481     ++MBBI;
1482
1483   // Darwin ABI requires FP to point to the stack slot that contains the
1484   // previous FP.
1485   if (STI.isTargetDarwin() || hasFP(MF)) {
1486     MachineInstrBuilder MIB =
1487       BuildMI(MBB, MBBI, TII.get(isThumb ? ARM::tADDrSPi : ARM::ADDri),FramePtr)
1488       .addFrameIndex(FramePtrSpillFI).addImm(0);
1489     if (!isThumb) AddDefaultCC(AddDefaultPred(MIB));
1490   }
1491
1492   if (!isThumb) {
1493     // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1494     emitSPUpdate(MBB, MBBI, -GPRCS2Size, ARMCC::AL, 0, false, TII);
1495
1496     // Build the new SUBri to adjust SP for FP callee-save spill area.
1497     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 2, STI);
1498     emitSPUpdate(MBB, MBBI, -DPRCSSize, ARMCC::AL, 0, false, TII);
1499   }
1500
1501   // Determine starting offsets of spill areas.
1502   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1503   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1504   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1505   AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
1506   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1507   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1508   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1509   
1510   NumBytes = DPRCSOffset;
1511   if (NumBytes) {
1512     // Insert it after all the callee-save spills.
1513     if (!isThumb)
1514       movePastCSLoadStoreOps(MBB, MBBI, ARM::FSTD, 3, STI);
1515     emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1516   }
1517
1518   if(STI.isTargetELF() && hasFP(MF)) {
1519     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1520                              AFI->getFramePtrSpillOffset());
1521   }
1522
1523   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1524   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1525   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1526 }
1527
1528 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1529   for (unsigned i = 0; CSRegs[i]; ++i)
1530     if (Reg == CSRegs[i])
1531       return true;
1532   return false;
1533 }
1534
1535 static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
1536   return ((MI->getOpcode() == ARM::FLDD ||
1537            MI->getOpcode() == ARM::LDR  ||
1538            MI->getOpcode() == ARM::tRestore) &&
1539           MI->getOperand(1).isFrameIndex() &&
1540           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1541 }
1542
1543 void ARMRegisterInfo::emitEpilogue(MachineFunction &MF,
1544                                    MachineBasicBlock &MBB) const {
1545   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1546   assert((MBBI->getOpcode() == ARM::BX_RET ||
1547           MBBI->getOpcode() == ARM::tBX_RET ||
1548           MBBI->getOpcode() == ARM::tPOP_RET) &&
1549          "Can only insert epilog into returning blocks");
1550
1551   MachineFrameInfo *MFI = MF.getFrameInfo();
1552   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1553   bool isThumb = AFI->isThumbFunction();
1554   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1555   int NumBytes = (int)MFI->getStackSize();
1556   if (!AFI->hasStackFrame()) {
1557     if (NumBytes != 0)
1558       emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1559   } else {
1560     // Unwind MBBI to point to first LDR / FLDD.
1561     const unsigned *CSRegs = getCalleeSavedRegs();
1562     if (MBBI != MBB.begin()) {
1563       do
1564         --MBBI;
1565       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
1566       if (!isCSRestore(MBBI, CSRegs))
1567         ++MBBI;
1568     }
1569
1570     // Move SP to start of FP callee save spill area.
1571     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1572                  AFI->getGPRCalleeSavedArea2Size() +
1573                  AFI->getDPRCalleeSavedAreaSize());
1574     if (isThumb) {
1575       if (hasFP(MF)) {
1576         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1577         // Reset SP based on frame pointer only if the stack frame extends beyond
1578         // frame pointer stack slot or target is ELF and the function has FP.
1579         if (NumBytes)
1580           emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes, TII);
1581         else
1582           BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::SP).addReg(FramePtr);
1583       } else {
1584         if (MBBI->getOpcode() == ARM::tBX_RET &&
1585             &MBB.front() != MBBI &&
1586             prior(MBBI)->getOpcode() == ARM::tPOP) {
1587           MachineBasicBlock::iterator PMBBI = prior(MBBI);
1588           emitSPUpdate(MBB, PMBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1589         } else
1590           emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1591       }
1592     } else {
1593       // Darwin ABI requires FP to point to the stack slot that contains the
1594       // previous FP.
1595       if ((STI.isTargetDarwin() && NumBytes) || hasFP(MF)) {
1596         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1597         // Reset SP based on frame pointer only if the stack frame extends beyond
1598         // frame pointer stack slot or target is ELF and the function has FP.
1599         if (AFI->getGPRCalleeSavedArea2Size() ||
1600             AFI->getDPRCalleeSavedAreaSize()  ||
1601             AFI->getDPRCalleeSavedAreaOffset()||
1602             hasFP(MF))
1603           if (NumBytes)
1604             BuildMI(MBB, MBBI, TII.get(ARM::SUBri), ARM::SP).addReg(FramePtr)
1605               .addImm(NumBytes)
1606               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1607           else
1608             BuildMI(MBB, MBBI, TII.get(ARM::MOVr), ARM::SP).addReg(FramePtr)
1609               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1610       } else if (NumBytes) {
1611         emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, false, TII);
1612       }
1613
1614       // Move SP to start of integer callee save spill area 2.
1615       movePastCSLoadStoreOps(MBB, MBBI, ARM::FLDD, 3, STI);
1616       emitSPUpdate(MBB, MBBI, AFI->getDPRCalleeSavedAreaSize(), ARMCC::AL, 0,
1617                    false, TII);
1618
1619       // Move SP to start of integer callee save spill area 1.
1620       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 2, STI);
1621       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea2Size(), ARMCC::AL, 0,
1622                    false, TII);
1623
1624       // Move SP to SP upon entry to the function.
1625       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 1, STI);
1626       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea1Size(), ARMCC::AL, 0,
1627                    false, TII);
1628     }
1629   }
1630
1631   if (VARegSaveSize) {
1632     if (isThumb)
1633       // Epilogue for vararg functions: pop LR to R3 and branch off it.
1634       // FIXME: Verify this is still ok when R3 is no longer being reserved.
1635       BuildMI(MBB, MBBI, TII.get(ARM::tPOP)).addReg(ARM::R3);
1636
1637     emitSPUpdate(MBB, MBBI, VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1638
1639     if (isThumb) {
1640       BuildMI(MBB, MBBI, TII.get(ARM::tBX_RET_vararg)).addReg(ARM::R3);
1641       MBB.erase(MBBI);
1642     }
1643   }
1644 }
1645
1646 unsigned ARMRegisterInfo::getRARegister() const {
1647   return ARM::LR;
1648 }
1649
1650 unsigned ARMRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1651   if (STI.isTargetDarwin() || hasFP(MF))
1652     return (STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11;
1653   else
1654     return ARM::SP;
1655 }
1656
1657 unsigned ARMRegisterInfo::getEHExceptionRegister() const {
1658   assert(0 && "What is the exception register");
1659   return 0;
1660 }
1661
1662 unsigned ARMRegisterInfo::getEHHandlerRegister() const {
1663   assert(0 && "What is the exception handler register");
1664   return 0;
1665 }
1666
1667 int ARMRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1668   assert(0 && "What is the dwarf register number");
1669   return -1;
1670 }
1671
1672 #include "ARMGenRegisterInfo.inc"
1673