LiveIntervalAnalysis.cpp revision 74de8b1b26b12fda3364382946e519a2e37b6709
1//===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the LiveInterval analysis pass which is used 11// by the Linear Scan Register allocator. This pass linearizes the 12// basic blocks of the function in DFS order and uses the 13// LiveVariables pass to conservatively compute live intervals for 14// each virtual and physical register. 15// 16//===----------------------------------------------------------------------===// 17 18#define DEBUG_TYPE "liveintervals" 19#include "LiveIntervals.h" 20#include "llvm/Value.h" 21#include "llvm/Analysis/LoopInfo.h" 22#include "llvm/CodeGen/LiveVariables.h" 23#include "llvm/CodeGen/MachineFrameInfo.h" 24#include "llvm/CodeGen/MachineInstr.h" 25#include "llvm/CodeGen/Passes.h" 26#include "llvm/CodeGen/SSARegMap.h" 27#include "llvm/Target/MRegisterInfo.h" 28#include "llvm/Target/TargetInstrInfo.h" 29#include "llvm/Target/TargetMachine.h" 30#include "Support/CommandLine.h" 31#include "Support/Debug.h" 32#include "Support/Statistic.h" 33#include "Support/STLExtras.h" 34#include "VirtRegMap.h" 35#include <cmath> 36#include <iostream> 37 38using namespace llvm; 39 40namespace { 41 RegisterAnalysis<LiveIntervals> X("liveintervals", 42 "Live Interval Analysis"); 43 44 Statistic<> numIntervals 45 ("liveintervals", "Number of original intervals"); 46 47 Statistic<> numIntervalsAfter 48 ("liveintervals", "Number of intervals after coalescing"); 49 50 Statistic<> numJoins 51 ("liveintervals", "Number of interval joins performed"); 52 53 Statistic<> numPeep 54 ("liveintervals", "Number of identity moves eliminated after coalescing"); 55 56 Statistic<> numFolded 57 ("liveintervals", "Number of loads/stores folded into instructions"); 58 59 cl::opt<bool> 60 EnableJoining("join-liveintervals", 61 cl::desc("Join compatible live intervals"), 62 cl::init(true)); 63}; 64 65void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const 66{ 67 AU.addPreserved<LiveVariables>(); 68 AU.addRequired<LiveVariables>(); 69 AU.addPreservedID(PHIEliminationID); 70 AU.addRequiredID(PHIEliminationID); 71 AU.addRequiredID(TwoAddressInstructionPassID); 72 AU.addRequired<LoopInfo>(); 73 MachineFunctionPass::getAnalysisUsage(AU); 74} 75 76void LiveIntervals::releaseMemory() 77{ 78 mi2iMap_.clear(); 79 i2miMap_.clear(); 80 r2iMap_.clear(); 81 r2rMap_.clear(); 82 intervals_.clear(); 83} 84 85 86/// runOnMachineFunction - Register allocate the whole function 87/// 88bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) { 89 mf_ = &fn; 90 tm_ = &fn.getTarget(); 91 mri_ = tm_->getRegisterInfo(); 92 lv_ = &getAnalysis<LiveVariables>(); 93 94 // number MachineInstrs 95 unsigned miIndex = 0; 96 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end(); 97 mbb != mbbEnd; ++mbb) 98 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end(); 99 mi != miEnd; ++mi) { 100 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second; 101 assert(inserted && "multiple MachineInstr -> index mappings"); 102 i2miMap_.push_back(mi); 103 miIndex += InstrSlots::NUM; 104 } 105 106 computeIntervals(); 107 108 numIntervals += intervals_.size(); 109 110 // join intervals if requested 111 if (EnableJoining) joinIntervals(); 112 //DEBUG(mf_->viewCFG()); 113 114 numIntervalsAfter += intervals_.size(); 115 116 // perform a final pass over the instructions and compute spill 117 // weights, coalesce virtual registers and remove identity moves 118 const LoopInfo& loopInfo = getAnalysis<LoopInfo>(); 119 const TargetInstrInfo& tii = *tm_->getInstrInfo(); 120 121 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 122 mbbi != mbbe; ++mbbi) { 123 MachineBasicBlock* mbb = mbbi; 124 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock()); 125 126 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end(); 127 mii != mie; ) { 128 // if the move will be an identity move delete it 129 unsigned srcReg, dstReg; 130 if (tii.isMoveInstr(*mii, srcReg, dstReg) && 131 rep(srcReg) == rep(dstReg)) { 132 // remove from def list 133 LiveInterval& interval = getOrCreateInterval(rep(dstReg)); 134 // remove index -> MachineInstr and 135 // MachineInstr -> index mappings 136 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii); 137 if (mi2i != mi2iMap_.end()) { 138 i2miMap_[mi2i->second/InstrSlots::NUM] = 0; 139 mi2iMap_.erase(mi2i); 140 } 141 mii = mbbi->erase(mii); 142 ++numPeep; 143 } 144 else { 145 for (unsigned i = 0; i < mii->getNumOperands(); ++i) { 146 const MachineOperand& mop = mii->getOperand(i); 147 if (mop.isRegister() && mop.getReg() && 148 MRegisterInfo::isVirtualRegister(mop.getReg())) { 149 // replace register with representative register 150 unsigned reg = rep(mop.getReg()); 151 mii->SetMachineOperandReg(i, reg); 152 153 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg); 154 assert(r2iit != r2iMap_.end()); 155 r2iit->second->weight += 156 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth); 157 } 158 } 159 ++mii; 160 } 161 } 162 } 163 164 intervals_.sort(); 165 DEBUG(std::cerr << "********** INTERVALS **********\n"); 166 DEBUG(std::copy(intervals_.begin(), intervals_.end(), 167 std::ostream_iterator<LiveInterval>(std::cerr, "\n"))); 168 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n"); 169 DEBUG( 170 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 171 mbbi != mbbe; ++mbbi) { 172 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n"; 173 for (MachineBasicBlock::iterator mii = mbbi->begin(), 174 mie = mbbi->end(); mii != mie; ++mii) { 175 std::cerr << getInstructionIndex(mii) << '\t'; 176 mii->print(std::cerr, tm_); 177 } 178 }); 179 180 return true; 181} 182 183namespace { 184 /// CompareIntervalStar - This is a simple comparison function for interval 185 /// pointers. It compares based on their starting point. 186 struct CompareIntervalStar { 187 bool operator()(LiveInterval *LHS, LiveInterval* RHS) const { 188 return LHS->start() < RHS->start(); 189 } 190 }; 191} 192 193std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills( 194 const LiveInterval& li, 195 VirtRegMap& vrm, 196 int slot) 197{ 198 std::vector<LiveInterval*> added; 199 200 assert(li.weight != HUGE_VAL && 201 "attempt to spill already spilled interval!"); 202 203 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: " 204 << li << '\n'); 205 206 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg); 207 208 for (LiveInterval::Ranges::const_iterator 209 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) { 210 unsigned index = getBaseIndex(i->first); 211 unsigned end = getBaseIndex(i->second-1) + InstrSlots::NUM; 212 for (; index < end; index += InstrSlots::NUM) { 213 // skip deleted instructions 214 while (!getInstructionFromIndex(index)) index += InstrSlots::NUM; 215 MachineBasicBlock::iterator mi = getInstructionFromIndex(index); 216 217 for_operand: 218 for (unsigned i = 0; i != mi->getNumOperands(); ++i) { 219 MachineOperand& mop = mi->getOperand(i); 220 if (mop.isRegister() && mop.getReg() == li.reg) { 221 if (MachineInstr* fmi = 222 mri_->foldMemoryOperand(mi, i, slot)) { 223 lv_->instructionChanged(mi, fmi); 224 vrm.virtFolded(li.reg, mi, fmi); 225 mi2iMap_.erase(mi); 226 i2miMap_[index/InstrSlots::NUM] = fmi; 227 mi2iMap_[fmi] = index; 228 MachineBasicBlock& mbb = *mi->getParent(); 229 mi = mbb.insert(mbb.erase(mi), fmi); 230 ++numFolded; 231 goto for_operand; 232 } 233 else { 234 // This is tricky. We need to add information in 235 // the interval about the spill code so we have to 236 // use our extra load/store slots. 237 // 238 // If we have a use we are going to have a load so 239 // we start the interval from the load slot 240 // onwards. Otherwise we start from the def slot. 241 unsigned start = (mop.isUse() ? 242 getLoadIndex(index) : 243 getDefIndex(index)); 244 // If we have a def we are going to have a store 245 // right after it so we end the interval after the 246 // use of the next instruction. Otherwise we end 247 // after the use of this instruction. 248 unsigned end = 1 + (mop.isDef() ? 249 getStoreIndex(index) : 250 getUseIndex(index)); 251 252 // create a new register for this spill 253 unsigned nReg = 254 mf_->getSSARegMap()->createVirtualRegister(rc); 255 mi->SetMachineOperandReg(i, nReg); 256 vrm.grow(); 257 vrm.assignVirt2StackSlot(nReg, slot); 258 LiveInterval& nI = getOrCreateInterval(nReg); 259 assert(nI.empty()); 260 // the spill weight is now infinity as it 261 // cannot be spilled again 262 nI.weight = HUGE_VAL; 263 nI.addRange(start, end); 264 added.push_back(&nI); 265 // update live variables 266 lv_->addVirtualRegisterKilled(nReg, mi); 267 DEBUG(std::cerr << "\t\t\t\tadded new interval: " 268 << nI << '\n'); 269 } 270 } 271 } 272 } 273 } 274 275 // FIXME: This method MUST return intervals in sorted order. If a 276 // particular machine instruction both uses and defines the vreg being 277 // spilled (e.g., vr = vr + 1) and if the def is processed before the 278 // use, the list ends up not sorted. 279 // 280 // The proper way to fix this is to process all uses of the vreg before we 281 // process any defs. However, this would require refactoring the above 282 // blob of code, which I'm not feeling up to right now. 283 std::sort(added.begin(), added.end(), CompareIntervalStar()); 284 return added; 285} 286 287void LiveIntervals::printRegName(unsigned reg) const 288{ 289 if (MRegisterInfo::isPhysicalRegister(reg)) 290 std::cerr << mri_->getName(reg); 291 else 292 std::cerr << "%reg" << reg; 293} 294 295void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb, 296 MachineBasicBlock::iterator mi, 297 LiveInterval& interval) 298{ 299 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg)); 300 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg); 301 302 // Virtual registers may be defined multiple times (due to phi 303 // elimination). Much of what we do only has to be done once for the vreg. 304 // We use an empty interval to detect the first time we see a vreg. 305 if (interval.empty()) { 306 307 // Get the Idx of the defining instructions. 308 unsigned defIndex = getDefIndex(getInstructionIndex(mi)); 309 310 // Loop over all of the blocks that the vreg is defined in. There are 311 // two cases we have to handle here. The most common case is a vreg 312 // whose lifetime is contained within a basic block. In this case there 313 // will be a single kill, in MBB, which comes after the definition. 314 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) { 315 // FIXME: what about dead vars? 316 unsigned killIdx; 317 if (vi.Kills[0] != mi) 318 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1; 319 else 320 killIdx = defIndex+1; 321 322 // If the kill happens after the definition, we have an intra-block 323 // live range. 324 if (killIdx > defIndex) { 325 assert(vi.AliveBlocks.empty() && 326 "Shouldn't be alive across any blocks!"); 327 interval.addRange(defIndex, killIdx); 328 return; 329 } 330 } 331 332 // The other case we handle is when a virtual register lives to the end 333 // of the defining block, potentially live across some blocks, then is 334 // live into some number of blocks, but gets killed. Start by adding a 335 // range that goes from this definition to the end of the defining block. 336 interval.addRange(defIndex, 337 getInstructionIndex(&mbb->back()) + InstrSlots::NUM); 338 339 // Iterate over all of the blocks that the variable is completely 340 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the 341 // live interval. 342 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) { 343 if (vi.AliveBlocks[i]) { 344 MachineBasicBlock* mbb = mf_->getBlockNumbered(i); 345 if (!mbb->empty()) { 346 interval.addRange( 347 getInstructionIndex(&mbb->front()), 348 getInstructionIndex(&mbb->back()) + InstrSlots::NUM); 349 } 350 } 351 } 352 353 // Finally, this virtual register is live from the start of any killing 354 // block to the 'use' slot of the killing instruction. 355 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) { 356 MachineInstr *Kill = vi.Kills[i]; 357 interval.addRange(getInstructionIndex(Kill->getParent()->begin()), 358 getUseIndex(getInstructionIndex(Kill))+1); 359 } 360 361 } else { 362 // If this is the second time we see a virtual register definition, it 363 // must be due to phi elimination. In this case, the defined value will 364 // be live until the end of the basic block it is defined in. 365 unsigned defIndex = getDefIndex(getInstructionIndex(mi)); 366 interval.addRange(defIndex, 367 getInstructionIndex(&mbb->back()) + InstrSlots::NUM); 368 } 369 370 DEBUG(std::cerr << '\n'); 371} 372 373void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb, 374 MachineBasicBlock::iterator mi, 375 LiveInterval& interval) 376{ 377 // A physical register cannot be live across basic block, so its 378 // lifetime must end somewhere in its defining basic block. 379 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg)); 380 typedef LiveVariables::killed_iterator KillIter; 381 382 MachineBasicBlock::iterator e = mbb->end(); 383 unsigned baseIndex = getInstructionIndex(mi); 384 unsigned start = getDefIndex(baseIndex); 385 unsigned end = start; 386 387 // If it is not used after definition, it is considered dead at 388 // the instruction defining it. Hence its interval is: 389 // [defSlot(def), defSlot(def)+1) 390 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi); 391 ki != ke; ++ki) { 392 if (interval.reg == ki->second) { 393 DEBUG(std::cerr << " dead"); 394 end = getDefIndex(start) + 1; 395 goto exit; 396 } 397 } 398 399 // If it is not dead on definition, it must be killed by a 400 // subsequent instruction. Hence its interval is: 401 // [defSlot(def), useSlot(kill)+1) 402 do { 403 ++mi; 404 baseIndex += InstrSlots::NUM; 405 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi); 406 ki != ke; ++ki) { 407 if (interval.reg == ki->second) { 408 DEBUG(std::cerr << " killed"); 409 end = getUseIndex(baseIndex) + 1; 410 goto exit; 411 } 412 } 413 } while (mi != e); 414 415exit: 416 assert(start < end && "did not find end of interval?"); 417 interval.addRange(start, end); 418 DEBUG(std::cerr << '\n'); 419} 420 421void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb, 422 MachineBasicBlock::iterator mi, 423 unsigned reg) 424{ 425 if (MRegisterInfo::isPhysicalRegister(reg)) { 426 if (lv_->getAllocatablePhysicalRegisters()[reg]) { 427 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(reg)); 428 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) 429 handlePhysicalRegisterDef(mbb, mi, getOrCreateInterval(*as)); 430 } 431 } 432 else 433 handleVirtualRegisterDef(mbb, mi, getOrCreateInterval(reg)); 434} 435 436unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const 437{ 438 Mi2IndexMap::const_iterator it = mi2iMap_.find(instr); 439 return (it == mi2iMap_.end() ? 440 std::numeric_limits<unsigned>::max() : 441 it->second); 442} 443 444MachineInstr* LiveIntervals::getInstructionFromIndex(unsigned index) const 445{ 446 index /= InstrSlots::NUM; // convert index to vector index 447 assert(index < i2miMap_.size() && 448 "index does not correspond to an instruction"); 449 return i2miMap_[index]; 450} 451 452/// computeIntervals - computes the live intervals for virtual 453/// registers. for some ordering of the machine instructions [1,N] a 454/// live interval is an interval [i, j) where 1 <= i <= j < N for 455/// which a variable is live 456void LiveIntervals::computeIntervals() 457{ 458 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n"); 459 DEBUG(std::cerr << "********** Function: " 460 << ((Value*)mf_->getFunction())->getName() << '\n'); 461 462 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); 463 I != E; ++I) { 464 MachineBasicBlock* mbb = I; 465 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n"); 466 467 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end(); 468 mi != miEnd; ++mi) { 469 const TargetInstrDescriptor& tid = 470 tm_->getInstrInfo()->get(mi->getOpcode()); 471 DEBUG(std::cerr << getInstructionIndex(mi) << "\t"; 472 mi->print(std::cerr, tm_)); 473 474 // handle implicit defs 475 for (const unsigned* id = tid.ImplicitDefs; *id; ++id) 476 handleRegisterDef(mbb, mi, *id); 477 478 // handle explicit defs 479 for (int i = mi->getNumOperands() - 1; i >= 0; --i) { 480 MachineOperand& mop = mi->getOperand(i); 481 // handle register defs - build intervals 482 if (mop.isRegister() && mop.getReg() && mop.isDef()) 483 handleRegisterDef(mbb, mi, mop.getReg()); 484 } 485 } 486 } 487} 488 489unsigned LiveIntervals::rep(unsigned reg) 490{ 491 Reg2RegMap::iterator it = r2rMap_.find(reg); 492 if (it != r2rMap_.end()) 493 return it->second = rep(it->second); 494 return reg; 495} 496 497void LiveIntervals::joinIntervals() 498{ 499 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n"); 500 501 const TargetInstrInfo& tii = *tm_->getInstrInfo(); 502 503 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end(); 504 mbbi != mbbe; ++mbbi) { 505 MachineBasicBlock* mbb = mbbi; 506 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n"); 507 508 for (MachineBasicBlock::iterator mi = mbb->begin(), mie = mbb->end(); 509 mi != mie; ++mi) { 510 const TargetInstrDescriptor& tid = tii.get(mi->getOpcode()); 511 DEBUG(std::cerr << getInstructionIndex(mi) << '\t'; 512 mi->print(std::cerr, tm_);); 513 514 // we only join virtual registers with allocatable 515 // physical registers since we do not have liveness information 516 // on not allocatable physical registers 517 unsigned regA, regB; 518 if (tii.isMoveInstr(*mi, regA, regB) && 519 (MRegisterInfo::isVirtualRegister(regA) || 520 lv_->getAllocatablePhysicalRegisters()[regA]) && 521 (MRegisterInfo::isVirtualRegister(regB) || 522 lv_->getAllocatablePhysicalRegisters()[regB])) { 523 524 // get representative registers 525 regA = rep(regA); 526 regB = rep(regB); 527 528 // if they are already joined we continue 529 if (regA == regB) 530 continue; 531 532 Reg2IntervalMap::iterator r2iA = r2iMap_.find(regA); 533 assert(r2iA != r2iMap_.end() && 534 "Found unknown vreg in 'isMoveInstr' instruction"); 535 Reg2IntervalMap::iterator r2iB = r2iMap_.find(regB); 536 assert(r2iB != r2iMap_.end() && 537 "Found unknown vreg in 'isMoveInstr' instruction"); 538 539 Intervals::iterator intA = r2iA->second; 540 Intervals::iterator intB = r2iB->second; 541 542 // both A and B are virtual registers 543 if (MRegisterInfo::isVirtualRegister(intA->reg) && 544 MRegisterInfo::isVirtualRegister(intB->reg)) { 545 546 const TargetRegisterClass *rcA, *rcB; 547 rcA = mf_->getSSARegMap()->getRegClass(intA->reg); 548 rcB = mf_->getSSARegMap()->getRegClass(intB->reg); 549 // if they are not of the same register class we continue 550 if (rcA != rcB) 551 continue; 552 553 // if their intervals do not overlap we join them 554 if (!intB->overlaps(*intA)) { 555 intA->join(*intB); 556 r2iB->second = r2iA->second; 557 r2rMap_.insert(std::make_pair(intB->reg, intA->reg)); 558 intervals_.erase(intB); 559 } 560 } else if (MRegisterInfo::isPhysicalRegister(intA->reg) ^ 561 MRegisterInfo::isPhysicalRegister(intB->reg)) { 562 if (MRegisterInfo::isPhysicalRegister(intB->reg)) { 563 std::swap(regA, regB); 564 std::swap(intA, intB); 565 std::swap(r2iA, r2iB); 566 } 567 568 assert(MRegisterInfo::isPhysicalRegister(intA->reg) && 569 MRegisterInfo::isVirtualRegister(intB->reg) && 570 "A must be physical and B must be virtual"); 571 572 const TargetRegisterClass *rcA, *rcB; 573 rcA = mri_->getRegClass(intA->reg); 574 rcB = mf_->getSSARegMap()->getRegClass(intB->reg); 575 // if they are not of the same register class we continue 576 if (rcA != rcB) 577 continue; 578 579 if (!intA->overlaps(*intB) && 580 !overlapsAliases(*intA, *intB)) { 581 intA->join(*intB); 582 r2iB->second = r2iA->second; 583 r2rMap_.insert(std::make_pair(intB->reg, intA->reg)); 584 intervals_.erase(intB); 585 } 586 } 587 } 588 } 589 } 590} 591 592bool LiveIntervals::overlapsAliases(const LiveInterval& lhs, 593 const LiveInterval& rhs) const 594{ 595 assert(MRegisterInfo::isPhysicalRegister(lhs.reg) && 596 "first interval must describe a physical register"); 597 598 for (const unsigned* as = mri_->getAliasSet(lhs.reg); *as; ++as) { 599 Reg2IntervalMap::const_iterator r2i = r2iMap_.find(*as); 600 assert(r2i != r2iMap_.end() && "alias does not have interval?"); 601 if (rhs.overlaps(*r2i->second)) 602 return true; 603 } 604 605 return false; 606} 607 608LiveInterval& LiveIntervals::getOrCreateInterval(unsigned reg) 609{ 610 Reg2IntervalMap::iterator r2iit = r2iMap_.lower_bound(reg); 611 if (r2iit == r2iMap_.end() || r2iit->first != reg) { 612 intervals_.push_back(LiveInterval(reg)); 613 r2iit = r2iMap_.insert(r2iit, std::make_pair(reg, --intervals_.end())); 614 } 615 616 return *r2iit->second; 617} 618 619LiveInterval::LiveInterval(unsigned r) 620 : reg(r), 621 weight((MRegisterInfo::isPhysicalRegister(r) ? HUGE_VAL : 0.0F)) 622{ 623} 624 625bool LiveInterval::spilled() const 626{ 627 return (weight == HUGE_VAL && 628 MRegisterInfo::isVirtualRegister(reg)); 629} 630 631// An example for liveAt(): 632// 633// this = [1,4), liveAt(0) will return false. The instruction defining 634// this spans slots [0,3]. The interval belongs to an spilled 635// definition of the variable it represents. This is because slot 1 is 636// used (def slot) and spans up to slot 3 (store slot). 637// 638bool LiveInterval::liveAt(unsigned index) const 639{ 640 Range dummy(index, index+1); 641 Ranges::const_iterator r = std::upper_bound(ranges.begin(), 642 ranges.end(), 643 dummy); 644 if (r == ranges.begin()) 645 return false; 646 647 --r; 648 return index >= r->first && index < r->second; 649} 650 651// An example for overlaps(): 652// 653// 0: A = ... 654// 4: B = ... 655// 8: C = A + B ;; last use of A 656// 657// The live intervals should look like: 658// 659// A = [3, 11) 660// B = [7, x) 661// C = [11, y) 662// 663// A->overlaps(C) should return false since we want to be able to join 664// A and C. 665bool LiveInterval::overlaps(const LiveInterval& other) const 666{ 667 Ranges::const_iterator i = ranges.begin(); 668 Ranges::const_iterator ie = ranges.end(); 669 Ranges::const_iterator j = other.ranges.begin(); 670 Ranges::const_iterator je = other.ranges.end(); 671 if (i->first < j->first) { 672 i = std::upper_bound(i, ie, *j); 673 if (i != ranges.begin()) --i; 674 } 675 else if (j->first < i->first) { 676 j = std::upper_bound(j, je, *i); 677 if (j != other.ranges.begin()) --j; 678 } 679 680 while (i != ie && j != je) { 681 if (i->first == j->first) { 682 return true; 683 } 684 else { 685 if (i->first > j->first) { 686 swap(i, j); 687 swap(ie, je); 688 } 689 assert(i->first < j->first); 690 691 if (i->second > j->first) { 692 return true; 693 } 694 else { 695 ++i; 696 } 697 } 698 } 699 700 return false; 701} 702 703void LiveInterval::addRange(unsigned start, unsigned end) 704{ 705 assert(start < end && "Invalid range to add!"); 706 DEBUG(std::cerr << " +[" << start << ',' << end << ")"); 707 //assert(start < end && "invalid range?"); 708 Range range = std::make_pair(start, end); 709 Ranges::iterator it = 710 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range), 711 range); 712 713 it = mergeRangesForward(it); 714 it = mergeRangesBackward(it); 715} 716 717void LiveInterval::join(const LiveInterval& other) 718{ 719 DEBUG(std::cerr << "\t\tjoining " << *this << " with " << other); 720 Ranges::iterator cur = ranges.begin(); 721 722 for (Ranges::const_iterator i = other.ranges.begin(), 723 e = other.ranges.end(); i != e; ++i) { 724 cur = ranges.insert(std::upper_bound(cur, ranges.end(), *i), *i); 725 cur = mergeRangesForward(cur); 726 cur = mergeRangesBackward(cur); 727 } 728 weight += other.weight; 729 ++numJoins; 730 DEBUG(std::cerr << ". Result = " << *this << "\n"); 731} 732 733LiveInterval::Ranges::iterator LiveInterval:: 734mergeRangesForward(Ranges::iterator it) 735{ 736 Ranges::iterator n; 737 while ((n = next(it)) != ranges.end()) { 738 if (n->first > it->second) 739 break; 740 it->second = std::max(it->second, n->second); 741 n = ranges.erase(n); 742 } 743 return it; 744} 745 746LiveInterval::Ranges::iterator LiveInterval:: 747mergeRangesBackward(Ranges::iterator it) 748{ 749 while (it != ranges.begin()) { 750 Ranges::iterator p = prior(it); 751 if (it->first > p->second) 752 break; 753 754 it->first = std::min(it->first, p->first); 755 it->second = std::max(it->second, p->second); 756 it = ranges.erase(p); 757 } 758 759 return it; 760} 761 762std::ostream& llvm::operator<<(std::ostream& os, const LiveInterval& li) 763{ 764 os << "%reg" << li.reg << ',' << li.weight; 765 if (li.empty()) 766 return os << "EMPTY"; 767 768 os << " = "; 769 for (LiveInterval::Ranges::const_iterator 770 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) { 771 os << "[" << i->first << "," << i->second << ")"; 772 } 773 return os; 774} 775