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