d3585bbd46df9a9459ba783023622f1422d757bd
[oota-llvm.git] / lib / Target / ARM / ARMBaseRegisterInfo.cpp
1 //===-- ARMBaseRegisterInfo.cpp - ARM Register Information ----------------===//
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 "ARMBaseRegisterInfo.h"
15 #include "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMFrameLowering.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/ADT/BitVector.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/Support/CommandLine.h"
40
41 #define GET_REGINFO_TARGET_DESC
42 #include "ARMGenRegisterInfo.inc"
43
44 using namespace llvm;
45
46 static cl::opt<bool>
47 ForceAllBaseRegAlloc("arm-force-base-reg-alloc", cl::Hidden, cl::init(false),
48           cl::desc("Force use of virtual base registers for stack load/store"));
49 static cl::opt<bool>
50 EnableLocalStackAlloc("enable-local-stack-alloc", cl::init(true), cl::Hidden,
51           cl::desc("Enable pre-regalloc stack frame index allocation"));
52 static cl::opt<bool>
53 EnableBasePointer("arm-use-base-pointer", cl::Hidden, cl::init(true),
54           cl::desc("Enable use of a base pointer for complex stack frames"));
55
56 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
57                                          const ARMSubtarget &sti)
58   : ARMGenRegisterInfo(ARM::LR), TII(tii), STI(sti),
59     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
60     BasePtr(ARM::R6) {
61 }
62
63 const uint16_t*
64 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
65   bool ghcCall = false;
66  
67   if (MF) {
68     const Function *F = MF->getFunction();
69     ghcCall = (F ? F->getCallingConv() == CallingConv::GHC : false);
70   }
71  
72   if (ghcCall) {
73       return CSR_GHC_SaveList;
74   }
75   else {
76   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
77     ? CSR_iOS_SaveList : CSR_AAPCS_SaveList;
78   }
79 }
80
81 const uint32_t*
82 ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
83   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
84     ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
85 }
86
87 BitVector ARMBaseRegisterInfo::
88 getReservedRegs(const MachineFunction &MF) const {
89   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
90
91   // FIXME: avoid re-calculating this every time.
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   // Reserve D16-D31 if the subtarget doesn't support them.
104   if (!STI.hasVFP3() || STI.hasD16()) {
105     assert(ARM::D31 == ARM::D16 + 15);
106     for (unsigned i = 0; i != 16; ++i)
107       Reserved.set(ARM::D16 + i);
108   }
109   const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
110   for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
111     for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
112       if (Reserved.test(*SI)) Reserved.set(*I);
113
114   return Reserved;
115 }
116
117 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
118                                         unsigned Reg) const {
119   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
120   const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
121   if (RC->contains(Reg)) {
122     for (MCSubRegIterator SI(Reg, this); SI.isValid(); ++SI)
123       if(isReservedReg(MF, *SI)) return true;
124     return false;
125   }
126
127   switch (Reg) {
128   default: break;
129   case ARM::SP:
130   case ARM::PC:
131     return true;
132   case ARM::R6:
133     if (hasBasePointer(MF))
134       return true;
135     break;
136   case ARM::R7:
137   case ARM::R11:
138     if (FramePtr == Reg && TFI->hasFP(MF))
139       return true;
140     break;
141   case ARM::R9:
142     return STI.isR9Reserved();
143   }
144
145   return false;
146 }
147
148 const TargetRegisterClass*
149 ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
150                                                                          const {
151   const TargetRegisterClass *Super = RC;
152   TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
153   do {
154     switch (Super->getID()) {
155     case ARM::GPRRegClassID:
156     case ARM::SPRRegClassID:
157     case ARM::DPRRegClassID:
158     case ARM::QPRRegClassID:
159     case ARM::QQPRRegClassID:
160     case ARM::QQQQPRRegClassID:
161     case ARM::GPRPairRegClassID:
162       return Super;
163     }
164     Super = *I++;
165   } while (Super);
166   return RC;
167 }
168
169 const TargetRegisterClass *
170 ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
171                                                                          const {
172   return &ARM::GPRRegClass;
173 }
174
175 const TargetRegisterClass *
176 ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
177   if (RC == &ARM::CCRRegClass)
178     return 0;  // Can't copy CCR registers.
179   return RC;
180 }
181
182 unsigned
183 ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
184                                          MachineFunction &MF) const {
185   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
186
187   switch (RC->getID()) {
188   default:
189     return 0;
190   case ARM::tGPRRegClassID:
191     return TFI->hasFP(MF) ? 4 : 5;
192   case ARM::GPRRegClassID: {
193     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
194     return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
195   }
196   case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
197   case ARM::DPRRegClassID:
198     return 32 - 10;
199   }
200 }
201
202 /// getRawAllocationOrder - Returns the register allocation order for a
203 /// specified register class with a target-dependent hint.
204 ArrayRef<uint16_t>
205 ARMBaseRegisterInfo::getRawAllocationOrder(const TargetRegisterClass *RC,
206                                            unsigned HintType, unsigned HintReg,
207                                            const MachineFunction &MF) const {
208   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
209   // Alternative register allocation orders when favoring even / odd registers
210   // of register pairs.
211
212   // No FP, R9 is available.
213   static const uint16_t GPREven1[] = {
214     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
215     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
216     ARM::R9, ARM::R11
217   };
218   static const uint16_t GPROdd1[] = {
219     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
220     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
221     ARM::R8, ARM::R10
222   };
223
224   // FP is R7, R9 is available.
225   static const uint16_t GPREven2[] = {
226     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
227     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
228     ARM::R9, ARM::R11
229   };
230   static const uint16_t GPROdd2[] = {
231     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
232     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
233     ARM::R8, ARM::R10
234   };
235
236   // FP is R11, R9 is available.
237   static const uint16_t GPREven3[] = {
238     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
239     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
240     ARM::R9
241   };
242   static const uint16_t GPROdd3[] = {
243     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
244     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
245     ARM::R8
246   };
247
248   // No FP, R9 is not available.
249   static const uint16_t GPREven4[] = {
250     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
251     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
252     ARM::R11
253   };
254   static const uint16_t GPROdd4[] = {
255     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
256     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
257     ARM::R10
258   };
259
260   // FP is R7, R9 is not available.
261   static const uint16_t GPREven5[] = {
262     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
263     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
264     ARM::R11
265   };
266   static const uint16_t GPROdd5[] = {
267     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
268     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
269     ARM::R10
270   };
271
272   // FP is R11, R9 is not available.
273   static const uint16_t GPREven6[] = {
274     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
275     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
276   };
277   static const uint16_t GPROdd6[] = {
278     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
279     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
280   };
281
282   // We only support even/odd hints for GPR and rGPR.
283   if (RC != &ARM::GPRRegClass && RC != &ARM::rGPRRegClass)
284     return RC->getRawAllocationOrder(MF);
285
286   if (HintType == ARMRI::RegPairEven) {
287     if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
288       // It's no longer possible to fulfill this hint. Return the default
289       // allocation order.
290       return RC->getRawAllocationOrder(MF);
291
292     if (!TFI->hasFP(MF)) {
293       if (!STI.isR9Reserved())
294         return makeArrayRef(GPREven1);
295       else
296         return makeArrayRef(GPREven4);
297     } else if (FramePtr == ARM::R7) {
298       if (!STI.isR9Reserved())
299         return makeArrayRef(GPREven2);
300       else
301         return makeArrayRef(GPREven5);
302     } else { // FramePtr == ARM::R11
303       if (!STI.isR9Reserved())
304         return makeArrayRef(GPREven3);
305       else
306         return makeArrayRef(GPREven6);
307     }
308   } else if (HintType == ARMRI::RegPairOdd) {
309     if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
310       // It's no longer possible to fulfill this hint. Return the default
311       // allocation order.
312       return RC->getRawAllocationOrder(MF);
313
314     if (!TFI->hasFP(MF)) {
315       if (!STI.isR9Reserved())
316         return makeArrayRef(GPROdd1);
317       else
318         return makeArrayRef(GPROdd4);
319     } else if (FramePtr == ARM::R7) {
320       if (!STI.isR9Reserved())
321         return makeArrayRef(GPROdd2);
322       else
323         return makeArrayRef(GPROdd5);
324     } else { // FramePtr == ARM::R11
325       if (!STI.isR9Reserved())
326         return makeArrayRef(GPROdd3);
327       else
328         return makeArrayRef(GPROdd6);
329     }
330   }
331   return RC->getRawAllocationOrder(MF);
332 }
333
334 /// ResolveRegAllocHint - Resolves the specified register allocation hint
335 /// to a physical register. Returns the physical register if it is successful.
336 unsigned
337 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
338                                          const MachineFunction &MF) const {
339   if (Reg == 0 || !isPhysicalRegister(Reg))
340     return 0;
341   if (Type == 0)
342     return Reg;
343   else if (Type == (unsigned)ARMRI::RegPairOdd)
344     // Odd register.
345     return getRegisterPairOdd(Reg, MF);
346   else if (Type == (unsigned)ARMRI::RegPairEven)
347     // Even register.
348     return getRegisterPairEven(Reg, MF);
349   return 0;
350 }
351
352 void
353 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
354                                         MachineFunction &MF) const {
355   MachineRegisterInfo *MRI = &MF.getRegInfo();
356   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
357   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
358        Hint.first == (unsigned)ARMRI::RegPairEven) &&
359       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
360     // If 'Reg' is one of the even / odd register pair and it's now changed
361     // (e.g. coalesced) into a different register. The other register of the
362     // pair allocation hint must be updated to reflect the relationship
363     // change.
364     unsigned OtherReg = Hint.second;
365     Hint = MRI->getRegAllocationHint(OtherReg);
366     if (Hint.second == Reg)
367       // Make sure the pair has not already divorced.
368       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
369   }
370 }
371
372 bool
373 ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
374   // CortexA9 has a Write-after-write hazard for NEON registers.
375   if (!STI.isLikeA9())
376     return false;
377
378   switch (RC->getID()) {
379   case ARM::DPRRegClassID:
380   case ARM::DPR_8RegClassID:
381   case ARM::DPR_VFP2RegClassID:
382   case ARM::QPRRegClassID:
383   case ARM::QPR_8RegClassID:
384   case ARM::QPR_VFP2RegClassID:
385   case ARM::SPRRegClassID:
386   case ARM::SPR_8RegClassID:
387     // Avoid reusing S, D, and Q registers.
388     // Don't increase register pressure for QQ and QQQQ.
389     return true;
390   default:
391     return false;
392   }
393 }
394
395 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
396   const MachineFrameInfo *MFI = MF.getFrameInfo();
397   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
398   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
399
400   if (!EnableBasePointer)
401     return false;
402
403   // When outgoing call frames are so large that we adjust the stack pointer
404   // around the call, we can no longer use the stack pointer to reach the
405   // emergency spill slot.
406   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
407     return true;
408
409   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
410   // negative range for ldr/str (255), and thumb1 is positive offsets only.
411   // It's going to be better to use the SP or Base Pointer instead. When there
412   // are variable sized objects, we can't reference off of the SP, so we
413   // reserve a Base Pointer.
414   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
415     // Conservatively estimate whether the negative offset from the frame
416     // pointer will be sufficient to reach. If a function has a smallish
417     // frame, it's less likely to have lots of spills and callee saved
418     // space, so it's all more likely to be within range of the frame pointer.
419     // If it's wrong, the scavenger will still enable access to work, it just
420     // won't be optimal.
421     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
422       return false;
423     return true;
424   }
425
426   return false;
427 }
428
429 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
430   const MachineRegisterInfo *MRI = &MF.getRegInfo();
431   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
432   // We can't realign the stack if:
433   // 1. Dynamic stack realignment is explicitly disabled,
434   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
435   // 3. There are VLAs in the function and the base pointer is disabled.
436   if (!MF.getTarget().Options.RealignStack)
437     return false;
438   if (AFI->isThumb1OnlyFunction())
439     return false;
440   // Stack realignment requires a frame pointer.  If we already started
441   // register allocation with frame pointer elimination, it is too late now.
442   if (!MRI->canReserveReg(FramePtr))
443     return false;
444   // We may also need a base pointer if there are dynamic allocas or stack
445   // pointer adjustments around calls.
446   if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
447     return true;
448   if (!EnableBasePointer)
449     return false;
450   // A base pointer is required and allowed.  Check that it isn't too late to
451   // reserve it.
452   return MRI->canReserveReg(BasePtr);
453 }
454
455 bool ARMBaseRegisterInfo::
456 needsStackRealignment(const MachineFunction &MF) const {
457   const MachineFrameInfo *MFI = MF.getFrameInfo();
458   const Function *F = MF.getFunction();
459   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
460   bool requiresRealignment =
461     ((MFI->getMaxAlignment() > StackAlign) ||
462      F->getFnAttributes().hasAttribute(Attributes::StackAlignment));
463
464   return requiresRealignment && canRealignStack(MF);
465 }
466
467 bool ARMBaseRegisterInfo::
468 cannotEliminateFrame(const MachineFunction &MF) const {
469   const MachineFrameInfo *MFI = MF.getFrameInfo();
470   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
471     return true;
472   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
473     || needsStackRealignment(MF);
474 }
475
476 unsigned
477 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
478   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
479
480   if (TFI->hasFP(MF))
481     return FramePtr;
482   return ARM::SP;
483 }
484
485 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
486   llvm_unreachable("What is the exception register");
487 }
488
489 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
490   llvm_unreachable("What is the exception handler register");
491 }
492
493 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
494                                               const MachineFunction &MF) const {
495   switch (Reg) {
496   default: break;
497   // Return 0 if either register of the pair is a special register.
498   // So no R12, etc.
499   case ARM::R1: return ARM::R0;
500   case ARM::R3: return ARM::R2;
501   case ARM::R5: return ARM::R4;
502   case ARM::R7:
503     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
504       ? 0 : ARM::R6;
505   case ARM::R9: return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R8;
506   case ARM::R11: return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
507
508   case ARM::S1: return ARM::S0;
509   case ARM::S3: return ARM::S2;
510   case ARM::S5: return ARM::S4;
511   case ARM::S7: return ARM::S6;
512   case ARM::S9: return ARM::S8;
513   case ARM::S11: return ARM::S10;
514   case ARM::S13: return ARM::S12;
515   case ARM::S15: return ARM::S14;
516   case ARM::S17: return ARM::S16;
517   case ARM::S19: return ARM::S18;
518   case ARM::S21: return ARM::S20;
519   case ARM::S23: return ARM::S22;
520   case ARM::S25: return ARM::S24;
521   case ARM::S27: return ARM::S26;
522   case ARM::S29: return ARM::S28;
523   case ARM::S31: return ARM::S30;
524
525   case ARM::D1: return ARM::D0;
526   case ARM::D3: return ARM::D2;
527   case ARM::D5: return ARM::D4;
528   case ARM::D7: return ARM::D6;
529   case ARM::D9: return ARM::D8;
530   case ARM::D11: return ARM::D10;
531   case ARM::D13: return ARM::D12;
532   case ARM::D15: return ARM::D14;
533   case ARM::D17: return ARM::D16;
534   case ARM::D19: return ARM::D18;
535   case ARM::D21: return ARM::D20;
536   case ARM::D23: return ARM::D22;
537   case ARM::D25: return ARM::D24;
538   case ARM::D27: return ARM::D26;
539   case ARM::D29: return ARM::D28;
540   case ARM::D31: return ARM::D30;
541   }
542
543   return 0;
544 }
545
546 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
547                                              const MachineFunction &MF) const {
548   switch (Reg) {
549   default: break;
550   // Return 0 if either register of the pair is a special register.
551   // So no R12, etc.
552   case ARM::R0: return ARM::R1;
553   case ARM::R2: return ARM::R3;
554   case ARM::R4: return ARM::R5;
555   case ARM::R6:
556     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
557       ? 0 : ARM::R7;
558   case ARM::R8: return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R9;
559   case ARM::R10: return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
560
561   case ARM::S0: return ARM::S1;
562   case ARM::S2: return ARM::S3;
563   case ARM::S4: return ARM::S5;
564   case ARM::S6: return ARM::S7;
565   case ARM::S8: return ARM::S9;
566   case ARM::S10: return ARM::S11;
567   case ARM::S12: return ARM::S13;
568   case ARM::S14: return ARM::S15;
569   case ARM::S16: return ARM::S17;
570   case ARM::S18: return ARM::S19;
571   case ARM::S20: return ARM::S21;
572   case ARM::S22: return ARM::S23;
573   case ARM::S24: return ARM::S25;
574   case ARM::S26: return ARM::S27;
575   case ARM::S28: return ARM::S29;
576   case ARM::S30: return ARM::S31;
577
578   case ARM::D0: return ARM::D1;
579   case ARM::D2: return ARM::D3;
580   case ARM::D4: return ARM::D5;
581   case ARM::D6: return ARM::D7;
582   case ARM::D8: return ARM::D9;
583   case ARM::D10: return ARM::D11;
584   case ARM::D12: return ARM::D13;
585   case ARM::D14: return ARM::D15;
586   case ARM::D16: return ARM::D17;
587   case ARM::D18: return ARM::D19;
588   case ARM::D20: return ARM::D21;
589   case ARM::D22: return ARM::D23;
590   case ARM::D24: return ARM::D25;
591   case ARM::D26: return ARM::D27;
592   case ARM::D28: return ARM::D29;
593   case ARM::D30: return ARM::D31;
594   }
595
596   return 0;
597 }
598
599 /// emitLoadConstPool - Emits a load from constpool to materialize the
600 /// specified immediate.
601 void ARMBaseRegisterInfo::
602 emitLoadConstPool(MachineBasicBlock &MBB,
603                   MachineBasicBlock::iterator &MBBI,
604                   DebugLoc dl,
605                   unsigned DestReg, unsigned SubIdx, int Val,
606                   ARMCC::CondCodes Pred,
607                   unsigned PredReg, unsigned MIFlags) const {
608   MachineFunction &MF = *MBB.getParent();
609   MachineConstantPool *ConstantPool = MF.getConstantPool();
610   const Constant *C =
611         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
612   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
613
614   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
615     .addReg(DestReg, getDefRegState(true), SubIdx)
616     .addConstantPoolIndex(Idx)
617     .addImm(0).addImm(Pred).addReg(PredReg)
618     .setMIFlags(MIFlags);
619 }
620
621 bool ARMBaseRegisterInfo::
622 requiresRegisterScavenging(const MachineFunction &MF) const {
623   return true;
624 }
625
626 bool ARMBaseRegisterInfo::
627 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
628   return true;
629 }
630
631 bool ARMBaseRegisterInfo::
632 requiresFrameIndexScavenging(const MachineFunction &MF) const {
633   return true;
634 }
635
636 bool ARMBaseRegisterInfo::
637 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
638   return EnableLocalStackAlloc;
639 }
640
641 static void
642 emitSPUpdate(bool isARM,
643              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
644              DebugLoc dl, const ARMBaseInstrInfo &TII,
645              int NumBytes,
646              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
647   if (isARM)
648     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
649                             Pred, PredReg, TII);
650   else
651     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
652                            Pred, PredReg, TII);
653 }
654
655
656 void ARMBaseRegisterInfo::
657 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
658                               MachineBasicBlock::iterator I) const {
659   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
660   if (!TFI->hasReservedCallFrame(MF)) {
661     // If we have alloca, convert as follows:
662     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
663     // ADJCALLSTACKUP   -> add, sp, sp, amount
664     MachineInstr *Old = I;
665     DebugLoc dl = Old->getDebugLoc();
666     unsigned Amount = Old->getOperand(0).getImm();
667     if (Amount != 0) {
668       // We need to keep the stack aligned properly.  To do this, we round the
669       // amount of space needed for the outgoing arguments up to the next
670       // alignment boundary.
671       unsigned Align = TFI->getStackAlignment();
672       Amount = (Amount+Align-1)/Align*Align;
673
674       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
675       assert(!AFI->isThumb1OnlyFunction() &&
676              "This eliminateCallFramePseudoInstr does not support Thumb1!");
677       bool isARM = !AFI->isThumbFunction();
678
679       // Replace the pseudo instruction with a new instruction...
680       unsigned Opc = Old->getOpcode();
681       int PIdx = Old->findFirstPredOperandIdx();
682       ARMCC::CondCodes Pred = (PIdx == -1)
683         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
684       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
685         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
686         unsigned PredReg = Old->getOperand(2).getReg();
687         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
688       } else {
689         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
690         unsigned PredReg = Old->getOperand(3).getReg();
691         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
692         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
693       }
694     }
695   }
696   MBB.erase(I);
697 }
698
699 int64_t ARMBaseRegisterInfo::
700 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
701   const MCInstrDesc &Desc = MI->getDesc();
702   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
703   int64_t InstrOffs = 0;
704   int Scale = 1;
705   unsigned ImmIdx = 0;
706   switch (AddrMode) {
707   case ARMII::AddrModeT2_i8:
708   case ARMII::AddrModeT2_i12:
709   case ARMII::AddrMode_i12:
710     InstrOffs = MI->getOperand(Idx+1).getImm();
711     Scale = 1;
712     break;
713   case ARMII::AddrMode5: {
714     // VFP address mode.
715     const MachineOperand &OffOp = MI->getOperand(Idx+1);
716     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
717     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
718       InstrOffs = -InstrOffs;
719     Scale = 4;
720     break;
721   }
722   case ARMII::AddrMode2: {
723     ImmIdx = Idx+2;
724     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
725     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
726       InstrOffs = -InstrOffs;
727     break;
728   }
729   case ARMII::AddrMode3: {
730     ImmIdx = Idx+2;
731     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
732     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
733       InstrOffs = -InstrOffs;
734     break;
735   }
736   case ARMII::AddrModeT1_s: {
737     ImmIdx = Idx+1;
738     InstrOffs = MI->getOperand(ImmIdx).getImm();
739     Scale = 4;
740     break;
741   }
742   default:
743     llvm_unreachable("Unsupported addressing mode!");
744   }
745
746   return InstrOffs * Scale;
747 }
748
749 /// needsFrameBaseReg - Returns true if the instruction's frame index
750 /// reference would be better served by a base register other than FP
751 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
752 /// references it should create new base registers for.
753 bool ARMBaseRegisterInfo::
754 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
755   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
756     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
757   }
758
759   // It's the load/store FI references that cause issues, as it can be difficult
760   // to materialize the offset if it won't fit in the literal field. Estimate
761   // based on the size of the local frame and some conservative assumptions
762   // about the rest of the stack frame (note, this is pre-regalloc, so
763   // we don't know everything for certain yet) whether this offset is likely
764   // to be out of range of the immediate. Return true if so.
765
766   // We only generate virtual base registers for loads and stores, so
767   // return false for everything else.
768   unsigned Opc = MI->getOpcode();
769   switch (Opc) {
770   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
771   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
772   case ARM::t2LDRi12: case ARM::t2LDRi8:
773   case ARM::t2STRi12: case ARM::t2STRi8:
774   case ARM::VLDRS: case ARM::VLDRD:
775   case ARM::VSTRS: case ARM::VSTRD:
776   case ARM::tSTRspi: case ARM::tLDRspi:
777     if (ForceAllBaseRegAlloc)
778       return true;
779     break;
780   default:
781     return false;
782   }
783
784   // Without a virtual base register, if the function has variable sized
785   // objects, all fixed-size local references will be via the frame pointer,
786   // Approximate the offset and see if it's legal for the instruction.
787   // Note that the incoming offset is based on the SP value at function entry,
788   // so it'll be negative.
789   MachineFunction &MF = *MI->getParent()->getParent();
790   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
791   MachineFrameInfo *MFI = MF.getFrameInfo();
792   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
793
794   // Estimate an offset from the frame pointer.
795   // Conservatively assume all callee-saved registers get pushed. R4-R6
796   // will be earlier than the FP, so we ignore those.
797   // R7, LR
798   int64_t FPOffset = Offset - 8;
799   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
800   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
801     FPOffset -= 80;
802   // Estimate an offset from the stack pointer.
803   // The incoming offset is relating to the SP at the start of the function,
804   // but when we access the local it'll be relative to the SP after local
805   // allocation, so adjust our SP-relative offset by that allocation size.
806   Offset = -Offset;
807   Offset += MFI->getLocalFrameSize();
808   // Assume that we'll have at least some spill slots allocated.
809   // FIXME: This is a total SWAG number. We should run some statistics
810   //        and pick a real one.
811   Offset += 128; // 128 bytes of spill slots
812
813   // If there is a frame pointer, try using it.
814   // The FP is only available if there is no dynamic realignment. We
815   // don't know for sure yet whether we'll need that, so we guess based
816   // on whether there are any local variables that would trigger it.
817   unsigned StackAlign = TFI->getStackAlignment();
818   if (TFI->hasFP(MF) &&
819       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
820     if (isFrameOffsetLegal(MI, FPOffset))
821       return false;
822   }
823   // If we can reference via the stack pointer, try that.
824   // FIXME: This (and the code that resolves the references) can be improved
825   //        to only disallow SP relative references in the live range of
826   //        the VLA(s). In practice, it's unclear how much difference that
827   //        would make, but it may be worth doing.
828   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
829     return false;
830
831   // The offset likely isn't legal, we want to allocate a virtual base register.
832   return true;
833 }
834
835 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
836 /// be a pointer to FrameIdx at the beginning of the basic block.
837 void ARMBaseRegisterInfo::
838 materializeFrameBaseRegister(MachineBasicBlock *MBB,
839                              unsigned BaseReg, int FrameIdx,
840                              int64_t Offset) const {
841   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
842   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
843     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
844
845   MachineBasicBlock::iterator Ins = MBB->begin();
846   DebugLoc DL;                  // Defaults to "unknown"
847   if (Ins != MBB->end())
848     DL = Ins->getDebugLoc();
849
850   const MCInstrDesc &MCID = TII.get(ADDriOpc);
851   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
852   const MachineFunction &MF = *MBB->getParent();
853   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
854
855   MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
856     .addFrameIndex(FrameIdx).addImm(Offset));
857
858   if (!AFI->isThumb1OnlyFunction())
859     AddDefaultCC(MIB);
860 }
861
862 void
863 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
864                                        unsigned BaseReg, int64_t Offset) const {
865   MachineInstr &MI = *I;
866   MachineBasicBlock &MBB = *MI.getParent();
867   MachineFunction &MF = *MBB.getParent();
868   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
869   int Off = Offset; // ARM doesn't need the general 64-bit offsets
870   unsigned i = 0;
871
872   assert(!AFI->isThumb1OnlyFunction() &&
873          "This resolveFrameIndex does not support Thumb1!");
874
875   while (!MI.getOperand(i).isFI()) {
876     ++i;
877     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
878   }
879   bool Done = false;
880   if (!AFI->isThumbFunction())
881     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
882   else {
883     assert(AFI->isThumb2Function());
884     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
885   }
886   assert (Done && "Unable to resolve frame index!");
887   (void)Done;
888 }
889
890 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
891                                              int64_t Offset) const {
892   const MCInstrDesc &Desc = MI->getDesc();
893   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
894   unsigned i = 0;
895
896   while (!MI->getOperand(i).isFI()) {
897     ++i;
898     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
899   }
900
901   // AddrMode4 and AddrMode6 cannot handle any offset.
902   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
903     return Offset == 0;
904
905   unsigned NumBits = 0;
906   unsigned Scale = 1;
907   bool isSigned = true;
908   switch (AddrMode) {
909   case ARMII::AddrModeT2_i8:
910   case ARMII::AddrModeT2_i12:
911     // i8 supports only negative, and i12 supports only positive, so
912     // based on Offset sign, consider the appropriate instruction
913     Scale = 1;
914     if (Offset < 0) {
915       NumBits = 8;
916       Offset = -Offset;
917     } else {
918       NumBits = 12;
919     }
920     break;
921   case ARMII::AddrMode5:
922     // VFP address mode.
923     NumBits = 8;
924     Scale = 4;
925     break;
926   case ARMII::AddrMode_i12:
927   case ARMII::AddrMode2:
928     NumBits = 12;
929     break;
930   case ARMII::AddrMode3:
931     NumBits = 8;
932     break;
933   case ARMII::AddrModeT1_s:
934     NumBits = 5;
935     Scale = 4;
936     isSigned = false;
937     break;
938   default:
939     llvm_unreachable("Unsupported addressing mode!");
940   }
941
942   Offset += getFrameIndexInstrOffset(MI, i);
943   // Make sure the offset is encodable for instructions that scale the
944   // immediate.
945   if ((Offset & (Scale-1)) != 0)
946     return false;
947
948   if (isSigned && Offset < 0)
949     Offset = -Offset;
950
951   unsigned Mask = (1 << NumBits) - 1;
952   if ((unsigned)Offset <= Mask * Scale)
953     return true;
954
955   return false;
956 }
957
958 void
959 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
960                                          int SPAdj, RegScavenger *RS) const {
961   unsigned i = 0;
962   MachineInstr &MI = *II;
963   MachineBasicBlock &MBB = *MI.getParent();
964   MachineFunction &MF = *MBB.getParent();
965   const ARMFrameLowering *TFI =
966     static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
967   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
968   assert(!AFI->isThumb1OnlyFunction() &&
969          "This eliminateFrameIndex does not support Thumb1!");
970
971   while (!MI.getOperand(i).isFI()) {
972     ++i;
973     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
974   }
975
976   int FrameIndex = MI.getOperand(i).getIndex();
977   unsigned FrameReg;
978
979   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
980
981   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
982   // call frame setup/destroy instructions have already been eliminated.  That
983   // means the stack pointer cannot be used to access the emergency spill slot
984   // when !hasReservedCallFrame().
985 #ifndef NDEBUG
986   if (RS && FrameReg == ARM::SP && FrameIndex == RS->getScavengingFrameIndex()){
987     assert(TFI->hasReservedCallFrame(MF) &&
988            "Cannot use SP to access the emergency spill slot in "
989            "functions without a reserved call frame");
990     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
991            "Cannot use SP to access the emergency spill slot in "
992            "functions with variable sized frame objects");
993   }
994 #endif // NDEBUG
995
996   // Special handling of dbg_value instructions.
997   if (MI.isDebugValue()) {
998     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
999     MI.getOperand(i+1).ChangeToImmediate(Offset);
1000     return;
1001   }
1002
1003   // Modify MI as necessary to handle as much of 'Offset' as possible
1004   bool Done = false;
1005   if (!AFI->isThumbFunction())
1006     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
1007   else {
1008     assert(AFI->isThumb2Function());
1009     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
1010   }
1011   if (Done)
1012     return;
1013
1014   // If we get here, the immediate doesn't fit into the instruction.  We folded
1015   // as much as possible above, handle the rest, providing a register that is
1016   // SP+LargeImm.
1017   assert((Offset ||
1018           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1019           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1020          "This code isn't needed if offset already handled!");
1021
1022   unsigned ScratchReg = 0;
1023   int PIdx = MI.findFirstPredOperandIdx();
1024   ARMCC::CondCodes Pred = (PIdx == -1)
1025     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1026   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1027   if (Offset == 0)
1028     // Must be addrmode4/6.
1029     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1030   else {
1031     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
1032     if (!AFI->isThumbFunction())
1033       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1034                               Offset, Pred, PredReg, TII);
1035     else {
1036       assert(AFI->isThumb2Function());
1037       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1038                              Offset, Pred, PredReg, TII);
1039     }
1040     // Update the original instruction to use the scratch register.
1041     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1042   }
1043 }