1 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===// 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 inline spiller modifies the machine function directly instead of 11 // inserting spills and restores in VirtRegMap. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "Spiller.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/ADT/TinyPtrVector.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 21 #include "llvm/CodeGen/LiveRangeEdit.h" 22 #include "llvm/CodeGen/LiveStackAnalysis.h" 23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 25 #include "llvm/CodeGen/MachineDominators.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineInstrBundle.h" 30 #include "llvm/CodeGen/MachineLoopInfo.h" 31 #include "llvm/CodeGen/MachineRegisterInfo.h" 32 #include "llvm/CodeGen/VirtRegMap.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetInstrInfo.h" 37 #include "llvm/Target/TargetMachine.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "regalloc" 42 43 STATISTIC(NumSpilledRanges, "Number of spilled live ranges"); 44 STATISTIC(NumSnippets, "Number of spilled snippets"); 45 STATISTIC(NumSpills, "Number of spills inserted"); 46 STATISTIC(NumSpillsRemoved, "Number of spills removed"); 47 STATISTIC(NumReloads, "Number of reloads inserted"); 48 STATISTIC(NumReloadsRemoved, "Number of reloads removed"); 49 STATISTIC(NumFolded, "Number of folded stack accesses"); 50 STATISTIC(NumFoldedLoads, "Number of folded loads"); 51 STATISTIC(NumRemats, "Number of rematerialized defs for spilling"); 52 STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads"); 53 STATISTIC(NumHoists, "Number of hoisted spills"); 54 55 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden, 56 cl::desc("Disable inline spill hoisting")); 57 58 namespace { 59 class InlineSpiller : public Spiller { 60 MachineFunction &MF; 61 LiveIntervals &LIS; 62 LiveStacks &LSS; 63 AliasAnalysis *AA; 64 MachineDominatorTree &MDT; 65 MachineLoopInfo &Loops; 66 VirtRegMap &VRM; 67 MachineFrameInfo &MFI; 68 MachineRegisterInfo &MRI; 69 const TargetInstrInfo &TII; 70 const TargetRegisterInfo &TRI; 71 const MachineBlockFrequencyInfo &MBFI; 72 73 // Variables that are valid during spill(), but used by multiple methods. 74 LiveRangeEdit *Edit; 75 LiveInterval *StackInt; 76 int StackSlot; 77 unsigned Original; 78 79 // All registers to spill to StackSlot, including the main register. 80 SmallVector<unsigned, 8> RegsToSpill; 81 82 // All COPY instructions to/from snippets. 83 // They are ignored since both operands refer to the same stack slot. 84 SmallPtrSet<MachineInstr*, 8> SnippetCopies; 85 86 // Values that failed to remat at some point. 87 SmallPtrSet<VNInfo*, 8> UsedValues; 88 89 public: 90 // Information about a value that was defined by a copy from a sibling 91 // register. 92 struct SibValueInfo { 93 // True when all reaching defs were reloads: No spill is necessary. 94 bool AllDefsAreReloads; 95 96 // True when value is defined by an original PHI not from splitting. 97 bool DefByOrigPHI; 98 99 // True when the COPY defining this value killed its source. 100 bool KillsSource; 101 102 // The preferred register to spill. 103 unsigned SpillReg; 104 105 // The value of SpillReg that should be spilled. 106 VNInfo *SpillVNI; 107 108 // The block where SpillVNI should be spilled. Currently, this must be the 109 // block containing SpillVNI->def. 110 MachineBasicBlock *SpillMBB; 111 112 // A defining instruction that is not a sibling copy or a reload, or NULL. 113 // This can be used as a template for rematerialization. 114 MachineInstr *DefMI; 115 116 // List of values that depend on this one. These values are actually the 117 // same, but live range splitting has placed them in different registers, 118 // or SSA update needed to insert PHI-defs to preserve SSA form. This is 119 // copies of the current value and phi-kills. Usually only phi-kills cause 120 // more than one dependent value. 121 TinyPtrVector<VNInfo*> Deps; 122 123 SibValueInfo(unsigned Reg, VNInfo *VNI) 124 : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false), 125 SpillReg(Reg), SpillVNI(VNI), SpillMBB(nullptr), DefMI(nullptr) {} 126 127 // Returns true when a def has been found. 128 bool hasDef() const { return DefByOrigPHI || DefMI; } 129 }; 130 131 private: 132 // Values in RegsToSpill defined by sibling copies. 133 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap; 134 SibValueMap SibValues; 135 136 // Dead defs generated during spilling. 137 SmallVector<MachineInstr*, 8> DeadDefs; 138 139 ~InlineSpiller() {} 140 141 public: 142 InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm) 143 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()), 144 LSS(pass.getAnalysis<LiveStacks>()), 145 AA(&pass.getAnalysis<AliasAnalysis>()), 146 MDT(pass.getAnalysis<MachineDominatorTree>()), 147 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm), 148 MFI(*mf.getFrameInfo()), MRI(mf.getRegInfo()), 149 TII(*mf.getSubtarget().getInstrInfo()), 150 TRI(*mf.getSubtarget().getRegisterInfo()), 151 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()) {} 152 153 void spill(LiveRangeEdit &) override; 154 155 private: 156 bool isSnippet(const LiveInterval &SnipLI); 157 void collectRegsToSpill(); 158 159 bool isRegToSpill(unsigned Reg) { 160 return std::find(RegsToSpill.begin(), 161 RegsToSpill.end(), Reg) != RegsToSpill.end(); 162 } 163 164 bool isSibling(unsigned Reg); 165 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*); 166 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = nullptr); 167 void analyzeSiblingValues(); 168 169 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI); 170 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI); 171 172 void markValueUsed(LiveInterval*, VNInfo*); 173 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI); 174 void reMaterializeAll(); 175 176 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg); 177 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >, 178 MachineInstr *LoadMI = nullptr); 179 void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI); 180 void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI); 181 182 void spillAroundUses(unsigned Reg); 183 void spillAll(); 184 }; 185 } 186 187 namespace llvm { 188 Spiller *createInlineSpiller(MachineFunctionPass &pass, 189 MachineFunction &mf, 190 VirtRegMap &vrm) { 191 return new InlineSpiller(pass, mf, vrm); 192 } 193 } 194 195 //===----------------------------------------------------------------------===// 196 // Snippets 197 //===----------------------------------------------------------------------===// 198 199 // When spilling a virtual register, we also spill any snippets it is connected 200 // to. The snippets are small live ranges that only have a single real use, 201 // leftovers from live range splitting. Spilling them enables memory operand 202 // folding or tightens the live range around the single use. 203 // 204 // This minimizes register pressure and maximizes the store-to-load distance for 205 // spill slots which can be important in tight loops. 206 207 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register, 208 /// otherwise return 0. 209 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) { 210 if (!MI->isFullCopy()) 211 return 0; 212 if (MI->getOperand(0).getReg() == Reg) 213 return MI->getOperand(1).getReg(); 214 if (MI->getOperand(1).getReg() == Reg) 215 return MI->getOperand(0).getReg(); 216 return 0; 217 } 218 219 /// isSnippet - Identify if a live interval is a snippet that should be spilled. 220 /// It is assumed that SnipLI is a virtual register with the same original as 221 /// Edit->getReg(). 222 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) { 223 unsigned Reg = Edit->getReg(); 224 225 // A snippet is a tiny live range with only a single instruction using it 226 // besides copies to/from Reg or spills/fills. We accept: 227 // 228 // %snip = COPY %Reg / FILL fi# 229 // %snip = USE %snip 230 // %Reg = COPY %snip / SPILL %snip, fi# 231 // 232 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI)) 233 return false; 234 235 MachineInstr *UseMI = nullptr; 236 237 // Check that all uses satisfy our criteria. 238 for (MachineRegisterInfo::reg_instr_nodbg_iterator 239 RI = MRI.reg_instr_nodbg_begin(SnipLI.reg), 240 E = MRI.reg_instr_nodbg_end(); RI != E; ) { 241 MachineInstr *MI = &*(RI++); 242 243 // Allow copies to/from Reg. 244 if (isFullCopyOf(MI, Reg)) 245 continue; 246 247 // Allow stack slot loads. 248 int FI; 249 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) 250 continue; 251 252 // Allow stack slot stores. 253 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) 254 continue; 255 256 // Allow a single additional instruction. 257 if (UseMI && MI != UseMI) 258 return false; 259 UseMI = MI; 260 } 261 return true; 262 } 263 264 /// collectRegsToSpill - Collect live range snippets that only have a single 265 /// real use. 266 void InlineSpiller::collectRegsToSpill() { 267 unsigned Reg = Edit->getReg(); 268 269 // Main register always spills. 270 RegsToSpill.assign(1, Reg); 271 SnippetCopies.clear(); 272 273 // Snippets all have the same original, so there can't be any for an original 274 // register. 275 if (Original == Reg) 276 return; 277 278 for (MachineRegisterInfo::reg_instr_iterator 279 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) { 280 MachineInstr *MI = &*(RI++); 281 unsigned SnipReg = isFullCopyOf(MI, Reg); 282 if (!isSibling(SnipReg)) 283 continue; 284 LiveInterval &SnipLI = LIS.getInterval(SnipReg); 285 if (!isSnippet(SnipLI)) 286 continue; 287 SnippetCopies.insert(MI); 288 if (isRegToSpill(SnipReg)) 289 continue; 290 RegsToSpill.push_back(SnipReg); 291 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n'); 292 ++NumSnippets; 293 } 294 } 295 296 297 //===----------------------------------------------------------------------===// 298 // Sibling Values 299 //===----------------------------------------------------------------------===// 300 301 // After live range splitting, some values to be spilled may be defined by 302 // copies from sibling registers. We trace the sibling copies back to the 303 // original value if it still exists. We need it for rematerialization. 304 // 305 // Even when the value can't be rematerialized, we still want to determine if 306 // the value has already been spilled, or we may want to hoist the spill from a 307 // loop. 308 309 bool InlineSpiller::isSibling(unsigned Reg) { 310 return TargetRegisterInfo::isVirtualRegister(Reg) && 311 VRM.getOriginal(Reg) == Original; 312 } 313 314 #ifndef NDEBUG 315 static raw_ostream &operator<<(raw_ostream &OS, 316 const InlineSpiller::SibValueInfo &SVI) { 317 OS << "spill " << PrintReg(SVI.SpillReg) << ':' 318 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def; 319 if (SVI.SpillMBB) 320 OS << " in BB#" << SVI.SpillMBB->getNumber(); 321 if (SVI.AllDefsAreReloads) 322 OS << " all-reloads"; 323 if (SVI.DefByOrigPHI) 324 OS << " orig-phi"; 325 if (SVI.KillsSource) 326 OS << " kill"; 327 OS << " deps["; 328 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i) 329 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def; 330 OS << " ]"; 331 if (SVI.DefMI) 332 OS << " def: " << *SVI.DefMI; 333 else 334 OS << '\n'; 335 return OS; 336 } 337 #endif 338 339 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is 340 /// known. Otherwise remember the dependency for later. 341 /// 342 /// @param SVIIter SibValues entry to propagate. 343 /// @param VNI Dependent value, or NULL to propagate to all saved dependents. 344 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter, 345 VNInfo *VNI) { 346 SibValueMap::value_type *SVI = &*SVIIter; 347 348 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that. 349 TinyPtrVector<VNInfo*> FirstDeps; 350 if (VNI) { 351 FirstDeps.push_back(VNI); 352 SVI->second.Deps.push_back(VNI); 353 } 354 355 // Has the value been completely determined yet? If not, defer propagation. 356 if (!SVI->second.hasDef()) 357 return; 358 359 // Work list of values to propagate. 360 SmallSetVector<SibValueMap::value_type *, 8> WorkList; 361 WorkList.insert(SVI); 362 363 do { 364 SVI = WorkList.pop_back_val(); 365 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps; 366 VNI = nullptr; 367 368 SibValueInfo &SV = SVI->second; 369 if (!SV.SpillMBB) 370 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def); 371 372 DEBUG(dbgs() << " prop to " << Deps->size() << ": " 373 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV); 374 375 assert(SV.hasDef() && "Propagating undefined value"); 376 377 // Should this value be propagated as a preferred spill candidate? We don't 378 // propagate values of registers that are about to spill. 379 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg); 380 unsigned SpillDepth = ~0u; 381 382 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(), 383 DepE = Deps->end(); DepI != DepE; ++DepI) { 384 SibValueMap::iterator DepSVI = SibValues.find(*DepI); 385 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues"); 386 SibValueInfo &DepSV = DepSVI->second; 387 if (!DepSV.SpillMBB) 388 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def); 389 390 bool Changed = false; 391 392 // Propagate defining instruction. 393 if (!DepSV.hasDef()) { 394 Changed = true; 395 DepSV.DefMI = SV.DefMI; 396 DepSV.DefByOrigPHI = SV.DefByOrigPHI; 397 } 398 399 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of 400 // all predecessors. 401 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) { 402 Changed = true; 403 DepSV.AllDefsAreReloads = false; 404 } 405 406 // Propagate best spill value. 407 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) { 408 if (SV.SpillMBB == DepSV.SpillMBB) { 409 // DepSV is in the same block. Hoist when dominated. 410 if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) { 411 // This is an alternative def earlier in the same MBB. 412 // Hoist the spill as far as possible in SpillMBB. This can ease 413 // register pressure: 414 // 415 // x = def 416 // y = use x 417 // s = copy x 418 // 419 // Hoisting the spill of s to immediately after the def removes the 420 // interference between x and y: 421 // 422 // x = def 423 // spill x 424 // y = use x<kill> 425 // 426 // This hoist only helps when the DepSV copy kills its source. 427 Changed = true; 428 DepSV.SpillReg = SV.SpillReg; 429 DepSV.SpillVNI = SV.SpillVNI; 430 DepSV.SpillMBB = SV.SpillMBB; 431 } 432 } else { 433 // DepSV is in a different block. 434 if (SpillDepth == ~0u) 435 SpillDepth = Loops.getLoopDepth(SV.SpillMBB); 436 437 // Also hoist spills to blocks with smaller loop depth, but make sure 438 // that the new value dominates. Non-phi dependents are always 439 // dominated, phis need checking. 440 441 const BranchProbability MarginProb(4, 5); // 80% 442 // Hoist a spill to outer loop if there are multiple dependents (it 443 // can be beneficial if more than one dependents are hoisted) or 444 // if DepSV (the hoisting source) is hotter than SV (the hoisting 445 // destination) (we add a 80% margin to bias a little towards 446 // loop depth). 447 bool HoistCondition = 448 (MBFI.getBlockFreq(DepSV.SpillMBB) >= 449 (MBFI.getBlockFreq(SV.SpillMBB) * MarginProb)) || 450 Deps->size() > 1; 451 452 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) && 453 HoistCondition && 454 (!DepSVI->first->isPHIDef() || 455 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) { 456 Changed = true; 457 DepSV.SpillReg = SV.SpillReg; 458 DepSV.SpillVNI = SV.SpillVNI; 459 DepSV.SpillMBB = SV.SpillMBB; 460 } 461 } 462 } 463 464 if (!Changed) 465 continue; 466 467 // Something changed in DepSVI. Propagate to dependents. 468 WorkList.insert(&*DepSVI); 469 470 DEBUG(dbgs() << " update " << DepSVI->first->id << '@' 471 << DepSVI->first->def << " to:\t" << DepSV); 472 } 473 } while (!WorkList.empty()); 474 } 475 476 /// traceSiblingValue - Trace a value that is about to be spilled back to the 477 /// real defining instructions by looking through sibling copies. Always stay 478 /// within the range of OrigVNI so the registers are known to carry the same 479 /// value. 480 /// 481 /// Determine if the value is defined by all reloads, so spilling isn't 482 /// necessary - the value is already in the stack slot. 483 /// 484 /// Return a defining instruction that may be a candidate for rematerialization. 485 /// 486 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI, 487 VNInfo *OrigVNI) { 488 // Check if a cached value already exists. 489 SibValueMap::iterator SVI; 490 bool Inserted; 491 std::tie(SVI, Inserted) = 492 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI))); 493 if (!Inserted) { 494 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':' 495 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second); 496 return SVI->second.DefMI; 497 } 498 499 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':' 500 << UseVNI->id << '@' << UseVNI->def << '\n'); 501 502 // List of (Reg, VNI) that have been inserted into SibValues, but need to be 503 // processed. 504 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList; 505 WorkList.push_back(std::make_pair(UseReg, UseVNI)); 506 507 do { 508 unsigned Reg; 509 VNInfo *VNI; 510 std::tie(Reg, VNI) = WorkList.pop_back_val(); 511 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def 512 << ":\t"); 513 514 // First check if this value has already been computed. 515 SVI = SibValues.find(VNI); 516 assert(SVI != SibValues.end() && "Missing SibValues entry"); 517 518 // Trace through PHI-defs created by live range splitting. 519 if (VNI->isPHIDef()) { 520 // Stop at original PHIs. We don't know the value at the predecessors. 521 if (VNI->def == OrigVNI->def) { 522 DEBUG(dbgs() << "orig phi value\n"); 523 SVI->second.DefByOrigPHI = true; 524 SVI->second.AllDefsAreReloads = false; 525 propagateSiblingValue(SVI); 526 continue; 527 } 528 529 // This is a PHI inserted by live range splitting. We could trace the 530 // live-out value from predecessor blocks, but that search can be very 531 // expensive if there are many predecessors and many more PHIs as 532 // generated by tail-dup when it sees an indirectbr. Instead, look at 533 // all the non-PHI defs that have the same value as OrigVNI. They must 534 // jointly dominate VNI->def. This is not optimal since VNI may actually 535 // be jointly dominated by a smaller subset of defs, so there is a change 536 // we will miss a AllDefsAreReloads optimization. 537 538 // Separate all values dominated by OrigVNI into PHIs and non-PHIs. 539 SmallVector<VNInfo*, 8> PHIs, NonPHIs; 540 LiveInterval &LI = LIS.getInterval(Reg); 541 LiveInterval &OrigLI = LIS.getInterval(Original); 542 543 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end(); 544 VI != VE; ++VI) { 545 VNInfo *VNI2 = *VI; 546 if (VNI2->isUnused()) 547 continue; 548 if (!OrigLI.containsOneValue() && 549 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI) 550 continue; 551 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def) 552 PHIs.push_back(VNI2); 553 else 554 NonPHIs.push_back(VNI2); 555 } 556 DEBUG(dbgs() << "split phi value, checking " << PHIs.size() 557 << " phi-defs, and " << NonPHIs.size() 558 << " non-phi/orig defs\n"); 559 560 // Create entries for all the PHIs. Don't add them to the worklist, we 561 // are processing all of them in one go here. 562 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) 563 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i]))); 564 565 // Add every PHI as a dependent of all the non-PHIs. 566 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) { 567 VNInfo *NonPHI = NonPHIs[i]; 568 // Known value? Try an insertion. 569 std::tie(SVI, Inserted) = 570 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI))); 571 // Add all the PHIs as dependents of NonPHI. 572 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi) 573 SVI->second.Deps.push_back(PHIs[pi]); 574 // This is the first time we see NonPHI, add it to the worklist. 575 if (Inserted) 576 WorkList.push_back(std::make_pair(Reg, NonPHI)); 577 else 578 // Propagate to all inserted PHIs, not just VNI. 579 propagateSiblingValue(SVI); 580 } 581 582 // Next work list item. 583 continue; 584 } 585 586 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 587 assert(MI && "Missing def"); 588 589 // Trace through sibling copies. 590 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) { 591 if (isSibling(SrcReg)) { 592 LiveInterval &SrcLI = LIS.getInterval(SrcReg); 593 LiveQueryResult SrcQ = SrcLI.Query(VNI->def); 594 assert(SrcQ.valueIn() && "Copy from non-existing value"); 595 // Check if this COPY kills its source. 596 SVI->second.KillsSource = SrcQ.isKill(); 597 VNInfo *SrcVNI = SrcQ.valueIn(); 598 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':' 599 << SrcVNI->id << '@' << SrcVNI->def 600 << " kill=" << unsigned(SVI->second.KillsSource) << '\n'); 601 // Known sibling source value? Try an insertion. 602 std::tie(SVI, Inserted) = SibValues.insert( 603 std::make_pair(SrcVNI, SibValueInfo(SrcReg, SrcVNI))); 604 // This is the first time we see Src, add it to the worklist. 605 if (Inserted) 606 WorkList.push_back(std::make_pair(SrcReg, SrcVNI)); 607 propagateSiblingValue(SVI, VNI); 608 // Next work list item. 609 continue; 610 } 611 } 612 613 // Track reachable reloads. 614 SVI->second.DefMI = MI; 615 SVI->second.SpillMBB = MI->getParent(); 616 int FI; 617 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) { 618 DEBUG(dbgs() << "reload\n"); 619 propagateSiblingValue(SVI); 620 // Next work list item. 621 continue; 622 } 623 624 // Potential remat candidate. 625 DEBUG(dbgs() << "def " << *MI); 626 SVI->second.AllDefsAreReloads = false; 627 propagateSiblingValue(SVI); 628 } while (!WorkList.empty()); 629 630 // Look up the value we were looking for. We already did this lookup at the 631 // top of the function, but SibValues may have been invalidated. 632 SVI = SibValues.find(UseVNI); 633 assert(SVI != SibValues.end() && "Didn't compute requested info"); 634 DEBUG(dbgs() << " traced to:\t" << SVI->second); 635 return SVI->second.DefMI; 636 } 637 638 /// analyzeSiblingValues - Trace values defined by sibling copies back to 639 /// something that isn't a sibling copy. 640 /// 641 /// Keep track of values that may be rematerializable. 642 void InlineSpiller::analyzeSiblingValues() { 643 SibValues.clear(); 644 645 // No siblings at all? 646 if (Edit->getReg() == Original) 647 return; 648 649 LiveInterval &OrigLI = LIS.getInterval(Original); 650 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 651 unsigned Reg = RegsToSpill[i]; 652 LiveInterval &LI = LIS.getInterval(Reg); 653 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(), 654 VE = LI.vni_end(); VI != VE; ++VI) { 655 VNInfo *VNI = *VI; 656 if (VNI->isUnused()) 657 continue; 658 MachineInstr *DefMI = nullptr; 659 if (!VNI->isPHIDef()) { 660 DefMI = LIS.getInstructionFromIndex(VNI->def); 661 assert(DefMI && "No defining instruction"); 662 } 663 // Check possible sibling copies. 664 if (VNI->isPHIDef() || DefMI->isCopy()) { 665 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def); 666 assert(OrigVNI && "Def outside original live range"); 667 if (OrigVNI->def != VNI->def) 668 DefMI = traceSiblingValue(Reg, VNI, OrigVNI); 669 } 670 if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) { 671 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@' 672 << VNI->def << " may remat from " << *DefMI); 673 } 674 } 675 } 676 } 677 678 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert 679 /// a spill at a better location. 680 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) { 681 SlotIndex Idx = LIS.getInstructionIndex(CopyMI); 682 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot()); 683 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy"); 684 SibValueMap::iterator I = SibValues.find(VNI); 685 if (I == SibValues.end()) 686 return false; 687 688 const SibValueInfo &SVI = I->second; 689 690 // Let the normal folding code deal with the boring case. 691 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI) 692 return false; 693 694 // SpillReg may have been deleted by remat and DCE. 695 if (!LIS.hasInterval(SVI.SpillReg)) { 696 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n'); 697 SibValues.erase(I); 698 return false; 699 } 700 701 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg); 702 if (!SibLI.containsValue(SVI.SpillVNI)) { 703 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n'); 704 SibValues.erase(I); 705 return false; 706 } 707 708 // Conservatively extend the stack slot range to the range of the original 709 // value. We may be able to do better with stack slot coloring by being more 710 // careful here. 711 assert(StackInt && "No stack slot assigned yet."); 712 LiveInterval &OrigLI = LIS.getInterval(Original); 713 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx); 714 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0)); 715 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": " 716 << *StackInt << '\n'); 717 718 // Already spilled everywhere. 719 if (SVI.AllDefsAreReloads) { 720 DEBUG(dbgs() << "\tno spill needed: " << SVI); 721 ++NumOmitReloadSpill; 722 return true; 723 } 724 // We are going to spill SVI.SpillVNI immediately after its def, so clear out 725 // any later spills of the same value. 726 eliminateRedundantSpills(SibLI, SVI.SpillVNI); 727 728 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def); 729 MachineBasicBlock::iterator MII; 730 if (SVI.SpillVNI->isPHIDef()) 731 MII = MBB->SkipPHIsAndLabels(MBB->begin()); 732 else { 733 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def); 734 assert(DefMI && "Defining instruction disappeared"); 735 MII = DefMI; 736 ++MII; 737 } 738 // Insert spill without kill flag immediately after def. 739 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot, 740 MRI.getRegClass(SVI.SpillReg), &TRI); 741 --MII; // Point to store instruction. 742 LIS.InsertMachineInstrInMaps(MII); 743 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII); 744 745 ++NumSpills; 746 ++NumHoists; 747 return true; 748 } 749 750 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any 751 /// redundant spills of this value in SLI.reg and sibling copies. 752 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) { 753 assert(VNI && "Missing value"); 754 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList; 755 WorkList.push_back(std::make_pair(&SLI, VNI)); 756 assert(StackInt && "No stack slot assigned yet."); 757 758 do { 759 LiveInterval *LI; 760 std::tie(LI, VNI) = WorkList.pop_back_val(); 761 unsigned Reg = LI->reg; 762 DEBUG(dbgs() << "Checking redundant spills for " 763 << VNI->id << '@' << VNI->def << " in " << *LI << '\n'); 764 765 // Regs to spill are taken care of. 766 if (isRegToSpill(Reg)) 767 continue; 768 769 // Add all of VNI's live range to StackInt. 770 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0)); 771 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n'); 772 773 // Find all spills and copies of VNI. 774 for (MachineRegisterInfo::use_instr_nodbg_iterator 775 UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end(); 776 UI != E; ) { 777 MachineInstr *MI = &*(UI++); 778 if (!MI->isCopy() && !MI->mayStore()) 779 continue; 780 SlotIndex Idx = LIS.getInstructionIndex(MI); 781 if (LI->getVNInfoAt(Idx) != VNI) 782 continue; 783 784 // Follow sibling copies down the dominator tree. 785 if (unsigned DstReg = isFullCopyOf(MI, Reg)) { 786 if (isSibling(DstReg)) { 787 LiveInterval &DstLI = LIS.getInterval(DstReg); 788 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot()); 789 assert(DstVNI && "Missing defined value"); 790 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot"); 791 WorkList.push_back(std::make_pair(&DstLI, DstVNI)); 792 } 793 continue; 794 } 795 796 // Erase spills. 797 int FI; 798 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) { 799 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI); 800 // eliminateDeadDefs won't normally remove stores, so switch opcode. 801 MI->setDesc(TII.get(TargetOpcode::KILL)); 802 DeadDefs.push_back(MI); 803 ++NumSpillsRemoved; 804 --NumSpills; 805 } 806 } 807 } while (!WorkList.empty()); 808 } 809 810 811 //===----------------------------------------------------------------------===// 812 // Rematerialization 813 //===----------------------------------------------------------------------===// 814 815 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining 816 /// instruction cannot be eliminated. See through snippet copies 817 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) { 818 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList; 819 WorkList.push_back(std::make_pair(LI, VNI)); 820 do { 821 std::tie(LI, VNI) = WorkList.pop_back_val(); 822 if (!UsedValues.insert(VNI)) 823 continue; 824 825 if (VNI->isPHIDef()) { 826 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); 827 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 828 PE = MBB->pred_end(); PI != PE; ++PI) { 829 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI)); 830 if (PVNI) 831 WorkList.push_back(std::make_pair(LI, PVNI)); 832 } 833 continue; 834 } 835 836 // Follow snippet copies. 837 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 838 if (!SnippetCopies.count(MI)) 839 continue; 840 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg()); 841 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy"); 842 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true)); 843 assert(SnipVNI && "Snippet undefined before copy"); 844 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI)); 845 } while (!WorkList.empty()); 846 } 847 848 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading. 849 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, 850 MachineBasicBlock::iterator MI) { 851 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true); 852 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex()); 853 854 if (!ParentVNI) { 855 DEBUG(dbgs() << "\tadding <undef> flags: "); 856 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 857 MachineOperand &MO = MI->getOperand(i); 858 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) 859 MO.setIsUndef(); 860 } 861 DEBUG(dbgs() << UseIdx << '\t' << *MI); 862 return true; 863 } 864 865 if (SnippetCopies.count(MI)) 866 return false; 867 868 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy. 869 LiveRangeEdit::Remat RM(ParentVNI); 870 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI); 871 if (SibI != SibValues.end()) 872 RM.OrigMI = SibI->second.DefMI; 873 if (!Edit->canRematerializeAt(RM, UseIdx, false)) { 874 markValueUsed(&VirtReg, ParentVNI); 875 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI); 876 return false; 877 } 878 879 // If the instruction also writes VirtReg.reg, it had better not require the 880 // same register for uses and defs. 881 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops; 882 MIBundleOperands::VirtRegInfo RI = 883 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops); 884 if (RI.Tied) { 885 markValueUsed(&VirtReg, ParentVNI); 886 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI); 887 return false; 888 } 889 890 // Before rematerializing into a register for a single instruction, try to 891 // fold a load into the instruction. That avoids allocating a new register. 892 if (RM.OrigMI->canFoldAsLoad() && 893 foldMemoryOperand(Ops, RM.OrigMI)) { 894 Edit->markRematerialized(RM.ParentVNI); 895 ++NumFoldedLoads; 896 return true; 897 } 898 899 // Alocate a new register for the remat. 900 unsigned NewVReg = Edit->createFrom(Original); 901 902 // Finally we can rematerialize OrigMI before MI. 903 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM, 904 TRI); 905 (void)DefIdx; 906 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t' 907 << *LIS.getInstructionFromIndex(DefIdx)); 908 909 // Replace operands 910 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 911 MachineOperand &MO = MI->getOperand(Ops[i].second); 912 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) { 913 MO.setReg(NewVReg); 914 MO.setIsKill(); 915 } 916 } 917 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI << '\n'); 918 919 ++NumRemats; 920 return true; 921 } 922 923 /// reMaterializeAll - Try to rematerialize as many uses as possible, 924 /// and trim the live ranges after. 925 void InlineSpiller::reMaterializeAll() { 926 // analyzeSiblingValues has already tested all relevant defining instructions. 927 if (!Edit->anyRematerializable(AA)) 928 return; 929 930 UsedValues.clear(); 931 932 // Try to remat before all uses of snippets. 933 bool anyRemat = false; 934 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 935 unsigned Reg = RegsToSpill[i]; 936 LiveInterval &LI = LIS.getInterval(Reg); 937 for (MachineRegisterInfo::use_bundle_nodbg_iterator 938 RI = MRI.use_bundle_nodbg_begin(Reg), E = MRI.use_bundle_nodbg_end(); 939 RI != E; ) { 940 MachineInstr *MI = &*(RI++); 941 anyRemat |= reMaterializeFor(LI, MI); 942 } 943 } 944 if (!anyRemat) 945 return; 946 947 // Remove any values that were completely rematted. 948 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 949 unsigned Reg = RegsToSpill[i]; 950 LiveInterval &LI = LIS.getInterval(Reg); 951 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end(); 952 I != E; ++I) { 953 VNInfo *VNI = *I; 954 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI)) 955 continue; 956 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 957 MI->addRegisterDead(Reg, &TRI); 958 if (!MI->allDefsAreDead()) 959 continue; 960 DEBUG(dbgs() << "All defs dead: " << *MI); 961 DeadDefs.push_back(MI); 962 } 963 } 964 965 // Eliminate dead code after remat. Note that some snippet copies may be 966 // deleted here. 967 if (DeadDefs.empty()) 968 return; 969 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n"); 970 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill); 971 972 // Get rid of deleted and empty intervals. 973 unsigned ResultPos = 0; 974 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 975 unsigned Reg = RegsToSpill[i]; 976 if (!LIS.hasInterval(Reg)) 977 continue; 978 979 LiveInterval &LI = LIS.getInterval(Reg); 980 if (LI.empty()) { 981 Edit->eraseVirtReg(Reg); 982 continue; 983 } 984 985 RegsToSpill[ResultPos++] = Reg; 986 } 987 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end()); 988 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"); 989 } 990 991 992 //===----------------------------------------------------------------------===// 993 // Spilling 994 //===----------------------------------------------------------------------===// 995 996 /// If MI is a load or store of StackSlot, it can be removed. 997 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) { 998 int FI = 0; 999 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI); 1000 bool IsLoad = InstrReg; 1001 if (!IsLoad) 1002 InstrReg = TII.isStoreToStackSlot(MI, FI); 1003 1004 // We have a stack access. Is it the right register and slot? 1005 if (InstrReg != Reg || FI != StackSlot) 1006 return false; 1007 1008 DEBUG(dbgs() << "Coalescing stack access: " << *MI); 1009 LIS.RemoveMachineInstrFromMaps(MI); 1010 MI->eraseFromParent(); 1011 1012 if (IsLoad) { 1013 ++NumReloadsRemoved; 1014 --NumReloads; 1015 } else { 1016 ++NumSpillsRemoved; 1017 --NumSpills; 1018 } 1019 1020 return true; 1021 } 1022 1023 #if !defined(NDEBUG) 1024 // Dump the range of instructions from B to E with their slot indexes. 1025 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B, 1026 MachineBasicBlock::iterator E, 1027 LiveIntervals const &LIS, 1028 const char *const header, 1029 unsigned VReg =0) { 1030 char NextLine = '\n'; 1031 char SlotIndent = '\t'; 1032 1033 if (std::next(B) == E) { 1034 NextLine = ' '; 1035 SlotIndent = ' '; 1036 } 1037 1038 dbgs() << '\t' << header << ": " << NextLine; 1039 1040 for (MachineBasicBlock::iterator I = B; I != E; ++I) { 1041 SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot(); 1042 1043 // If a register was passed in and this instruction has it as a 1044 // destination that is marked as an early clobber, print the 1045 // early-clobber slot index. 1046 if (VReg) { 1047 MachineOperand *MO = I->findRegisterDefOperand(VReg); 1048 if (MO && MO->isEarlyClobber()) 1049 Idx = Idx.getRegSlot(true); 1050 } 1051 1052 dbgs() << SlotIndent << Idx << '\t' << *I; 1053 } 1054 } 1055 #endif 1056 1057 /// foldMemoryOperand - Try folding stack slot references in Ops into their 1058 /// instructions. 1059 /// 1060 /// @param Ops Operand indices from analyzeVirtReg(). 1061 /// @param LoadMI Load instruction to use instead of stack slot when non-null. 1062 /// @return True on success. 1063 bool InlineSpiller:: 1064 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops, 1065 MachineInstr *LoadMI) { 1066 if (Ops.empty()) 1067 return false; 1068 // Don't attempt folding in bundles. 1069 MachineInstr *MI = Ops.front().first; 1070 if (Ops.back().first != MI || MI->isBundled()) 1071 return false; 1072 1073 bool WasCopy = MI->isCopy(); 1074 unsigned ImpReg = 0; 1075 1076 bool SpillSubRegs = (MI->getOpcode() == TargetOpcode::PATCHPOINT || 1077 MI->getOpcode() == TargetOpcode::STACKMAP); 1078 1079 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied 1080 // operands. 1081 SmallVector<unsigned, 8> FoldOps; 1082 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1083 unsigned Idx = Ops[i].second; 1084 MachineOperand &MO = MI->getOperand(Idx); 1085 if (MO.isImplicit()) { 1086 ImpReg = MO.getReg(); 1087 continue; 1088 } 1089 // FIXME: Teach targets to deal with subregs. 1090 if (!SpillSubRegs && MO.getSubReg()) 1091 return false; 1092 // We cannot fold a load instruction into a def. 1093 if (LoadMI && MO.isDef()) 1094 return false; 1095 // Tied use operands should not be passed to foldMemoryOperand. 1096 if (!MI->isRegTiedToDefOperand(Idx)) 1097 FoldOps.push_back(Idx); 1098 } 1099 1100 MachineInstrSpan MIS(MI); 1101 1102 MachineInstr *FoldMI = 1103 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI) 1104 : TII.foldMemoryOperand(MI, FoldOps, StackSlot); 1105 if (!FoldMI) 1106 return false; 1107 1108 // Remove LIS for any dead defs in the original MI not in FoldMI. 1109 for (MIBundleOperands MO(MI); MO.isValid(); ++MO) { 1110 if (!MO->isReg()) 1111 continue; 1112 unsigned Reg = MO->getReg(); 1113 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || 1114 MRI.isReserved(Reg)) { 1115 continue; 1116 } 1117 // Skip non-Defs, including undef uses and internal reads. 1118 if (MO->isUse()) 1119 continue; 1120 MIBundleOperands::PhysRegInfo RI = 1121 MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI); 1122 if (RI.Defines) 1123 continue; 1124 // FoldMI does not define this physreg. Remove the LI segment. 1125 assert(MO->isDead() && "Cannot fold physreg def"); 1126 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) { 1127 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) { 1128 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); 1129 if (VNInfo *VNI = LR->getVNInfoAt(Idx)) 1130 LR->removeValNo(VNI); 1131 } 1132 } 1133 } 1134 1135 LIS.ReplaceMachineInstrInMaps(MI, FoldMI); 1136 MI->eraseFromParent(); 1137 1138 // Insert any new instructions other than FoldMI into the LIS maps. 1139 assert(!MIS.empty() && "Unexpected empty span of instructions!"); 1140 for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end(); 1141 MII != End; ++MII) 1142 if (&*MII != FoldMI) 1143 LIS.InsertMachineInstrInMaps(&*MII); 1144 1145 // TII.foldMemoryOperand may have left some implicit operands on the 1146 // instruction. Strip them. 1147 if (ImpReg) 1148 for (unsigned i = FoldMI->getNumOperands(); i; --i) { 1149 MachineOperand &MO = FoldMI->getOperand(i - 1); 1150 if (!MO.isReg() || !MO.isImplicit()) 1151 break; 1152 if (MO.getReg() == ImpReg) 1153 FoldMI->RemoveOperand(i - 1); 1154 } 1155 1156 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS, 1157 "folded")); 1158 1159 if (!WasCopy) 1160 ++NumFolded; 1161 else if (Ops.front().second == 0) 1162 ++NumSpills; 1163 else 1164 ++NumReloads; 1165 return true; 1166 } 1167 1168 void InlineSpiller::insertReload(unsigned NewVReg, 1169 SlotIndex Idx, 1170 MachineBasicBlock::iterator MI) { 1171 MachineBasicBlock &MBB = *MI->getParent(); 1172 1173 MachineInstrSpan MIS(MI); 1174 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot, 1175 MRI.getRegClass(NewVReg), &TRI); 1176 1177 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI); 1178 1179 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload", 1180 NewVReg)); 1181 ++NumReloads; 1182 } 1183 1184 /// insertSpill - Insert a spill of NewVReg after MI. 1185 void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill, 1186 MachineBasicBlock::iterator MI) { 1187 MachineBasicBlock &MBB = *MI->getParent(); 1188 1189 MachineInstrSpan MIS(MI); 1190 TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot, 1191 MRI.getRegClass(NewVReg), &TRI); 1192 1193 LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end()); 1194 1195 DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS, 1196 "spill")); 1197 ++NumSpills; 1198 } 1199 1200 /// spillAroundUses - insert spill code around each use of Reg. 1201 void InlineSpiller::spillAroundUses(unsigned Reg) { 1202 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n'); 1203 LiveInterval &OldLI = LIS.getInterval(Reg); 1204 1205 // Iterate over instructions using Reg. 1206 for (MachineRegisterInfo::reg_bundle_iterator 1207 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end(); 1208 RegI != E; ) { 1209 MachineInstr *MI = &*(RegI++); 1210 1211 // Debug values are not allowed to affect codegen. 1212 if (MI->isDebugValue()) { 1213 // Modify DBG_VALUE now that the value is in a spill slot. 1214 bool IsIndirect = MI->isIndirectDebugValue(); 1215 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0; 1216 const MDNode *MDPtr = MI->getOperand(2).getMetadata(); 1217 DebugLoc DL = MI->getDebugLoc(); 1218 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI); 1219 MachineBasicBlock *MBB = MI->getParent(); 1220 BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE)) 1221 .addFrameIndex(StackSlot).addImm(Offset).addMetadata(MDPtr); 1222 continue; 1223 } 1224 1225 // Ignore copies to/from snippets. We'll delete them. 1226 if (SnippetCopies.count(MI)) 1227 continue; 1228 1229 // Stack slot accesses may coalesce away. 1230 if (coalesceStackAccess(MI, Reg)) 1231 continue; 1232 1233 // Analyze instruction. 1234 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops; 1235 MIBundleOperands::VirtRegInfo RI = 1236 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops); 1237 1238 // Find the slot index where this instruction reads and writes OldLI. 1239 // This is usually the def slot, except for tied early clobbers. 1240 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); 1241 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true))) 1242 if (SlotIndex::isSameInstr(Idx, VNI->def)) 1243 Idx = VNI->def; 1244 1245 // Check for a sibling copy. 1246 unsigned SibReg = isFullCopyOf(MI, Reg); 1247 if (SibReg && isSibling(SibReg)) { 1248 // This may actually be a copy between snippets. 1249 if (isRegToSpill(SibReg)) { 1250 DEBUG(dbgs() << "Found new snippet copy: " << *MI); 1251 SnippetCopies.insert(MI); 1252 continue; 1253 } 1254 if (RI.Writes) { 1255 // Hoist the spill of a sib-reg copy. 1256 if (hoistSpill(OldLI, MI)) { 1257 // This COPY is now dead, the value is already in the stack slot. 1258 MI->getOperand(0).setIsDead(); 1259 DeadDefs.push_back(MI); 1260 continue; 1261 } 1262 } else { 1263 // This is a reload for a sib-reg copy. Drop spills downstream. 1264 LiveInterval &SibLI = LIS.getInterval(SibReg); 1265 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx)); 1266 // The COPY will fold to a reload below. 1267 } 1268 } 1269 1270 // Attempt to fold memory ops. 1271 if (foldMemoryOperand(Ops)) 1272 continue; 1273 1274 // Create a new virtual register for spill/fill. 1275 // FIXME: Infer regclass from instruction alone. 1276 unsigned NewVReg = Edit->createFrom(Reg); 1277 1278 if (RI.Reads) 1279 insertReload(NewVReg, Idx, MI); 1280 1281 // Rewrite instruction operands. 1282 bool hasLiveDef = false; 1283 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1284 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second); 1285 MO.setReg(NewVReg); 1286 if (MO.isUse()) { 1287 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second)) 1288 MO.setIsKill(); 1289 } else { 1290 if (!MO.isDead()) 1291 hasLiveDef = true; 1292 } 1293 } 1294 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n'); 1295 1296 // FIXME: Use a second vreg if instruction has no tied ops. 1297 if (RI.Writes) 1298 if (hasLiveDef) 1299 insertSpill(NewVReg, true, MI); 1300 } 1301 } 1302 1303 /// spillAll - Spill all registers remaining after rematerialization. 1304 void InlineSpiller::spillAll() { 1305 // Update LiveStacks now that we are committed to spilling. 1306 if (StackSlot == VirtRegMap::NO_STACK_SLOT) { 1307 StackSlot = VRM.assignVirt2StackSlot(Original); 1308 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original)); 1309 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator()); 1310 } else 1311 StackInt = &LSS.getInterval(StackSlot); 1312 1313 if (Original != Edit->getReg()) 1314 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot); 1315 1316 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values"); 1317 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 1318 StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]), 1319 StackInt->getValNumInfo(0)); 1320 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n'); 1321 1322 // Spill around uses of all RegsToSpill. 1323 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 1324 spillAroundUses(RegsToSpill[i]); 1325 1326 // Hoisted spills may cause dead code. 1327 if (!DeadDefs.empty()) { 1328 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n"); 1329 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill); 1330 } 1331 1332 // Finally delete the SnippetCopies. 1333 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 1334 for (MachineRegisterInfo::reg_instr_iterator 1335 RI = MRI.reg_instr_begin(RegsToSpill[i]), E = MRI.reg_instr_end(); 1336 RI != E; ) { 1337 MachineInstr *MI = &*(RI++); 1338 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy"); 1339 // FIXME: Do this with a LiveRangeEdit callback. 1340 LIS.RemoveMachineInstrFromMaps(MI); 1341 MI->eraseFromParent(); 1342 } 1343 } 1344 1345 // Delete all spilled registers. 1346 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 1347 Edit->eraseVirtReg(RegsToSpill[i]); 1348 } 1349 1350 void InlineSpiller::spill(LiveRangeEdit &edit) { 1351 ++NumSpilledRanges; 1352 Edit = &edit; 1353 assert(!TargetRegisterInfo::isStackSlot(edit.getReg()) 1354 && "Trying to spill a stack slot."); 1355 // Share a stack slot among all descendants of Original. 1356 Original = VRM.getOriginal(edit.getReg()); 1357 StackSlot = VRM.getStackSlot(Original); 1358 StackInt = nullptr; 1359 1360 DEBUG(dbgs() << "Inline spilling " 1361 << MRI.getRegClass(edit.getReg())->getName() 1362 << ':' << edit.getParent() 1363 << "\nFrom original " << PrintReg(Original) << '\n'); 1364 assert(edit.getParent().isSpillable() && 1365 "Attempting to spill already spilled value."); 1366 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs"); 1367 1368 collectRegsToSpill(); 1369 analyzeSiblingValues(); 1370 reMaterializeAll(); 1371 1372 // Remat may handle everything. 1373 if (!RegsToSpill.empty()) 1374 spillAll(); 1375 1376 Edit->calculateRegClassAndHint(MF, Loops, MBFI); 1377 } 1378