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