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