1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
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 a simple register coalescing pass that attempts to
11 // aggressively coalesce every register copy that it can.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regcoalescing"
16 #include "llvm/CodeGen/SimpleRegisterCoalescing.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "VirtRegMap.h"
19 #include "llvm/Value.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/CodeGen/LiveVariables.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
38 STATISTIC(numJoins , "Number of interval joins performed");
39 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
40 STATISTIC(numAborts , "Number of times interval joining aborted");
42 char SimpleRegisterCoalescing::ID = 0;
45 EnableJoining("join-liveintervals",
46 cl::desc("Coalesce copies (default=true)"),
49 RegisterPass<SimpleRegisterCoalescing>
50 X("simple-register-coalescing", "Simple Register Coalescing");
53 const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
55 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
56 //AU.addPreserved<LiveVariables>();
57 AU.addPreserved<LiveIntervals>();
58 AU.addPreservedID(PHIEliminationID);
59 AU.addPreservedID(TwoAddressInstructionPassID);
60 AU.addRequired<LiveVariables>();
61 AU.addRequired<LiveIntervals>();
62 AU.addRequired<LoopInfo>();
63 MachineFunctionPass::getAnalysisUsage(AU);
66 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
67 /// being the source and IntB being the dest, thus this defines a value number
68 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
69 /// see if we can merge these two pieces of B into a single value number,
70 /// eliminating a copy. For example:
74 /// B1 = A3 <- this copy
76 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
77 /// value number to be replaced with B0 (which simplifies the B liveinterval).
79 /// This returns true if an interval was modified.
81 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
82 MachineInstr *CopyMI) {
83 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
85 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
87 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
88 VNInfo *BValNo = BLR->valno;
90 // Get the location that B is defined at. Two options: either this value has
91 // an unknown definition point or it is defined at CopyIdx. If unknown, we
93 if (!BValNo->reg) return false;
94 assert(BValNo->def == CopyIdx &&
95 "Copy doesn't define the value?");
97 // AValNo is the value number in A that defines the copy, A0 in the example.
98 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
99 VNInfo *AValNo = AValLR->valno;
101 // If AValNo is defined as a copy from IntB, we can potentially process this.
103 // Get the instruction that defines this value number.
104 unsigned SrcReg = AValNo->reg;
105 if (!SrcReg) return false; // Not defined by a copy.
107 // If the value number is not defined by a copy instruction, ignore it.
109 // If the source register comes from an interval other than IntB, we can't
111 if (rep(SrcReg) != IntB.reg) return false;
113 // Get the LiveRange in IntB that this value number starts with.
114 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
116 // Make sure that the end of the live range is inside the same block as
118 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
120 ValLREndInst->getParent() != CopyMI->getParent()) return false;
122 // Okay, we now know that ValLR ends in the same block that the CopyMI
123 // live-range starts. If there are no intervening live ranges between them in
124 // IntB, we can merge them.
125 if (ValLR+1 != BLR) return false;
127 // If a live interval is a physical register, conservatively check if any
128 // of its sub-registers is overlapping the live interval of the virtual
129 // register. If so, do not coalesce.
130 if (MRegisterInfo::isPhysicalRegister(IntB.reg) &&
131 *mri_->getSubRegisters(IntB.reg)) {
132 for (const unsigned* SR = mri_->getSubRegisters(IntB.reg); *SR; ++SR)
133 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
134 DOUT << "Interfere with sub-register ";
135 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
140 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
142 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
143 // We are about to delete CopyMI, so need to remove it as the 'instruction
144 // that defines this value #'. Update the the valnum with the new defining
146 BValNo->def = FillerStart;
149 // Okay, we can merge them. We need to insert a new liverange:
150 // [ValLR.end, BLR.begin) of either value number, then we merge the
151 // two value numbers.
152 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
154 // If the IntB live range is assigned to a physical register, and if that
155 // physreg has aliases,
156 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
157 // Update the liveintervals of sub-registers.
158 for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
159 LiveInterval &AliasLI = li_->getInterval(*AS);
160 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
161 AliasLI.getNextValue(FillerStart, 0)));
165 // Okay, merge "B1" into the same value number as "B0".
166 if (BValNo != ValLR->valno)
167 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
168 DOUT << " result = "; IntB.print(DOUT, mri_);
171 // If the source instruction was killing the source register before the
172 // merge, unset the isKill marker given the live range has been extended.
173 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
175 ValLREndInst->getOperand(UIdx).unsetIsKill();
177 // Finally, delete the copy instruction.
178 li_->RemoveMachineInstrFromMaps(CopyMI);
179 CopyMI->eraseFromParent();
184 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
185 /// which are the src/dst of the copy instruction CopyMI. This returns true
186 /// if the copy was successfully coalesced away, or if it is never possible
187 /// to coalesce this copy, due to register constraints. It returns
188 /// false if it is not currently possible to coalesce this interval, but
189 /// it may be possible if other things get coalesced.
190 bool SimpleRegisterCoalescing::JoinCopy(MachineInstr *CopyMI,
191 unsigned SrcReg, unsigned DstReg, bool PhysOnly) {
192 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
194 // Get representative registers.
195 unsigned repSrcReg = rep(SrcReg);
196 unsigned repDstReg = rep(DstReg);
198 // If they are already joined we continue.
199 if (repSrcReg == repDstReg) {
200 DOUT << "\tCopy already coalesced.\n";
201 return true; // Not coalescable.
204 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
205 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
206 if (PhysOnly && !SrcIsPhys && !DstIsPhys)
207 // Only joining physical registers with virtual registers in this round.
210 // If they are both physical registers, we cannot join them.
211 if (SrcIsPhys && DstIsPhys) {
212 DOUT << "\tCan not coalesce physregs.\n";
213 return true; // Not coalescable.
216 // We only join virtual registers with allocatable physical registers.
217 if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
218 DOUT << "\tSrc reg is unallocatable physreg.\n";
219 return true; // Not coalescable.
221 if (DstIsPhys && !allocatableRegs_[repDstReg]) {
222 DOUT << "\tDst reg is unallocatable physreg.\n";
223 return true; // Not coalescable.
226 // If they are not of the same register class, we cannot join them.
227 if (differingRegisterClasses(repSrcReg, repDstReg)) {
228 DOUT << "\tSrc/Dest are different register classes.\n";
229 return true; // Not coalescable.
232 LiveInterval &SrcInt = li_->getInterval(repSrcReg);
233 LiveInterval &DstInt = li_->getInterval(repDstReg);
234 assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
235 "Register mapping is horribly broken!");
237 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
238 DOUT << " and "; DstInt.print(DOUT, mri_);
241 // Check if it is necessary to propagate "isDead" property before intervals
243 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
244 bool isDead = mopd->isDead();
245 bool isShorten = false;
246 unsigned SrcStart = 0, RemoveStart = 0;
247 unsigned SrcEnd = 0, RemoveEnd = 0;
249 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
250 LiveInterval::iterator SrcLR =
251 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
252 RemoveStart = SrcStart = SrcLR->start;
253 RemoveEnd = SrcEnd = SrcLR->end;
254 // The instruction which defines the src is only truly dead if there are
255 // no intermediate uses and there isn't a use beyond the copy.
256 // FIXME: find the last use, mark is kill and shorten the live range.
257 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
261 MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
263 // Shorten the liveinterval to the end of last use.
267 RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
270 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
272 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
274 // A dead def should have a single cycle interval.
281 // We need to be careful about coalescing a source physical register with a
282 // virtual register. Once the coalescing is done, it cannot be broken and
283 // these are not spillable! If the destination interval uses are far away,
284 // think twice about coalescing them!
285 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys)) {
286 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
287 unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
288 unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
289 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
290 unsigned Threshold = allocatableRCRegs_[RC].count();
292 // If the virtual register live interval is long has it has low use desity,
293 // do not join them, instead mark the physical register as its allocation
295 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
296 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
297 if (Length > Threshold &&
298 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
299 JoinVInt.preference = JoinPReg;
301 DOUT << "\tMay tie down a physical register, abort!\n";
306 // Okay, attempt to join these two intervals. On failure, this returns false.
307 // Otherwise, if one of the intervals being joined is a physreg, this method
308 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
309 // been modified, so we can use this information below to update aliases.
310 bool Swapped = false;
311 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
313 // Result of the copy is dead. Propagate this property.
315 assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
316 "Live-in must be a physical register!");
317 // Live-in to the function but dead. Remove it from entry live-in set.
318 // JoinIntervals may end up swapping the two intervals.
319 mf_->begin()->removeLiveIn(repSrcReg);
321 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
323 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
330 if (isShorten || isDead) {
331 // Shorten the destination live interval.
333 SrcInt.removeRange(RemoveStart, RemoveEnd);
336 // Coalescing failed.
338 // If we can eliminate the copy without merging the live ranges, do so now.
339 if (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI))
342 // Otherwise, we are unable to join the intervals.
343 DOUT << "Interference!\n";
347 LiveInterval *ResSrcInt = &SrcInt;
348 LiveInterval *ResDstInt = &DstInt;
350 std::swap(repSrcReg, repDstReg);
351 std::swap(ResSrcInt, ResDstInt);
353 assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
354 "LiveInterval::join didn't work right!");
356 // If we're about to merge live ranges into a physical register live range,
357 // we have to update any aliased register's live ranges to indicate that they
358 // have clobbered values for this range.
359 if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
360 // Unset unnecessary kills.
361 if (!ResDstInt->containsOneValue()) {
362 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
363 E = ResSrcInt->end(); I != E; ++I)
364 unsetRegisterKills(I->start, I->end, repDstReg);
367 // Update the liveintervals of sub-registers.
368 for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
369 li_->getInterval(*AS).MergeInClobberRanges(*ResSrcInt);
371 // Merge use info if the destination is a virtual register.
372 LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
373 LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
374 dVI.NumUses += sVI.NumUses;
377 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, mri_);
380 // Remember these liveintervals have been joined.
381 JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
382 if (MRegisterInfo::isVirtualRegister(repDstReg))
383 JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
385 // repSrcReg is guarateed to be the register whose live interval that is
387 li_->removeInterval(repSrcReg);
388 r2rMap_[repSrcReg] = repDstReg;
390 // Finally, delete the copy instruction.
391 li_->RemoveMachineInstrFromMaps(CopyMI);
392 CopyMI->eraseFromParent();
398 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
399 /// compute what the resultant value numbers for each value in the input two
400 /// ranges will be. This is complicated by copies between the two which can
401 /// and will commonly cause multiple value numbers to be merged into one.
403 /// VN is the value number that we're trying to resolve. InstDefiningValue
404 /// keeps track of the new InstDefiningValue assignment for the result
405 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
406 /// whether a value in this or other is a copy from the opposite set.
407 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
408 /// already been assigned.
410 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
411 /// contains the value number the copy is from.
413 static unsigned ComputeUltimateVN(VNInfo *VNI,
414 SmallVector<VNInfo*, 16> &NewVNInfo,
415 SmallVector<VNInfo*, 16> &ThisFromOther,
416 SmallVector<VNInfo*, 16> &OtherFromThis,
417 SmallVector<int, 16> &ThisValNoAssignments,
418 SmallVector<int, 16> &OtherValNoAssignments) {
419 unsigned VN = VNI->id;
421 // If the VN has already been computed, just return it.
422 if (ThisValNoAssignments[VN] >= 0)
423 return ThisValNoAssignments[VN];
424 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
426 // If this val is not a copy from the other val, then it must be a new value
427 // number in the destination.
428 VNInfo *OtherValNo = ThisFromOther[VN];
430 NewVNInfo.push_back(VNI);
431 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
434 // Otherwise, this *is* a copy from the RHS. If the other side has already
435 // been computed, return it.
436 if (OtherValNoAssignments[OtherValNo->id] >= 0)
437 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
439 // Mark this value number as currently being computed, then ask what the
440 // ultimate value # of the other value is.
441 ThisValNoAssignments[VN] = -2;
442 unsigned UltimateVN =
443 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
444 OtherValNoAssignments, ThisValNoAssignments);
445 return ThisValNoAssignments[VN] = UltimateVN;
448 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
449 return std::find(V.begin(), V.end(), Val) != V.end();
452 /// SimpleJoin - Attempt to joint the specified interval into this one. The
453 /// caller of this method must guarantee that the RHS only contains a single
454 /// value number and that the RHS is not defined by a copy from this
455 /// interval. This returns false if the intervals are not joinable, or it
456 /// joins them and returns true.
457 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
458 assert(RHS.containsOneValue());
460 // Some number (potentially more than one) value numbers in the current
461 // interval may be defined as copies from the RHS. Scan the overlapping
462 // portions of the LHS and RHS, keeping track of this and looking for
463 // overlapping live ranges that are NOT defined as copies. If these exist, we
466 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
467 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
469 if (LHSIt->start < RHSIt->start) {
470 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
471 if (LHSIt != LHS.begin()) --LHSIt;
472 } else if (RHSIt->start < LHSIt->start) {
473 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
474 if (RHSIt != RHS.begin()) --RHSIt;
477 SmallVector<VNInfo*, 8> EliminatedLHSVals;
480 // Determine if these live intervals overlap.
481 bool Overlaps = false;
482 if (LHSIt->start <= RHSIt->start)
483 Overlaps = LHSIt->end > RHSIt->start;
485 Overlaps = RHSIt->end > LHSIt->start;
487 // If the live intervals overlap, there are two interesting cases: if the
488 // LHS interval is defined by a copy from the RHS, it's ok and we record
489 // that the LHS value # is the same as the RHS. If it's not, then we cannot
490 // coalesce these live ranges and we bail out.
492 // If we haven't already recorded that this value # is safe, check it.
493 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
494 // Copy from the RHS?
495 unsigned SrcReg = LHSIt->valno->reg;
496 if (rep(SrcReg) != RHS.reg)
497 return false; // Nope, bail out.
499 EliminatedLHSVals.push_back(LHSIt->valno);
502 // We know this entire LHS live range is okay, so skip it now.
503 if (++LHSIt == LHSEnd) break;
507 if (LHSIt->end < RHSIt->end) {
508 if (++LHSIt == LHSEnd) break;
510 // One interesting case to check here. It's possible that we have
511 // something like "X3 = Y" which defines a new value number in the LHS,
512 // and is the last use of this liverange of the RHS. In this case, we
513 // want to notice this copy (so that it gets coalesced away) even though
514 // the live ranges don't actually overlap.
515 if (LHSIt->start == RHSIt->end) {
516 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
517 // We already know that this value number is going to be merged in
518 // if coalescing succeeds. Just skip the liverange.
519 if (++LHSIt == LHSEnd) break;
521 // Otherwise, if this is a copy from the RHS, mark it as being merged
523 if (rep(LHSIt->valno->reg) == RHS.reg) {
524 EliminatedLHSVals.push_back(LHSIt->valno);
526 // We know this entire LHS live range is okay, so skip it now.
527 if (++LHSIt == LHSEnd) break;
532 if (++RHSIt == RHSEnd) break;
536 // If we got here, we know that the coalescing will be successful and that
537 // the value numbers in EliminatedLHSVals will all be merged together. Since
538 // the most common case is that EliminatedLHSVals has a single number, we
539 // optimize for it: if there is more than one value, we merge them all into
540 // the lowest numbered one, then handle the interval as if we were merging
541 // with one value number.
543 if (EliminatedLHSVals.size() > 1) {
544 // Loop through all the equal value numbers merging them into the smallest
546 VNInfo *Smallest = EliminatedLHSVals[0];
547 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
548 if (EliminatedLHSVals[i]->id < Smallest->id) {
549 // Merge the current notion of the smallest into the smaller one.
550 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
551 Smallest = EliminatedLHSVals[i];
553 // Merge into the smallest.
554 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
559 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
560 LHSValNo = EliminatedLHSVals[0];
563 // Okay, now that there is a single LHS value number that we're merging the
564 // RHS into, update the value number info for the LHS to indicate that the
565 // value number is defined where the RHS value number was.
566 const VNInfo *VNI = RHS.getFirstValNumInfo();
567 LHSValNo->def = VNI->def;
568 LHSValNo->reg = VNI->reg;
570 // Okay, the final step is to loop over the RHS live intervals, adding them to
572 LHS.addKills(*LHSValNo, VNI->kills);
573 LHS.MergeRangesInAsValue(RHS, LHSValNo);
574 LHS.weight += RHS.weight;
575 if (RHS.preference && !LHS.preference)
576 LHS.preference = RHS.preference;
581 /// JoinIntervals - Attempt to join these two intervals. On failure, this
582 /// returns false. Otherwise, if one of the intervals being joined is a
583 /// physreg, this method always canonicalizes LHS to be it. The output
584 /// "RHS" will not have been modified, so we can use this information
585 /// below to update aliases.
586 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
587 LiveInterval &RHS, bool &Swapped) {
588 // Compute the final value assignment, assuming that the live ranges can be
590 SmallVector<int, 16> LHSValNoAssignments;
591 SmallVector<int, 16> RHSValNoAssignments;
592 SmallVector<VNInfo*, 16> LHSValsDefinedFromRHS;
593 SmallVector<VNInfo*, 16> RHSValsDefinedFromLHS;
594 SmallVector<VNInfo*, 16> NewVNInfo;
596 // If a live interval is a physical register, conservatively check if any
597 // of its sub-registers is overlapping the live interval of the virtual
598 // register. If so, do not coalesce.
599 if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
600 *mri_->getSubRegisters(LHS.reg)) {
601 for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
602 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
603 DOUT << "Interfere with sub-register ";
604 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
607 } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
608 *mri_->getSubRegisters(RHS.reg)) {
609 for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
610 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
611 DOUT << "Interfere with sub-register ";
612 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
617 LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), NULL);
618 RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), NULL);
620 // Compute ultimate value numbers for the LHS and RHS values.
621 if (RHS.containsOneValue()) {
622 // Copies from a liveinterval with a single value are simple to handle and
623 // very common, handle the special case here. This is important, because
624 // often RHS is small and LHS is large (e.g. a physreg).
626 // Find out if the RHS is defined as a copy from some value in the LHS.
627 int RHSVal0DefinedFromLHS = -1;
629 VNInfo *RHSValNoInfo = NULL;
630 unsigned RHSSrcReg = RHS.getFirstValNumInfo()->reg;
631 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
632 // If RHS is not defined as a copy from the LHS, we can use simpler and
633 // faster checks to see if the live ranges are coalescable. This joiner
634 // can't swap the LHS/RHS intervals though.
635 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
636 return SimpleJoin(LHS, RHS);
638 RHSValNoInfo = RHS.getFirstValNumInfo();
641 // It was defined as a copy from the LHS, find out what value # it is.
642 const VNInfo *VNI = RHS.getFirstValNumInfo();
643 RHSValNoInfo = LHS.getLiveRangeContaining(VNI->def-1)->valno;
644 RHSValID = RHSValNoInfo->id;
645 RHSVal0DefinedFromLHS = RHSValID;
648 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
649 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
650 NewVNInfo.resize(LHS.getNumValNums(), NULL);
652 // Okay, *all* of the values in LHS that are defined as a copy from RHS
653 // should now get updated.
654 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
657 unsigned VN = VNI->id;
658 if (unsigned LHSSrcReg = VNI->reg) {
659 if (rep(LHSSrcReg) != RHS.reg) {
660 // If this is not a copy from the RHS, its value number will be
661 // unmodified by the coalescing.
663 LHSValNoAssignments[VN] = VN;
664 } else if (RHSValID == -1) {
665 // Otherwise, it is a copy from the RHS, and we don't already have a
666 // value# for it. Keep the current value number, but remember it.
667 LHSValNoAssignments[VN] = RHSValID = VN;
668 NewVNInfo[VN] = RHSValNoInfo;
669 LHSValsDefinedFromRHS[VN] = VNI;
671 // Otherwise, use the specified value #.
672 LHSValNoAssignments[VN] = RHSValID;
673 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
674 NewVNInfo[VN] = RHSValNoInfo;
675 LHSValsDefinedFromRHS[VN] = VNI;
680 LHSValNoAssignments[VN] = VN;
684 assert(RHSValID != -1 && "Didn't find value #?");
685 RHSValNoAssignments[0] = RHSValID;
686 if (RHSVal0DefinedFromLHS != -1) {
687 const VNInfo *VNI = RHS.getFirstValNumInfo();
688 RHSValsDefinedFromLHS[0] = LHS.getLiveRangeContaining(VNI->def-1)->valno;
691 // Loop over the value numbers of the LHS, seeing if any are defined from
693 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
696 unsigned VN = VNI->id;
697 unsigned ValSrcReg = VNI->reg;
698 if (ValSrcReg == 0) // Src not defined by a copy?
701 // DstReg is known to be a register in the LHS interval. If the src is
702 // from the RHS interval, we can use its value #.
703 if (rep(ValSrcReg) != RHS.reg)
706 // Figure out the value # from the RHS.
707 LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
710 // Loop over the value numbers of the RHS, seeing if any are defined from
712 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
715 unsigned VN = VNI->id;
716 unsigned ValSrcReg = VNI->reg;
717 if (ValSrcReg == 0) // Src not defined by a copy?
720 // DstReg is known to be a register in the RHS interval. If the src is
721 // from the LHS interval, we can use its value #.
722 if (rep(ValSrcReg) != LHS.reg)
725 // Figure out the value # from the LHS.
726 RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(VNI->def-1)->valno;
729 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
730 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
731 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
733 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
736 unsigned VN = VNI->id;
737 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
739 ComputeUltimateVN(VNI, NewVNInfo,
740 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
741 LHSValNoAssignments, RHSValNoAssignments);
743 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
746 unsigned VN = VNI->id;
747 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
749 // If this value number isn't a copy from the LHS, it's a new number.
750 if (!RHSValsDefinedFromLHS[VN]) {
751 NewVNInfo.push_back(VNI);
752 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
756 ComputeUltimateVN(VNI, NewVNInfo,
757 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
758 RHSValNoAssignments, LHSValNoAssignments);
762 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
763 // interval lists to see if these intervals are coalescable.
764 LiveInterval::const_iterator I = LHS.begin();
765 LiveInterval::const_iterator IE = LHS.end();
766 LiveInterval::const_iterator J = RHS.begin();
767 LiveInterval::const_iterator JE = RHS.end();
769 // Skip ahead until the first place of potential sharing.
770 if (I->start < J->start) {
771 I = std::upper_bound(I, IE, J->start);
772 if (I != LHS.begin()) --I;
773 } else if (J->start < I->start) {
774 J = std::upper_bound(J, JE, I->start);
775 if (J != RHS.begin()) --J;
779 // Determine if these two live ranges overlap.
781 if (I->start < J->start) {
782 Overlaps = I->end > J->start;
784 Overlaps = J->end > I->start;
787 // If so, check value # info to determine if they are really different.
789 // If the live range overlap will map to the same value number in the
790 // result liverange, we can still coalesce them. If not, we can't.
791 if (LHSValNoAssignments[I->valno->id] !=
792 RHSValNoAssignments[J->valno->id])
796 if (I->end < J->end) {
805 // Update kill info. Some live ranges are extended due to copy coalescing.
806 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
809 unsigned VN = VNI->id;
810 if (VN >= RHSValsDefinedFromLHS.size() || !RHSValsDefinedFromLHS[VN])
812 unsigned RHSValID = RHSValNoAssignments[VN];
813 LiveInterval::removeKill(*NewVNInfo[RHSValID], VNI->def);
814 LHS.addKills(*NewVNInfo[RHSValID], VNI->kills);
816 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
819 unsigned VN = VNI->id;
820 if (VN >= LHSValsDefinedFromRHS.size() || !LHSValsDefinedFromRHS[VN])
822 unsigned LHSValID = LHSValNoAssignments[VN];
823 LiveInterval::removeKill(*NewVNInfo[LHSValID], VNI->def);
824 RHS.addKills(*NewVNInfo[LHSValID], VNI->kills);
827 // If we get here, we know that we can coalesce the live ranges. Ask the
828 // intervals to coalesce themselves now.
829 if ((RHS.ranges.size() > LHS.ranges.size() &&
830 MRegisterInfo::isVirtualRegister(LHS.reg)) ||
831 MRegisterInfo::isPhysicalRegister(RHS.reg)) {
832 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
835 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
842 // DepthMBBCompare - Comparison predicate that sort first based on the loop
843 // depth of the basic block (the unsigned), and then on the MBB number.
844 struct DepthMBBCompare {
845 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
846 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
847 if (LHS.first > RHS.first) return true; // Deeper loops first
848 return LHS.first == RHS.first &&
849 LHS.second->getNumber() < RHS.second->getNumber();
854 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
855 std::vector<CopyRec> *TryAgain, bool PhysOnly) {
856 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
858 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
860 MachineInstr *Inst = MII++;
862 // If this isn't a copy, we can't join intervals.
863 unsigned SrcReg, DstReg;
864 if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
866 if (TryAgain && !JoinCopy(Inst, SrcReg, DstReg, PhysOnly))
867 TryAgain->push_back(getCopyRec(Inst, SrcReg, DstReg));
871 void SimpleRegisterCoalescing::joinIntervals() {
872 DOUT << "********** JOINING INTERVALS ***********\n";
874 JoinedLIs.resize(li_->getNumIntervals());
877 std::vector<CopyRec> TryAgainList;
878 const LoopInfo &LI = getAnalysis<LoopInfo>();
879 if (LI.begin() == LI.end()) {
880 // If there are no loops in the function, join intervals in function order.
881 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
883 CopyCoalesceInMBB(I, &TryAgainList);
885 // Otherwise, join intervals in inner loops before other intervals.
886 // Unfortunately we can't just iterate over loop hierarchy here because
887 // there may be more MBB's than BB's. Collect MBB's for sorting.
889 // Join intervals in the function prolog first. We want to join physical
890 // registers with virtual registers before the intervals got too long.
891 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
892 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
893 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
895 // Sort by loop depth.
896 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
898 // Finally, join intervals in loop nest order.
899 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
900 CopyCoalesceInMBB(MBBs[i].second, NULL, true);
901 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
902 CopyCoalesceInMBB(MBBs[i].second, &TryAgainList, false);
905 // Joining intervals can allow other intervals to be joined. Iteratively join
906 // until we make no progress.
907 bool ProgressMade = true;
908 while (ProgressMade) {
909 ProgressMade = false;
911 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
912 CopyRec &TheCopy = TryAgainList[i];
914 JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
915 TheCopy.MI = 0; // Mark this one as done.
921 // Some live range has been lengthened due to colaescing, eliminate the
922 // unnecessary kills.
923 int RegNum = JoinedLIs.find_first();
924 while (RegNum != -1) {
925 unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
926 unsigned repReg = rep(Reg);
927 LiveInterval &LI = li_->getInterval(repReg);
928 LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
929 for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
930 MachineInstr *Kill = svi.Kills[i];
931 // Suppose vr1 = op vr2, x
932 // and vr1 and vr2 are coalesced. vr2 should still be marked kill
933 // unless it is a two-address operand.
934 if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
936 if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
937 unsetRegisterKill(Kill, repReg);
939 RegNum = JoinedLIs.find_next(RegNum);
942 DOUT << "*** Register mapping ***\n";
943 for (int i = 0, e = r2rMap_.size(); i != e; ++i)
945 DOUT << " reg " << i << " -> ";
946 DEBUG(printRegName(r2rMap_[i]));
951 /// Return true if the two specified registers belong to different register
952 /// classes. The registers may be either phys or virt regs.
953 bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
954 unsigned RegB) const {
956 // Get the register classes for the first reg.
957 if (MRegisterInfo::isPhysicalRegister(RegA)) {
958 assert(MRegisterInfo::isVirtualRegister(RegB) &&
959 "Shouldn't consider two physregs!");
960 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
963 // Compare against the regclass for the second reg.
964 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
965 if (MRegisterInfo::isVirtualRegister(RegB))
966 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
968 return !RegClass->contains(RegB);
971 /// lastRegisterUse - Returns the last use of the specific register between
972 /// cycles Start and End. It also returns the use operand by reference. It
973 /// returns NULL if there are no uses.
975 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
976 MachineOperand *&MOU) {
977 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
980 // Skip deleted instructions
981 MachineInstr *MI = li_->getInstructionFromIndex(e);
982 while ((e - InstrSlots::NUM) >= s && !MI) {
983 e -= InstrSlots::NUM;
984 MI = li_->getInstructionFromIndex(e);
986 if (e < s || MI == NULL)
989 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
990 MachineOperand &MO = MI->getOperand(i);
991 if (MO.isReg() && MO.isUse() && MO.getReg() &&
992 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
998 e -= InstrSlots::NUM;
1005 /// findDefOperand - Returns the MachineOperand that is a def of the specific
1006 /// register. It returns NULL if the def is not found.
1007 MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
1008 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1009 MachineOperand &MO = MI->getOperand(i);
1010 if (MO.isReg() && MO.isDef() &&
1011 mri_->regsOverlap(rep(MO.getReg()), Reg))
1017 /// unsetRegisterKill - Unset IsKill property of all uses of specific register
1018 /// of the specific instruction.
1019 void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1020 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1021 MachineOperand &MO = MI->getOperand(i);
1022 if (MO.isReg() && MO.isKill() && MO.getReg() &&
1023 mri_->regsOverlap(rep(MO.getReg()), Reg))
1028 /// unsetRegisterKills - Unset IsKill property of all uses of specific register
1029 /// between cycles Start and End.
1030 void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1032 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1035 // Skip deleted instructions
1036 MachineInstr *MI = li_->getInstructionFromIndex(e);
1037 while ((e - InstrSlots::NUM) >= s && !MI) {
1038 e -= InstrSlots::NUM;
1039 MI = li_->getInstructionFromIndex(e);
1041 if (e < s || MI == NULL)
1044 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1045 MachineOperand &MO = MI->getOperand(i);
1046 if (MO.isReg() && MO.isKill() && MO.getReg() &&
1047 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1052 e -= InstrSlots::NUM;
1056 /// hasRegisterDef - True if the instruction defines the specific register.
1058 bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1059 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1060 MachineOperand &MO = MI->getOperand(i);
1061 if (MO.isReg() && MO.isDef() &&
1062 mri_->regsOverlap(rep(MO.getReg()), Reg))
1068 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1069 if (MRegisterInfo::isPhysicalRegister(reg))
1070 cerr << mri_->getName(reg);
1072 cerr << "%reg" << reg;
1075 void SimpleRegisterCoalescing::releaseMemory() {
1080 static bool isZeroLengthInterval(LiveInterval *li) {
1081 for (LiveInterval::Ranges::const_iterator
1082 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1083 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1088 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1090 tm_ = &fn.getTarget();
1091 mri_ = tm_->getRegisterInfo();
1092 tii_ = tm_->getInstrInfo();
1093 li_ = &getAnalysis<LiveIntervals>();
1094 lv_ = &getAnalysis<LiveVariables>();
1096 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1097 << "********** Function: "
1098 << ((Value*)mf_->getFunction())->getName() << '\n';
1100 allocatableRegs_ = mri_->getAllocatableSet(fn);
1101 for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1102 E = mri_->regclass_end(); I != E; ++I)
1103 allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1105 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
1107 // Join (coalesce) intervals if requested.
1108 if (EnableJoining) {
1110 DOUT << "********** INTERVALS POST JOINING **********\n";
1111 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1112 I->second.print(DOUT, mri_);
1117 // perform a final pass over the instructions and compute spill
1118 // weights, coalesce virtual registers and remove identity moves.
1119 const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
1121 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1122 mbbi != mbbe; ++mbbi) {
1123 MachineBasicBlock* mbb = mbbi;
1124 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
1126 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1128 // if the move will be an identity move delete it
1129 unsigned srcReg, dstReg, RegRep;
1130 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1131 (RegRep = rep(srcReg)) == rep(dstReg)) {
1132 // remove from def list
1133 LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1134 MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1135 // If def of this move instruction is dead, remove its live range from
1136 // the dstination register's live interval.
1138 unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1139 LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1140 RegInt.removeRange(MLR->start, MoveIdx+1);
1142 li_->removeInterval(RegRep);
1144 li_->RemoveMachineInstrFromMaps(mii);
1145 mii = mbbi->erase(mii);
1148 SmallSet<unsigned, 4> UniqueUses;
1149 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1150 const MachineOperand &mop = mii->getOperand(i);
1151 if (mop.isRegister() && mop.getReg() &&
1152 MRegisterInfo::isVirtualRegister(mop.getReg())) {
1153 // replace register with representative register
1154 unsigned reg = rep(mop.getReg());
1155 mii->getOperand(i).setReg(reg);
1157 // Multiple uses of reg by the same instruction. It should not
1158 // contribute to spill weight again.
1159 if (UniqueUses.count(reg) != 0)
1161 LiveInterval &RegInt = li_->getInterval(reg);
1162 float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
1164 UniqueUses.insert(reg);
1172 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1173 LiveInterval &LI = I->second;
1174 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1175 // If the live interval length is essentially zero, i.e. in every live
1176 // range the use follows def immediately, it doesn't make sense to spill
1177 // it and hope it will be easier to allocate for this li.
1178 if (isZeroLengthInterval(&LI))
1179 LI.weight = HUGE_VALF;
1181 // Slightly prefer live interval that has been assigned a preferred reg.
1185 // Divide the weight of the interval by its size. This encourages
1186 // spilling of intervals that are large and have few uses, and
1187 // discourages spilling of small intervals with many uses.
1188 LI.weight /= LI.getSize();
1196 /// print - Implement the dump method.
1197 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {