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/Analysis/AliasAnalysis.h" 20 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 21 #include "llvm/CodeGen/LiveStackAnalysis.h" 22 #include "llvm/CodeGen/MachineDominators.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/CodeGen/MachineLoopInfo.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/Target/TargetMachine.h" 28 #include "llvm/Target/TargetInstrInfo.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 using namespace llvm; 33 34 namespace { 35 class InlineSpiller : public Spiller { 36 MachineFunctionPass &Pass; 37 MachineFunction &MF; 38 LiveIntervals &LIS; 39 LiveStacks &LSS; 40 AliasAnalysis *AA; 41 MachineDominatorTree &MDT; 42 MachineLoopInfo &Loops; 43 VirtRegMap &VRM; 44 MachineFrameInfo &MFI; 45 MachineRegisterInfo &MRI; 46 const TargetInstrInfo &TII; 47 const TargetRegisterInfo &TRI; 48 49 // Variables that are valid during spill(), but used by multiple methods. 50 LiveRangeEdit *Edit; 51 LiveInterval *StackInt; 52 int StackSlot; 53 unsigned Original; 54 55 // All registers to spill to StackSlot, including the main register. 56 SmallVector<unsigned, 8> RegsToSpill; 57 58 // All COPY instructions to/from snippets. 59 // They are ignored since both operands refer to the same stack slot. 60 SmallPtrSet<MachineInstr*, 8> SnippetCopies; 61 62 // Values that failed to remat at some point. 63 SmallPtrSet<VNInfo*, 8> UsedValues; 64 65 // Information about a value that was defined by a copy from a sibling 66 // register. 67 struct SibValueInfo { 68 // True when all reaching defs were reloads: No spill is necessary. 69 bool AllDefsAreReloads; 70 71 // The preferred register to spill. 72 unsigned SpillReg; 73 74 // The value of SpillReg that should be spilled. 75 VNInfo *SpillVNI; 76 77 // A defining instruction that is not a sibling copy or a reload, or NULL. 78 // This can be used as a template for rematerialization. 79 MachineInstr *DefMI; 80 81 SibValueInfo(unsigned Reg, VNInfo *VNI) 82 : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {} 83 }; 84 85 // Values in RegsToSpill defined by sibling copies. 86 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap; 87 SibValueMap SibValues; 88 89 // Dead defs generated during spilling. 90 SmallVector<MachineInstr*, 8> DeadDefs; 91 92 ~InlineSpiller() {} 93 94 public: 95 InlineSpiller(MachineFunctionPass &pass, 96 MachineFunction &mf, 97 VirtRegMap &vrm) 98 : Pass(pass), 99 MF(mf), 100 LIS(pass.getAnalysis<LiveIntervals>()), 101 LSS(pass.getAnalysis<LiveStacks>()), 102 AA(&pass.getAnalysis<AliasAnalysis>()), 103 MDT(pass.getAnalysis<MachineDominatorTree>()), 104 Loops(pass.getAnalysis<MachineLoopInfo>()), 105 VRM(vrm), 106 MFI(*mf.getFrameInfo()), 107 MRI(mf.getRegInfo()), 108 TII(*mf.getTarget().getInstrInfo()), 109 TRI(*mf.getTarget().getRegisterInfo()) {} 110 111 void spill(LiveRangeEdit &); 112 113 private: 114 bool isSnippet(const LiveInterval &SnipLI); 115 void collectRegsToSpill(); 116 117 bool isRegToSpill(unsigned Reg) { 118 return std::find(RegsToSpill.begin(), 119 RegsToSpill.end(), Reg) != RegsToSpill.end(); 120 } 121 122 bool isSibling(unsigned Reg); 123 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*); 124 void analyzeSiblingValues(); 125 126 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI); 127 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI); 128 129 void markValueUsed(LiveInterval*, VNInfo*); 130 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI); 131 void reMaterializeAll(); 132 133 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg); 134 bool foldMemoryOperand(MachineBasicBlock::iterator MI, 135 const SmallVectorImpl<unsigned> &Ops, 136 MachineInstr *LoadMI = 0); 137 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI); 138 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI, 139 MachineBasicBlock::iterator MI); 140 141 void spillAroundUses(unsigned Reg); 142 void spillAll(); 143 }; 144 } 145 146 namespace llvm { 147 Spiller *createInlineSpiller(MachineFunctionPass &pass, 148 MachineFunction &mf, 149 VirtRegMap &vrm) { 150 return new InlineSpiller(pass, mf, vrm); 151 } 152 } 153 154 //===----------------------------------------------------------------------===// 155 // Snippets 156 //===----------------------------------------------------------------------===// 157 158 // When spilling a virtual register, we also spill any snippets it is connected 159 // to. The snippets are small live ranges that only have a single real use, 160 // leftovers from live range splitting. Spilling them enables memory operand 161 // folding or tightens the live range around the single use. 162 // 163 // This minimizes register pressure and maximizes the store-to-load distance for 164 // spill slots which can be important in tight loops. 165 166 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register, 167 /// otherwise return 0. 168 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) { 169 if (!MI->isCopy()) 170 return 0; 171 if (MI->getOperand(0).getSubReg() != 0) 172 return 0; 173 if (MI->getOperand(1).getSubReg() != 0) 174 return 0; 175 if (MI->getOperand(0).getReg() == Reg) 176 return MI->getOperand(1).getReg(); 177 if (MI->getOperand(1).getReg() == Reg) 178 return MI->getOperand(0).getReg(); 179 return 0; 180 } 181 182 /// isSnippet - Identify if a live interval is a snippet that should be spilled. 183 /// It is assumed that SnipLI is a virtual register with the same original as 184 /// Edit->getReg(). 185 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) { 186 unsigned Reg = Edit->getReg(); 187 188 // A snippet is a tiny live range with only a single instruction using it 189 // besides copies to/from Reg or spills/fills. We accept: 190 // 191 // %snip = COPY %Reg / FILL fi# 192 // %snip = USE %snip 193 // %Reg = COPY %snip / SPILL %snip, fi# 194 // 195 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI)) 196 return false; 197 198 MachineInstr *UseMI = 0; 199 200 // Check that all uses satisfy our criteria. 201 for (MachineRegisterInfo::reg_nodbg_iterator 202 RI = MRI.reg_nodbg_begin(SnipLI.reg); 203 MachineInstr *MI = RI.skipInstruction();) { 204 205 // Allow copies to/from Reg. 206 if (isFullCopyOf(MI, Reg)) 207 continue; 208 209 // Allow stack slot loads. 210 int FI; 211 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) 212 continue; 213 214 // Allow stack slot stores. 215 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) 216 continue; 217 218 // Allow a single additional instruction. 219 if (UseMI && MI != UseMI) 220 return false; 221 UseMI = MI; 222 } 223 return true; 224 } 225 226 /// collectRegsToSpill - Collect live range snippets that only have a single 227 /// real use. 228 void InlineSpiller::collectRegsToSpill() { 229 unsigned Reg = Edit->getReg(); 230 231 // Main register always spills. 232 RegsToSpill.assign(1, Reg); 233 SnippetCopies.clear(); 234 235 // Snippets all have the same original, so there can't be any for an original 236 // register. 237 if (Original == Reg) 238 return; 239 240 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg); 241 MachineInstr *MI = RI.skipInstruction();) { 242 unsigned SnipReg = isFullCopyOf(MI, Reg); 243 if (!isSibling(SnipReg)) 244 continue; 245 LiveInterval &SnipLI = LIS.getInterval(SnipReg); 246 if (!isSnippet(SnipLI)) 247 continue; 248 SnippetCopies.insert(MI); 249 if (!isRegToSpill(SnipReg)) 250 RegsToSpill.push_back(SnipReg); 251 252 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n'); 253 } 254 } 255 256 257 //===----------------------------------------------------------------------===// 258 // Sibling Values 259 //===----------------------------------------------------------------------===// 260 261 // After live range splitting, some values to be spilled may be defined by 262 // copies from sibling registers. We trace the sibling copies back to the 263 // original value if it still exists. We need it for rematerialization. 264 // 265 // Even when the value can't be rematerialized, we still want to determine if 266 // the value has already been spilled, or we may want to hoist the spill from a 267 // loop. 268 269 bool InlineSpiller::isSibling(unsigned Reg) { 270 return TargetRegisterInfo::isVirtualRegister(Reg) && 271 VRM.getOriginal(Reg) == Original; 272 } 273 274 /// traceSiblingValue - Trace a value that is about to be spilled back to the 275 /// real defining instructions by looking through sibling copies. Always stay 276 /// within the range of OrigVNI so the registers are known to carry the same 277 /// value. 278 /// 279 /// Determine if the value is defined by all reloads, so spilling isn't 280 /// necessary - the value is already in the stack slot. 281 /// 282 /// Return a defining instruction that may be a candidate for rematerialization. 283 /// 284 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI, 285 VNInfo *OrigVNI) { 286 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':' 287 << UseVNI->id << '@' << UseVNI->def << '\n'); 288 SmallPtrSet<VNInfo*, 8> Visited; 289 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList; 290 WorkList.push_back(std::make_pair(UseReg, UseVNI)); 291 292 // Best spill candidate seen so far. This must dominate UseVNI. 293 SibValueInfo SVI(UseReg, UseVNI); 294 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def); 295 unsigned SpillDepth = Loops.getLoopDepth(UseMBB); 296 bool SeenOrigPHI = false; // Original PHI met. 297 298 do { 299 unsigned Reg; 300 VNInfo *VNI; 301 tie(Reg, VNI) = WorkList.pop_back_val(); 302 if (!Visited.insert(VNI)) 303 continue; 304 305 // Is this value a better spill candidate? 306 if (!isRegToSpill(Reg)) { 307 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); 308 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) { 309 // This is a valid spill location dominating UseVNI. 310 // Prefer to spill at a smaller loop depth. 311 unsigned Depth = Loops.getLoopDepth(MBB); 312 if (Depth < SpillDepth) { 313 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg) 314 << ':' << VNI->id << '@' << VNI->def << '\n'); 315 SVI.SpillReg = Reg; 316 SVI.SpillVNI = VNI; 317 SpillDepth = Depth; 318 } 319 } 320 } 321 322 // Trace through PHI-defs created by live range splitting. 323 if (VNI->isPHIDef()) { 324 if (VNI->def == OrigVNI->def) { 325 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':' 326 << VNI->id << '@' << VNI->def << '\n'); 327 SeenOrigPHI = true; 328 continue; 329 } 330 // Get values live-out of predecessors. 331 LiveInterval &LI = LIS.getInterval(Reg); 332 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); 333 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 334 PE = MBB->pred_end(); PI != PE; ++PI) { 335 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot()); 336 if (PVNI) 337 WorkList.push_back(std::make_pair(Reg, PVNI)); 338 } 339 continue; 340 } 341 342 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 343 assert(MI && "Missing def"); 344 345 // Trace through sibling copies. 346 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) { 347 if (isSibling(SrcReg)) { 348 LiveInterval &SrcLI = LIS.getInterval(SrcReg); 349 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex()); 350 assert(SrcVNI && "Copy from non-existing value"); 351 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':' 352 << SrcVNI->id << '@' << SrcVNI->def << '\n'); 353 WorkList.push_back(std::make_pair(SrcReg, SrcVNI)); 354 continue; 355 } 356 } 357 358 // Track reachable reloads. 359 int FI; 360 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) { 361 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':' 362 << VNI->id << "@" << VNI->def << '\n'); 363 SVI.AllDefsAreReloads = true; 364 continue; 365 } 366 367 // We have an 'original' def. Don't record trivial cases. 368 if (VNI == UseVNI) { 369 DEBUG(dbgs() << "Not a sibling copy.\n"); 370 return MI; 371 } 372 373 // Potential remat candidate. 374 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':' 375 << VNI->id << '@' << VNI->def << '\t' << *MI); 376 SVI.DefMI = MI; 377 } while (!WorkList.empty()); 378 379 if (SeenOrigPHI || SVI.DefMI) 380 SVI.AllDefsAreReloads = false; 381 382 DEBUG({ 383 if (SVI.AllDefsAreReloads) 384 dbgs() << "All defs are reloads.\n"; 385 else 386 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':' 387 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n'; 388 }); 389 SibValues.insert(std::make_pair(UseVNI, SVI)); 390 return SVI.DefMI; 391 } 392 393 /// analyzeSiblingValues - Trace values defined by sibling copies back to 394 /// something that isn't a sibling copy. 395 /// 396 /// Keep track of values that may be rematerializable. 397 void InlineSpiller::analyzeSiblingValues() { 398 SibValues.clear(); 399 400 // No siblings at all? 401 if (Edit->getReg() == Original) 402 return; 403 404 LiveInterval &OrigLI = LIS.getInterval(Original); 405 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 406 unsigned Reg = RegsToSpill[i]; 407 LiveInterval &LI = LIS.getInterval(Reg); 408 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(), 409 VE = LI.vni_end(); VI != VE; ++VI) { 410 VNInfo *VNI = *VI; 411 if (VNI->isUnused()) 412 continue; 413 MachineInstr *DefMI = 0; 414 // Check possible sibling copies. 415 if (VNI->isPHIDef() || VNI->getCopy()) { 416 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def); 417 if (OrigVNI->def != VNI->def) 418 DefMI = traceSiblingValue(Reg, VNI, OrigVNI); 419 } 420 if (!DefMI && !VNI->isPHIDef()) 421 DefMI = LIS.getInstructionFromIndex(VNI->def); 422 if (DefMI) 423 Edit->checkRematerializable(VNI, DefMI, TII, AA); 424 } 425 } 426 } 427 428 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert 429 /// a spill at a better location. 430 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) { 431 SlotIndex Idx = LIS.getInstructionIndex(CopyMI); 432 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex()); 433 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy"); 434 SibValueMap::const_iterator I = SibValues.find(VNI); 435 if (I == SibValues.end()) 436 return false; 437 438 const SibValueInfo &SVI = I->second; 439 440 // Let the normal folding code deal with the boring case. 441 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI) 442 return false; 443 444 // Conservatively extend the stack slot range to the range of the original 445 // value. We may be able to do better with stack slot coloring by being more 446 // careful here. 447 assert(StackInt && "No stack slot assigned yet."); 448 LiveInterval &OrigLI = LIS.getInterval(Original); 449 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx); 450 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0)); 451 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": " 452 << *StackInt << '\n'); 453 454 // Already spilled everywhere. 455 if (SVI.AllDefsAreReloads) 456 return true; 457 458 // We are going to spill SVI.SpillVNI immediately after its def, so clear out 459 // any later spills of the same value. 460 eliminateRedundantSpills(LIS.getInterval(SVI.SpillReg), SVI.SpillVNI); 461 462 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def); 463 MachineBasicBlock::iterator MII; 464 if (SVI.SpillVNI->isPHIDef()) 465 MII = MBB->SkipPHIsAndLabels(MBB->begin()); 466 else { 467 MII = LIS.getInstructionFromIndex(SVI.SpillVNI->def); 468 ++MII; 469 } 470 // Insert spill without kill flag immediately after def. 471 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot, 472 MRI.getRegClass(SVI.SpillReg), &TRI); 473 --MII; // Point to store instruction. 474 LIS.InsertMachineInstrInMaps(MII); 475 VRM.addSpillSlotUse(StackSlot, MII); 476 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII); 477 return true; 478 } 479 480 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any 481 /// redundant spills of this value in SLI.reg and sibling copies. 482 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) { 483 assert(VNI && "Missing value"); 484 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList; 485 WorkList.push_back(std::make_pair(&SLI, VNI)); 486 assert(StackInt && "No stack slot assigned yet."); 487 488 do { 489 LiveInterval *LI; 490 tie(LI, VNI) = WorkList.pop_back_val(); 491 unsigned Reg = LI->reg; 492 DEBUG(dbgs() << "Checking redundant spills for " << PrintReg(Reg) << ':' 493 << VNI->id << '@' << VNI->def << '\n'); 494 495 // Regs to spill are taken care of. 496 if (isRegToSpill(Reg)) 497 continue; 498 499 // Add all of VNI's live range to StackInt. 500 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0)); 501 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n'); 502 503 // Find all spills and copies of VNI. 504 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg); 505 MachineInstr *MI = UI.skipInstruction();) { 506 if (!MI->isCopy() && !MI->getDesc().mayStore()) 507 continue; 508 SlotIndex Idx = LIS.getInstructionIndex(MI); 509 if (LI->getVNInfoAt(Idx) != VNI) 510 continue; 511 512 // Follow sibling copies down the dominator tree. 513 if (unsigned DstReg = isFullCopyOf(MI, Reg)) { 514 if (isSibling(DstReg)) { 515 LiveInterval &DstLI = LIS.getInterval(DstReg); 516 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex()); 517 assert(DstVNI && "Missing defined value"); 518 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot"); 519 WorkList.push_back(std::make_pair(&DstLI, DstVNI)); 520 } 521 continue; 522 } 523 524 // Erase spills. 525 int FI; 526 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) { 527 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI); 528 // eliminateDeadDefs won't normally remove stores, so switch opcode. 529 MI->setDesc(TII.get(TargetOpcode::KILL)); 530 DeadDefs.push_back(MI); 531 } 532 } 533 } while (!WorkList.empty()); 534 } 535 536 537 //===----------------------------------------------------------------------===// 538 // Rematerialization 539 //===----------------------------------------------------------------------===// 540 541 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining 542 /// instruction cannot be eliminated. See through snippet copies 543 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) { 544 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList; 545 WorkList.push_back(std::make_pair(LI, VNI)); 546 do { 547 tie(LI, VNI) = WorkList.pop_back_val(); 548 if (!UsedValues.insert(VNI)) 549 continue; 550 551 if (VNI->isPHIDef()) { 552 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); 553 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(), 554 PE = MBB->pred_end(); PI != PE; ++PI) { 555 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot()); 556 if (PVNI) 557 WorkList.push_back(std::make_pair(LI, PVNI)); 558 } 559 continue; 560 } 561 562 // Follow snippet copies. 563 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 564 if (!SnippetCopies.count(MI)) 565 continue; 566 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg()); 567 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy"); 568 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex()); 569 assert(SnipVNI && "Snippet undefined before copy"); 570 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI)); 571 } while (!WorkList.empty()); 572 } 573 574 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading. 575 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, 576 MachineBasicBlock::iterator MI) { 577 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex(); 578 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx); 579 580 if (!ParentVNI) { 581 DEBUG(dbgs() << "\tadding <undef> flags: "); 582 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 583 MachineOperand &MO = MI->getOperand(i); 584 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) 585 MO.setIsUndef(); 586 } 587 DEBUG(dbgs() << UseIdx << '\t' << *MI); 588 return true; 589 } 590 591 if (SnippetCopies.count(MI)) 592 return false; 593 594 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy. 595 LiveRangeEdit::Remat RM(ParentVNI); 596 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI); 597 if (SibI != SibValues.end()) 598 RM.OrigMI = SibI->second.DefMI; 599 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) { 600 markValueUsed(&VirtReg, ParentVNI); 601 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI); 602 return false; 603 } 604 605 // If the instruction also writes VirtReg.reg, it had better not require the 606 // same register for uses and defs. 607 bool Reads, Writes; 608 SmallVector<unsigned, 8> Ops; 609 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops); 610 if (Writes) { 611 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 612 MachineOperand &MO = MI->getOperand(Ops[i]); 613 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) { 614 markValueUsed(&VirtReg, ParentVNI); 615 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI); 616 return false; 617 } 618 } 619 } 620 621 // Before rematerializing into a register for a single instruction, try to 622 // fold a load into the instruction. That avoids allocating a new register. 623 if (RM.OrigMI->getDesc().canFoldAsLoad() && 624 foldMemoryOperand(MI, Ops, RM.OrigMI)) { 625 Edit->markRematerialized(RM.ParentVNI); 626 return true; 627 } 628 629 // Alocate a new register for the remat. 630 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM); 631 NewLI.markNotSpillable(); 632 633 // Finally we can rematerialize OrigMI before MI. 634 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM, 635 LIS, TII, TRI); 636 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t' 637 << *LIS.getInstructionFromIndex(DefIdx)); 638 639 // Replace operands 640 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 641 MachineOperand &MO = MI->getOperand(Ops[i]); 642 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) { 643 MO.setReg(NewLI.reg); 644 MO.setIsKill(); 645 } 646 } 647 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI); 648 649 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator()); 650 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI)); 651 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n'); 652 return true; 653 } 654 655 /// reMaterializeAll - Try to rematerialize as many uses as possible, 656 /// and trim the live ranges after. 657 void InlineSpiller::reMaterializeAll() { 658 // analyzeSiblingValues has already tested all relevant defining instructions. 659 if (!Edit->anyRematerializable(LIS, TII, AA)) 660 return; 661 662 UsedValues.clear(); 663 664 // Try to remat before all uses of snippets. 665 bool anyRemat = false; 666 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 667 unsigned Reg = RegsToSpill[i]; 668 LiveInterval &LI = LIS.getInterval(Reg); 669 for (MachineRegisterInfo::use_nodbg_iterator 670 RI = MRI.use_nodbg_begin(Reg); 671 MachineInstr *MI = RI.skipInstruction();) 672 anyRemat |= reMaterializeFor(LI, MI); 673 } 674 if (!anyRemat) 675 return; 676 677 // Remove any values that were completely rematted. 678 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) { 679 unsigned Reg = RegsToSpill[i]; 680 LiveInterval &LI = LIS.getInterval(Reg); 681 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end(); 682 I != E; ++I) { 683 VNInfo *VNI = *I; 684 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI)) 685 continue; 686 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); 687 MI->addRegisterDead(Reg, &TRI); 688 if (!MI->allDefsAreDead()) 689 continue; 690 DEBUG(dbgs() << "All defs dead: " << *MI); 691 DeadDefs.push_back(MI); 692 } 693 } 694 695 // Eliminate dead code after remat. Note that some snippet copies may be 696 // deleted here. 697 if (DeadDefs.empty()) 698 return; 699 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n"); 700 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII); 701 702 // Get rid of deleted and empty intervals. 703 for (unsigned i = RegsToSpill.size(); i != 0; --i) { 704 unsigned Reg = RegsToSpill[i-1]; 705 if (!LIS.hasInterval(Reg)) { 706 RegsToSpill.erase(RegsToSpill.begin() + (i - 1)); 707 continue; 708 } 709 LiveInterval &LI = LIS.getInterval(Reg); 710 if (!LI.empty()) 711 continue; 712 Edit->eraseVirtReg(Reg, LIS); 713 RegsToSpill.erase(RegsToSpill.begin() + (i - 1)); 714 } 715 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n"); 716 } 717 718 719 //===----------------------------------------------------------------------===// 720 // Spilling 721 //===----------------------------------------------------------------------===// 722 723 /// If MI is a load or store of StackSlot, it can be removed. 724 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) { 725 int FI = 0; 726 unsigned InstrReg; 727 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) && 728 !(InstrReg = TII.isStoreToStackSlot(MI, FI))) 729 return false; 730 731 // We have a stack access. Is it the right register and slot? 732 if (InstrReg != Reg || FI != StackSlot) 733 return false; 734 735 DEBUG(dbgs() << "Coalescing stack access: " << *MI); 736 LIS.RemoveMachineInstrFromMaps(MI); 737 MI->eraseFromParent(); 738 return true; 739 } 740 741 /// foldMemoryOperand - Try folding stack slot references in Ops into MI. 742 /// @param MI Instruction using or defining the current register. 743 /// @param Ops Operand indices from readsWritesVirtualRegister(). 744 /// @param LoadMI Load instruction to use instead of stack slot when non-null. 745 /// @return True on success, and MI will be erased. 746 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI, 747 const SmallVectorImpl<unsigned> &Ops, 748 MachineInstr *LoadMI) { 749 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied 750 // operands. 751 SmallVector<unsigned, 8> FoldOps; 752 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 753 unsigned Idx = Ops[i]; 754 MachineOperand &MO = MI->getOperand(Idx); 755 if (MO.isImplicit()) 756 continue; 757 // FIXME: Teach targets to deal with subregs. 758 if (MO.getSubReg()) 759 return false; 760 // We cannot fold a load instruction into a def. 761 if (LoadMI && MO.isDef()) 762 return false; 763 // Tied use operands should not be passed to foldMemoryOperand. 764 if (!MI->isRegTiedToDefOperand(Idx)) 765 FoldOps.push_back(Idx); 766 } 767 768 MachineInstr *FoldMI = 769 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI) 770 : TII.foldMemoryOperand(MI, FoldOps, StackSlot); 771 if (!FoldMI) 772 return false; 773 LIS.ReplaceMachineInstrInMaps(MI, FoldMI); 774 if (!LoadMI) 775 VRM.addSpillSlotUse(StackSlot, FoldMI); 776 MI->eraseFromParent(); 777 DEBUG(dbgs() << "\tfolded: " << *FoldMI); 778 return true; 779 } 780 781 /// insertReload - Insert a reload of NewLI.reg before MI. 782 void InlineSpiller::insertReload(LiveInterval &NewLI, 783 MachineBasicBlock::iterator MI) { 784 MachineBasicBlock &MBB = *MI->getParent(); 785 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex(); 786 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot, 787 MRI.getRegClass(NewLI.reg), &TRI); 788 --MI; // Point to load instruction. 789 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex(); 790 VRM.addSpillSlotUse(StackSlot, MI); 791 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI); 792 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0, 793 LIS.getVNInfoAllocator()); 794 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI)); 795 } 796 797 /// insertSpill - Insert a spill of NewLI.reg after MI. 798 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI, 799 MachineBasicBlock::iterator MI) { 800 MachineBasicBlock &MBB = *MI->getParent(); 801 802 // Get the defined value. It could be an early clobber so keep the def index. 803 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex(); 804 VNInfo *VNI = OldLI.getVNInfoAt(Idx); 805 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo"); 806 Idx = VNI->def; 807 808 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot, 809 MRI.getRegClass(NewLI.reg), &TRI); 810 --MI; // Point to store instruction. 811 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex(); 812 VRM.addSpillSlotUse(StackSlot, MI); 813 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI); 814 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator()); 815 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI)); 816 } 817 818 /// spillAroundUses - insert spill code around each use of Reg. 819 void InlineSpiller::spillAroundUses(unsigned Reg) { 820 LiveInterval &OldLI = LIS.getInterval(Reg); 821 822 // Iterate over instructions using Reg. 823 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg); 824 MachineInstr *MI = RI.skipInstruction();) { 825 826 // Debug values are not allowed to affect codegen. 827 if (MI->isDebugValue()) { 828 // Modify DBG_VALUE now that the value is in a spill slot. 829 uint64_t Offset = MI->getOperand(1).getImm(); 830 const MDNode *MDPtr = MI->getOperand(2).getMetadata(); 831 DebugLoc DL = MI->getDebugLoc(); 832 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot, 833 Offset, MDPtr, DL)) { 834 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI); 835 MachineBasicBlock *MBB = MI->getParent(); 836 MBB->insert(MBB->erase(MI), NewDV); 837 } else { 838 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI); 839 MI->eraseFromParent(); 840 } 841 continue; 842 } 843 844 // Ignore copies to/from snippets. We'll delete them. 845 if (SnippetCopies.count(MI)) 846 continue; 847 848 // Stack slot accesses may coalesce away. 849 if (coalesceStackAccess(MI, Reg)) 850 continue; 851 852 // Analyze instruction. 853 bool Reads, Writes; 854 SmallVector<unsigned, 8> Ops; 855 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops); 856 857 // Check for a sibling copy. 858 unsigned SibReg = isFullCopyOf(MI, Reg); 859 if (SibReg && isSibling(SibReg)) { 860 if (Writes) { 861 // Hoist the spill of a sib-reg copy. 862 if (hoistSpill(OldLI, MI)) { 863 // This COPY is now dead, the value is already in the stack slot. 864 MI->getOperand(0).setIsDead(); 865 DeadDefs.push_back(MI); 866 continue; 867 } 868 } else { 869 // This is a reload for a sib-reg copy. Drop spills downstream. 870 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex(); 871 LiveInterval &SibLI = LIS.getInterval(SibReg); 872 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx)); 873 // The COPY will fold to a reload below. 874 } 875 } 876 877 // Attempt to fold memory ops. 878 if (foldMemoryOperand(MI, Ops)) 879 continue; 880 881 // Allocate interval around instruction. 882 // FIXME: Infer regclass from instruction alone. 883 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM); 884 NewLI.markNotSpillable(); 885 886 if (Reads) 887 insertReload(NewLI, MI); 888 889 // Rewrite instruction operands. 890 bool hasLiveDef = false; 891 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 892 MachineOperand &MO = MI->getOperand(Ops[i]); 893 MO.setReg(NewLI.reg); 894 if (MO.isUse()) { 895 if (!MI->isRegTiedToDefOperand(Ops[i])) 896 MO.setIsKill(); 897 } else { 898 if (!MO.isDead()) 899 hasLiveDef = true; 900 } 901 } 902 903 // FIXME: Use a second vreg if instruction has no tied ops. 904 if (Writes && hasLiveDef) 905 insertSpill(NewLI, OldLI, MI); 906 907 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n'); 908 } 909 } 910 911 /// spillAll - Spill all registers remaining after rematerialization. 912 void InlineSpiller::spillAll() { 913 // Update LiveStacks now that we are committed to spilling. 914 if (StackSlot == VirtRegMap::NO_STACK_SLOT) { 915 StackSlot = VRM.assignVirt2StackSlot(Original); 916 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original)); 917 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator()); 918 } else 919 StackInt = &LSS.getInterval(StackSlot); 920 921 if (Original != Edit->getReg()) 922 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot); 923 924 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values"); 925 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 926 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]), 927 StackInt->getValNumInfo(0)); 928 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n'); 929 930 // Spill around uses of all RegsToSpill. 931 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 932 spillAroundUses(RegsToSpill[i]); 933 934 // Hoisted spills may cause dead code. 935 if (!DeadDefs.empty()) { 936 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n"); 937 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII); 938 } 939 940 // Finally delete the SnippetCopies. 941 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()); 942 MachineInstr *MI = RI.skipInstruction();) { 943 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy"); 944 // FIXME: Do this with a LiveRangeEdit callback. 945 VRM.RemoveMachineInstrFromMaps(MI); 946 LIS.RemoveMachineInstrFromMaps(MI); 947 MI->eraseFromParent(); 948 } 949 950 // Delete all spilled registers. 951 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) 952 Edit->eraseVirtReg(RegsToSpill[i], LIS); 953 } 954 955 void InlineSpiller::spill(LiveRangeEdit &edit) { 956 Edit = &edit; 957 assert(!TargetRegisterInfo::isStackSlot(edit.getReg()) 958 && "Trying to spill a stack slot."); 959 // Share a stack slot among all descendants of Original. 960 Original = VRM.getOriginal(edit.getReg()); 961 StackSlot = VRM.getStackSlot(Original); 962 StackInt = 0; 963 964 DEBUG(dbgs() << "Inline spilling " 965 << MRI.getRegClass(edit.getReg())->getName() 966 << ':' << edit.getParent() << "\nFrom original " 967 << LIS.getInterval(Original) << '\n'); 968 assert(edit.getParent().isSpillable() && 969 "Attempting to spill already spilled value."); 970 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs"); 971 972 collectRegsToSpill(); 973 analyzeSiblingValues(); 974 reMaterializeAll(); 975 976 // Remat may handle everything. 977 if (!RegsToSpill.empty()) 978 spillAll(); 979 980 Edit->calculateRegClassAndHint(MF, LIS, Loops); 981 } 982