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