171b323f4c71ff8415c7a2b653a68c142ed7178d
[oota-llvm.git] / lib / Target / ARM / ARMBaseRegisterInfo.cpp
1 //===- ARMBaseRegisterInfo.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 base ARM implementation of TargetRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMFrameInfo.h"
19 #include "ARMInstrInfo.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMSubtarget.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/LLVMContext.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineLocation.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/RegisterScavenging.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetFrameInfo.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/BitVector.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/Support/CommandLine.h"
42
43 using namespace llvm;
44
45 static cl::opt<bool>
46 ForceAllBaseRegAlloc("arm-force-base-reg-alloc", cl::Hidden, cl::init(false),
47           cl::desc("Force use of virtual base registers for stack load/store"));
48 static cl::opt<bool>
49 EnableLocalStackAlloc("enable-local-stack-alloc", cl::init(true), cl::Hidden,
50           cl::desc("Enable pre-regalloc stack frame index allocation"));
51 static cl::opt<bool>
52 EnableBasePointer("arm-use-base-pointer", cl::Hidden, cl::init(true),
53           cl::desc("Enable use of a base pointer for complex stack frames"));
54
55 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
56                                          const ARMSubtarget &sti)
57   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
58     TII(tii), STI(sti),
59     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
60     BasePtr(ARM::R6) {
61 }
62
63 const unsigned*
64 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
65   static const unsigned CalleeSavedRegs[] = {
66     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
67     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
68
69     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
70     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
71     0
72   };
73
74   static const unsigned DarwinCalleeSavedRegs[] = {
75     // Darwin ABI deviates from ARM standard ABI. R9 is not a callee-saved
76     // register.
77     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
78     ARM::R11, ARM::R10, ARM::R8,
79
80     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
81     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
82     0
83   };
84   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
85 }
86
87 BitVector ARMBaseRegisterInfo::
88 getReservedRegs(const MachineFunction &MF) const {
89   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
90
91   // FIXME: avoid re-calculating this everytime.
92   BitVector Reserved(getNumRegs());
93   Reserved.set(ARM::SP);
94   Reserved.set(ARM::PC);
95   Reserved.set(ARM::FPSCR);
96   if (TFI->hasFP(MF))
97     Reserved.set(FramePtr);
98   if (hasBasePointer(MF))
99     Reserved.set(BasePtr);
100   // Some targets reserve R9.
101   if (STI.isR9Reserved())
102     Reserved.set(ARM::R9);
103   return Reserved;
104 }
105
106 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
107                                         unsigned Reg) const {
108   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
109
110   switch (Reg) {
111   default: break;
112   case ARM::SP:
113   case ARM::PC:
114     return true;
115   case ARM::R6:
116     if (hasBasePointer(MF))
117       return true;
118     break;
119   case ARM::R7:
120   case ARM::R11:
121     if (FramePtr == Reg && TFI->hasFP(MF))
122       return true;
123     break;
124   case ARM::R9:
125     return STI.isR9Reserved();
126   }
127
128   return false;
129 }
130
131 const TargetRegisterClass *
132 ARMBaseRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
133                                               const TargetRegisterClass *B,
134                                               unsigned SubIdx) const {
135   switch (SubIdx) {
136   default: return 0;
137   case ARM::ssub_0:
138   case ARM::ssub_1:
139   case ARM::ssub_2:
140   case ARM::ssub_3: {
141     // S sub-registers.
142     if (A->getSize() == 8) {
143       if (B == &ARM::SPR_8RegClass)
144         return &ARM::DPR_8RegClass;
145       assert(B == &ARM::SPRRegClass && "Expecting SPR register class!");
146       if (A == &ARM::DPR_8RegClass)
147         return A;
148       return &ARM::DPR_VFP2RegClass;
149     }
150
151     if (A->getSize() == 16) {
152       if (B == &ARM::SPR_8RegClass)
153         return &ARM::QPR_8RegClass;
154       return &ARM::QPR_VFP2RegClass;
155     }
156
157     if (A->getSize() == 32) {
158       if (B == &ARM::SPR_8RegClass)
159         return 0;  // Do not allow coalescing!
160       return &ARM::QQPR_VFP2RegClass;
161     }
162
163     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
164     return 0;  // Do not allow coalescing!
165   }
166   case ARM::dsub_0:
167   case ARM::dsub_1:
168   case ARM::dsub_2:
169   case ARM::dsub_3: {
170     // D sub-registers.
171     if (A->getSize() == 16) {
172       if (B == &ARM::DPR_VFP2RegClass)
173         return &ARM::QPR_VFP2RegClass;
174       if (B == &ARM::DPR_8RegClass)
175         return 0;  // Do not allow coalescing!
176       return A;
177     }
178
179     if (A->getSize() == 32) {
180       if (B == &ARM::DPR_VFP2RegClass)
181         return &ARM::QQPR_VFP2RegClass;
182       if (B == &ARM::DPR_8RegClass)
183         return 0;  // Do not allow coalescing!
184       return A;
185     }
186
187     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
188     if (B != &ARM::DPRRegClass)
189       return 0;  // Do not allow coalescing!
190     return A;
191   }
192   case ARM::dsub_4:
193   case ARM::dsub_5:
194   case ARM::dsub_6:
195   case ARM::dsub_7: {
196     // D sub-registers of QQQQ registers.
197     if (A->getSize() == 64 && B == &ARM::DPRRegClass)
198       return A;
199     return 0;  // Do not allow coalescing!
200   }
201
202   case ARM::qsub_0:
203   case ARM::qsub_1: {
204     // Q sub-registers.
205     if (A->getSize() == 32) {
206       if (B == &ARM::QPR_VFP2RegClass)
207         return &ARM::QQPR_VFP2RegClass;
208       if (B == &ARM::QPR_8RegClass)
209         return 0;  // Do not allow coalescing!
210       return A;
211     }
212
213     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
214     if (B == &ARM::QPRRegClass)
215       return A;
216     return 0;  // Do not allow coalescing!
217   }
218   case ARM::qsub_2:
219   case ARM::qsub_3: {
220     // Q sub-registers of QQQQ registers.
221     if (A->getSize() == 64 && B == &ARM::QPRRegClass)
222       return A;
223     return 0;  // Do not allow coalescing!
224   }
225   }
226   return 0;
227 }
228
229 bool
230 ARMBaseRegisterInfo::canCombineSubRegIndices(const TargetRegisterClass *RC,
231                                           SmallVectorImpl<unsigned> &SubIndices,
232                                           unsigned &NewSubIdx) const {
233
234   unsigned Size = RC->getSize() * 8;
235   if (Size < 6)
236     return 0;
237
238   NewSubIdx = 0;  // Whole register.
239   unsigned NumRegs = SubIndices.size();
240   if (NumRegs == 8) {
241     // 8 D registers -> 1 QQQQ register.
242     return (Size == 512 &&
243             SubIndices[0] == ARM::dsub_0 &&
244             SubIndices[1] == ARM::dsub_1 &&
245             SubIndices[2] == ARM::dsub_2 &&
246             SubIndices[3] == ARM::dsub_3 &&
247             SubIndices[4] == ARM::dsub_4 &&
248             SubIndices[5] == ARM::dsub_5 &&
249             SubIndices[6] == ARM::dsub_6 &&
250             SubIndices[7] == ARM::dsub_7);
251   } else if (NumRegs == 4) {
252     if (SubIndices[0] == ARM::qsub_0) {
253       // 4 Q registers -> 1 QQQQ register.
254       return (Size == 512 &&
255               SubIndices[1] == ARM::qsub_1 &&
256               SubIndices[2] == ARM::qsub_2 &&
257               SubIndices[3] == ARM::qsub_3);
258     } else if (SubIndices[0] == ARM::dsub_0) {
259       // 4 D registers -> 1 QQ register.
260       if (Size >= 256 &&
261           SubIndices[1] == ARM::dsub_1 &&
262           SubIndices[2] == ARM::dsub_2 &&
263           SubIndices[3] == ARM::dsub_3) {
264         if (Size == 512)
265           NewSubIdx = ARM::qqsub_0;
266         return true;
267       }
268     } else if (SubIndices[0] == ARM::dsub_4) {
269       // 4 D registers -> 1 QQ register (2nd).
270       if (Size == 512 &&
271           SubIndices[1] == ARM::dsub_5 &&
272           SubIndices[2] == ARM::dsub_6 &&
273           SubIndices[3] == ARM::dsub_7) {
274         NewSubIdx = ARM::qqsub_1;
275         return true;
276       }
277     } else if (SubIndices[0] == ARM::ssub_0) {
278       // 4 S registers -> 1 Q register.
279       if (Size >= 128 &&
280           SubIndices[1] == ARM::ssub_1 &&
281           SubIndices[2] == ARM::ssub_2 &&
282           SubIndices[3] == ARM::ssub_3) {
283         if (Size >= 256)
284           NewSubIdx = ARM::qsub_0;
285         return true;
286       }
287     }
288   } else if (NumRegs == 2) {
289     if (SubIndices[0] == ARM::qsub_0) {
290       // 2 Q registers -> 1 QQ register.
291       if (Size >= 256 && SubIndices[1] == ARM::qsub_1) {
292         if (Size == 512)
293           NewSubIdx = ARM::qqsub_0;
294         return true;
295       }
296     } else if (SubIndices[0] == ARM::qsub_2) {
297       // 2 Q registers -> 1 QQ register (2nd).
298       if (Size == 512 && SubIndices[1] == ARM::qsub_3) {
299         NewSubIdx = ARM::qqsub_1;
300         return true;
301       }
302     } else if (SubIndices[0] == ARM::dsub_0) {
303       // 2 D registers -> 1 Q register.
304       if (Size >= 128 && SubIndices[1] == ARM::dsub_1) {
305         if (Size >= 256)
306           NewSubIdx = ARM::qsub_0;
307         return true;
308       }
309     } else if (SubIndices[0] == ARM::dsub_2) {
310       // 2 D registers -> 1 Q register (2nd).
311       if (Size >= 256 && SubIndices[1] == ARM::dsub_3) {
312         NewSubIdx = ARM::qsub_1;
313         return true;
314       }
315     } else if (SubIndices[0] == ARM::dsub_4) {
316       // 2 D registers -> 1 Q register (3rd).
317       if (Size == 512 && SubIndices[1] == ARM::dsub_5) {
318         NewSubIdx = ARM::qsub_2;
319         return true;
320       }
321     } else if (SubIndices[0] == ARM::dsub_6) {
322       // 2 D registers -> 1 Q register (3rd).
323       if (Size == 512 && SubIndices[1] == ARM::dsub_7) {
324         NewSubIdx = ARM::qsub_3;
325         return true;
326       }
327     } else if (SubIndices[0] == ARM::ssub_0) {
328       // 2 S registers -> 1 D register.
329       if (SubIndices[1] == ARM::ssub_1) {
330         if (Size >= 128)
331           NewSubIdx = ARM::dsub_0;
332         return true;
333       }
334     } else if (SubIndices[0] == ARM::ssub_2) {
335       // 2 S registers -> 1 D register (2nd).
336       if (Size >= 128 && SubIndices[1] == ARM::ssub_3) {
337         NewSubIdx = ARM::dsub_1;
338         return true;
339       }
340     }
341   }
342   return false;
343 }
344
345
346 const TargetRegisterClass *
347 ARMBaseRegisterInfo::getPointerRegClass(unsigned Kind) const {
348   return ARM::GPRRegisterClass;
349 }
350
351 /// getAllocationOrder - Returns the register allocation order for a specified
352 /// register class in the form of a pair of TargetRegisterClass iterators.
353 std::pair<TargetRegisterClass::iterator,TargetRegisterClass::iterator>
354 ARMBaseRegisterInfo::getAllocationOrder(const TargetRegisterClass *RC,
355                                         unsigned HintType, unsigned HintReg,
356                                         const MachineFunction &MF) const {
357   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
358   // Alternative register allocation orders when favoring even / odd registers
359   // of register pairs.
360
361   // No FP, R9 is available.
362   static const unsigned GPREven1[] = {
363     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
364     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
365     ARM::R9, ARM::R11
366   };
367   static const unsigned GPROdd1[] = {
368     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
369     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
370     ARM::R8, ARM::R10
371   };
372
373   // FP is R7, R9 is available.
374   static const unsigned GPREven2[] = {
375     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
376     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
377     ARM::R9, ARM::R11
378   };
379   static const unsigned GPROdd2[] = {
380     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
381     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
382     ARM::R8, ARM::R10
383   };
384
385   // FP is R11, R9 is available.
386   static const unsigned GPREven3[] = {
387     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
388     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
389     ARM::R9
390   };
391   static const unsigned GPROdd3[] = {
392     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
393     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
394     ARM::R8
395   };
396
397   // No FP, R9 is not available.
398   static const unsigned GPREven4[] = {
399     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
400     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
401     ARM::R11
402   };
403   static const unsigned GPROdd4[] = {
404     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
405     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
406     ARM::R10
407   };
408
409   // FP is R7, R9 is not available.
410   static const unsigned GPREven5[] = {
411     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
412     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
413     ARM::R11
414   };
415   static const unsigned GPROdd5[] = {
416     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
417     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
418     ARM::R10
419   };
420
421   // FP is R11, R9 is not available.
422   static const unsigned GPREven6[] = {
423     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
424     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
425   };
426   static const unsigned GPROdd6[] = {
427     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
428     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
429   };
430
431
432   if (HintType == ARMRI::RegPairEven) {
433     if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
434       // It's no longer possible to fulfill this hint. Return the default
435       // allocation order.
436       return std::make_pair(RC->allocation_order_begin(MF),
437                             RC->allocation_order_end(MF));
438
439     if (!TFI->hasFP(MF)) {
440       if (!STI.isR9Reserved())
441         return std::make_pair(GPREven1,
442                               GPREven1 + (sizeof(GPREven1)/sizeof(unsigned)));
443       else
444         return std::make_pair(GPREven4,
445                               GPREven4 + (sizeof(GPREven4)/sizeof(unsigned)));
446     } else if (FramePtr == ARM::R7) {
447       if (!STI.isR9Reserved())
448         return std::make_pair(GPREven2,
449                               GPREven2 + (sizeof(GPREven2)/sizeof(unsigned)));
450       else
451         return std::make_pair(GPREven5,
452                               GPREven5 + (sizeof(GPREven5)/sizeof(unsigned)));
453     } else { // FramePtr == ARM::R11
454       if (!STI.isR9Reserved())
455         return std::make_pair(GPREven3,
456                               GPREven3 + (sizeof(GPREven3)/sizeof(unsigned)));
457       else
458         return std::make_pair(GPREven6,
459                               GPREven6 + (sizeof(GPREven6)/sizeof(unsigned)));
460     }
461   } else if (HintType == ARMRI::RegPairOdd) {
462     if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
463       // It's no longer possible to fulfill this hint. Return the default
464       // allocation order.
465       return std::make_pair(RC->allocation_order_begin(MF),
466                             RC->allocation_order_end(MF));
467
468     if (!TFI->hasFP(MF)) {
469       if (!STI.isR9Reserved())
470         return std::make_pair(GPROdd1,
471                               GPROdd1 + (sizeof(GPROdd1)/sizeof(unsigned)));
472       else
473         return std::make_pair(GPROdd4,
474                               GPROdd4 + (sizeof(GPROdd4)/sizeof(unsigned)));
475     } else if (FramePtr == ARM::R7) {
476       if (!STI.isR9Reserved())
477         return std::make_pair(GPROdd2,
478                               GPROdd2 + (sizeof(GPROdd2)/sizeof(unsigned)));
479       else
480         return std::make_pair(GPROdd5,
481                               GPROdd5 + (sizeof(GPROdd5)/sizeof(unsigned)));
482     } else { // FramePtr == ARM::R11
483       if (!STI.isR9Reserved())
484         return std::make_pair(GPROdd3,
485                               GPROdd3 + (sizeof(GPROdd3)/sizeof(unsigned)));
486       else
487         return std::make_pair(GPROdd6,
488                               GPROdd6 + (sizeof(GPROdd6)/sizeof(unsigned)));
489     }
490   }
491   return std::make_pair(RC->allocation_order_begin(MF),
492                         RC->allocation_order_end(MF));
493 }
494
495 /// ResolveRegAllocHint - Resolves the specified register allocation hint
496 /// to a physical register. Returns the physical register if it is successful.
497 unsigned
498 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
499                                          const MachineFunction &MF) const {
500   if (Reg == 0 || !isPhysicalRegister(Reg))
501     return 0;
502   if (Type == 0)
503     return Reg;
504   else if (Type == (unsigned)ARMRI::RegPairOdd)
505     // Odd register.
506     return getRegisterPairOdd(Reg, MF);
507   else if (Type == (unsigned)ARMRI::RegPairEven)
508     // Even register.
509     return getRegisterPairEven(Reg, MF);
510   return 0;
511 }
512
513 void
514 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
515                                         MachineFunction &MF) const {
516   MachineRegisterInfo *MRI = &MF.getRegInfo();
517   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
518   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
519        Hint.first == (unsigned)ARMRI::RegPairEven) &&
520       Hint.second && TargetRegisterInfo::isVirtualRegister(Hint.second)) {
521     // If 'Reg' is one of the even / odd register pair and it's now changed
522     // (e.g. coalesced) into a different register. The other register of the
523     // pair allocation hint must be updated to reflect the relationship
524     // change.
525     unsigned OtherReg = Hint.second;
526     Hint = MRI->getRegAllocationHint(OtherReg);
527     if (Hint.second == Reg)
528       // Make sure the pair has not already divorced.
529       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
530   }
531 }
532
533 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
534   const MachineFrameInfo *MFI = MF.getFrameInfo();
535   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
536
537   if (!EnableBasePointer)
538     return false;
539
540   if (needsStackRealignment(MF) && MFI->hasVarSizedObjects())
541     return true;
542
543   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
544   // negative range for ldr/str (255), and thumb1 is positive offsets only.
545   // It's going to be better to use the SP or Base Pointer instead. When there
546   // are variable sized objects, we can't reference off of the SP, so we
547   // reserve a Base Pointer.
548   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
549     // Conservatively estimate whether the negative offset from the frame
550     // pointer will be sufficient to reach. If a function has a smallish
551     // frame, it's less likely to have lots of spills and callee saved
552     // space, so it's all more likely to be within range of the frame pointer.
553     // If it's wrong, the scavenger will still enable access to work, it just
554     // won't be optimal.
555     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
556       return false;
557     return true;
558   }
559
560   return false;
561 }
562
563 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
564   const MachineFrameInfo *MFI = MF.getFrameInfo();
565   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
566   // We can't realign the stack if:
567   // 1. Dynamic stack realignment is explicitly disabled,
568   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
569   // 3. There are VLAs in the function and the base pointer is disabled.
570   return (RealignStack && !AFI->isThumb1OnlyFunction() &&
571           (!MFI->hasVarSizedObjects() || EnableBasePointer));
572 }
573
574 bool ARMBaseRegisterInfo::
575 needsStackRealignment(const MachineFunction &MF) const {
576   const MachineFrameInfo *MFI = MF.getFrameInfo();
577   const Function *F = MF.getFunction();
578   unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
579   bool requiresRealignment = ((MFI->getLocalFrameMaxAlign() > StackAlign) ||
580                                F->hasFnAttr(Attribute::StackAlignment));
581
582   return requiresRealignment && canRealignStack(MF);
583 }
584
585 bool ARMBaseRegisterInfo::
586 cannotEliminateFrame(const MachineFunction &MF) const {
587   const MachineFrameInfo *MFI = MF.getFrameInfo();
588   if (DisableFramePointerElim(MF) && MFI->adjustsStack())
589     return true;
590   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
591     || needsStackRealignment(MF);
592 }
593
594 /// estimateStackSize - Estimate and return the size of the frame.
595 static unsigned estimateStackSize(MachineFunction &MF) {
596   const MachineFrameInfo *FFI = MF.getFrameInfo();
597   int Offset = 0;
598   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
599     int FixedOff = -FFI->getObjectOffset(i);
600     if (FixedOff > Offset) Offset = FixedOff;
601   }
602   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
603     if (FFI->isDeadObjectIndex(i))
604       continue;
605     Offset += FFI->getObjectSize(i);
606     unsigned Align = FFI->getObjectAlignment(i);
607     // Adjust to alignment boundary
608     Offset = (Offset+Align-1)/Align*Align;
609   }
610   return (unsigned)Offset;
611 }
612
613 /// estimateRSStackSizeLimit - Look at each instruction that references stack
614 /// frames and return the stack size limit beyond which some of these
615 /// instructions will require a scratch register during their expansion later.
616 unsigned
617 ARMBaseRegisterInfo::estimateRSStackSizeLimit(MachineFunction &MF) const {
618   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
619   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
620   unsigned Limit = (1 << 12) - 1;
621   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
622     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
623          I != E; ++I) {
624       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
625         if (!I->getOperand(i).isFI()) continue;
626
627         // When using ADDri to get the address of a stack object, 255 is the
628         // largest offset guaranteed to fit in the immediate offset.
629         if (I->getOpcode() == ARM::ADDri) {
630           Limit = std::min(Limit, (1U << 8) - 1);
631           break;
632         }
633
634         // Otherwise check the addressing mode.
635         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
636         case ARMII::AddrMode3:
637         case ARMII::AddrModeT2_i8:
638           Limit = std::min(Limit, (1U << 8) - 1);
639           break;
640         case ARMII::AddrMode5:
641         case ARMII::AddrModeT2_i8s4:
642           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
643           break;
644         case ARMII::AddrModeT2_i12:
645           // i12 supports only positive offset so these will be converted to
646           // i8 opcodes. See llvm::rewriteT2FrameIndex.
647           if (TFI->hasFP(MF) && AFI->hasStackFrame())
648             Limit = std::min(Limit, (1U << 8) - 1);
649           break;
650         case ARMII::AddrMode4:
651         case ARMII::AddrMode6:
652           // Addressing modes 4 & 6 (load/store) instructions can't encode an
653           // immediate offset for stack references.
654           return 0;
655         default:
656           break;
657         }
658         break; // At most one FI per instruction
659       }
660     }
661   }
662
663   return Limit;
664 }
665
666 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
667                                        const ARMBaseInstrInfo &TII) {
668   unsigned FnSize = 0;
669   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
670        MBBI != E; ++MBBI) {
671     const MachineBasicBlock &MBB = *MBBI;
672     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
673          I != E; ++I)
674       FnSize += TII.GetInstSizeInBytes(I);
675   }
676   return FnSize;
677 }
678
679 void
680 ARMBaseRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
681                                                        RegScavenger *RS) const {
682   // This tells PEI to spill the FP as if it is any other callee-save register
683   // to take advantage the eliminateFrameIndex machinery. This also ensures it
684   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
685   // to combine multiple loads / stores.
686   bool CanEliminateFrame = true;
687   bool CS1Spilled = false;
688   bool LRSpilled = false;
689   unsigned NumGPRSpills = 0;
690   SmallVector<unsigned, 4> UnspilledCS1GPRs;
691   SmallVector<unsigned, 4> UnspilledCS2GPRs;
692   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
693   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
694   MachineFrameInfo *MFI = MF.getFrameInfo();
695
696   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
697   // scratch register.
698   // FIXME: It will be better just to find spare register here.
699   if (needsStackRealignment(MF) &&
700       AFI->isThumb2Function())
701     MF.getRegInfo().setPhysRegUsed(ARM::R4);
702
703   // Spill LR if Thumb1 function uses variable length argument lists.
704   if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
705     MF.getRegInfo().setPhysRegUsed(ARM::LR);
706
707   // Spill the BasePtr if it's used.
708   if (hasBasePointer(MF))
709     MF.getRegInfo().setPhysRegUsed(BasePtr);
710
711   // Don't spill FP if the frame can be eliminated. This is determined
712   // by scanning the callee-save registers to see if any is used.
713   const unsigned *CSRegs = getCalleeSavedRegs();
714   for (unsigned i = 0; CSRegs[i]; ++i) {
715     unsigned Reg = CSRegs[i];
716     bool Spilled = false;
717     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
718       AFI->setCSRegisterIsSpilled(Reg);
719       Spilled = true;
720       CanEliminateFrame = false;
721     } else {
722       // Check alias registers too.
723       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
724         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
725           Spilled = true;
726           CanEliminateFrame = false;
727         }
728       }
729     }
730
731     if (!ARM::GPRRegisterClass->contains(Reg))
732       continue;
733
734     if (Spilled) {
735       NumGPRSpills++;
736
737       if (!STI.isTargetDarwin()) {
738         if (Reg == ARM::LR)
739           LRSpilled = true;
740         CS1Spilled = true;
741         continue;
742       }
743
744       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
745       switch (Reg) {
746       case ARM::LR:
747         LRSpilled = true;
748         // Fallthrough
749       case ARM::R4:
750       case ARM::R5:
751       case ARM::R6:
752       case ARM::R7:
753         CS1Spilled = true;
754         break;
755       default:
756         break;
757       }
758     } else {
759       if (!STI.isTargetDarwin()) {
760         UnspilledCS1GPRs.push_back(Reg);
761         continue;
762       }
763
764       switch (Reg) {
765       case ARM::R4:
766       case ARM::R5:
767       case ARM::R6:
768       case ARM::R7:
769       case ARM::LR:
770         UnspilledCS1GPRs.push_back(Reg);
771         break;
772       default:
773         UnspilledCS2GPRs.push_back(Reg);
774         break;
775       }
776     }
777   }
778
779   bool ForceLRSpill = false;
780   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
781     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
782     // Force LR to be spilled if the Thumb function size is > 2048. This enables
783     // use of BL to implement far jump. If it turns out that it's not needed
784     // then the branch fix up path will undo it.
785     if (FnSize >= (1 << 11)) {
786       CanEliminateFrame = false;
787       ForceLRSpill = true;
788     }
789   }
790
791   // If any of the stack slot references may be out of range of an immediate
792   // offset, make sure a register (or a spill slot) is available for the
793   // register scavenger. Note that if we're indexing off the frame pointer, the
794   // effective stack size is 4 bytes larger since the FP points to the stack
795   // slot of the previous FP. Also, if we have variable sized objects in the
796   // function, stack slot references will often be negative, and some of
797   // our instructions are positive-offset only, so conservatively consider
798   // that case to want a spill slot (or register) as well. Similarly, if
799   // the function adjusts the stack pointer during execution and the
800   // adjustments aren't already part of our stack size estimate, our offset
801   // calculations may be off, so be conservative.
802   // FIXME: We could add logic to be more precise about negative offsets
803   //        and which instructions will need a scratch register for them. Is it
804   //        worth the effort and added fragility?
805   bool BigStack =
806     (RS &&
807      (estimateStackSize(MF) + ((TFI->hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
808       estimateRSStackSizeLimit(MF)))
809     || MFI->hasVarSizedObjects()
810     || (MFI->adjustsStack() && !TFI->canSimplifyCallFramePseudos(MF));
811
812   bool ExtraCSSpill = false;
813   if (BigStack || !CanEliminateFrame || cannotEliminateFrame(MF)) {
814     AFI->setHasStackFrame(true);
815
816     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
817     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
818     if (!LRSpilled && CS1Spilled) {
819       MF.getRegInfo().setPhysRegUsed(ARM::LR);
820       AFI->setCSRegisterIsSpilled(ARM::LR);
821       NumGPRSpills++;
822       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
823                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
824       ForceLRSpill = false;
825       ExtraCSSpill = true;
826     }
827
828     if (TFI->hasFP(MF)) {
829       MF.getRegInfo().setPhysRegUsed(FramePtr);
830       NumGPRSpills++;
831     }
832
833     // If stack and double are 8-byte aligned and we are spilling an odd number
834     // of GPRs, spill one extra callee save GPR so we won't have to pad between
835     // the integer and double callee save areas.
836     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
837     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
838       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
839         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
840           unsigned Reg = UnspilledCS1GPRs[i];
841           // Don't spill high register if the function is thumb1
842           if (!AFI->isThumb1OnlyFunction() ||
843               isARMLowRegister(Reg) || Reg == ARM::LR) {
844             MF.getRegInfo().setPhysRegUsed(Reg);
845             AFI->setCSRegisterIsSpilled(Reg);
846             if (!isReservedReg(MF, Reg))
847               ExtraCSSpill = true;
848             break;
849           }
850         }
851       } else if (!UnspilledCS2GPRs.empty() &&
852                  !AFI->isThumb1OnlyFunction()) {
853         unsigned Reg = UnspilledCS2GPRs.front();
854         MF.getRegInfo().setPhysRegUsed(Reg);
855         AFI->setCSRegisterIsSpilled(Reg);
856         if (!isReservedReg(MF, Reg))
857           ExtraCSSpill = true;
858       }
859     }
860
861     // Estimate if we might need to scavenge a register at some point in order
862     // to materialize a stack offset. If so, either spill one additional
863     // callee-saved register or reserve a special spill slot to facilitate
864     // register scavenging. Thumb1 needs a spill slot for stack pointer
865     // adjustments also, even when the frame itself is small.
866     if (BigStack && !ExtraCSSpill) {
867       // If any non-reserved CS register isn't spilled, just spill one or two
868       // extra. That should take care of it!
869       unsigned NumExtras = TargetAlign / 4;
870       SmallVector<unsigned, 2> Extras;
871       while (NumExtras && !UnspilledCS1GPRs.empty()) {
872         unsigned Reg = UnspilledCS1GPRs.back();
873         UnspilledCS1GPRs.pop_back();
874         if (!isReservedReg(MF, Reg) &&
875             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
876              Reg == ARM::LR)) {
877           Extras.push_back(Reg);
878           NumExtras--;
879         }
880       }
881       // For non-Thumb1 functions, also check for hi-reg CS registers
882       if (!AFI->isThumb1OnlyFunction()) {
883         while (NumExtras && !UnspilledCS2GPRs.empty()) {
884           unsigned Reg = UnspilledCS2GPRs.back();
885           UnspilledCS2GPRs.pop_back();
886           if (!isReservedReg(MF, Reg)) {
887             Extras.push_back(Reg);
888             NumExtras--;
889           }
890         }
891       }
892       if (Extras.size() && NumExtras == 0) {
893         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
894           MF.getRegInfo().setPhysRegUsed(Extras[i]);
895           AFI->setCSRegisterIsSpilled(Extras[i]);
896         }
897       } else if (!AFI->isThumb1OnlyFunction()) {
898         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
899         // closest to SP or frame pointer.
900         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
901         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
902                                                            RC->getAlignment(),
903                                                            false));
904       }
905     }
906   }
907
908   if (ForceLRSpill) {
909     MF.getRegInfo().setPhysRegUsed(ARM::LR);
910     AFI->setCSRegisterIsSpilled(ARM::LR);
911     AFI->setLRIsSpilledForFarJump(true);
912   }
913 }
914
915 unsigned ARMBaseRegisterInfo::getRARegister() const {
916   return ARM::LR;
917 }
918
919 unsigned
920 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
921   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
922
923   if (TFI->hasFP(MF))
924     return FramePtr;
925   return ARM::SP;
926 }
927
928 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
929   llvm_unreachable("What is the exception register");
930   return 0;
931 }
932
933 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
934   llvm_unreachable("What is the exception handler register");
935   return 0;
936 }
937
938 int ARMBaseRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
939   return ARMGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
940 }
941
942 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
943                                               const MachineFunction &MF) const {
944   switch (Reg) {
945   default: break;
946   // Return 0 if either register of the pair is a special register.
947   // So no R12, etc.
948   case ARM::R1:
949     return ARM::R0;
950   case ARM::R3:
951     return ARM::R2;
952   case ARM::R5:
953     return ARM::R4;
954   case ARM::R7:
955     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
956       ? 0 : ARM::R6;
957   case ARM::R9:
958     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R8;
959   case ARM::R11:
960     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
961
962   case ARM::S1:
963     return ARM::S0;
964   case ARM::S3:
965     return ARM::S2;
966   case ARM::S5:
967     return ARM::S4;
968   case ARM::S7:
969     return ARM::S6;
970   case ARM::S9:
971     return ARM::S8;
972   case ARM::S11:
973     return ARM::S10;
974   case ARM::S13:
975     return ARM::S12;
976   case ARM::S15:
977     return ARM::S14;
978   case ARM::S17:
979     return ARM::S16;
980   case ARM::S19:
981     return ARM::S18;
982   case ARM::S21:
983     return ARM::S20;
984   case ARM::S23:
985     return ARM::S22;
986   case ARM::S25:
987     return ARM::S24;
988   case ARM::S27:
989     return ARM::S26;
990   case ARM::S29:
991     return ARM::S28;
992   case ARM::S31:
993     return ARM::S30;
994
995   case ARM::D1:
996     return ARM::D0;
997   case ARM::D3:
998     return ARM::D2;
999   case ARM::D5:
1000     return ARM::D4;
1001   case ARM::D7:
1002     return ARM::D6;
1003   case ARM::D9:
1004     return ARM::D8;
1005   case ARM::D11:
1006     return ARM::D10;
1007   case ARM::D13:
1008     return ARM::D12;
1009   case ARM::D15:
1010     return ARM::D14;
1011   case ARM::D17:
1012     return ARM::D16;
1013   case ARM::D19:
1014     return ARM::D18;
1015   case ARM::D21:
1016     return ARM::D20;
1017   case ARM::D23:
1018     return ARM::D22;
1019   case ARM::D25:
1020     return ARM::D24;
1021   case ARM::D27:
1022     return ARM::D26;
1023   case ARM::D29:
1024     return ARM::D28;
1025   case ARM::D31:
1026     return ARM::D30;
1027   }
1028
1029   return 0;
1030 }
1031
1032 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
1033                                              const MachineFunction &MF) const {
1034   switch (Reg) {
1035   default: break;
1036   // Return 0 if either register of the pair is a special register.
1037   // So no R12, etc.
1038   case ARM::R0:
1039     return ARM::R1;
1040   case ARM::R2:
1041     return ARM::R3;
1042   case ARM::R4:
1043     return ARM::R5;
1044   case ARM::R6:
1045     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
1046       ? 0 : ARM::R7;
1047   case ARM::R8:
1048     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R9;
1049   case ARM::R10:
1050     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
1051
1052   case ARM::S0:
1053     return ARM::S1;
1054   case ARM::S2:
1055     return ARM::S3;
1056   case ARM::S4:
1057     return ARM::S5;
1058   case ARM::S6:
1059     return ARM::S7;
1060   case ARM::S8:
1061     return ARM::S9;
1062   case ARM::S10:
1063     return ARM::S11;
1064   case ARM::S12:
1065     return ARM::S13;
1066   case ARM::S14:
1067     return ARM::S15;
1068   case ARM::S16:
1069     return ARM::S17;
1070   case ARM::S18:
1071     return ARM::S19;
1072   case ARM::S20:
1073     return ARM::S21;
1074   case ARM::S22:
1075     return ARM::S23;
1076   case ARM::S24:
1077     return ARM::S25;
1078   case ARM::S26:
1079     return ARM::S27;
1080   case ARM::S28:
1081     return ARM::S29;
1082   case ARM::S30:
1083     return ARM::S31;
1084
1085   case ARM::D0:
1086     return ARM::D1;
1087   case ARM::D2:
1088     return ARM::D3;
1089   case ARM::D4:
1090     return ARM::D5;
1091   case ARM::D6:
1092     return ARM::D7;
1093   case ARM::D8:
1094     return ARM::D9;
1095   case ARM::D10:
1096     return ARM::D11;
1097   case ARM::D12:
1098     return ARM::D13;
1099   case ARM::D14:
1100     return ARM::D15;
1101   case ARM::D16:
1102     return ARM::D17;
1103   case ARM::D18:
1104     return ARM::D19;
1105   case ARM::D20:
1106     return ARM::D21;
1107   case ARM::D22:
1108     return ARM::D23;
1109   case ARM::D24:
1110     return ARM::D25;
1111   case ARM::D26:
1112     return ARM::D27;
1113   case ARM::D28:
1114     return ARM::D29;
1115   case ARM::D30:
1116     return ARM::D31;
1117   }
1118
1119   return 0;
1120 }
1121
1122 /// emitLoadConstPool - Emits a load from constpool to materialize the
1123 /// specified immediate.
1124 void ARMBaseRegisterInfo::
1125 emitLoadConstPool(MachineBasicBlock &MBB,
1126                   MachineBasicBlock::iterator &MBBI,
1127                   DebugLoc dl,
1128                   unsigned DestReg, unsigned SubIdx, int Val,
1129                   ARMCC::CondCodes Pred,
1130                   unsigned PredReg) const {
1131   MachineFunction &MF = *MBB.getParent();
1132   MachineConstantPool *ConstantPool = MF.getConstantPool();
1133   const Constant *C =
1134         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
1135   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
1136
1137   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
1138     .addReg(DestReg, getDefRegState(true), SubIdx)
1139     .addConstantPoolIndex(Idx)
1140     .addImm(0).addImm(Pred).addReg(PredReg);
1141 }
1142
1143 bool ARMBaseRegisterInfo::
1144 requiresRegisterScavenging(const MachineFunction &MF) const {
1145   return true;
1146 }
1147
1148 bool ARMBaseRegisterInfo::
1149 requiresFrameIndexScavenging(const MachineFunction &MF) const {
1150   return true;
1151 }
1152
1153 bool ARMBaseRegisterInfo::
1154 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
1155   return EnableLocalStackAlloc;
1156 }
1157
1158 static void
1159 emitSPUpdate(bool isARM,
1160              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1161              DebugLoc dl, const ARMBaseInstrInfo &TII,
1162              int NumBytes,
1163              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
1164   if (isARM)
1165     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1166                             Pred, PredReg, TII);
1167   else
1168     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1169                            Pred, PredReg, TII);
1170 }
1171
1172
1173 void ARMBaseRegisterInfo::
1174 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1175                               MachineBasicBlock::iterator I) const {
1176   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1177   if (!TFI->hasReservedCallFrame(MF)) {
1178     // If we have alloca, convert as follows:
1179     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1180     // ADJCALLSTACKUP   -> add, sp, sp, amount
1181     MachineInstr *Old = I;
1182     DebugLoc dl = Old->getDebugLoc();
1183     unsigned Amount = Old->getOperand(0).getImm();
1184     if (Amount != 0) {
1185       // We need to keep the stack aligned properly.  To do this, we round the
1186       // amount of space needed for the outgoing arguments up to the next
1187       // alignment boundary.
1188       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1189       Amount = (Amount+Align-1)/Align*Align;
1190
1191       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1192       assert(!AFI->isThumb1OnlyFunction() &&
1193              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1194       bool isARM = !AFI->isThumbFunction();
1195
1196       // Replace the pseudo instruction with a new instruction...
1197       unsigned Opc = Old->getOpcode();
1198       int PIdx = Old->findFirstPredOperandIdx();
1199       ARMCC::CondCodes Pred = (PIdx == -1)
1200         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1201       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1202         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1203         unsigned PredReg = Old->getOperand(2).getReg();
1204         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
1205       } else {
1206         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1207         unsigned PredReg = Old->getOperand(3).getReg();
1208         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1209         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
1210       }
1211     }
1212   }
1213   MBB.erase(I);
1214 }
1215
1216 int64_t ARMBaseRegisterInfo::
1217 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
1218   const TargetInstrDesc &Desc = MI->getDesc();
1219   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1220   int64_t InstrOffs = 0;;
1221   int Scale = 1;
1222   unsigned ImmIdx = 0;
1223   switch (AddrMode) {
1224   case ARMII::AddrModeT2_i8:
1225   case ARMII::AddrModeT2_i12:
1226   case ARMII::AddrMode_i12:
1227     InstrOffs = MI->getOperand(Idx+1).getImm();
1228     Scale = 1;
1229     break;
1230   case ARMII::AddrMode5: {
1231     // VFP address mode.
1232     const MachineOperand &OffOp = MI->getOperand(Idx+1);
1233     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
1234     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
1235       InstrOffs = -InstrOffs;
1236     Scale = 4;
1237     break;
1238   }
1239   case ARMII::AddrMode2: {
1240     ImmIdx = Idx+2;
1241     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
1242     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1243       InstrOffs = -InstrOffs;
1244     break;
1245   }
1246   case ARMII::AddrMode3: {
1247     ImmIdx = Idx+2;
1248     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
1249     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1250       InstrOffs = -InstrOffs;
1251     break;
1252   }
1253   case ARMII::AddrModeT1_s: {
1254     ImmIdx = Idx+1;
1255     InstrOffs = MI->getOperand(ImmIdx).getImm();
1256     Scale = 4;
1257     break;
1258   }
1259   default:
1260     llvm_unreachable("Unsupported addressing mode!");
1261     break;
1262   }
1263
1264   return InstrOffs * Scale;
1265 }
1266
1267 /// needsFrameBaseReg - Returns true if the instruction's frame index
1268 /// reference would be better served by a base register other than FP
1269 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1270 /// references it should create new base registers for.
1271 bool ARMBaseRegisterInfo::
1272 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1273   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
1274     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1275   }
1276
1277   // It's the load/store FI references that cause issues, as it can be difficult
1278   // to materialize the offset if it won't fit in the literal field. Estimate
1279   // based on the size of the local frame and some conservative assumptions
1280   // about the rest of the stack frame (note, this is pre-regalloc, so
1281   // we don't know everything for certain yet) whether this offset is likely
1282   // to be out of range of the immediate. Return true if so.
1283
1284   // We only generate virtual base registers for loads and stores, so
1285   // return false for everything else.
1286   unsigned Opc = MI->getOpcode();
1287   switch (Opc) {
1288   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
1289   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
1290   case ARM::t2LDRi12: case ARM::t2LDRi8:
1291   case ARM::t2STRi12: case ARM::t2STRi8:
1292   case ARM::VLDRS: case ARM::VLDRD:
1293   case ARM::VSTRS: case ARM::VSTRD:
1294   case ARM::tSTRspi: case ARM::tLDRspi:
1295     if (ForceAllBaseRegAlloc)
1296       return true;
1297     break;
1298   default:
1299     return false;
1300   }
1301
1302   // Without a virtual base register, if the function has variable sized
1303   // objects, all fixed-size local references will be via the frame pointer,
1304   // Approximate the offset and see if it's legal for the instruction.
1305   // Note that the incoming offset is based on the SP value at function entry,
1306   // so it'll be negative.
1307   MachineFunction &MF = *MI->getParent()->getParent();
1308   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1309   MachineFrameInfo *MFI = MF.getFrameInfo();
1310   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1311
1312   // Estimate an offset from the frame pointer.
1313   // Conservatively assume all callee-saved registers get pushed. R4-R6
1314   // will be earlier than the FP, so we ignore those.
1315   // R7, LR
1316   int64_t FPOffset = Offset - 8;
1317   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
1318   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
1319     FPOffset -= 80;
1320   // Estimate an offset from the stack pointer.
1321   // The incoming offset is relating to the SP at the start of the function,
1322   // but when we access the local it'll be relative to the SP after local
1323   // allocation, so adjust our SP-relative offset by that allocation size.
1324   Offset = -Offset;
1325   Offset += MFI->getLocalFrameSize();
1326   // Assume that we'll have at least some spill slots allocated.
1327   // FIXME: This is a total SWAG number. We should run some statistics
1328   //        and pick a real one.
1329   Offset += 128; // 128 bytes of spill slots
1330
1331   // If there is a frame pointer, try using it.
1332   // The FP is only available if there is no dynamic realignment. We
1333   // don't know for sure yet whether we'll need that, so we guess based
1334   // on whether there are any local variables that would trigger it.
1335   unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1336   if (TFI->hasFP(MF) &&
1337       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
1338     if (isFrameOffsetLegal(MI, FPOffset))
1339       return false;
1340   }
1341   // If we can reference via the stack pointer, try that.
1342   // FIXME: This (and the code that resolves the references) can be improved
1343   //        to only disallow SP relative references in the live range of
1344   //        the VLA(s). In practice, it's unclear how much difference that
1345   //        would make, but it may be worth doing.
1346   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
1347     return false;
1348
1349   // The offset likely isn't legal, we want to allocate a virtual base register.
1350   return true;
1351 }
1352
1353 /// materializeFrameBaseRegister - Insert defining instruction(s) for
1354 /// BaseReg to be a pointer to FrameIdx before insertion point I.
1355 void ARMBaseRegisterInfo::
1356 materializeFrameBaseRegister(MachineBasicBlock::iterator I, unsigned BaseReg,
1357                              int FrameIdx, int64_t Offset) const {
1358   ARMFunctionInfo *AFI =
1359     I->getParent()->getParent()->getInfo<ARMFunctionInfo>();
1360   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
1361     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
1362
1363   MachineInstrBuilder MIB =
1364     BuildMI(*I->getParent(), I, I->getDebugLoc(), TII.get(ADDriOpc), BaseReg)
1365     .addFrameIndex(FrameIdx).addImm(Offset);
1366   if (!AFI->isThumb1OnlyFunction())
1367     AddDefaultCC(AddDefaultPred(MIB));
1368 }
1369
1370 void
1371 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
1372                                        unsigned BaseReg, int64_t Offset) const {
1373   MachineInstr &MI = *I;
1374   MachineBasicBlock &MBB = *MI.getParent();
1375   MachineFunction &MF = *MBB.getParent();
1376   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1377   int Off = Offset; // ARM doesn't need the general 64-bit offsets
1378   unsigned i = 0;
1379
1380   assert(!AFI->isThumb1OnlyFunction() &&
1381          "This resolveFrameIndex does not support Thumb1!");
1382
1383   while (!MI.getOperand(i).isFI()) {
1384     ++i;
1385     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1386   }
1387   bool Done = false;
1388   if (!AFI->isThumbFunction())
1389     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
1390   else {
1391     assert(AFI->isThumb2Function());
1392     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
1393   }
1394   assert (Done && "Unable to resolve frame index!");
1395 }
1396
1397 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1398                                              int64_t Offset) const {
1399   const TargetInstrDesc &Desc = MI->getDesc();
1400   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1401   unsigned i = 0;
1402
1403   while (!MI->getOperand(i).isFI()) {
1404     ++i;
1405     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1406   }
1407
1408   // AddrMode4 and AddrMode6 cannot handle any offset.
1409   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
1410     return Offset == 0;
1411
1412   unsigned NumBits = 0;
1413   unsigned Scale = 1;
1414   bool isSigned = true;
1415   switch (AddrMode) {
1416   case ARMII::AddrModeT2_i8:
1417   case ARMII::AddrModeT2_i12:
1418     // i8 supports only negative, and i12 supports only positive, so
1419     // based on Offset sign, consider the appropriate instruction
1420     Scale = 1;
1421     if (Offset < 0) {
1422       NumBits = 8;
1423       Offset = -Offset;
1424     } else {
1425       NumBits = 12;
1426     }
1427     break;
1428   case ARMII::AddrMode5:
1429     // VFP address mode.
1430     NumBits = 8;
1431     Scale = 4;
1432     break;
1433   case ARMII::AddrMode_i12:
1434   case ARMII::AddrMode2:
1435     NumBits = 12;
1436     break;
1437   case ARMII::AddrMode3:
1438     NumBits = 8;
1439     break;
1440   case ARMII::AddrModeT1_s:
1441     NumBits = 5;
1442     Scale = 4;
1443     isSigned = false;
1444     break;
1445   default:
1446     llvm_unreachable("Unsupported addressing mode!");
1447     break;
1448   }
1449
1450   Offset += getFrameIndexInstrOffset(MI, i);
1451   // Make sure the offset is encodable for instructions that scale the
1452   // immediate.
1453   if ((Offset & (Scale-1)) != 0)
1454     return false;
1455
1456   if (isSigned && Offset < 0)
1457     Offset = -Offset;
1458
1459   unsigned Mask = (1 << NumBits) - 1;
1460   if ((unsigned)Offset <= Mask * Scale)
1461     return true;
1462
1463   return false;
1464 }
1465
1466 void
1467 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1468                                          int SPAdj, RegScavenger *RS) const {
1469   unsigned i = 0;
1470   MachineInstr &MI = *II;
1471   MachineBasicBlock &MBB = *MI.getParent();
1472   MachineFunction &MF = *MBB.getParent();
1473   const ARMFrameInfo *TFI =
1474     static_cast<const ARMFrameInfo*>(MF.getTarget().getFrameInfo());
1475   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1476   assert(!AFI->isThumb1OnlyFunction() &&
1477          "This eliminateFrameIndex does not support Thumb1!");
1478
1479   while (!MI.getOperand(i).isFI()) {
1480     ++i;
1481     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1482   }
1483
1484   int FrameIndex = MI.getOperand(i).getIndex();
1485   unsigned FrameReg;
1486
1487   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
1488
1489   // Special handling of dbg_value instructions.
1490   if (MI.isDebugValue()) {
1491     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
1492     MI.getOperand(i+1).ChangeToImmediate(Offset);
1493     return;
1494   }
1495
1496   // Modify MI as necessary to handle as much of 'Offset' as possible
1497   bool Done = false;
1498   if (!AFI->isThumbFunction())
1499     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
1500   else {
1501     assert(AFI->isThumb2Function());
1502     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
1503   }
1504   if (Done)
1505     return;
1506
1507   // If we get here, the immediate doesn't fit into the instruction.  We folded
1508   // as much as possible above, handle the rest, providing a register that is
1509   // SP+LargeImm.
1510   assert((Offset ||
1511           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1512           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1513          "This code isn't needed if offset already handled!");
1514
1515   unsigned ScratchReg = 0;
1516   int PIdx = MI.findFirstPredOperandIdx();
1517   ARMCC::CondCodes Pred = (PIdx == -1)
1518     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1519   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1520   if (Offset == 0)
1521     // Must be addrmode4/6.
1522     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1523   else {
1524     ScratchReg = MF.getRegInfo().createVirtualRegister(ARM::GPRRegisterClass);
1525     if (!AFI->isThumbFunction())
1526       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1527                               Offset, Pred, PredReg, TII);
1528     else {
1529       assert(AFI->isThumb2Function());
1530       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1531                              Offset, Pred, PredReg, TII);
1532     }
1533     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1534   }
1535 }
1536
1537 #include "ARMGenRegisterInfo.inc"