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