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 852 // Analyze instruction 853 SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops; 854 MIBundleOperands::VirtRegInfo RI = 855 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops); 856 857 if (!RI.Reads) 858 return false; 859 860 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true); 861 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex()); 862 863 if (!ParentVNI) { 864 DEBUG(dbgs() << "\tadding <undef> flags: "); 865 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 866 MachineOperand &MO = MI->getOperand(i); 867 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) 868 MO.setIsUndef(); 869 } 870 DEBUG(dbgs() << UseIdx << '\t' << *MI); 871 return true; 872 } 873 874 if (SnippetCopies.count(MI)) 875 return false; 876 877 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy. 878 LiveRangeEdit::Remat RM(ParentVNI); 879 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI); 880 if (SibI != SibValues.end()) 881 RM.OrigMI = SibI->second.DefMI; 882 if (!Edit->canRematerializeAt(RM, UseIdx, false)) { 883 markValueUsed(&VirtReg, ParentVNI); 884 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI); 885 return false; 886 } 887 888 // If the instruction also writes VirtReg.reg, it had better not require the 889 // same register for uses and defs. 890 if (RI.Tied) { 891 markValueUsed(&VirtReg, ParentVNI); 892 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI); 893 return false; 894 } 895 896 // Before rematerializing into a register for a single instruction, try to 897 // fold a load into the instruction. That avoids allocating a new register. 898 if (RM.OrigMI->canFoldAsLoad() && 899 foldMemoryOperand(Ops, RM.OrigMI)) { 900 Edit->markRematerialized(RM.ParentVNI); 901 ++NumFoldedLoads; 902 return true; 903 } 904 905 // Alocate a new register for the remat. 906 unsigned NewVReg = Edit->createFrom(Original); 907 908 // Finally we can rematerialize OrigMI before MI. 909 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM, 910 TRI); 911 (void)DefIdx; 912 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t' 913 << *LIS.getInstructionFromIndex(DefIdx)); 914 915 // Replace operands 916 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 917 MachineOperand &MO = MI->getOperand(Ops[i].second); 918 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) { 919 MO.setReg(NewVReg); 920 MO.setIsKill(); 921 } 922 } 923 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI << '\n'); 924 925 ++NumRemats; 926 return true; 927 } 928 929 /// reMaterializeAll - Try to rematerialize as many uses as possible, 930 /// and trim the live ranges after. 931 void InlineSpiller::reMaterializeAll() { 932 // analyzeSiblingValues has already tested all relevant defining instructions. 933 if (!Edit->anyRematerializable(AA)) 934 return; 935 936 UsedValues.clear(); 937 938 // Try to remat before all uses of snippets. 939 bool anyRemat = false; 940 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 941 unsigned Reg = RegsToSpill[i]; 942 LiveInterval &LI = LIS.getInterval(Reg); 943 for (MachineRegisterInfo::reg_bundle_iterator 944 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end(); 945 RegI != E; ) { 946 MachineInstr *MI = &*(RegI++); 947 948 // Debug values are not allowed to affect codegen. 949 if (MI->isDebugValue()) 950 continue; 951 952 anyRemat |= reMaterializeFor(LI, MI); 953 } 954 } 955 if (!anyRemat) 956 return; 957 958 // Remove any values that were completely rematted. 959 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 960 unsigned Reg = RegsToSpill[i]; 961 LiveInterval &LI = LIS.getInterval(Reg); 962 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end(); 963 I != E; ++I) { 964 VNInfo *VNI = *I; 965 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI)) 966 continue; 967 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 968 MI->addRegisterDead(Reg, &TRI); 969 if (!MI->allDefsAreDead()) 970 continue; 971 DEBUG(dbgs() << "All defs dead: " << *MI); 972 DeadDefs.push_back(MI); 973 } 974 } 975 976 // Eliminate dead code after remat. Note that some snippet copies may be 977 // deleted here. 978 if (DeadDefs.empty()) 979 return; 980 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n"); 981 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill); 982 983 // Get rid of deleted and empty intervals. 984 unsigned ResultPos = 0; 985 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 986 unsigned Reg = RegsToSpill[i]; 987 if (!LIS.hasInterval(Reg)) 988 continue; 989 990 LiveInterval &LI = LIS.getInterval(Reg); 991 if (LI.empty()) { 992 Edit->eraseVirtReg(Reg); 993 continue; 994 } 995 996 RegsToSpill[ResultPos++] = Reg; 997 } 998 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end()); 999 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"); 1000 } 1001 1002 1003 //===----------------------------------------------------------------------===// 1004 // Spilling 1005 //===----------------------------------------------------------------------===// 1006 1007 /// If MI is a load or store of StackSlot, it can be removed. 1008 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) { 1009 int FI = 0; 1010 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI); 1011 bool IsLoad = InstrReg; 1012 if (!IsLoad) 1013 InstrReg = TII.isStoreToStackSlot(MI, FI); 1014 1015 // We have a stack access. Is it the right register and slot? 1016 if (InstrReg != Reg || FI != StackSlot) 1017 return false; 1018 1019 DEBUG(dbgs() << "Coalescing stack access: " << *MI); 1020 LIS.RemoveMachineInstrFromMaps(MI); 1021 MI->eraseFromParent(); 1022 1023 if (IsLoad) { 1024 ++NumReloadsRemoved; 1025 --NumReloads; 1026 } else { 1027 ++NumSpillsRemoved; 1028 --NumSpills; 1029 } 1030 1031 return true; 1032 } 1033 1034 #if !defined(NDEBUG) 1035 // Dump the range of instructions from B to E with their slot indexes. 1036 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B, 1037 MachineBasicBlock::iterator E, 1038 LiveIntervals const &LIS, 1039 const char *const header, 1040 unsigned VReg =0) { 1041 char NextLine = '\n'; 1042 char SlotIndent = '\t'; 1043 1044 if (std::next(B) == E) { 1045 NextLine = ' '; 1046 SlotIndent = ' '; 1047 } 1048 1049 dbgs() << '\t' << header << ": " << NextLine; 1050 1051 for (MachineBasicBlock::iterator I = B; I != E; ++I) { 1052 SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot(); 1053 1054 // If a register was passed in and this instruction has it as a 1055 // destination that is marked as an early clobber, print the 1056 // early-clobber slot index. 1057 if (VReg) { 1058 MachineOperand *MO = I->findRegisterDefOperand(VReg); 1059 if (MO && MO->isEarlyClobber()) 1060 Idx = Idx.getRegSlot(true); 1061 } 1062 1063 dbgs() << SlotIndent << Idx << '\t' << *I; 1064 } 1065 } 1066 #endif 1067 1068 /// foldMemoryOperand - Try folding stack slot references in Ops into their 1069 /// instructions. 1070 /// 1071 /// @param Ops Operand indices from analyzeVirtReg(). 1072 /// @param LoadMI Load instruction to use instead of stack slot when non-null. 1073 /// @return True on success. 1074 bool InlineSpiller:: 1075 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops, 1076 MachineInstr *LoadMI) { 1077 if (Ops.empty()) 1078 return false; 1079 // Don't attempt folding in bundles. 1080 MachineInstr *MI = Ops.front().first; 1081 if (Ops.back().first != MI || MI->isBundled()) 1082 return false; 1083 1084 bool WasCopy = MI->isCopy(); 1085 unsigned ImpReg = 0; 1086 1087 bool SpillSubRegs = (MI->getOpcode() == TargetOpcode::PATCHPOINT || 1088 MI->getOpcode() == TargetOpcode::STACKMAP); 1089 1090 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied 1091 // operands. 1092 SmallVector<unsigned, 8> FoldOps; 1093 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1094 unsigned Idx = Ops[i].second; 1095 MachineOperand &MO = MI->getOperand(Idx); 1096 if (MO.isImplicit()) { 1097 ImpReg = MO.getReg(); 1098 continue; 1099 } 1100 // FIXME: Teach targets to deal with subregs. 1101 if (!SpillSubRegs && MO.getSubReg()) 1102 return false; 1103 // We cannot fold a load instruction into a def. 1104 if (LoadMI && MO.isDef()) 1105 return false; 1106 // Tied use operands should not be passed to foldMemoryOperand. 1107 if (!MI->isRegTiedToDefOperand(Idx)) 1108 FoldOps.push_back(Idx); 1109 } 1110 1111 MachineInstrSpan MIS(MI); 1112 1113 MachineInstr *FoldMI = 1114 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI) 1115 : TII.foldMemoryOperand(MI, FoldOps, StackSlot); 1116 if (!FoldMI) 1117 return false; 1118 1119 // Remove LIS for any dead defs in the original MI not in FoldMI. 1120 for (MIBundleOperands MO(MI); MO.isValid(); ++MO) { 1121 if (!MO->isReg()) 1122 continue; 1123 unsigned Reg = MO->getReg(); 1124 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) || 1125 MRI.isReserved(Reg)) { 1126 continue; 1127 } 1128 // Skip non-Defs, including undef uses and internal reads. 1129 if (MO->isUse()) 1130 continue; 1131 MIBundleOperands::PhysRegInfo RI = 1132 MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI); 1133 if (RI.Defines) 1134 continue; 1135 // FoldMI does not define this physreg. Remove the LI segment. 1136 assert(MO->isDead() && "Cannot fold physreg def"); 1137 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) { 1138 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) { 1139 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); 1140 if (VNInfo *VNI = LR->getVNInfoAt(Idx)) 1141 LR->removeValNo(VNI); 1142 } 1143 } 1144 } 1145 1146 LIS.ReplaceMachineInstrInMaps(MI, FoldMI); 1147 MI->eraseFromParent(); 1148 1149 // Insert any new instructions other than FoldMI into the LIS maps. 1150 assert(!MIS.empty() && "Unexpected empty span of instructions!"); 1151 for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end(); 1152 MII != End; ++MII) 1153 if (&*MII != FoldMI) 1154 LIS.InsertMachineInstrInMaps(&*MII); 1155 1156 // TII.foldMemoryOperand may have left some implicit operands on the 1157 // instruction. Strip them. 1158 if (ImpReg) 1159 for (unsigned i = FoldMI->getNumOperands(); i; --i) { 1160 MachineOperand &MO = FoldMI->getOperand(i - 1); 1161 if (!MO.isReg() || !MO.isImplicit()) 1162 break; 1163 if (MO.getReg() == ImpReg) 1164 FoldMI->RemoveOperand(i - 1); 1165 } 1166 1167 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS, 1168 "folded")); 1169 1170 if (!WasCopy) 1171 ++NumFolded; 1172 else if (Ops.front().second == 0) 1173 ++NumSpills; 1174 else 1175 ++NumReloads; 1176 return true; 1177 } 1178 1179 void InlineSpiller::insertReload(unsigned NewVReg, 1180 SlotIndex Idx, 1181 MachineBasicBlock::iterator MI) { 1182 MachineBasicBlock &MBB = *MI->getParent(); 1183 1184 MachineInstrSpan MIS(MI); 1185 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot, 1186 MRI.getRegClass(NewVReg), &TRI); 1187 1188 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI); 1189 1190 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload", 1191 NewVReg)); 1192 ++NumReloads; 1193 } 1194 1195 /// insertSpill - Insert a spill of NewVReg after MI. 1196 void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill, 1197 MachineBasicBlock::iterator MI) { 1198 MachineBasicBlock &MBB = *MI->getParent(); 1199 1200 MachineInstrSpan MIS(MI); 1201 TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot, 1202 MRI.getRegClass(NewVReg), &TRI); 1203 1204 LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end()); 1205 1206 DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS, 1207 "spill")); 1208 ++NumSpills; 1209 } 1210 1211 /// spillAroundUses - insert spill code around each use of Reg. 1212 void InlineSpiller::spillAroundUses(unsigned Reg) { 1213 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n'); 1214 LiveInterval &OldLI = LIS.getInterval(Reg); 1215 1216 // Iterate over instructions using Reg. 1217 for (MachineRegisterInfo::reg_bundle_iterator 1218 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end(); 1219 RegI != E; ) { 1220 MachineInstr *MI = &*(RegI++); 1221 1222 // Debug values are not allowed to affect codegen. 1223 if (MI->isDebugValue()) { 1224 // Modify DBG_VALUE now that the value is in a spill slot. 1225 bool IsIndirect = MI->isIndirectDebugValue(); 1226 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0; 1227 const MDNode *MDPtr = MI->getOperand(2).getMetadata(); 1228 DebugLoc DL = MI->getDebugLoc(); 1229 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI); 1230 MachineBasicBlock *MBB = MI->getParent(); 1231 BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE)) 1232 .addFrameIndex(StackSlot).addImm(Offset).addMetadata(MDPtr); 1233 continue; 1234 } 1235 1236 // Ignore copies to/from snippets. We'll delete them. 1237 if (SnippetCopies.count(MI)) 1238 continue; 1239 1240 // Stack slot accesses may coalesce away. 1241 if (coalesceStackAccess(MI, Reg)) 1242 continue; 1243 1244 // Analyze instruction. 1245 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops; 1246 MIBundleOperands::VirtRegInfo RI = 1247 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops); 1248 1249 // Find the slot index where this instruction reads and writes OldLI. 1250 // This is usually the def slot, except for tied early clobbers. 1251 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot(); 1252 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true))) 1253 if (SlotIndex::isSameInstr(Idx, VNI->def)) 1254 Idx = VNI->def; 1255 1256 // Check for a sibling copy. 1257 unsigned SibReg = isFullCopyOf(MI, Reg); 1258 if (SibReg && isSibling(SibReg)) { 1259 // This may actually be a copy between snippets. 1260 if (isRegToSpill(SibReg)) { 1261 DEBUG(dbgs() << "Found new snippet copy: " << *MI); 1262 SnippetCopies.insert(MI); 1263 continue; 1264 } 1265 if (RI.Writes) { 1266 // Hoist the spill of a sib-reg copy. 1267 if (hoistSpill(OldLI, MI)) { 1268 // This COPY is now dead, the value is already in the stack slot. 1269 MI->getOperand(0).setIsDead(); 1270 DeadDefs.push_back(MI); 1271 continue; 1272 } 1273 } else { 1274 // This is a reload for a sib-reg copy. Drop spills downstream. 1275 LiveInterval &SibLI = LIS.getInterval(SibReg); 1276 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx)); 1277 // The COPY will fold to a reload below. 1278 } 1279 } 1280 1281 // Attempt to fold memory ops. 1282 if (foldMemoryOperand(Ops)) 1283 continue; 1284 1285 // Create a new virtual register for spill/fill. 1286 // FIXME: Infer regclass from instruction alone. 1287 unsigned NewVReg = Edit->createFrom(Reg); 1288 1289 if (RI.Reads) 1290 insertReload(NewVReg, Idx, MI); 1291 1292 // Rewrite instruction operands. 1293 bool hasLiveDef = false; 1294 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 1295 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second); 1296 MO.setReg(NewVReg); 1297 if (MO.isUse()) { 1298 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second)) 1299 MO.setIsKill(); 1300 } else { 1301 if (!MO.isDead()) 1302 hasLiveDef = true; 1303 } 1304 } 1305 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n'); 1306 1307 // FIXME: Use a second vreg if instruction has no tied ops. 1308 if (RI.Writes) 1309 if (hasLiveDef) 1310 insertSpill(NewVReg, true, MI); 1311 } 1312 } 1313 1314 /// spillAll - Spill all registers remaining after rematerialization. 1315 void InlineSpiller::spillAll() { 1316 // Update LiveStacks now that we are committed to spilling. 1317 if (StackSlot == VirtRegMap::NO_STACK_SLOT) { 1318 StackSlot = VRM.assignVirt2StackSlot(Original); 1319 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original)); 1320 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator()); 1321 } else 1322 StackInt = &LSS.getInterval(StackSlot); 1323 1324 if (Original != Edit->getReg()) 1325 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot); 1326 1327 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values"); 1328 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 1329 StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]), 1330 StackInt->getValNumInfo(0)); 1331 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n'); 1332 1333 // Spill around uses of all RegsToSpill. 1334 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 1335 spillAroundUses(RegsToSpill[i]); 1336 1337 // Hoisted spills may cause dead code. 1338 if (!DeadDefs.empty()) { 1339 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n"); 1340 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill); 1341 } 1342 1343 // Finally delete the SnippetCopies. 1344 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 1345 for (MachineRegisterInfo::reg_instr_iterator 1346 RI = MRI.reg_instr_begin(RegsToSpill[i]), E = MRI.reg_instr_end(); 1347 RI != E; ) { 1348 MachineInstr *MI = &*(RI++); 1349 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy"); 1350 // FIXME: Do this with a LiveRangeEdit callback. 1351 LIS.RemoveMachineInstrFromMaps(MI); 1352 MI->eraseFromParent(); 1353 } 1354 } 1355 1356 // Delete all spilled registers. 1357 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 1358 Edit->eraseVirtReg(RegsToSpill[i]); 1359 } 1360 1361 void InlineSpiller::spill(LiveRangeEdit &edit) { 1362 ++NumSpilledRanges; 1363 Edit = &edit; 1364 assert(!TargetRegisterInfo::isStackSlot(edit.getReg()) 1365 && "Trying to spill a stack slot."); 1366 // Share a stack slot among all descendants of Original. 1367 Original = VRM.getOriginal(edit.getReg()); 1368 StackSlot = VRM.getStackSlot(Original); 1369 StackInt = nullptr; 1370 1371 DEBUG(dbgs() << "Inline spilling " 1372 << MRI.getRegClass(edit.getReg())->getName() 1373 << ':' << edit.getParent() 1374 << "\nFrom original " << PrintReg(Original) << '\n'); 1375 assert(edit.getParent().isSpillable() && 1376 "Attempting to spill already spilled value."); 1377 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs"); 1378 1379 collectRegsToSpill(); 1380 analyzeSiblingValues(); 1381 reMaterializeAll(); 1382 1383 // Remat may handle everything. 1384 if (!RegsToSpill.empty()) 1385 spillAll(); 1386 1387 Edit->calculateRegClassAndHint(MF, Loops, MBFI); 1388 } 1389