1 //===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "liveintervals"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "VirtRegMap.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/MRegisterInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
39 STATISTIC(numIntervals, "Number of original intervals");
40 STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
41 STATISTIC(numJoins , "Number of interval joins performed");
42 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
43 STATISTIC(numFolded , "Number of loads/stores folded into instructions");
46 RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
49 EnableJoining("join-liveintervals",
50 cl::desc("Coallesce copies (default=true)"),
54 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
55 AU.addRequired<LiveVariables>();
56 AU.addPreservedID(PHIEliminationID);
57 AU.addRequiredID(PHIEliminationID);
58 AU.addRequiredID(TwoAddressInstructionPassID);
59 AU.addRequired<LoopInfo>();
60 MachineFunctionPass::getAnalysisUsage(AU);
63 void LiveIntervals::releaseMemory() {
71 static bool isZeroLengthInterval(LiveInterval *li) {
72 for (LiveInterval::Ranges::const_iterator
73 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
74 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
80 /// runOnMachineFunction - Register allocate the whole function
82 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
84 tm_ = &fn.getTarget();
85 mri_ = tm_->getRegisterInfo();
86 tii_ = tm_->getInstrInfo();
87 lv_ = &getAnalysis<LiveVariables>();
88 allocatableRegs_ = mri_->getAllocatableSet(fn);
89 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
91 // If this function has any live ins, insert a dummy instruction at the
92 // beginning of the function that we will pretend "defines" the values. This
93 // is to make the interval analysis simpler by providing a number.
94 if (fn.livein_begin() != fn.livein_end()) {
95 unsigned FirstLiveIn = fn.livein_begin()->first;
97 // Find a reg class that contains this live in.
98 const TargetRegisterClass *RC = 0;
99 for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
100 E = mri_->regclass_end(); RCI != E; ++RCI)
101 if ((*RCI)->contains(FirstLiveIn)) {
106 MachineInstr *OldFirstMI = fn.begin()->begin();
107 mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
108 FirstLiveIn, FirstLiveIn, RC);
109 assert(OldFirstMI != fn.begin()->begin() &&
110 "copyRetToReg didn't insert anything!");
113 // Number MachineInstrs and MachineBasicBlocks.
114 // Initialize MBB indexes to a sentinal.
115 MBB2IdxMap.resize(mf_->getNumBlockIDs(), ~0U);
117 unsigned MIIndex = 0;
118 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
120 // Set the MBB2IdxMap entry for this MBB.
121 MBB2IdxMap[MBB->getNumber()] = MIIndex;
123 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
125 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
126 assert(inserted && "multiple MachineInstr -> index mappings");
127 i2miMap_.push_back(I);
128 MIIndex += InstrSlots::NUM;
132 // Note intervals due to live-in values.
133 if (fn.livein_begin() != fn.livein_end()) {
134 MachineBasicBlock *Entry = fn.begin();
135 for (MachineFunction::livein_iterator I = fn.livein_begin(),
136 E = fn.livein_end(); I != E; ++I) {
137 handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
138 getOrCreateInterval(I->first), 0);
139 for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
140 handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
141 getOrCreateInterval(*AS), 0);
147 numIntervals += getNumIntervals();
149 DOUT << "********** INTERVALS **********\n";
150 for (iterator I = begin(), E = end(); I != E; ++I) {
151 I->second.print(DOUT, mri_);
155 // Join (coallesce) intervals if requested.
156 if (EnableJoining) joinIntervals();
158 numIntervalsAfter += getNumIntervals();
161 // perform a final pass over the instructions and compute spill
162 // weights, coalesce virtual registers and remove identity moves.
163 const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
165 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
166 mbbi != mbbe; ++mbbi) {
167 MachineBasicBlock* mbb = mbbi;
168 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
170 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
172 // if the move will be an identity move delete it
173 unsigned srcReg, dstReg, RegRep;
174 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
175 (RegRep = rep(srcReg)) == rep(dstReg)) {
176 // remove from def list
177 getOrCreateInterval(RegRep);
178 RemoveMachineInstrFromMaps(mii);
179 mii = mbbi->erase(mii);
183 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
184 const MachineOperand &mop = mii->getOperand(i);
185 if (mop.isRegister() && mop.getReg() &&
186 MRegisterInfo::isVirtualRegister(mop.getReg())) {
187 // replace register with representative register
188 unsigned reg = rep(mop.getReg());
189 mii->getOperand(i).setReg(reg);
191 LiveInterval &RegInt = getInterval(reg);
193 (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
202 for (iterator I = begin(), E = end(); I != E; ++I) {
203 LiveInterval &LI = I->second;
204 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
205 // If the live interval length is essentially zero, i.e. in every live
206 // range the use follows def immediately, it doesn't make sense to spill
207 // it and hope it will be easier to allocate for this li.
208 if (isZeroLengthInterval(&LI))
209 LI.weight = HUGE_VALF;
211 // Divide the weight of the interval by its size. This encourages
212 // spilling of intervals that are large and have few uses, and
213 // discourages spilling of small intervals with many uses.
215 for (LiveInterval::iterator II = LI.begin(), E = LI.end(); II != E;++II)
216 Size += II->end - II->start;
226 /// print - Implement the dump method.
227 void LiveIntervals::print(std::ostream &O, const Module* ) const {
228 O << "********** INTERVALS **********\n";
229 for (const_iterator I = begin(), E = end(); I != E; ++I) {
230 I->second.print(DOUT, mri_);
234 O << "********** MACHINEINSTRS **********\n";
235 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
236 mbbi != mbbe; ++mbbi) {
237 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
238 for (MachineBasicBlock::iterator mii = mbbi->begin(),
239 mie = mbbi->end(); mii != mie; ++mii) {
240 O << getInstructionIndex(mii) << '\t' << *mii;
245 /// CreateNewLiveInterval - Create a new live interval with the given live
246 /// ranges. The new live interval will have an infinite spill weight.
248 LiveIntervals::CreateNewLiveInterval(const LiveInterval *LI,
249 const std::vector<LiveRange> &LRs) {
250 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(LI->reg);
252 // Create a new virtual register for the spill interval.
253 unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(RC);
255 // Replace the old virtual registers in the machine operands with the shiny
257 for (std::vector<LiveRange>::const_iterator
258 I = LRs.begin(), E = LRs.end(); I != E; ++I) {
259 unsigned Index = getBaseIndex(I->start);
260 unsigned End = getBaseIndex(I->end - 1) + InstrSlots::NUM;
262 for (; Index != End; Index += InstrSlots::NUM) {
263 // Skip deleted instructions
264 while (Index != End && !getInstructionFromIndex(Index))
265 Index += InstrSlots::NUM;
267 if (Index == End) break;
269 MachineInstr *MI = getInstructionFromIndex(Index);
271 for (unsigned J = 0, e = MI->getNumOperands(); J != e; ++J) {
272 MachineOperand &MOp = MI->getOperand(J);
273 if (MOp.isRegister() && rep(MOp.getReg()) == LI->reg)
279 LiveInterval &NewLI = getOrCreateInterval(NewVReg);
281 // The spill weight is now infinity as it cannot be spilled again
282 NewLI.weight = float(HUGE_VAL);
284 for (std::vector<LiveRange>::const_iterator
285 I = LRs.begin(), E = LRs.end(); I != E; ++I) {
286 DOUT << " Adding live range " << *I << " to new interval\n";
290 DOUT << "Created new live interval " << NewLI << "\n";
294 std::vector<LiveInterval*> LiveIntervals::
295 addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
296 // since this is called after the analysis is done we don't know if
297 // LiveVariables is available
298 lv_ = getAnalysisToUpdate<LiveVariables>();
300 std::vector<LiveInterval*> added;
302 assert(li.weight != HUGE_VALF &&
303 "attempt to spill already spilled interval!");
305 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
306 li.print(DOUT, mri_);
309 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
311 for (LiveInterval::Ranges::const_iterator
312 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
313 unsigned index = getBaseIndex(i->start);
314 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
315 for (; index != end; index += InstrSlots::NUM) {
316 // skip deleted instructions
317 while (index != end && !getInstructionFromIndex(index))
318 index += InstrSlots::NUM;
319 if (index == end) break;
321 MachineInstr *MI = getInstructionFromIndex(index);
324 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
325 MachineOperand& mop = MI->getOperand(i);
326 if (mop.isRegister() && mop.getReg() == li.reg) {
327 if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
328 // Attempt to fold the memory reference into the instruction. If we
329 // can do this, we don't need to insert spill code.
331 lv_->instructionChanged(MI, fmi);
332 MachineBasicBlock &MBB = *MI->getParent();
333 vrm.virtFolded(li.reg, MI, i, fmi);
335 i2miMap_[index/InstrSlots::NUM] = fmi;
336 mi2iMap_[fmi] = index;
337 MI = MBB.insert(MBB.erase(MI), fmi);
339 // Folding the load/store can completely change the instruction in
340 // unpredictable ways, rescan it from the beginning.
341 goto RestartInstruction;
343 // Create a new virtual register for the spill interval.
344 unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
346 // Scan all of the operands of this instruction rewriting operands
347 // to use NewVReg instead of li.reg as appropriate. We do this for
350 // 1. If the instr reads the same spilled vreg multiple times, we
351 // want to reuse the NewVReg.
352 // 2. If the instr is a two-addr instruction, we are required to
353 // keep the src/dst regs pinned.
355 // Keep track of whether we replace a use and/or def so that we can
356 // create the spill interval with the appropriate range.
359 bool HasUse = mop.isUse();
360 bool HasDef = mop.isDef();
361 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
362 if (MI->getOperand(j).isReg() &&
363 MI->getOperand(j).getReg() == li.reg) {
364 MI->getOperand(j).setReg(NewVReg);
365 HasUse |= MI->getOperand(j).isUse();
366 HasDef |= MI->getOperand(j).isDef();
370 // create a new register for this spill
372 vrm.assignVirt2StackSlot(NewVReg, slot);
373 LiveInterval &nI = getOrCreateInterval(NewVReg);
376 // the spill weight is now infinity as it
377 // cannot be spilled again
378 nI.weight = HUGE_VALF;
381 LiveRange LR(getLoadIndex(index), getUseIndex(index),
382 nI.getNextValue(~0U, 0));
387 LiveRange LR(getDefIndex(index), getStoreIndex(index),
388 nI.getNextValue(~0U, 0));
393 added.push_back(&nI);
395 // update live variables if it is available
397 lv_->addVirtualRegisterKilled(NewVReg, MI);
399 DOUT << "\t\t\t\tadded new interval: ";
400 nI.print(DOUT, mri_);
411 void LiveIntervals::printRegName(unsigned reg) const {
412 if (MRegisterInfo::isPhysicalRegister(reg))
413 cerr << mri_->getName(reg);
415 cerr << "%reg" << reg;
418 /// isReDefinedByTwoAddr - Returns true if the Reg re-definition is due to
419 /// two addr elimination.
420 static bool isReDefinedByTwoAddr(MachineInstr *MI, unsigned Reg,
421 const TargetInstrInfo *TII) {
422 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
423 MachineOperand &MO1 = MI->getOperand(i);
424 if (MO1.isRegister() && MO1.isDef() && MO1.getReg() == Reg) {
425 for (unsigned j = i+1; j < e; ++j) {
426 MachineOperand &MO2 = MI->getOperand(j);
427 if (MO2.isRegister() && MO2.isUse() && MO2.getReg() == Reg &&
428 MI->getInstrDescriptor()->
429 getOperandConstraint(j, TOI::TIED_TO) == (int)i)
437 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
438 MachineBasicBlock::iterator mi,
440 LiveInterval &interval) {
441 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
442 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
444 // Virtual registers may be defined multiple times (due to phi
445 // elimination and 2-addr elimination). Much of what we do only has to be
446 // done once for the vreg. We use an empty interval to detect the first
447 // time we see a vreg.
448 if (interval.empty()) {
449 // Get the Idx of the defining instructions.
450 unsigned defIndex = getDefIndex(MIIdx);
453 unsigned SrcReg, DstReg;
454 if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
455 ValNum = interval.getNextValue(~0U, 0);
457 ValNum = interval.getNextValue(defIndex, SrcReg);
459 assert(ValNum == 0 && "First value in interval is not 0?");
460 ValNum = 0; // Clue in the optimizer.
462 // Loop over all of the blocks that the vreg is defined in. There are
463 // two cases we have to handle here. The most common case is a vreg
464 // whose lifetime is contained within a basic block. In this case there
465 // will be a single kill, in MBB, which comes after the definition.
466 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
467 // FIXME: what about dead vars?
469 if (vi.Kills[0] != mi)
470 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
472 killIdx = defIndex+1;
474 // If the kill happens after the definition, we have an intra-block
476 if (killIdx > defIndex) {
477 assert(vi.AliveBlocks.empty() &&
478 "Shouldn't be alive across any blocks!");
479 LiveRange LR(defIndex, killIdx, ValNum);
480 interval.addRange(LR);
481 DOUT << " +" << LR << "\n";
486 // The other case we handle is when a virtual register lives to the end
487 // of the defining block, potentially live across some blocks, then is
488 // live into some number of blocks, but gets killed. Start by adding a
489 // range that goes from this definition to the end of the defining block.
490 LiveRange NewLR(defIndex,
491 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
493 DOUT << " +" << NewLR;
494 interval.addRange(NewLR);
496 // Iterate over all of the blocks that the variable is completely
497 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
499 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
500 if (vi.AliveBlocks[i]) {
501 MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
503 LiveRange LR(getMBBStartIdx(i),
504 getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
506 interval.addRange(LR);
512 // Finally, this virtual register is live from the start of any killing
513 // block to the 'use' slot of the killing instruction.
514 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
515 MachineInstr *Kill = vi.Kills[i];
516 LiveRange LR(getMBBStartIdx(Kill->getParent()),
517 getUseIndex(getInstructionIndex(Kill))+1,
519 interval.addRange(LR);
524 // If this is the second time we see a virtual register definition, it
525 // must be due to phi elimination or two addr elimination. If this is
526 // the result of two address elimination, then the vreg is one of the
527 // def-and-use register operand.
528 if (isReDefinedByTwoAddr(mi, interval.reg, tii_)) {
529 // If this is a two-address definition, then we have already processed
530 // the live range. The only problem is that we didn't realize there
531 // are actually two values in the live interval. Because of this we
532 // need to take the LiveRegion that defines this register and split it
534 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
535 unsigned RedefIndex = getDefIndex(MIIdx);
537 // Delete the initial value, which should be short and continuous,
538 // because the 2-addr copy must be in the same MBB as the redef.
539 interval.removeRange(DefIndex, RedefIndex);
541 // Two-address vregs should always only be redefined once. This means
542 // that at this point, there should be exactly one value number in it.
543 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
545 // The new value number (#1) is defined by the instruction we claimed
547 unsigned ValNo = interval.getNextValue(0, 0);
548 interval.setValueNumberInfo(1, interval.getValNumInfo(0));
550 // Value#0 is now defined by the 2-addr instruction.
551 interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
553 // Add the new live interval which replaces the range for the input copy.
554 LiveRange LR(DefIndex, RedefIndex, ValNo);
555 DOUT << " replace range with " << LR;
556 interval.addRange(LR);
558 // If this redefinition is dead, we need to add a dummy unit live
559 // range covering the def slot.
560 if (lv_->RegisterDefIsDead(mi, interval.reg))
561 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
564 interval.print(DOUT, mri_);
567 // Otherwise, this must be because of phi elimination. If this is the
568 // first redefinition of the vreg that we have seen, go back and change
569 // the live range in the PHI block to be a different value number.
570 if (interval.containsOneValue()) {
571 assert(vi.Kills.size() == 1 &&
572 "PHI elimination vreg should have one kill, the PHI itself!");
574 // Remove the old range that we now know has an incorrect number.
575 MachineInstr *Killer = vi.Kills[0];
576 unsigned Start = getMBBStartIdx(Killer->getParent());
577 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
578 DOUT << "Removing [" << Start << "," << End << "] from: ";
579 interval.print(DOUT, mri_); DOUT << "\n";
580 interval.removeRange(Start, End);
581 DOUT << "RESULT: "; interval.print(DOUT, mri_);
583 // Replace the interval with one of a NEW value number. Note that this
584 // value number isn't actually defined by an instruction, weird huh? :)
585 LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
586 DOUT << " replace range with " << LR;
587 interval.addRange(LR);
588 DOUT << "RESULT: "; interval.print(DOUT, mri_);
591 // In the case of PHI elimination, each variable definition is only
592 // live until the end of the block. We've already taken care of the
593 // rest of the live range.
594 unsigned defIndex = getDefIndex(MIIdx);
597 unsigned SrcReg, DstReg;
598 if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
599 ValNum = interval.getNextValue(~0U, 0);
601 ValNum = interval.getNextValue(defIndex, SrcReg);
603 LiveRange LR(defIndex,
604 getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
605 interval.addRange(LR);
613 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
614 MachineBasicBlock::iterator mi,
616 LiveInterval &interval,
618 // A physical register cannot be live across basic block, so its
619 // lifetime must end somewhere in its defining basic block.
620 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
622 unsigned baseIndex = MIIdx;
623 unsigned start = getDefIndex(baseIndex);
624 unsigned end = start;
626 // If it is not used after definition, it is considered dead at
627 // the instruction defining it. Hence its interval is:
628 // [defSlot(def), defSlot(def)+1)
629 if (lv_->RegisterDefIsDead(mi, interval.reg)) {
631 end = getDefIndex(start) + 1;
635 // If it is not dead on definition, it must be killed by a
636 // subsequent instruction. Hence its interval is:
637 // [defSlot(def), useSlot(kill)+1)
638 while (++mi != MBB->end()) {
639 baseIndex += InstrSlots::NUM;
640 if (lv_->KillsRegister(mi, interval.reg)) {
642 end = getUseIndex(baseIndex) + 1;
644 } else if (lv_->ModifiesRegister(mi, interval.reg)) {
645 // Another instruction redefines the register before it is ever read.
646 // Then the register is essentially dead at the instruction that defines
647 // it. Hence its interval is:
648 // [defSlot(def), defSlot(def)+1)
650 end = getDefIndex(start) + 1;
655 // The only case we should have a dead physreg here without a killing or
656 // instruction where we know it's dead is if it is live-in to the function
658 assert(!SrcReg && "physreg was not killed in defining block!");
659 end = getDefIndex(start) + 1; // It's dead.
662 assert(start < end && "did not find end of interval?");
664 LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
666 interval.addRange(LR);
667 DOUT << " +" << LR << '\n';
670 void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
671 MachineBasicBlock::iterator MI,
674 if (MRegisterInfo::isVirtualRegister(reg))
675 handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
676 else if (allocatableRegs_[reg]) {
677 unsigned SrcReg, DstReg;
678 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
680 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
681 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
682 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
686 /// computeIntervals - computes the live intervals for virtual
687 /// registers. for some ordering of the machine instructions [1,N] a
688 /// live interval is an interval [i, j) where 1 <= i <= j < N for
689 /// which a variable is live
690 void LiveIntervals::computeIntervals() {
691 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
692 << "********** Function: "
693 << ((Value*)mf_->getFunction())->getName() << '\n';
694 bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
696 // Track the index of the current machine instr.
697 unsigned MIIndex = 0;
698 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
700 MachineBasicBlock *MBB = MBBI;
701 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
703 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
704 if (IgnoreFirstInstr) {
706 IgnoreFirstInstr = false;
707 MIIndex += InstrSlots::NUM;
710 for (; MI != miEnd; ++MI) {
711 DOUT << MIIndex << "\t" << *MI;
714 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
715 MachineOperand &MO = MI->getOperand(i);
716 // handle register defs - build intervals
717 if (MO.isRegister() && MO.getReg() && MO.isDef())
718 handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
721 MIIndex += InstrSlots::NUM;
726 /// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
727 /// being the source and IntB being the dest, thus this defines a value number
728 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
729 /// see if we can merge these two pieces of B into a single value number,
730 /// eliminating a copy. For example:
734 /// B1 = A3 <- this copy
736 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
737 /// value number to be replaced with B0 (which simplifies the B liveinterval).
739 /// This returns true if an interval was modified.
741 bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
742 MachineInstr *CopyMI) {
743 unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
745 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
746 // the example above.
747 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
748 unsigned BValNo = BLR->ValId;
750 // Get the location that B is defined at. Two options: either this value has
751 // an unknown definition point or it is defined at CopyIdx. If unknown, we
753 unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
754 if (BValNoDefIdx == ~0U) return false;
755 assert(BValNoDefIdx == CopyIdx &&
756 "Copy doesn't define the value?");
758 // AValNo is the value number in A that defines the copy, A0 in the example.
759 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
760 unsigned AValNo = AValLR->ValId;
762 // If AValNo is defined as a copy from IntB, we can potentially process this.
764 // Get the instruction that defines this value number.
765 unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
766 if (!SrcReg) return false; // Not defined by a copy.
768 // If the value number is not defined by a copy instruction, ignore it.
770 // If the source register comes from an interval other than IntB, we can't
772 if (rep(SrcReg) != IntB.reg) return false;
774 // Get the LiveRange in IntB that this value number starts with.
775 unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
776 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
778 // Make sure that the end of the live range is inside the same block as
780 MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
782 ValLREndInst->getParent() != CopyMI->getParent()) return false;
784 // Okay, we now know that ValLR ends in the same block that the CopyMI
785 // live-range starts. If there are no intervening live ranges between them in
786 // IntB, we can merge them.
787 if (ValLR+1 != BLR) return false;
789 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
791 // We are about to delete CopyMI, so need to remove it as the 'instruction
792 // that defines this value #'.
793 IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
795 // Okay, we can merge them. We need to insert a new liverange:
796 // [ValLR.end, BLR.begin) of either value number, then we merge the
797 // two value numbers.
798 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
799 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
801 // If the IntB live range is assigned to a physical register, and if that
802 // physreg has aliases,
803 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
804 for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
805 LiveInterval &AliasLI = getInterval(*AS);
806 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
807 AliasLI.getNextValue(~0U, 0)));
811 // Okay, merge "B1" into the same value number as "B0".
812 if (BValNo != ValLR->ValId)
813 IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
814 DOUT << " result = "; IntB.print(DOUT, mri_);
817 // Finally, delete the copy instruction.
818 RemoveMachineInstrFromMaps(CopyMI);
819 CopyMI->eraseFromParent();
825 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
826 /// which are the src/dst of the copy instruction CopyMI. This returns true
827 /// if the copy was successfully coallesced away, or if it is never possible
828 /// to coallesce these this copy, due to register constraints. It returns
829 /// false if it is not currently possible to coallesce this interval, but
830 /// it may be possible if other things get coallesced.
831 bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
832 unsigned SrcReg, unsigned DstReg) {
833 DOUT << getInstructionIndex(CopyMI) << '\t' << *CopyMI;
835 // Get representative registers.
836 SrcReg = rep(SrcReg);
837 DstReg = rep(DstReg);
839 // If they are already joined we continue.
840 if (SrcReg == DstReg) {
841 DOUT << "\tCopy already coallesced.\n";
842 return true; // Not coallescable.
845 // If they are both physical registers, we cannot join them.
846 if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
847 MRegisterInfo::isPhysicalRegister(DstReg)) {
848 DOUT << "\tCan not coallesce physregs.\n";
849 return true; // Not coallescable.
852 // We only join virtual registers with allocatable physical registers.
853 if (MRegisterInfo::isPhysicalRegister(SrcReg) && !allocatableRegs_[SrcReg]){
854 DOUT << "\tSrc reg is unallocatable physreg.\n";
855 return true; // Not coallescable.
857 if (MRegisterInfo::isPhysicalRegister(DstReg) && !allocatableRegs_[DstReg]){
858 DOUT << "\tDst reg is unallocatable physreg.\n";
859 return true; // Not coallescable.
862 // If they are not of the same register class, we cannot join them.
863 if (differingRegisterClasses(SrcReg, DstReg)) {
864 DOUT << "\tSrc/Dest are different register classes.\n";
865 return true; // Not coallescable.
868 LiveInterval &SrcInt = getInterval(SrcReg);
869 LiveInterval &DestInt = getInterval(DstReg);
870 assert(SrcInt.reg == SrcReg && DestInt.reg == DstReg &&
871 "Register mapping is horribly broken!");
873 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
874 DOUT << " and "; DestInt.print(DOUT, mri_);
877 // Okay, attempt to join these two intervals. On failure, this returns false.
878 // Otherwise, if one of the intervals being joined is a physreg, this method
879 // always canonicalizes DestInt to be it. The output "SrcInt" will not have
880 // been modified, so we can use this information below to update aliases.
881 if (!JoinIntervals(DestInt, SrcInt)) {
882 // Coallescing failed.
884 // If we can eliminate the copy without merging the live ranges, do so now.
885 if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
888 // Otherwise, we are unable to join the intervals.
889 DOUT << "Interference!\n";
893 bool Swapped = SrcReg == DestInt.reg;
895 std::swap(SrcReg, DstReg);
896 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
897 "LiveInterval::join didn't work right!");
899 // If we're about to merge live ranges into a physical register live range,
900 // we have to update any aliased register's live ranges to indicate that they
901 // have clobbered values for this range.
902 if (MRegisterInfo::isPhysicalRegister(DstReg)) {
903 for (const unsigned *AS = mri_->getAliasSet(DstReg); *AS; ++AS)
904 getInterval(*AS).MergeInClobberRanges(SrcInt);
907 DOUT << "\n\t\tJoined. Result = "; DestInt.print(DOUT, mri_);
910 // If the intervals were swapped by Join, swap them back so that the register
911 // mapping (in the r2i map) is correct.
912 if (Swapped) SrcInt.swap(DestInt);
913 r2iMap_.erase(SrcReg);
914 r2rMap_[SrcReg] = DstReg;
916 // Finally, delete the copy instruction.
917 RemoveMachineInstrFromMaps(CopyMI);
918 CopyMI->eraseFromParent();
924 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
925 /// compute what the resultant value numbers for each value in the input two
926 /// ranges will be. This is complicated by copies between the two which can
927 /// and will commonly cause multiple value numbers to be merged into one.
929 /// VN is the value number that we're trying to resolve. InstDefiningValue
930 /// keeps track of the new InstDefiningValue assignment for the result
931 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
932 /// whether a value in this or other is a copy from the opposite set.
933 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
934 /// already been assigned.
936 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
937 /// contains the value number the copy is from.
939 static unsigned ComputeUltimateVN(unsigned VN,
940 SmallVector<std::pair<unsigned,
941 unsigned>, 16> &ValueNumberInfo,
942 SmallVector<int, 16> &ThisFromOther,
943 SmallVector<int, 16> &OtherFromThis,
944 SmallVector<int, 16> &ThisValNoAssignments,
945 SmallVector<int, 16> &OtherValNoAssignments,
946 LiveInterval &ThisLI, LiveInterval &OtherLI) {
947 // If the VN has already been computed, just return it.
948 if (ThisValNoAssignments[VN] >= 0)
949 return ThisValNoAssignments[VN];
950 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
952 // If this val is not a copy from the other val, then it must be a new value
953 // number in the destination.
954 int OtherValNo = ThisFromOther[VN];
955 if (OtherValNo == -1) {
956 ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
957 return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
960 // Otherwise, this *is* a copy from the RHS. If the other side has already
961 // been computed, return it.
962 if (OtherValNoAssignments[OtherValNo] >= 0)
963 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
965 // Mark this value number as currently being computed, then ask what the
966 // ultimate value # of the other value is.
967 ThisValNoAssignments[VN] = -2;
968 unsigned UltimateVN =
969 ComputeUltimateVN(OtherValNo, ValueNumberInfo,
970 OtherFromThis, ThisFromOther,
971 OtherValNoAssignments, ThisValNoAssignments,
973 return ThisValNoAssignments[VN] = UltimateVN;
976 static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
977 return std::find(V.begin(), V.end(), Val) != V.end();
980 /// SimpleJoin - Attempt to joint the specified interval into this one. The
981 /// caller of this method must guarantee that the RHS only contains a single
982 /// value number and that the RHS is not defined by a copy from this
983 /// interval. This returns false if the intervals are not joinable, or it
984 /// joins them and returns true.
985 bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
986 assert(RHS.containsOneValue());
988 // Some number (potentially more than one) value numbers in the current
989 // interval may be defined as copies from the RHS. Scan the overlapping
990 // portions of the LHS and RHS, keeping track of this and looking for
991 // overlapping live ranges that are NOT defined as copies. If these exist, we
994 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
995 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
997 if (LHSIt->start < RHSIt->start) {
998 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
999 if (LHSIt != LHS.begin()) --LHSIt;
1000 } else if (RHSIt->start < LHSIt->start) {
1001 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1002 if (RHSIt != RHS.begin()) --RHSIt;
1005 SmallVector<unsigned, 8> EliminatedLHSVals;
1008 // Determine if these live intervals overlap.
1009 bool Overlaps = false;
1010 if (LHSIt->start <= RHSIt->start)
1011 Overlaps = LHSIt->end > RHSIt->start;
1013 Overlaps = RHSIt->end > LHSIt->start;
1015 // If the live intervals overlap, there are two interesting cases: if the
1016 // LHS interval is defined by a copy from the RHS, it's ok and we record
1017 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1018 // coallesce these live ranges and we bail out.
1020 // If we haven't already recorded that this value # is safe, check it.
1021 if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
1022 // Copy from the RHS?
1023 unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
1024 if (rep(SrcReg) != RHS.reg)
1025 return false; // Nope, bail out.
1027 EliminatedLHSVals.push_back(LHSIt->ValId);
1030 // We know this entire LHS live range is okay, so skip it now.
1031 if (++LHSIt == LHSEnd) break;
1035 if (LHSIt->end < RHSIt->end) {
1036 if (++LHSIt == LHSEnd) break;
1038 // One interesting case to check here. It's possible that we have
1039 // something like "X3 = Y" which defines a new value number in the LHS,
1040 // and is the last use of this liverange of the RHS. In this case, we
1041 // want to notice this copy (so that it gets coallesced away) even though
1042 // the live ranges don't actually overlap.
1043 if (LHSIt->start == RHSIt->end) {
1044 if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
1045 // We already know that this value number is going to be merged in
1046 // if coallescing succeeds. Just skip the liverange.
1047 if (++LHSIt == LHSEnd) break;
1049 // Otherwise, if this is a copy from the RHS, mark it as being merged
1051 if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
1052 EliminatedLHSVals.push_back(LHSIt->ValId);
1054 // We know this entire LHS live range is okay, so skip it now.
1055 if (++LHSIt == LHSEnd) break;
1060 if (++RHSIt == RHSEnd) break;
1064 // If we got here, we know that the coallescing will be successful and that
1065 // the value numbers in EliminatedLHSVals will all be merged together. Since
1066 // the most common case is that EliminatedLHSVals has a single number, we
1067 // optimize for it: if there is more than one value, we merge them all into
1068 // the lowest numbered one, then handle the interval as if we were merging
1069 // with one value number.
1071 if (EliminatedLHSVals.size() > 1) {
1072 // Loop through all the equal value numbers merging them into the smallest
1074 unsigned Smallest = EliminatedLHSVals[0];
1075 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1076 if (EliminatedLHSVals[i] < Smallest) {
1077 // Merge the current notion of the smallest into the smaller one.
1078 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1079 Smallest = EliminatedLHSVals[i];
1081 // Merge into the smallest.
1082 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1085 LHSValNo = Smallest;
1087 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1088 LHSValNo = EliminatedLHSVals[0];
1091 // Okay, now that there is a single LHS value number that we're merging the
1092 // RHS into, update the value number info for the LHS to indicate that the
1093 // value number is defined where the RHS value number was.
1094 LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1096 // Okay, the final step is to loop over the RHS live intervals, adding them to
1098 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1099 LHS.weight += RHS.weight;
1104 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1105 /// returns false. Otherwise, if one of the intervals being joined is a
1106 /// physreg, this method always canonicalizes LHS to be it. The output
1107 /// "RHS" will not have been modified, so we can use this information
1108 /// below to update aliases.
1109 bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
1110 // Compute the final value assignment, assuming that the live ranges can be
1112 SmallVector<int, 16> LHSValNoAssignments;
1113 SmallVector<int, 16> RHSValNoAssignments;
1114 SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
1116 // Compute ultimate value numbers for the LHS and RHS values.
1117 if (RHS.containsOneValue()) {
1118 // Copies from a liveinterval with a single value are simple to handle and
1119 // very common, handle the special case here. This is important, because
1120 // often RHS is small and LHS is large (e.g. a physreg).
1122 // Find out if the RHS is defined as a copy from some value in the LHS.
1124 std::pair<unsigned,unsigned> RHSValNoInfo;
1125 unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1126 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1127 // If RHS is not defined as a copy from the LHS, we can use simpler and
1128 // faster checks to see if the live ranges are coallescable. This joiner
1129 // can't swap the LHS/RHS intervals though.
1130 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1131 return SimpleJoin(LHS, RHS);
1133 RHSValNoInfo = RHS.getValNumInfo(0);
1136 // It was defined as a copy from the LHS, find out what value # it is.
1137 unsigned ValInst = RHS.getInstForValNum(0);
1138 RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1139 RHSValNoInfo = LHS.getValNumInfo(RHSValID);
1142 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1143 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1144 ValueNumberInfo.resize(LHS.getNumValNums());
1146 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1147 // should now get updated.
1148 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1149 if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1150 if (rep(LHSSrcReg) != RHS.reg) {
1151 // If this is not a copy from the RHS, its value number will be
1152 // unmodified by the coallescing.
1153 ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1154 LHSValNoAssignments[VN] = VN;
1155 } else if (RHSValID == -1) {
1156 // Otherwise, it is a copy from the RHS, and we don't already have a
1157 // value# for it. Keep the current value number, but remember it.
1158 LHSValNoAssignments[VN] = RHSValID = VN;
1159 ValueNumberInfo[VN] = RHSValNoInfo;
1161 // Otherwise, use the specified value #.
1162 LHSValNoAssignments[VN] = RHSValID;
1163 if (VN != (unsigned)RHSValID)
1164 ValueNumberInfo[VN].first = ~1U;
1166 ValueNumberInfo[VN] = RHSValNoInfo;
1169 ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1170 LHSValNoAssignments[VN] = VN;
1174 assert(RHSValID != -1 && "Didn't find value #?");
1175 RHSValNoAssignments[0] = RHSValID;
1178 // Loop over the value numbers of the LHS, seeing if any are defined from
1180 SmallVector<int, 16> LHSValsDefinedFromRHS;
1181 LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1182 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1183 unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1184 if (ValSrcReg == 0) // Src not defined by a copy?
1187 // DstReg is known to be a register in the LHS interval. If the src is
1188 // from the RHS interval, we can use its value #.
1189 if (rep(ValSrcReg) != RHS.reg)
1192 // Figure out the value # from the RHS.
1193 unsigned ValInst = LHS.getInstForValNum(VN);
1194 LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1197 // Loop over the value numbers of the RHS, seeing if any are defined from
1199 SmallVector<int, 16> RHSValsDefinedFromLHS;
1200 RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1201 for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1202 unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1203 if (ValSrcReg == 0) // Src not defined by a copy?
1206 // DstReg is known to be a register in the RHS interval. If the src is
1207 // from the LHS interval, we can use its value #.
1208 if (rep(ValSrcReg) != LHS.reg)
1211 // Figure out the value # from the LHS.
1212 unsigned ValInst = RHS.getInstForValNum(VN);
1213 RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1216 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1217 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1218 ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1220 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1221 if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U)
1223 ComputeUltimateVN(VN, ValueNumberInfo,
1224 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1225 LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1227 for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1228 if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1230 // If this value number isn't a copy from the LHS, it's a new number.
1231 if (RHSValsDefinedFromLHS[VN] == -1) {
1232 ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1233 RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1237 ComputeUltimateVN(VN, ValueNumberInfo,
1238 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1239 RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1243 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1244 // interval lists to see if these intervals are coallescable.
1245 LiveInterval::const_iterator I = LHS.begin();
1246 LiveInterval::const_iterator IE = LHS.end();
1247 LiveInterval::const_iterator J = RHS.begin();
1248 LiveInterval::const_iterator JE = RHS.end();
1250 // Skip ahead until the first place of potential sharing.
1251 if (I->start < J->start) {
1252 I = std::upper_bound(I, IE, J->start);
1253 if (I != LHS.begin()) --I;
1254 } else if (J->start < I->start) {
1255 J = std::upper_bound(J, JE, I->start);
1256 if (J != RHS.begin()) --J;
1260 // Determine if these two live ranges overlap.
1262 if (I->start < J->start) {
1263 Overlaps = I->end > J->start;
1265 Overlaps = J->end > I->start;
1268 // If so, check value # info to determine if they are really different.
1270 // If the live range overlap will map to the same value number in the
1271 // result liverange, we can still coallesce them. If not, we can't.
1272 if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1276 if (I->end < J->end) {
1285 // If we get here, we know that we can coallesce the live ranges. Ask the
1286 // intervals to coallesce themselves now.
1287 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
1294 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1295 // depth of the basic block (the unsigned), and then on the MBB number.
1296 struct DepthMBBCompare {
1297 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1298 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1299 if (LHS.first > RHS.first) return true; // Deeper loops first
1300 return LHS.first == RHS.first &&
1301 LHS.second->getNumber() < RHS.second->getNumber();
1307 void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1308 std::vector<CopyRec> &TryAgain) {
1309 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1311 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1313 MachineInstr *Inst = MII++;
1315 // If this isn't a copy, we can't join intervals.
1316 unsigned SrcReg, DstReg;
1317 if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1319 if (!JoinCopy(Inst, SrcReg, DstReg))
1320 TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
1325 void LiveIntervals::joinIntervals() {
1326 DOUT << "********** JOINING INTERVALS ***********\n";
1328 std::vector<CopyRec> TryAgainList;
1330 const LoopInfo &LI = getAnalysis<LoopInfo>();
1331 if (LI.begin() == LI.end()) {
1332 // If there are no loops in the function, join intervals in function order.
1333 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1335 CopyCoallesceInMBB(I, TryAgainList);
1337 // Otherwise, join intervals in inner loops before other intervals.
1338 // Unfortunately we can't just iterate over loop hierarchy here because
1339 // there may be more MBB's than BB's. Collect MBB's for sorting.
1340 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1341 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1343 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1345 // Sort by loop depth.
1346 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1348 // Finally, join intervals in loop nest order.
1349 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
1350 CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1353 // Joining intervals can allow other intervals to be joined. Iteratively join
1354 // until we make no progress.
1355 bool ProgressMade = true;
1356 while (ProgressMade) {
1357 ProgressMade = false;
1359 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1360 CopyRec &TheCopy = TryAgainList[i];
1362 JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1363 TheCopy.MI = 0; // Mark this one as done.
1364 ProgressMade = true;
1369 DOUT << "*** Register mapping ***\n";
1370 for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1372 DOUT << " reg " << i << " -> ";
1373 DEBUG(printRegName(r2rMap_[i]));
1378 /// Return true if the two specified registers belong to different register
1379 /// classes. The registers may be either phys or virt regs.
1380 bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1381 unsigned RegB) const {
1383 // Get the register classes for the first reg.
1384 if (MRegisterInfo::isPhysicalRegister(RegA)) {
1385 assert(MRegisterInfo::isVirtualRegister(RegB) &&
1386 "Shouldn't consider two physregs!");
1387 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1390 // Compare against the regclass for the second reg.
1391 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1392 if (MRegisterInfo::isVirtualRegister(RegB))
1393 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1395 return !RegClass->contains(RegB);
1398 LiveInterval LiveIntervals::createInterval(unsigned reg) {
1399 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
1401 return LiveInterval(reg, Weight);