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