ARM: improve WoA ABI conformance for frame register
[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/ADT/BitVector.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/CodeGen/VirtRegMap.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetFrameLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40
41 #define GET_REGINFO_TARGET_DESC
42 #include "ARMGenRegisterInfo.inc"
43
44 using namespace llvm;
45
46 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMSubtarget &sti)
47     : ARMGenRegisterInfo(ARM::LR, 0, 0, ARM::PC), STI(sti), BasePtr(ARM::R6) {
48   if (STI.isTargetMachO())
49     FramePtr = ARM::R7;
50   else if (STI.isTargetWindows())
51     FramePtr = ARM::R11;
52   else // ARM EABI
53     FramePtr = STI.isThumb() ? ARM::R7 : ARM::R11;
54 }
55
56 const MCPhysReg*
57 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
58   const MCPhysReg *RegList = (STI.isTargetIOS() && !STI.isAAPCS_ABI())
59                                 ? CSR_iOS_SaveList
60                                 : CSR_AAPCS_SaveList;
61
62   if (!MF) return RegList;
63
64   const Function *F = MF->getFunction();
65   if (F->getCallingConv() == CallingConv::GHC) {
66     // GHC set of callee saved regs is empty as all those regs are
67     // used for passing STG regs around
68     return CSR_NoRegs_SaveList;
69   } else if (F->hasFnAttribute("interrupt")) {
70     if (STI.isMClass()) {
71       // M-class CPUs have hardware which saves the registers needed to allow a
72       // function conforming to the AAPCS to function as a handler.
73       return CSR_AAPCS_SaveList;
74     } else if (F->getFnAttribute("interrupt").getValueAsString() == "FIQ") {
75       // Fast interrupt mode gives the handler a private copy of R8-R14, so less
76       // need to be saved to restore user-mode state.
77       return CSR_FIQ_SaveList;
78     } else {
79       // Generally only R13-R14 (i.e. SP, LR) are automatically preserved by
80       // exception handling.
81       return CSR_GenericInt_SaveList;
82     }
83   }
84
85   return RegList;
86 }
87
88 const uint32_t*
89 ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
90   if (CC == CallingConv::GHC)
91     // This is academic becase all GHC calls are (supposed to be) tail calls
92     return CSR_NoRegs_RegMask;
93   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
94     ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
95 }
96
97 const uint32_t*
98 ARMBaseRegisterInfo::getNoPreservedMask() const {
99   return CSR_NoRegs_RegMask;
100 }
101
102 const uint32_t*
103 ARMBaseRegisterInfo::getThisReturnPreservedMask(CallingConv::ID CC) const {
104   // This should return a register mask that is the same as that returned by
105   // getCallPreservedMask but that additionally preserves the register used for
106   // the first i32 argument (which must also be the register used to return a
107   // single i32 return value)
108   //
109   // In case that the calling convention does not use the same register for
110   // both or otherwise does not want to enable this optimization, the function
111   // should return NULL
112   if (CC == CallingConv::GHC)
113     // This is academic becase all GHC calls are (supposed to be) tail calls
114     return nullptr;
115   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
116     ? CSR_iOS_ThisReturn_RegMask : CSR_AAPCS_ThisReturn_RegMask;
117 }
118
119 BitVector ARMBaseRegisterInfo::
120 getReservedRegs(const MachineFunction &MF) const {
121   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
122
123   // FIXME: avoid re-calculating this every time.
124   BitVector Reserved(getNumRegs());
125   Reserved.set(ARM::SP);
126   Reserved.set(ARM::PC);
127   Reserved.set(ARM::FPSCR);
128   Reserved.set(ARM::APSR_NZCV);
129   if (TFI->hasFP(MF))
130     Reserved.set(FramePtr);
131   if (hasBasePointer(MF))
132     Reserved.set(BasePtr);
133   // Some targets reserve R9.
134   if (STI.isR9Reserved())
135     Reserved.set(ARM::R9);
136   // Reserve D16-D31 if the subtarget doesn't support them.
137   if (!STI.hasVFP3() || STI.hasD16()) {
138     assert(ARM::D31 == ARM::D16 + 15);
139     for (unsigned i = 0; i != 16; ++i)
140       Reserved.set(ARM::D16 + i);
141   }
142   const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
143   for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
144     for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
145       if (Reserved.test(*SI)) Reserved.set(*I);
146
147   return Reserved;
148 }
149
150 const TargetRegisterClass*
151 ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
152                                                                          const {
153   const TargetRegisterClass *Super = RC;
154   TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
155   do {
156     switch (Super->getID()) {
157     case ARM::GPRRegClassID:
158     case ARM::SPRRegClassID:
159     case ARM::DPRRegClassID:
160     case ARM::QPRRegClassID:
161     case ARM::QQPRRegClassID:
162     case ARM::QQQQPRRegClassID:
163     case ARM::GPRPairRegClassID:
164       return Super;
165     }
166     Super = *I++;
167   } while (Super);
168   return RC;
169 }
170
171 const TargetRegisterClass *
172 ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
173                                                                          const {
174   return &ARM::GPRRegClass;
175 }
176
177 const TargetRegisterClass *
178 ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
179   if (RC == &ARM::CCRRegClass)
180     return nullptr;  // Can't copy CCR registers.
181   return RC;
182 }
183
184 unsigned
185 ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
186                                          MachineFunction &MF) const {
187   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
188
189   switch (RC->getID()) {
190   default:
191     return 0;
192   case ARM::tGPRRegClassID:
193     return TFI->hasFP(MF) ? 4 : 5;
194   case ARM::GPRRegClassID: {
195     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
196     return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
197   }
198   case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
199   case ARM::DPRRegClassID:
200     return 32 - 10;
201   }
202 }
203
204 // Get the other register in a GPRPair.
205 static unsigned getPairedGPR(unsigned Reg, bool Odd, const MCRegisterInfo *RI) {
206   for (MCSuperRegIterator Supers(Reg, RI); Supers.isValid(); ++Supers)
207     if (ARM::GPRPairRegClass.contains(*Supers))
208       return RI->getSubReg(*Supers, Odd ? ARM::gsub_1 : ARM::gsub_0);
209   return 0;
210 }
211
212 // Resolve the RegPairEven / RegPairOdd register allocator hints.
213 void
214 ARMBaseRegisterInfo::getRegAllocationHints(unsigned VirtReg,
215                                            ArrayRef<MCPhysReg> Order,
216                                            SmallVectorImpl<MCPhysReg> &Hints,
217                                            const MachineFunction &MF,
218                                            const VirtRegMap *VRM) const {
219   const MachineRegisterInfo &MRI = MF.getRegInfo();
220   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
221
222   unsigned Odd;
223   switch (Hint.first) {
224   case ARMRI::RegPairEven:
225     Odd = 0;
226     break;
227   case ARMRI::RegPairOdd:
228     Odd = 1;
229     break;
230   default:
231     TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);
232     return;
233   }
234
235   // This register should preferably be even (Odd == 0) or odd (Odd == 1).
236   // Check if the other part of the pair has already been assigned, and provide
237   // the paired register as the first hint.
238   unsigned PairedPhys = 0;
239   if (VRM && VRM->hasPhys(Hint.second)) {
240     PairedPhys = getPairedGPR(VRM->getPhys(Hint.second), Odd, this);
241     if (PairedPhys && MRI.isReserved(PairedPhys))
242       PairedPhys = 0;
243   }
244
245   // First prefer the paired physreg.
246   if (PairedPhys &&
247       std::find(Order.begin(), Order.end(), PairedPhys) != Order.end())
248     Hints.push_back(PairedPhys);
249
250   // Then prefer even or odd registers.
251   for (unsigned I = 0, E = Order.size(); I != E; ++I) {
252     unsigned Reg = Order[I];
253     if (Reg == PairedPhys || (getEncodingValue(Reg) & 1) != Odd)
254       continue;
255     // Don't provide hints that are paired to a reserved register.
256     unsigned Paired = getPairedGPR(Reg, !Odd, this);
257     if (!Paired || MRI.isReserved(Paired))
258       continue;
259     Hints.push_back(Reg);
260   }
261 }
262
263 void
264 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
265                                         MachineFunction &MF) const {
266   MachineRegisterInfo *MRI = &MF.getRegInfo();
267   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
268   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
269        Hint.first == (unsigned)ARMRI::RegPairEven) &&
270       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
271     // If 'Reg' is one of the even / odd register pair and it's now changed
272     // (e.g. coalesced) into a different register. The other register of the
273     // pair allocation hint must be updated to reflect the relationship
274     // change.
275     unsigned OtherReg = Hint.second;
276     Hint = MRI->getRegAllocationHint(OtherReg);
277     if (Hint.second == Reg)
278       // Make sure the pair has not already divorced.
279       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
280   }
281 }
282
283 bool
284 ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
285   // CortexA9 has a Write-after-write hazard for NEON registers.
286   if (!STI.isLikeA9())
287     return false;
288
289   switch (RC->getID()) {
290   case ARM::DPRRegClassID:
291   case ARM::DPR_8RegClassID:
292   case ARM::DPR_VFP2RegClassID:
293   case ARM::QPRRegClassID:
294   case ARM::QPR_8RegClassID:
295   case ARM::QPR_VFP2RegClassID:
296   case ARM::SPRRegClassID:
297   case ARM::SPR_8RegClassID:
298     // Avoid reusing S, D, and Q registers.
299     // Don't increase register pressure for QQ and QQQQ.
300     return true;
301   default:
302     return false;
303   }
304 }
305
306 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
307   const MachineFrameInfo *MFI = MF.getFrameInfo();
308   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
309   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
310
311   // When outgoing call frames are so large that we adjust the stack pointer
312   // around the call, we can no longer use the stack pointer to reach the
313   // emergency spill slot.
314   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
315     return true;
316
317   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
318   // negative range for ldr/str (255), and thumb1 is positive offsets only.
319   // It's going to be better to use the SP or Base Pointer instead. When there
320   // are variable sized objects, we can't reference off of the SP, so we
321   // reserve a Base Pointer.
322   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
323     // Conservatively estimate whether the negative offset from the frame
324     // pointer will be sufficient to reach. If a function has a smallish
325     // frame, it's less likely to have lots of spills and callee saved
326     // space, so it's all more likely to be within range of the frame pointer.
327     // If it's wrong, the scavenger will still enable access to work, it just
328     // won't be optimal.
329     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
330       return false;
331     return true;
332   }
333
334   return false;
335 }
336
337 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
338   const MachineRegisterInfo *MRI = &MF.getRegInfo();
339   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
340   // We can't realign the stack if:
341   // 1. Dynamic stack realignment is explicitly disabled,
342   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
343   // 3. There are VLAs in the function and the base pointer is disabled.
344   if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
345     return false;
346   if (AFI->isThumb1OnlyFunction())
347     return false;
348   // Stack realignment requires a frame pointer.  If we already started
349   // register allocation with frame pointer elimination, it is too late now.
350   if (!MRI->canReserveReg(FramePtr))
351     return false;
352   // We may also need a base pointer if there are dynamic allocas or stack
353   // pointer adjustments around calls.
354   if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
355     return true;
356   // A base pointer is required and allowed.  Check that it isn't too late to
357   // reserve it.
358   return MRI->canReserveReg(BasePtr);
359 }
360
361 bool ARMBaseRegisterInfo::
362 needsStackRealignment(const MachineFunction &MF) const {
363   const MachineFrameInfo *MFI = MF.getFrameInfo();
364   const Function *F = MF.getFunction();
365   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
366   bool requiresRealignment =
367     ((MFI->getMaxAlignment() > StackAlign) ||
368      F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
369                                      Attribute::StackAlignment));
370
371   return requiresRealignment && canRealignStack(MF);
372 }
373
374 bool ARMBaseRegisterInfo::
375 cannotEliminateFrame(const MachineFunction &MF) const {
376   const MachineFrameInfo *MFI = MF.getFrameInfo();
377   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
378     return true;
379   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
380     || needsStackRealignment(MF);
381 }
382
383 unsigned
384 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
385   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
386
387   if (TFI->hasFP(MF))
388     return FramePtr;
389   return ARM::SP;
390 }
391
392 /// emitLoadConstPool - Emits a load from constpool to materialize the
393 /// specified immediate.
394 void ARMBaseRegisterInfo::
395 emitLoadConstPool(MachineBasicBlock &MBB,
396                   MachineBasicBlock::iterator &MBBI,
397                   DebugLoc dl,
398                   unsigned DestReg, unsigned SubIdx, int Val,
399                   ARMCC::CondCodes Pred,
400                   unsigned PredReg, unsigned MIFlags) const {
401   MachineFunction &MF = *MBB.getParent();
402   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
403   MachineConstantPool *ConstantPool = MF.getConstantPool();
404   const Constant *C =
405         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
406   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
407
408   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
409     .addReg(DestReg, getDefRegState(true), SubIdx)
410     .addConstantPoolIndex(Idx)
411     .addImm(0).addImm(Pred).addReg(PredReg)
412     .setMIFlags(MIFlags);
413 }
414
415 bool ARMBaseRegisterInfo::mayOverrideLocalAssignment() const {
416   // The native linux build hits a downstream codegen bug when this is enabled.
417   return STI.isTargetDarwin();
418 }
419
420 bool ARMBaseRegisterInfo::
421 requiresRegisterScavenging(const MachineFunction &MF) const {
422   return true;
423 }
424
425 bool ARMBaseRegisterInfo::
426 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
427   return true;
428 }
429
430 bool ARMBaseRegisterInfo::
431 requiresFrameIndexScavenging(const MachineFunction &MF) const {
432   return true;
433 }
434
435 bool ARMBaseRegisterInfo::
436 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
437   return true;
438 }
439
440 int64_t ARMBaseRegisterInfo::
441 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
442   const MCInstrDesc &Desc = MI->getDesc();
443   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
444   int64_t InstrOffs = 0;
445   int Scale = 1;
446   unsigned ImmIdx = 0;
447   switch (AddrMode) {
448   case ARMII::AddrModeT2_i8:
449   case ARMII::AddrModeT2_i12:
450   case ARMII::AddrMode_i12:
451     InstrOffs = MI->getOperand(Idx+1).getImm();
452     Scale = 1;
453     break;
454   case ARMII::AddrMode5: {
455     // VFP address mode.
456     const MachineOperand &OffOp = MI->getOperand(Idx+1);
457     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
458     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
459       InstrOffs = -InstrOffs;
460     Scale = 4;
461     break;
462   }
463   case ARMII::AddrMode2: {
464     ImmIdx = Idx+2;
465     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
466     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
467       InstrOffs = -InstrOffs;
468     break;
469   }
470   case ARMII::AddrMode3: {
471     ImmIdx = Idx+2;
472     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
473     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
474       InstrOffs = -InstrOffs;
475     break;
476   }
477   case ARMII::AddrModeT1_s: {
478     ImmIdx = Idx+1;
479     InstrOffs = MI->getOperand(ImmIdx).getImm();
480     Scale = 4;
481     break;
482   }
483   default:
484     llvm_unreachable("Unsupported addressing mode!");
485   }
486
487   return InstrOffs * Scale;
488 }
489
490 /// needsFrameBaseReg - Returns true if the instruction's frame index
491 /// reference would be better served by a base register other than FP
492 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
493 /// references it should create new base registers for.
494 bool ARMBaseRegisterInfo::
495 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
496   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
497     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
498   }
499
500   // It's the load/store FI references that cause issues, as it can be difficult
501   // to materialize the offset if it won't fit in the literal field. Estimate
502   // based on the size of the local frame and some conservative assumptions
503   // about the rest of the stack frame (note, this is pre-regalloc, so
504   // we don't know everything for certain yet) whether this offset is likely
505   // to be out of range of the immediate. Return true if so.
506
507   // We only generate virtual base registers for loads and stores, so
508   // return false for everything else.
509   unsigned Opc = MI->getOpcode();
510   switch (Opc) {
511   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
512   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
513   case ARM::t2LDRi12: case ARM::t2LDRi8:
514   case ARM::t2STRi12: case ARM::t2STRi8:
515   case ARM::VLDRS: case ARM::VLDRD:
516   case ARM::VSTRS: case ARM::VSTRD:
517   case ARM::tSTRspi: case ARM::tLDRspi:
518     break;
519   default:
520     return false;
521   }
522
523   // Without a virtual base register, if the function has variable sized
524   // objects, all fixed-size local references will be via the frame pointer,
525   // Approximate the offset and see if it's legal for the instruction.
526   // Note that the incoming offset is based on the SP value at function entry,
527   // so it'll be negative.
528   MachineFunction &MF = *MI->getParent()->getParent();
529   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
530   MachineFrameInfo *MFI = MF.getFrameInfo();
531   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
532
533   // Estimate an offset from the frame pointer.
534   // Conservatively assume all callee-saved registers get pushed. R4-R6
535   // will be earlier than the FP, so we ignore those.
536   // R7, LR
537   int64_t FPOffset = Offset - 8;
538   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
539   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
540     FPOffset -= 80;
541   // Estimate an offset from the stack pointer.
542   // The incoming offset is relating to the SP at the start of the function,
543   // but when we access the local it'll be relative to the SP after local
544   // allocation, so adjust our SP-relative offset by that allocation size.
545   Offset = -Offset;
546   Offset += MFI->getLocalFrameSize();
547   // Assume that we'll have at least some spill slots allocated.
548   // FIXME: This is a total SWAG number. We should run some statistics
549   //        and pick a real one.
550   Offset += 128; // 128 bytes of spill slots
551
552   // If there is a frame pointer, try using it.
553   // The FP is only available if there is no dynamic realignment. We
554   // don't know for sure yet whether we'll need that, so we guess based
555   // on whether there are any local variables that would trigger it.
556   unsigned StackAlign = TFI->getStackAlignment();
557   if (TFI->hasFP(MF) &&
558       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
559     if (isFrameOffsetLegal(MI, FPOffset))
560       return false;
561   }
562   // If we can reference via the stack pointer, try that.
563   // FIXME: This (and the code that resolves the references) can be improved
564   //        to only disallow SP relative references in the live range of
565   //        the VLA(s). In practice, it's unclear how much difference that
566   //        would make, but it may be worth doing.
567   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
568     return false;
569
570   // The offset likely isn't legal, we want to allocate a virtual base register.
571   return true;
572 }
573
574 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
575 /// be a pointer to FrameIdx at the beginning of the basic block.
576 void ARMBaseRegisterInfo::
577 materializeFrameBaseRegister(MachineBasicBlock *MBB,
578                              unsigned BaseReg, int FrameIdx,
579                              int64_t Offset) const {
580   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
581   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
582     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
583
584   MachineBasicBlock::iterator Ins = MBB->begin();
585   DebugLoc DL;                  // Defaults to "unknown"
586   if (Ins != MBB->end())
587     DL = Ins->getDebugLoc();
588
589   const MachineFunction &MF = *MBB->getParent();
590   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
591   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
592   const MCInstrDesc &MCID = TII.get(ADDriOpc);
593   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
594
595   MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
596     .addFrameIndex(FrameIdx).addImm(Offset));
597
598   if (!AFI->isThumb1OnlyFunction())
599     AddDefaultCC(MIB);
600 }
601
602 void ARMBaseRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
603                                             int64_t Offset) const {
604   MachineBasicBlock &MBB = *MI.getParent();
605   MachineFunction &MF = *MBB.getParent();
606   const ARMBaseInstrInfo &TII =
607     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
608   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
609   int Off = Offset; // ARM doesn't need the general 64-bit offsets
610   unsigned i = 0;
611
612   assert(!AFI->isThumb1OnlyFunction() &&
613          "This resolveFrameIndex does not support Thumb1!");
614
615   while (!MI.getOperand(i).isFI()) {
616     ++i;
617     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
618   }
619   bool Done = false;
620   if (!AFI->isThumbFunction())
621     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
622   else {
623     assert(AFI->isThumb2Function());
624     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
625   }
626   assert (Done && "Unable to resolve frame index!");
627   (void)Done;
628 }
629
630 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
631                                              int64_t Offset) const {
632   const MCInstrDesc &Desc = MI->getDesc();
633   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
634   unsigned i = 0;
635
636   while (!MI->getOperand(i).isFI()) {
637     ++i;
638     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
639   }
640
641   // AddrMode4 and AddrMode6 cannot handle any offset.
642   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
643     return Offset == 0;
644
645   unsigned NumBits = 0;
646   unsigned Scale = 1;
647   bool isSigned = true;
648   switch (AddrMode) {
649   case ARMII::AddrModeT2_i8:
650   case ARMII::AddrModeT2_i12:
651     // i8 supports only negative, and i12 supports only positive, so
652     // based on Offset sign, consider the appropriate instruction
653     Scale = 1;
654     if (Offset < 0) {
655       NumBits = 8;
656       Offset = -Offset;
657     } else {
658       NumBits = 12;
659     }
660     break;
661   case ARMII::AddrMode5:
662     // VFP address mode.
663     NumBits = 8;
664     Scale = 4;
665     break;
666   case ARMII::AddrMode_i12:
667   case ARMII::AddrMode2:
668     NumBits = 12;
669     break;
670   case ARMII::AddrMode3:
671     NumBits = 8;
672     break;
673   case ARMII::AddrModeT1_s:
674     NumBits = 5;
675     Scale = 4;
676     isSigned = false;
677     break;
678   default:
679     llvm_unreachable("Unsupported addressing mode!");
680   }
681
682   Offset += getFrameIndexInstrOffset(MI, i);
683   // Make sure the offset is encodable for instructions that scale the
684   // immediate.
685   if ((Offset & (Scale-1)) != 0)
686     return false;
687
688   if (isSigned && Offset < 0)
689     Offset = -Offset;
690
691   unsigned Mask = (1 << NumBits) - 1;
692   if ((unsigned)Offset <= Mask * Scale)
693     return true;
694
695   return false;
696 }
697
698 void
699 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
700                                          int SPAdj, unsigned FIOperandNum,
701                                          RegScavenger *RS) const {
702   MachineInstr &MI = *II;
703   MachineBasicBlock &MBB = *MI.getParent();
704   MachineFunction &MF = *MBB.getParent();
705   const ARMBaseInstrInfo &TII =
706     *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
707   const ARMFrameLowering *TFI =
708     static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
709   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
710   assert(!AFI->isThumb1OnlyFunction() &&
711          "This eliminateFrameIndex does not support Thumb1!");
712   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
713   unsigned FrameReg;
714
715   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
716
717   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
718   // call frame setup/destroy instructions have already been eliminated.  That
719   // means the stack pointer cannot be used to access the emergency spill slot
720   // when !hasReservedCallFrame().
721 #ifndef NDEBUG
722   if (RS && FrameReg == ARM::SP && RS->isScavengingFrameIndex(FrameIndex)){
723     assert(TFI->hasReservedCallFrame(MF) &&
724            "Cannot use SP to access the emergency spill slot in "
725            "functions without a reserved call frame");
726     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
727            "Cannot use SP to access the emergency spill slot in "
728            "functions with variable sized frame objects");
729   }
730 #endif // NDEBUG
731
732   assert(!MI.isDebugValue() && "DBG_VALUEs should be handled in target-independent code");
733
734   // Modify MI as necessary to handle as much of 'Offset' as possible
735   bool Done = false;
736   if (!AFI->isThumbFunction())
737     Done = rewriteARMFrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
738   else {
739     assert(AFI->isThumb2Function());
740     Done = rewriteT2FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
741   }
742   if (Done)
743     return;
744
745   // If we get here, the immediate doesn't fit into the instruction.  We folded
746   // as much as possible above, handle the rest, providing a register that is
747   // SP+LargeImm.
748   assert((Offset ||
749           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
750           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
751          "This code isn't needed if offset already handled!");
752
753   unsigned ScratchReg = 0;
754   int PIdx = MI.findFirstPredOperandIdx();
755   ARMCC::CondCodes Pred = (PIdx == -1)
756     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
757   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
758   if (Offset == 0)
759     // Must be addrmode4/6.
760     MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false, false, false);
761   else {
762     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
763     if (!AFI->isThumbFunction())
764       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
765                               Offset, Pred, PredReg, TII);
766     else {
767       assert(AFI->isThumb2Function());
768       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
769                              Offset, Pred, PredReg, TII);
770     }
771     // Update the original instruction to use the scratch register.
772     MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false,true);
773   }
774 }