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