1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===// 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 // The LiveRangeEdit class represents changes done to a virtual register when it 10 // is spilled or split. 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/LiveRangeEdit.h" 14 #include "llvm/ADT/Statistic.h" 15 #include "llvm/CodeGen/CalcSpillWeights.h" 16 #include "llvm/CodeGen/LiveIntervals.h" 17 #include "llvm/CodeGen/MachineRegisterInfo.h" 18 #include "llvm/CodeGen/TargetInstrInfo.h" 19 #include "llvm/CodeGen/VirtRegMap.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 23 using namespace llvm; 24 25 #define DEBUG_TYPE "regalloc" 26 27 STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE"); 28 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE"); 29 STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE"); 30 31 void LiveRangeEdit::Delegate::anchor() { } 32 33 LiveInterval &LiveRangeEdit::createEmptyIntervalFrom(Register OldReg, 34 bool createSubRanges) { 35 Register VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg)); 36 if (VRM) 37 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg)); 38 39 LiveInterval &LI = LIS.createEmptyInterval(VReg); 40 if (Parent && !Parent->isSpillable()) 41 LI.markNotSpillable(); 42 if (createSubRanges) { 43 // Create empty subranges if the OldReg's interval has them. Do not create 44 // the main range here---it will be constructed later after the subranges 45 // have been finalized. 46 LiveInterval &OldLI = LIS.getInterval(OldReg); 47 VNInfo::Allocator &Alloc = LIS.getVNInfoAllocator(); 48 for (LiveInterval::SubRange &S : OldLI.subranges()) 49 LI.createSubRange(Alloc, S.LaneMask); 50 } 51 return LI; 52 } 53 54 Register LiveRangeEdit::createFrom(Register OldReg) { 55 Register VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg)); 56 if (VRM) { 57 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg)); 58 } 59 // FIXME: Getting the interval here actually computes it. 60 // In theory, this may not be what we want, but in practice 61 // the createEmptyIntervalFrom API is used when this is not 62 // the case. Generally speaking we just want to annotate the 63 // LiveInterval when it gets created but we cannot do that at 64 // the moment. 65 if (Parent && !Parent->isSpillable()) 66 LIS.getInterval(VReg).markNotSpillable(); 67 return VReg; 68 } 69 70 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI, 71 const MachineInstr *DefMI, 72 AAResults *aa) { 73 assert(DefMI && "Missing instruction"); 74 ScannedRemattable = true; 75 if (!TII.isTriviallyReMaterializable(*DefMI, aa)) 76 return false; 77 Remattable.insert(VNI); 78 return true; 79 } 80 81 void LiveRangeEdit::scanRemattable(AAResults *aa) { 82 for (VNInfo *VNI : getParent().valnos) { 83 if (VNI->isUnused()) 84 continue; 85 unsigned Original = VRM->getOriginal(getReg()); 86 LiveInterval &OrigLI = LIS.getInterval(Original); 87 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def); 88 if (!OrigVNI) 89 continue; 90 MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def); 91 if (!DefMI) 92 continue; 93 checkRematerializable(OrigVNI, DefMI, aa); 94 } 95 ScannedRemattable = true; 96 } 97 98 bool LiveRangeEdit::anyRematerializable(AAResults *aa) { 99 if (!ScannedRemattable) 100 scanRemattable(aa); 101 return !Remattable.empty(); 102 } 103 104 /// allUsesAvailableAt - Return true if all registers used by OrigMI at 105 /// OrigIdx are also available with the same value at UseIdx. 106 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI, 107 SlotIndex OrigIdx, 108 SlotIndex UseIdx) const { 109 OrigIdx = OrigIdx.getRegSlot(true); 110 UseIdx = std::max(UseIdx, UseIdx.getRegSlot(true)); 111 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) { 112 const MachineOperand &MO = OrigMI->getOperand(i); 113 if (!MO.isReg() || !MO.getReg() || !MO.readsReg()) 114 continue; 115 116 // We can't remat physreg uses, unless it is a constant or target wants 117 // to ignore this use. 118 if (Register::isPhysicalRegister(MO.getReg())) { 119 if (MRI.isConstantPhysReg(MO.getReg()) || TII.isIgnorableUse(MO)) 120 continue; 121 return false; 122 } 123 124 LiveInterval &li = LIS.getInterval(MO.getReg()); 125 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx); 126 if (!OVNI) 127 continue; 128 129 // Don't allow rematerialization immediately after the original def. 130 // It would be incorrect if OrigMI redefines the register. 131 // See PR14098. 132 if (SlotIndex::isSameInstr(OrigIdx, UseIdx)) 133 return false; 134 135 if (OVNI != li.getVNInfoAt(UseIdx)) 136 return false; 137 } 138 return true; 139 } 140 141 bool LiveRangeEdit::canRematerializeAt(Remat &RM, VNInfo *OrigVNI, 142 SlotIndex UseIdx, bool cheapAsAMove) { 143 assert(ScannedRemattable && "Call anyRematerializable first"); 144 145 // Use scanRemattable info. 146 if (!Remattable.count(OrigVNI)) 147 return false; 148 149 // No defining instruction provided. 150 SlotIndex DefIdx; 151 assert(RM.OrigMI && "No defining instruction for remattable value"); 152 DefIdx = LIS.getInstructionIndex(*RM.OrigMI); 153 154 // If only cheap remats were requested, bail out early. 155 if (cheapAsAMove && !TII.isAsCheapAsAMove(*RM.OrigMI)) 156 return false; 157 158 // Verify that all used registers are available with the same values. 159 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx)) 160 return false; 161 162 return true; 163 } 164 165 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB, 166 MachineBasicBlock::iterator MI, 167 unsigned DestReg, 168 const Remat &RM, 169 const TargetRegisterInfo &tri, 170 bool Late) { 171 assert(RM.OrigMI && "Invalid remat"); 172 TII.reMaterialize(MBB, MI, DestReg, 0, *RM.OrigMI, tri); 173 // DestReg of the cloned instruction cannot be Dead. Set isDead of DestReg 174 // to false anyway in case the isDead flag of RM.OrigMI's dest register 175 // is true. 176 (*--MI).getOperand(0).setIsDead(false); 177 Rematted.insert(RM.ParentVNI); 178 return LIS.getSlotIndexes()->insertMachineInstrInMaps(*MI, Late).getRegSlot(); 179 } 180 181 void LiveRangeEdit::eraseVirtReg(Register Reg) { 182 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg)) 183 LIS.removeInterval(Reg); 184 } 185 186 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI, 187 SmallVectorImpl<MachineInstr*> &Dead) { 188 MachineInstr *DefMI = nullptr, *UseMI = nullptr; 189 190 // Check that there is a single def and a single use. 191 for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg())) { 192 MachineInstr *MI = MO.getParent(); 193 if (MO.isDef()) { 194 if (DefMI && DefMI != MI) 195 return false; 196 if (!MI->canFoldAsLoad()) 197 return false; 198 DefMI = MI; 199 } else if (!MO.isUndef()) { 200 if (UseMI && UseMI != MI) 201 return false; 202 // FIXME: Targets don't know how to fold subreg uses. 203 if (MO.getSubReg()) 204 return false; 205 UseMI = MI; 206 } 207 } 208 if (!DefMI || !UseMI) 209 return false; 210 211 // Since we're moving the DefMI load, make sure we're not extending any live 212 // ranges. 213 if (!allUsesAvailableAt(DefMI, LIS.getInstructionIndex(*DefMI), 214 LIS.getInstructionIndex(*UseMI))) 215 return false; 216 217 // We also need to make sure it is safe to move the load. 218 // Assume there are stores between DefMI and UseMI. 219 bool SawStore = true; 220 if (!DefMI->isSafeToMove(nullptr, SawStore)) 221 return false; 222 223 LLVM_DEBUG(dbgs() << "Try to fold single def: " << *DefMI 224 << " into single use: " << *UseMI); 225 226 SmallVector<unsigned, 8> Ops; 227 if (UseMI->readsWritesVirtualRegister(LI->reg(), &Ops).second) 228 return false; 229 230 MachineInstr *FoldMI = TII.foldMemoryOperand(*UseMI, Ops, *DefMI, &LIS); 231 if (!FoldMI) 232 return false; 233 LLVM_DEBUG(dbgs() << " folded: " << *FoldMI); 234 LIS.ReplaceMachineInstrInMaps(*UseMI, *FoldMI); 235 // Update the call site info. 236 if (UseMI->shouldUpdateCallSiteInfo()) 237 UseMI->getMF()->moveCallSiteInfo(UseMI, FoldMI); 238 UseMI->eraseFromParent(); 239 DefMI->addRegisterDead(LI->reg(), nullptr); 240 Dead.push_back(DefMI); 241 ++NumDCEFoldedLoads; 242 return true; 243 } 244 245 bool LiveRangeEdit::useIsKill(const LiveInterval &LI, 246 const MachineOperand &MO) const { 247 const MachineInstr &MI = *MO.getParent(); 248 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); 249 if (LI.Query(Idx).isKill()) 250 return true; 251 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 252 unsigned SubReg = MO.getSubReg(); 253 LaneBitmask LaneMask = TRI.getSubRegIndexLaneMask(SubReg); 254 for (const LiveInterval::SubRange &S : LI.subranges()) { 255 if ((S.LaneMask & LaneMask).any() && S.Query(Idx).isKill()) 256 return true; 257 } 258 return false; 259 } 260 261 /// Find all live intervals that need to shrink, then remove the instruction. 262 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink, 263 AAResults *AA) { 264 assert(MI->allDefsAreDead() && "Def isn't really dead"); 265 SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot(); 266 267 // Never delete a bundled instruction. 268 if (MI->isBundled()) { 269 return; 270 } 271 // Never delete inline asm. 272 if (MI->isInlineAsm()) { 273 LLVM_DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI); 274 return; 275 } 276 277 // Use the same criteria as DeadMachineInstructionElim. 278 bool SawStore = false; 279 if (!MI->isSafeToMove(nullptr, SawStore)) { 280 LLVM_DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI); 281 return; 282 } 283 284 LLVM_DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI); 285 286 // Collect virtual registers to be erased after MI is gone. 287 SmallVector<unsigned, 8> RegsToErase; 288 bool ReadsPhysRegs = false; 289 bool isOrigDef = false; 290 unsigned Dest; 291 // Only optimize rematerialize case when the instruction has one def, since 292 // otherwise we could leave some dead defs in the code. This case is 293 // extremely rare. 294 if (VRM && MI->getOperand(0).isReg() && MI->getOperand(0).isDef() && 295 MI->getDesc().getNumDefs() == 1) { 296 Dest = MI->getOperand(0).getReg(); 297 unsigned Original = VRM->getOriginal(Dest); 298 LiveInterval &OrigLI = LIS.getInterval(Original); 299 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx); 300 // The original live-range may have been shrunk to 301 // an empty live-range. It happens when it is dead, but 302 // we still keep it around to be able to rematerialize 303 // other values that depend on it. 304 if (OrigVNI) 305 isOrigDef = SlotIndex::isSameInstr(OrigVNI->def, Idx); 306 } 307 308 bool HasLiveVRegUses = false; 309 310 // Check for live intervals that may shrink 311 for (const MachineOperand &MO : MI->operands()) { 312 if (!MO.isReg()) 313 continue; 314 Register Reg = MO.getReg(); 315 if (!Register::isVirtualRegister(Reg)) { 316 // Check if MI reads any unreserved physregs. 317 if (Reg && MO.readsReg() && !MRI.isReserved(Reg)) 318 ReadsPhysRegs = true; 319 else if (MO.isDef()) 320 LIS.removePhysRegDefAt(Reg.asMCReg(), Idx); 321 continue; 322 } 323 LiveInterval &LI = LIS.getInterval(Reg); 324 325 // Shrink read registers, unless it is likely to be expensive and 326 // unlikely to change anything. We typically don't want to shrink the 327 // PIC base register that has lots of uses everywhere. 328 // Always shrink COPY uses that probably come from live range splitting. 329 if ((MI->readsVirtualRegister(Reg) && (MI->isCopy() || MO.isDef())) || 330 (MO.readsReg() && (MRI.hasOneNonDBGUse(Reg) || useIsKill(LI, MO)))) 331 ToShrink.insert(&LI); 332 else if (MO.readsReg()) 333 HasLiveVRegUses = true; 334 335 // Remove defined value. 336 if (MO.isDef()) { 337 if (TheDelegate && LI.getVNInfoAt(Idx) != nullptr) 338 TheDelegate->LRE_WillShrinkVirtReg(LI.reg()); 339 LIS.removeVRegDefAt(LI, Idx); 340 if (LI.empty()) 341 RegsToErase.push_back(Reg); 342 } 343 } 344 345 // Currently, we don't support DCE of physreg live ranges. If MI reads 346 // any unreserved physregs, don't erase the instruction, but turn it into 347 // a KILL instead. This way, the physreg live ranges don't end up 348 // dangling. 349 // FIXME: It would be better to have something like shrinkToUses() for 350 // physregs. That could potentially enable more DCE and it would free up 351 // the physreg. It would not happen often, though. 352 if (ReadsPhysRegs) { 353 MI->setDesc(TII.get(TargetOpcode::KILL)); 354 // Remove all operands that aren't physregs. 355 for (unsigned i = MI->getNumOperands(); i; --i) { 356 const MachineOperand &MO = MI->getOperand(i-1); 357 if (MO.isReg() && Register::isPhysicalRegister(MO.getReg())) 358 continue; 359 MI->RemoveOperand(i-1); 360 } 361 LLVM_DEBUG(dbgs() << "Converted physregs to:\t" << *MI); 362 } else { 363 // If the dest of MI is an original reg and MI is reMaterializable, 364 // don't delete the inst. Replace the dest with a new reg, and keep 365 // the inst for remat of other siblings. The inst is saved in 366 // LiveRangeEdit::DeadRemats and will be deleted after all the 367 // allocations of the func are done. 368 // However, immediately delete instructions which have unshrunk virtual 369 // register uses. That may provoke RA to split an interval at the KILL 370 // and later result in an invalid live segment end. 371 if (isOrigDef && DeadRemats && !HasLiveVRegUses && 372 TII.isTriviallyReMaterializable(*MI, AA)) { 373 LiveInterval &NewLI = createEmptyIntervalFrom(Dest, false); 374 VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator()); 375 NewLI.addSegment(LiveInterval::Segment(Idx, Idx.getDeadSlot(), VNI)); 376 pop_back(); 377 DeadRemats->insert(MI); 378 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo(); 379 MI->substituteRegister(Dest, NewLI.reg(), 0, TRI); 380 MI->getOperand(0).setIsDead(true); 381 } else { 382 if (TheDelegate) 383 TheDelegate->LRE_WillEraseInstruction(MI); 384 LIS.RemoveMachineInstrFromMaps(*MI); 385 MI->eraseFromParent(); 386 ++NumDCEDeleted; 387 } 388 } 389 390 // Erase any virtregs that are now empty and unused. There may be <undef> 391 // uses around. Keep the empty live range in that case. 392 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) { 393 Register Reg = RegsToErase[i]; 394 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) { 395 ToShrink.remove(&LIS.getInterval(Reg)); 396 eraseVirtReg(Reg); 397 } 398 } 399 } 400 401 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr *> &Dead, 402 ArrayRef<Register> RegsBeingSpilled, 403 AAResults *AA) { 404 ToShrinkSet ToShrink; 405 406 for (;;) { 407 // Erase all dead defs. 408 while (!Dead.empty()) 409 eliminateDeadDef(Dead.pop_back_val(), ToShrink, AA); 410 411 if (ToShrink.empty()) 412 break; 413 414 // Shrink just one live interval. Then delete new dead defs. 415 LiveInterval *LI = ToShrink.pop_back_val(); 416 if (foldAsLoad(LI, Dead)) 417 continue; 418 unsigned VReg = LI->reg(); 419 if (TheDelegate) 420 TheDelegate->LRE_WillShrinkVirtReg(VReg); 421 if (!LIS.shrinkToUses(LI, &Dead)) 422 continue; 423 424 // Don't create new intervals for a register being spilled. 425 // The new intervals would have to be spilled anyway so its not worth it. 426 // Also they currently aren't spilled so creating them and not spilling 427 // them results in incorrect code. 428 bool BeingSpilled = false; 429 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) { 430 if (VReg == RegsBeingSpilled[i]) { 431 BeingSpilled = true; 432 break; 433 } 434 } 435 436 if (BeingSpilled) continue; 437 438 // LI may have been separated, create new intervals. 439 LI->RenumberValues(); 440 SmallVector<LiveInterval*, 8> SplitLIs; 441 LIS.splitSeparateComponents(*LI, SplitLIs); 442 if (!SplitLIs.empty()) 443 ++NumFracRanges; 444 445 Register Original = VRM ? VRM->getOriginal(VReg) : Register(); 446 for (const LiveInterval *SplitLI : SplitLIs) { 447 // If LI is an original interval that hasn't been split yet, make the new 448 // intervals their own originals instead of referring to LI. The original 449 // interval must contain all the split products, and LI doesn't. 450 if (Original != VReg && Original != 0) 451 VRM->setIsSplitFromReg(SplitLI->reg(), Original); 452 if (TheDelegate) 453 TheDelegate->LRE_DidCloneVirtReg(SplitLI->reg(), VReg); 454 } 455 } 456 } 457 458 // Keep track of new virtual registers created via 459 // MachineRegisterInfo::createVirtualRegister. 460 void 461 LiveRangeEdit::MRI_NoteNewVirtualRegister(Register VReg) { 462 if (VRM) 463 VRM->grow(); 464 465 NewRegs.push_back(VReg); 466 } 467 468 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF, 469 VirtRegAuxInfo &VRAI) { 470 for (unsigned I = 0, Size = size(); I < Size; ++I) { 471 LiveInterval &LI = LIS.getInterval(get(I)); 472 if (MRI.recomputeRegClass(LI.reg())) 473 LLVM_DEBUG({ 474 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 475 dbgs() << "Inflated " << printReg(LI.reg()) << " to " 476 << TRI->getRegClassName(MRI.getRegClass(LI.reg())) << '\n'; 477 }); 478 VRAI.calculateSpillWeightAndHint(LI); 479 } 480 } 481