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