1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===// 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 // The LiveRangeEdit class represents changes done to a virtual register when it 11 // is spilled or split. 12 //===----------------------------------------------------------------------===// 13 14 #define DEBUG_TYPE "regalloc" 15 #include "llvm/CodeGen/LiveRangeEdit.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/CodeGen/CalcSpillWeights.h" 18 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 19 #include "llvm/CodeGen/MachineRegisterInfo.h" 20 #include "llvm/CodeGen/VirtRegMap.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include "llvm/Target/TargetInstrInfo.h" 24 25 using namespace llvm; 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(unsigned OldReg) { 34 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg)); 35 if (VRM) { 36 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg)); 37 } 38 LiveInterval &LI = LIS.createEmptyInterval(VReg); 39 return LI; 40 } 41 42 unsigned LiveRangeEdit::createFrom(unsigned OldReg) { 43 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg)); 44 if (VRM) { 45 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg)); 46 } 47 return VReg; 48 } 49 50 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI, 51 const MachineInstr *DefMI, 52 AliasAnalysis *aa) { 53 assert(DefMI && "Missing instruction"); 54 ScannedRemattable = true; 55 if (!TII.isTriviallyReMaterializable(DefMI, aa)) 56 return false; 57 Remattable.insert(VNI); 58 return true; 59 } 60 61 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) { 62 for (LiveInterval::vni_iterator I = getParent().vni_begin(), 63 E = getParent().vni_end(); I != E; ++I) { 64 VNInfo *VNI = *I; 65 if (VNI->isUnused()) 66 continue; 67 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def); 68 if (!DefMI) 69 continue; 70 checkRematerializable(VNI, DefMI, aa); 71 } 72 ScannedRemattable = true; 73 } 74 75 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) { 76 if (!ScannedRemattable) 77 scanRemattable(aa); 78 return !Remattable.empty(); 79 } 80 81 /// allUsesAvailableAt - Return true if all registers used by OrigMI at 82 /// OrigIdx are also available with the same value at UseIdx. 83 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI, 84 SlotIndex OrigIdx, 85 SlotIndex UseIdx) const { 86 OrigIdx = OrigIdx.getRegSlot(true); 87 UseIdx = UseIdx.getRegSlot(true); 88 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) { 89 const MachineOperand &MO = OrigMI->getOperand(i); 90 if (!MO.isReg() || !MO.getReg() || !MO.readsReg()) 91 continue; 92 93 // We can't remat physreg uses, unless it is a constant. 94 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) { 95 if (MRI.isConstantPhysReg(MO.getReg(), *OrigMI->getParent()->getParent())) 96 continue; 97 return false; 98 } 99 100 LiveInterval &li = LIS.getInterval(MO.getReg()); 101 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx); 102 if (!OVNI) 103 continue; 104 105 // Don't allow rematerialization immediately after the original def. 106 // It would be incorrect if OrigMI redefines the register. 107 // See PR14098. 108 if (SlotIndex::isSameInstr(OrigIdx, UseIdx)) 109 return false; 110 111 if (OVNI != li.getVNInfoAt(UseIdx)) 112 return false; 113 } 114 return true; 115 } 116 117 bool LiveRangeEdit::canRematerializeAt(Remat &RM, 118 SlotIndex UseIdx, 119 bool cheapAsAMove) { 120 assert(ScannedRemattable && "Call anyRematerializable first"); 121 122 // Use scanRemattable info. 123 if (!Remattable.count(RM.ParentVNI)) 124 return false; 125 126 // No defining instruction provided. 127 SlotIndex DefIdx; 128 if (RM.OrigMI) 129 DefIdx = LIS.getInstructionIndex(RM.OrigMI); 130 else { 131 DefIdx = RM.ParentVNI->def; 132 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx); 133 assert(RM.OrigMI && "No defining instruction for remattable value"); 134 } 135 136 // If only cheap remats were requested, bail out early. 137 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove()) 138 return false; 139 140 // Verify that all used registers are available with the same values. 141 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx)) 142 return false; 143 144 return true; 145 } 146 147 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB, 148 MachineBasicBlock::iterator MI, 149 unsigned DestReg, 150 const Remat &RM, 151 const TargetRegisterInfo &tri, 152 bool Late) { 153 assert(RM.OrigMI && "Invalid remat"); 154 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri); 155 Rematted.insert(RM.ParentVNI); 156 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late) 157 .getRegSlot(); 158 } 159 160 void LiveRangeEdit::eraseVirtReg(unsigned Reg) { 161 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg)) 162 LIS.removeInterval(Reg); 163 } 164 165 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI, 166 SmallVectorImpl<MachineInstr*> &Dead) { 167 MachineInstr *DefMI = 0, *UseMI = 0; 168 169 // Check that there is a single def and a single use. 170 for (MachineOperand &MO : MRI.reg_nodbg_operands(LI->reg)) { 171 MachineInstr *MI = MO.getParent(); 172 if (MO.isDef()) { 173 if (DefMI && DefMI != MI) 174 return false; 175 if (!MI->canFoldAsLoad()) 176 return false; 177 DefMI = MI; 178 } else if (!MO.isUndef()) { 179 if (UseMI && UseMI != MI) 180 return false; 181 // FIXME: Targets don't know how to fold subreg uses. 182 if (MO.getSubReg()) 183 return false; 184 UseMI = MI; 185 } 186 } 187 if (!DefMI || !UseMI) 188 return false; 189 190 // Since we're moving the DefMI load, make sure we're not extending any live 191 // ranges. 192 if (!allUsesAvailableAt(DefMI, 193 LIS.getInstructionIndex(DefMI), 194 LIS.getInstructionIndex(UseMI))) 195 return false; 196 197 // We also need to make sure it is safe to move the load. 198 // Assume there are stores between DefMI and UseMI. 199 bool SawStore = true; 200 if (!DefMI->isSafeToMove(&TII, 0, SawStore)) 201 return false; 202 203 DEBUG(dbgs() << "Try to fold single def: " << *DefMI 204 << " into single use: " << *UseMI); 205 206 SmallVector<unsigned, 8> Ops; 207 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second) 208 return false; 209 210 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI); 211 if (!FoldMI) 212 return false; 213 DEBUG(dbgs() << " folded: " << *FoldMI); 214 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI); 215 UseMI->eraseFromParent(); 216 DefMI->addRegisterDead(LI->reg, 0); 217 Dead.push_back(DefMI); 218 ++NumDCEFoldedLoads; 219 return true; 220 } 221 222 /// Find all live intervals that need to shrink, then remove the instruction. 223 void LiveRangeEdit::eliminateDeadDef(MachineInstr *MI, ToShrinkSet &ToShrink) { 224 assert(MI->allDefsAreDead() && "Def isn't really dead"); 225 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); 226 227 // Never delete a bundled instruction. 228 if (MI->isBundled()) { 229 return; 230 } 231 // Never delete inline asm. 232 if (MI->isInlineAsm()) { 233 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI); 234 return; 235 } 236 237 // Use the same criteria as DeadMachineInstructionElim. 238 bool SawStore = false; 239 if (!MI->isSafeToMove(&TII, 0, SawStore)) { 240 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI); 241 return; 242 } 243 244 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI); 245 246 // Collect virtual registers to be erased after MI is gone. 247 SmallVector<unsigned, 8> RegsToErase; 248 bool ReadsPhysRegs = false; 249 250 // Check for live intervals that may shrink 251 for (MachineInstr::mop_iterator MOI = MI->operands_begin(), 252 MOE = MI->operands_end(); MOI != MOE; ++MOI) { 253 if (!MOI->isReg()) 254 continue; 255 unsigned Reg = MOI->getReg(); 256 if (!TargetRegisterInfo::isVirtualRegister(Reg)) { 257 // Check if MI reads any unreserved physregs. 258 if (Reg && MOI->readsReg() && !MRI.isReserved(Reg)) 259 ReadsPhysRegs = true; 260 else if (MOI->isDef()) { 261 for (MCRegUnitIterator Units(Reg, MRI.getTargetRegisterInfo()); 262 Units.isValid(); ++Units) { 263 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) { 264 if (VNInfo *VNI = LR->getVNInfoAt(Idx)) 265 LR->removeValNo(VNI); 266 } 267 } 268 } 269 continue; 270 } 271 LiveInterval &LI = LIS.getInterval(Reg); 272 273 // Shrink read registers, unless it is likely to be expensive and 274 // unlikely to change anything. We typically don't want to shrink the 275 // PIC base register that has lots of uses everywhere. 276 // Always shrink COPY uses that probably come from live range splitting. 277 if (MI->readsVirtualRegister(Reg) && 278 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) || 279 LI.Query(Idx).isKill())) 280 ToShrink.insert(&LI); 281 282 // Remove defined value. 283 if (MOI->isDef()) { 284 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) { 285 if (TheDelegate) 286 TheDelegate->LRE_WillShrinkVirtReg(LI.reg); 287 LI.removeValNo(VNI); 288 if (LI.empty()) 289 RegsToErase.push_back(Reg); 290 } 291 } 292 } 293 294 // Currently, we don't support DCE of physreg live ranges. If MI reads 295 // any unreserved physregs, don't erase the instruction, but turn it into 296 // a KILL instead. This way, the physreg live ranges don't end up 297 // dangling. 298 // FIXME: It would be better to have something like shrinkToUses() for 299 // physregs. That could potentially enable more DCE and it would free up 300 // the physreg. It would not happen often, though. 301 if (ReadsPhysRegs) { 302 MI->setDesc(TII.get(TargetOpcode::KILL)); 303 // Remove all operands that aren't physregs. 304 for (unsigned i = MI->getNumOperands(); i; --i) { 305 const MachineOperand &MO = MI->getOperand(i-1); 306 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg())) 307 continue; 308 MI->RemoveOperand(i-1); 309 } 310 DEBUG(dbgs() << "Converted physregs to:\t" << *MI); 311 } else { 312 if (TheDelegate) 313 TheDelegate->LRE_WillEraseInstruction(MI); 314 LIS.RemoveMachineInstrFromMaps(MI); 315 MI->eraseFromParent(); 316 ++NumDCEDeleted; 317 } 318 319 // Erase any virtregs that are now empty and unused. There may be <undef> 320 // uses around. Keep the empty live range in that case. 321 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) { 322 unsigned Reg = RegsToErase[i]; 323 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) { 324 ToShrink.remove(&LIS.getInterval(Reg)); 325 eraseVirtReg(Reg); 326 } 327 } 328 } 329 330 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead, 331 ArrayRef<unsigned> RegsBeingSpilled) { 332 ToShrinkSet ToShrink; 333 334 for (;;) { 335 // Erase all dead defs. 336 while (!Dead.empty()) 337 eliminateDeadDef(Dead.pop_back_val(), ToShrink); 338 339 if (ToShrink.empty()) 340 break; 341 342 // Shrink just one live interval. Then delete new dead defs. 343 LiveInterval *LI = ToShrink.back(); 344 ToShrink.pop_back(); 345 if (foldAsLoad(LI, Dead)) 346 continue; 347 if (TheDelegate) 348 TheDelegate->LRE_WillShrinkVirtReg(LI->reg); 349 if (!LIS.shrinkToUses(LI, &Dead)) 350 continue; 351 352 // Don't create new intervals for a register being spilled. 353 // The new intervals would have to be spilled anyway so its not worth it. 354 // Also they currently aren't spilled so creating them and not spilling 355 // them results in incorrect code. 356 bool BeingSpilled = false; 357 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) { 358 if (LI->reg == RegsBeingSpilled[i]) { 359 BeingSpilled = true; 360 break; 361 } 362 } 363 364 if (BeingSpilled) continue; 365 366 // LI may have been separated, create new intervals. 367 LI->RenumberValues(); 368 ConnectedVNInfoEqClasses ConEQ(LIS); 369 unsigned NumComp = ConEQ.Classify(LI); 370 if (NumComp <= 1) 371 continue; 372 ++NumFracRanges; 373 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg; 374 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n'); 375 SmallVector<LiveInterval*, 8> Dups(1, LI); 376 for (unsigned i = 1; i != NumComp; ++i) { 377 Dups.push_back(&createEmptyIntervalFrom(LI->reg)); 378 // If LI is an original interval that hasn't been split yet, make the new 379 // intervals their own originals instead of referring to LI. The original 380 // interval must contain all the split products, and LI doesn't. 381 if (IsOriginal) 382 VRM->setIsSplitFromReg(Dups.back()->reg, 0); 383 if (TheDelegate) 384 TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg); 385 } 386 ConEQ.Distribute(&Dups[0], MRI); 387 DEBUG({ 388 for (unsigned i = 0; i != NumComp; ++i) 389 dbgs() << '\t' << *Dups[i] << '\n'; 390 }); 391 } 392 } 393 394 // Keep track of new virtual registers created via 395 // MachineRegisterInfo::createVirtualRegister. 396 void 397 LiveRangeEdit::MRI_NoteNewVirtualRegister(unsigned VReg) 398 { 399 if (VRM) 400 VRM->grow(); 401 402 NewRegs.push_back(VReg); 403 } 404 405 void 406 LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF, 407 const MachineLoopInfo &Loops, 408 const MachineBlockFrequencyInfo &MBFI) { 409 VirtRegAuxInfo VRAI(MF, LIS, Loops, MBFI); 410 for (unsigned I = 0, Size = size(); I < Size; ++I) { 411 LiveInterval &LI = LIS.getInterval(get(I)); 412 if (MRI.recomputeRegClass(LI.reg, MF.getTarget())) 413 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to " 414 << MRI.getRegClass(LI.reg)->getName() << '\n'); 415 VRAI.calculateSpillWeightAndHint(LI); 416 } 417 } 418