1 //===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "SimpleRegisterCoalescing.h"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/Value.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
37 STATISTIC(numJoins , "Number of interval joins performed");
38 STATISTIC(numSubJoins , "Number of subclass joins performed");
39 STATISTIC(numCommutes , "Number of instruction commuting performed");
40 STATISTIC(numExtends , "Number of copies extended");
41 STATISTIC(NumReMats , "Number of instructions re-materialized");
42 STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
43 STATISTIC(numAborts , "Number of times interval joining aborted");
45 char SimpleRegisterCoalescing::ID = 0;
47 EnableJoining("join-liveintervals",
48 cl::desc("Coalesce copies (default=true)"),
52 NewHeuristic("new-coalescer-heuristic",
53 cl::desc("Use new coalescer heuristic"),
54 cl::init(false), cl::Hidden);
57 CrossClassJoin("join-subclass-copies",
58 cl::desc("Coalesce copies to sub- register class"),
59 cl::init(false), cl::Hidden);
61 static RegisterPass<SimpleRegisterCoalescing>
62 X("simple-register-coalescing", "Simple Register Coalescing");
64 // Declare that we implement the RegisterCoalescer interface
65 static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
67 const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
69 void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addPreserved<LiveIntervals>();
71 AU.addPreserved<MachineLoopInfo>();
72 AU.addPreservedID(MachineDominatorsID);
73 AU.addPreservedID(PHIEliminationID);
74 AU.addPreservedID(TwoAddressInstructionPassID);
75 AU.addRequired<LiveIntervals>();
76 AU.addRequired<MachineLoopInfo>();
77 MachineFunctionPass::getAnalysisUsage(AU);
80 /// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
81 /// being the source and IntB being the dest, thus this defines a value number
82 /// in IntB. If the source value number (in IntA) is defined by a copy from B,
83 /// see if we can merge these two pieces of B into a single value number,
84 /// eliminating a copy. For example:
88 /// B1 = A3 <- this copy
90 /// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
91 /// value number to be replaced with B0 (which simplifies the B liveinterval).
93 /// This returns true if an interval was modified.
95 bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
97 MachineInstr *CopyMI) {
98 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
100 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
101 // the example above.
102 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
103 if (BLR == IntB.end()) // Should never happen!
105 VNInfo *BValNo = BLR->valno;
107 // Get the location that B is defined at. Two options: either this value has
108 // an unknown definition point or it is defined at CopyIdx. If unknown, we
110 if (!BValNo->copy) return false;
111 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
113 // AValNo is the value number in A that defines the copy, A3 in the example.
114 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
115 if (ALR == IntA.end()) // Should never happen!
117 VNInfo *AValNo = ALR->valno;
119 // If AValNo is defined as a copy from IntB, we can potentially process this.
120 // Get the instruction that defines this value number.
121 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
122 if (!SrcReg) return false; // Not defined by a copy.
124 // If the value number is not defined by a copy instruction, ignore it.
126 // If the source register comes from an interval other than IntB, we can't
128 if (SrcReg != IntB.reg) return false;
130 // Get the LiveRange in IntB that this value number starts with.
131 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
132 if (ValLR == IntB.end()) // Should never happen!
135 // Make sure that the end of the live range is inside the same block as
137 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
139 ValLREndInst->getParent() != CopyMI->getParent()) return false;
141 // Okay, we now know that ValLR ends in the same block that the CopyMI
142 // live-range starts. If there are no intervening live ranges between them in
143 // IntB, we can merge them.
144 if (ValLR+1 != BLR) return false;
146 // If a live interval is a physical register, conservatively check if any
147 // of its sub-registers is overlapping the live interval of the virtual
148 // register. If so, do not coalesce.
149 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
150 *tri_->getSubRegisters(IntB.reg)) {
151 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
152 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
153 DOUT << "Interfere with sub-register ";
154 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
159 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
161 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
162 // We are about to delete CopyMI, so need to remove it as the 'instruction
163 // that defines this value #'. Update the the valnum with the new defining
165 BValNo->def = FillerStart;
168 // Okay, we can merge them. We need to insert a new liverange:
169 // [ValLR.end, BLR.begin) of either value number, then we merge the
170 // two value numbers.
171 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
173 // If the IntB live range is assigned to a physical register, and if that
174 // physreg has aliases,
175 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
176 // Update the liveintervals of sub-registers.
177 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
178 LiveInterval &AliasLI = li_->getInterval(*AS);
179 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
180 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
184 // Okay, merge "B1" into the same value number as "B0".
185 if (BValNo != ValLR->valno)
186 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
187 DOUT << " result = "; IntB.print(DOUT, tri_);
190 // If the source instruction was killing the source register before the
191 // merge, unset the isKill marker given the live range has been extended.
192 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
194 ValLREndInst->getOperand(UIdx).setIsKill(false);
200 /// HasOtherReachingDefs - Return true if there are definitions of IntB
201 /// other than BValNo val# that can reach uses of AValno val# of IntA.
202 bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
206 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
208 if (AI->valno != AValNo) continue;
209 LiveInterval::Ranges::iterator BI =
210 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
211 if (BI != IntB.ranges.begin())
213 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
214 if (BI->valno == BValNo)
216 if (BI->start <= AI->start && BI->end > AI->start)
218 if (BI->start > AI->start && BI->start < AI->end)
225 /// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
226 /// being the source and IntB being the dest, thus this defines a value number
227 /// in IntB. If the source value number (in IntA) is defined by a commutable
228 /// instruction and its other operand is coalesced to the copy dest register,
229 /// see if we can transform the copy into a noop by commuting the definition. For
232 /// A3 = op A2 B0<kill>
234 /// B1 = A3 <- this copy
236 /// = op A3 <- more uses
240 /// B2 = op B0 A2<kill>
242 /// B1 = B2 <- now an identify copy
244 /// = op B2 <- more uses
246 /// This returns true if an interval was modified.
248 bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
250 MachineInstr *CopyMI) {
251 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
253 // FIXME: For now, only eliminate the copy by commuting its def when the
254 // source register is a virtual register. We want to guard against cases
255 // where the copy is a back edge copy and commuting the def lengthen the
256 // live interval of the source register to the entire loop.
257 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
260 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
261 // the example above.
262 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
263 if (BLR == IntB.end()) // Should never happen!
265 VNInfo *BValNo = BLR->valno;
267 // Get the location that B is defined at. Two options: either this value has
268 // an unknown definition point or it is defined at CopyIdx. If unknown, we
270 if (!BValNo->copy) return false;
271 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
273 // AValNo is the value number in A that defines the copy, A3 in the example.
274 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
275 if (ALR == IntA.end()) // Should never happen!
277 VNInfo *AValNo = ALR->valno;
278 // If other defs can reach uses of this def, then it's not safe to perform
280 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
282 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
283 const TargetInstrDesc &TID = DefMI->getDesc();
285 if (!TID.isCommutable() ||
286 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
289 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
290 unsigned NewReg = NewDstMO.getReg();
291 if (NewReg != IntB.reg || !NewDstMO.isKill())
294 // Make sure there are no other definitions of IntB that would reach the
295 // uses which the new definition can reach.
296 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
299 // If some of the uses of IntA.reg is already coalesced away, return false.
300 // It's not possible to determine whether it's safe to perform the coalescing.
301 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
302 UE = mri_->use_end(); UI != UE; ++UI) {
303 MachineInstr *UseMI = &*UI;
304 unsigned UseIdx = li_->getInstructionIndex(UseMI);
305 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
306 if (ULR == IntA.end())
308 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
312 // At this point we have decided that it is legal to do this
313 // transformation. Start by commuting the instruction.
314 MachineBasicBlock *MBB = DefMI->getParent();
315 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
318 if (NewMI != DefMI) {
319 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
320 MBB->insert(DefMI, NewMI);
323 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
324 NewMI->getOperand(OpIdx).setIsKill();
326 bool BHasPHIKill = BValNo->hasPHIKill;
327 SmallVector<VNInfo*, 4> BDeadValNos;
328 SmallVector<unsigned, 4> BKills;
329 std::map<unsigned, unsigned> BExtend;
331 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
340 // then do not add kills of A to the newly created B interval.
341 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
343 BExtend[ALR->end] = BLR->end;
345 // Update uses of IntA of the specific Val# with IntB.
346 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
347 UE = mri_->use_end(); UI != UE;) {
348 MachineOperand &UseMO = UI.getOperand();
349 MachineInstr *UseMI = &*UI;
351 if (JoinedCopies.count(UseMI))
353 unsigned UseIdx = li_->getInstructionIndex(UseMI);
354 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
355 if (ULR == IntA.end() || ULR->valno != AValNo)
357 UseMO.setReg(NewReg);
360 if (UseMO.isKill()) {
362 UseMO.setIsKill(false);
364 BKills.push_back(li_->getUseIndex(UseIdx)+1);
366 unsigned SrcReg, DstReg;
367 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
369 if (DstReg == IntB.reg) {
370 // This copy will become a noop. If it's defining a new val#,
371 // remove that val# as well. However this live range is being
372 // extended to the end of the existing live range defined by the copy.
373 unsigned DefIdx = li_->getDefIndex(UseIdx);
374 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
375 BHasPHIKill |= DLR->valno->hasPHIKill;
376 assert(DLR->valno->def == DefIdx);
377 BDeadValNos.push_back(DLR->valno);
378 BExtend[DLR->start] = DLR->end;
379 JoinedCopies.insert(UseMI);
380 // If this is a kill but it's going to be removed, the last use
381 // of the same val# is the new kill.
387 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
388 // simply extend BLR if CopyMI doesn't end the range.
389 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
391 // Remove val#'s defined by copies that will be coalesced away.
392 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
393 IntB.removeValNo(BDeadValNos[i]);
395 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
396 // is updated. Kills are also updated.
397 VNInfo *ValNo = BValNo;
398 ValNo->def = AValNo->def;
400 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
401 unsigned Kill = ValNo->kills[j];
402 if (Kill != BLR->end)
403 BKills.push_back(Kill);
405 ValNo->kills.clear();
406 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
408 if (AI->valno != AValNo) continue;
409 unsigned End = AI->end;
410 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
411 if (EI != BExtend.end())
413 IntB.addRange(LiveRange(AI->start, End, ValNo));
415 IntB.addKills(ValNo, BKills);
416 ValNo->hasPHIKill = BHasPHIKill;
418 DOUT << " result = "; IntB.print(DOUT, tri_);
421 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
422 IntA.removeValNo(AValNo);
423 DOUT << " result = "; IntA.print(DOUT, tri_);
430 /// ReMaterializeTrivialDef - If the source of a copy is defined by a trivial
431 /// computation, replace the copy by rematerialize the definition.
432 bool SimpleRegisterCoalescing::ReMaterializeTrivialDef(LiveInterval &SrcInt,
434 MachineInstr *CopyMI) {
435 unsigned CopyIdx = li_->getUseIndex(li_->getInstructionIndex(CopyMI));
436 LiveInterval::iterator SrcLR = SrcInt.FindLiveRangeContaining(CopyIdx);
437 if (SrcLR == SrcInt.end()) // Should never happen!
439 VNInfo *ValNo = SrcLR->valno;
440 // If other defs can reach uses of this def, then it's not safe to perform
442 if (ValNo->def == ~0U || ValNo->def == ~1U || ValNo->hasPHIKill)
444 MachineInstr *DefMI = li_->getInstructionFromIndex(ValNo->def);
445 const TargetInstrDesc &TID = DefMI->getDesc();
446 if (!TID.isAsCheapAsAMove())
448 bool SawStore = false;
449 if (!DefMI->isSafeToMove(tii_, SawStore))
452 unsigned DefIdx = li_->getDefIndex(CopyIdx);
453 const LiveRange *DLR= li_->getInterval(DstReg).getLiveRangeContaining(DefIdx);
454 DLR->valno->copy = NULL;
456 MachineBasicBlock::iterator MII = CopyMI;
457 MachineBasicBlock *MBB = CopyMI->getParent();
458 tii_->reMaterialize(*MBB, MII, DstReg, DefMI);
459 MachineInstr *NewMI = prior(MII);
460 // CopyMI may have implicit instructions, transfer them over to the newly
461 // rematerialized instruction. And update implicit def interval valnos.
462 for (unsigned i = CopyMI->getDesc().getNumOperands(),
463 e = CopyMI->getNumOperands(); i != e; ++i) {
464 MachineOperand &MO = CopyMI->getOperand(i);
465 if (MO.isReg() && MO.isImplicit())
466 NewMI->addOperand(MO);
467 if (MO.isDef() && li_->hasInterval(MO.getReg())) {
468 unsigned Reg = MO.getReg();
469 DLR = li_->getInterval(Reg).getLiveRangeContaining(DefIdx);
470 if (DLR && DLR->valno->copy == CopyMI)
471 DLR->valno->copy = NULL;
475 li_->ReplaceMachineInstrInMaps(CopyMI, NewMI);
476 CopyMI->eraseFromParent();
477 ReMatCopies.insert(CopyMI);
482 /// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
484 bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
485 unsigned DstReg) const {
486 MachineBasicBlock *MBB = CopyMI->getParent();
487 const MachineLoop *L = loopInfo->getLoopFor(MBB);
490 if (MBB != L->getLoopLatch())
493 LiveInterval &LI = li_->getInterval(DstReg);
494 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
495 LiveInterval::const_iterator DstLR =
496 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
497 if (DstLR == LI.end())
499 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
500 if (DstLR->valno->kills.size() == 1 &&
501 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
506 /// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
507 /// update the subregister number if it is not zero. If DstReg is a
508 /// physical register and the existing subregister number of the def / use
509 /// being updated is not zero, make sure to set it to the correct physical
512 SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
514 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
515 if (DstIsPhys && SubIdx) {
516 // Figure out the real physical register we are updating with.
517 DstReg = tri_->getSubReg(DstReg, SubIdx);
521 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
522 E = mri_->reg_end(); I != E; ) {
523 MachineOperand &O = I.getOperand();
524 MachineInstr *UseMI = &*I;
526 unsigned OldSubIdx = O.getSubReg();
528 unsigned UseDstReg = DstReg;
530 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
532 unsigned CopySrcReg, CopyDstReg;
533 if (tii_->isMoveInstr(*UseMI, CopySrcReg, CopyDstReg) &&
534 CopySrcReg != CopyDstReg &&
535 CopySrcReg == SrcReg && CopyDstReg != UseDstReg) {
536 // If the use is a copy and it won't be coalesced away, and its source
537 // is defined by a trivial computation, try to rematerialize it instead.
538 if (ReMaterializeTrivialDef(li_->getInterval(SrcReg), CopyDstReg,UseMI))
545 // Sub-register indexes goes from small to large. e.g.
546 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
547 // EAX: 1 -> AL, 2 -> AX
548 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
549 // sub-register 2 is also AX.
550 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
551 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
554 // Remove would-be duplicated kill marker.
555 if (O.isKill() && UseMI->killsRegister(DstReg))
562 /// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
563 /// registers due to insert_subreg coalescing. e.g.
565 /// r1025 = implicit_def
566 /// r1025 = insert_subreg r1025, r1024
570 /// r1025 = implicit_def
571 /// r1025 = insert_subreg r1025, r1025
574 SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
575 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
576 E = mri_->reg_end(); I != E; ) {
577 MachineOperand &O = I.getOperand();
578 MachineInstr *DefMI = &*I;
582 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
584 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
586 li_->RemoveMachineInstrFromMaps(DefMI);
587 DefMI->eraseFromParent();
591 /// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
592 /// due to live range lengthening as the result of coalescing.
593 void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
595 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
596 UE = mri_->use_end(); UI != UE; ++UI) {
597 MachineOperand &UseMO = UI.getOperand();
598 if (UseMO.isKill()) {
599 MachineInstr *UseMI = UseMO.getParent();
600 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
601 if (JoinedCopies.count(UseMI))
603 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
604 if (!UI || !LI.isKill(UI->valno, UseIdx+1))
605 UseMO.setIsKill(false);
610 /// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
611 /// from a physical register live interval as well as from the live intervals
612 /// of its sub-registers.
613 static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
614 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
615 li.removeRange(Start, End, true);
616 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
617 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
618 if (!li_->hasInterval(*SR))
620 LiveInterval &sli = li_->getInterval(*SR);
621 unsigned RemoveEnd = Start;
622 while (RemoveEnd != End) {
623 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
626 RemoveEnd = (LR->end < End) ? LR->end : End;
627 sli.removeRange(Start, RemoveEnd, true);
634 /// removeIntervalIfEmpty - Check if the live interval of a physical register
635 /// is empty, if so remove it and also remove the empty intervals of its
636 /// sub-registers. Return true if live interval is removed.
637 static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
638 const TargetRegisterInfo *tri_) {
640 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
641 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
642 if (!li_->hasInterval(*SR))
644 LiveInterval &sli = li_->getInterval(*SR);
646 li_->removeInterval(*SR);
648 li_->removeInterval(li.reg);
654 /// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
655 /// Return true if live interval is removed.
656 bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
657 MachineInstr *CopyMI) {
658 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
659 LiveInterval::iterator MLR =
660 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
662 return false; // Already removed by ShortenDeadCopySrcLiveRange.
663 unsigned RemoveStart = MLR->start;
664 unsigned RemoveEnd = MLR->end;
665 // Remove the liverange that's defined by this.
666 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
667 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
668 return removeIntervalIfEmpty(li, li_, tri_);
673 /// PropagateDeadness - Propagate the dead marker to the instruction which
674 /// defines the val#.
675 static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
676 unsigned &LRStart, LiveIntervals *li_,
677 const TargetRegisterInfo* tri_) {
678 MachineInstr *DefMI =
679 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
680 if (DefMI && DefMI != CopyMI) {
681 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
683 DefMI->getOperand(DeadIdx).setIsDead();
684 // A dead def should have a single cycle interval.
690 /// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
691 /// fallthoughs to SuccMBB.
692 static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
693 MachineBasicBlock *SuccMBB,
694 const TargetInstrInfo *tii_) {
697 MachineBasicBlock *TBB = 0, *FBB = 0;
698 SmallVector<MachineOperand, 4> Cond;
699 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
700 MBB->isSuccessor(SuccMBB);
703 /// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
704 /// extended by a dead copy. Mark the last use (if any) of the val# as kill as
705 /// ends the live range there. If there isn't another use, then this live range
706 /// is dead. Return true if live interval is removed.
708 SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
709 MachineInstr *CopyMI) {
710 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
712 // FIXME: special case: function live in. It can be a general case if the
713 // first instruction index starts at > 0 value.
714 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
715 // Live-in to the function but dead. Remove it from entry live-in set.
716 if (mf_->begin()->isLiveIn(li.reg))
717 mf_->begin()->removeLiveIn(li.reg);
718 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
719 removeRange(li, LR->start, LR->end, li_, tri_);
720 return removeIntervalIfEmpty(li, li_, tri_);
723 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
725 // Livein but defined by a phi.
728 unsigned RemoveStart = LR->start;
729 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
730 if (LR->end > RemoveEnd)
731 // More uses past this copy? Nothing to do.
734 MachineBasicBlock *CopyMBB = CopyMI->getParent();
735 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
737 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
740 MachineInstr *LastUseMI = LastUse->getParent();
741 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
748 // r1025<dead> = r1024<kill>
749 if (MBBStart < LR->end)
750 removeRange(li, MBBStart, LR->end, li_, tri_);
754 // There are uses before the copy, just shorten the live range to the end
756 LastUse->setIsKill();
757 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
758 unsigned SrcReg, DstReg;
759 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
761 // Last use is itself an identity code.
762 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
763 LastUseMI->getOperand(DeadIdx).setIsDead();
769 if (LR->start <= MBBStart && LR->end > MBBStart) {
770 if (LR->start == 0) {
771 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
772 // Live-in to the function but dead. Remove it from entry live-in set.
773 mf_->begin()->removeLiveIn(li.reg);
775 // FIXME: Shorten intervals in BBs that reaches this BB.
778 if (LR->valno->def == RemoveStart)
779 // If the def MI defines the val#, propagate the dead marker.
780 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
782 removeRange(li, RemoveStart, LR->end, li_, tri_);
783 return removeIntervalIfEmpty(li, li_, tri_);
786 /// CanCoalesceWithImpDef - Returns true if the specified copy instruction
787 /// from an implicit def to another register can be coalesced away.
788 bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
790 LiveInterval &ImpLi) const{
791 if (!CopyMI->killsRegister(ImpLi.reg))
793 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
794 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
797 if (LR->valno->hasPHIKill)
799 if (LR->valno->def != CopyIdx)
801 // Make sure all of val# uses are copies.
802 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
803 UE = mri_->use_end(); UI != UE;) {
804 MachineInstr *UseMI = &*UI;
806 if (JoinedCopies.count(UseMI))
808 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
809 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
810 if (ULR == li.end() || ULR->valno != LR->valno)
812 // If the use is not a use, then it's not safe to coalesce the move.
813 unsigned SrcReg, DstReg;
814 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
815 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
816 UseMI->getOperand(1).getReg() == li.reg)
825 /// RemoveCopiesFromValNo - The specified value# is defined by an implicit
826 /// def and it is being removed. Turn all copies from this value# into
827 /// identity copies so they will be removed.
828 void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
830 SmallVector<MachineInstr*, 4> ImpDefs;
831 MachineOperand *LastUse = NULL;
832 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
833 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
834 RE = mri_->reg_end(); RI != RE;) {
835 MachineOperand *MO = &RI.getOperand();
836 MachineInstr *MI = &*RI;
839 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
840 ImpDefs.push_back(MI);
844 if (JoinedCopies.count(MI))
846 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
847 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
848 if (ULR == li.end() || ULR->valno != VNI)
850 // If the use is a copy, turn it into an identity copy.
851 unsigned SrcReg, DstReg;
852 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
853 // Each use MI may have multiple uses of this register. Change them all.
854 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
855 MachineOperand &MO = MI->getOperand(i);
856 if (MO.isReg() && MO.getReg() == li.reg)
859 JoinedCopies.insert(MI);
860 } else if (UseIdx > LastUseIdx) {
866 LastUse->setIsKill();
868 // Remove dead implicit_def's.
869 while (!ImpDefs.empty()) {
870 MachineInstr *ImpDef = ImpDefs.back();
872 li_->RemoveMachineInstrFromMaps(ImpDef);
873 ImpDef->eraseFromParent();
878 /// getMatchingSuperReg - Return a super-register of the specified register
879 /// Reg so its sub-register of index SubIdx is Reg.
880 static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
881 const TargetRegisterClass *RC,
882 const TargetRegisterInfo* TRI) {
883 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
884 unsigned SR = *SRs; ++SRs)
885 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
890 /// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
891 /// a subset of the register class of SrcReg, return true if it's profitable
892 /// to coalesce the two registers.
894 SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
896 MachineBasicBlock *MBB){
900 // First let's make sure all uses are in the same MBB.
901 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
902 RE = mri_->reg_end(); RI != RE; ++RI) {
903 MachineInstr &MI = *RI;
904 if (MI.getParent() != MBB)
907 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
908 RE = mri_->reg_end(); RI != RE; ++RI) {
909 MachineInstr &MI = *RI;
910 if (MI.getParent() != MBB)
914 // Then make sure the intervals are *short*.
915 LiveInterval &SrcInt = li_->getInterval(SrcReg);
916 LiveInterval &DstInt = li_->getInterval(DstReg);
917 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
918 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
919 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
920 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
921 return (SrcSize + DstSize) <= Threshold;
924 /// HasIncompatibleSubRegDefUse - If we are trying to coalesce a virtual
925 /// register with a physical register, check if any of the virtual register
926 /// operand is a sub-register use or def. If so, make sure it won't result
927 /// in an illegal extract_subreg or insert_subreg instruction. e.g.
928 /// vr1024 = extract_subreg vr1025, 1
930 /// vr1024 = mov8rr AH
931 /// If vr1024 is coalesced with AH, the extract_subreg is now illegal since
932 /// AH does not have a super-reg whose sub-register 1 is AH.
934 SimpleRegisterCoalescing::HasIncompatibleSubRegDefUse(MachineInstr *CopyMI,
937 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(VirtReg),
938 E = mri_->reg_end(); I != E; ++I) {
939 MachineOperand &O = I.getOperand();
940 MachineInstr *MI = &*I;
941 if (MI == CopyMI || JoinedCopies.count(MI))
943 unsigned SubIdx = O.getSubReg();
944 if (SubIdx && !tri_->getSubReg(PhysReg, SubIdx))
946 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
947 SubIdx = MI->getOperand(2).getImm();
948 if (O.isUse() && !tri_->getSubReg(PhysReg, SubIdx))
951 unsigned SrcReg = MI->getOperand(1).getReg();
952 const TargetRegisterClass *RC =
953 TargetRegisterInfo::isPhysicalRegister(SrcReg)
954 ? tri_->getPhysicalRegisterRegClass(SrcReg)
955 : mri_->getRegClass(SrcReg);
956 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
960 if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
961 SubIdx = MI->getOperand(3).getImm();
962 if (VirtReg == MI->getOperand(0).getReg()) {
963 if (!tri_->getSubReg(PhysReg, SubIdx))
966 unsigned DstReg = MI->getOperand(0).getReg();
967 const TargetRegisterClass *RC =
968 TargetRegisterInfo::isPhysicalRegister(DstReg)
969 ? tri_->getPhysicalRegisterRegClass(DstReg)
970 : mri_->getRegClass(DstReg);
971 if (!getMatchingSuperReg(PhysReg, SubIdx, RC, tri_))
980 /// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
981 /// which are the src/dst of the copy instruction CopyMI. This returns true
982 /// if the copy was successfully coalesced away. If it is not currently
983 /// possible to coalesce this interval, but it may be possible if other
984 /// things get coalesced, then it returns true by reference in 'Again'.
985 bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
986 MachineInstr *CopyMI = TheCopy.MI;
989 if (JoinedCopies.count(CopyMI) || ReMatCopies.count(CopyMI))
990 return false; // Already done.
992 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
996 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
997 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
1000 DstReg = CopyMI->getOperand(0).getReg();
1001 SrcReg = CopyMI->getOperand(1).getReg();
1002 } else if (isInsSubReg) {
1003 if (CopyMI->getOperand(2).getSubReg()) {
1004 DOUT << "\tSource of insert_subreg is already coalesced "
1005 << "to another register.\n";
1006 return false; // Not coalescable.
1008 DstReg = CopyMI->getOperand(0).getReg();
1009 SrcReg = CopyMI->getOperand(2).getReg();
1010 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
1011 assert(0 && "Unrecognized copy instruction!");
1015 // If they are already joined we continue.
1016 if (SrcReg == DstReg) {
1017 DOUT << "\tCopy already coalesced.\n";
1018 return false; // Not coalescable.
1021 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1022 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1024 // If they are both physical registers, we cannot join them.
1025 if (SrcIsPhys && DstIsPhys) {
1026 DOUT << "\tCan not coalesce physregs.\n";
1027 return false; // Not coalescable.
1030 // We only join virtual registers with allocatable physical registers.
1031 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
1032 DOUT << "\tSrc reg is unallocatable physreg.\n";
1033 return false; // Not coalescable.
1035 if (DstIsPhys && !allocatableRegs_[DstReg]) {
1036 DOUT << "\tDst reg is unallocatable physreg.\n";
1037 return false; // Not coalescable.
1040 // Should be non-null only when coalescing to a sub-register class.
1041 const TargetRegisterClass *SubRC = NULL;
1042 MachineBasicBlock *CopyMBB = CopyMI->getParent();
1043 unsigned RealDstReg = 0;
1044 unsigned RealSrcReg = 0;
1045 if (isExtSubReg || isInsSubReg) {
1046 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
1047 if (SrcIsPhys && isExtSubReg) {
1048 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
1049 // coalesced with AX.
1050 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
1052 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
1053 // coalesced to a larger register so the subreg indices cancel out.
1054 if (DstSubIdx != SubIdx) {
1055 DOUT << "\t Sub-register indices mismatch.\n";
1056 return false; // Not coalescable.
1059 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
1061 } else if (DstIsPhys && isInsSubReg) {
1062 // EAX = INSERT_SUBREG EAX, r1024, 0
1063 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
1065 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
1066 // coalesced to a larger register so the subreg indices cancel out.
1067 if (SrcSubIdx != SubIdx) {
1068 DOUT << "\t Sub-register indices mismatch.\n";
1069 return false; // Not coalescable.
1072 DstReg = tri_->getSubReg(DstReg, SubIdx);
1074 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
1075 // If this is a extract_subreg where dst is a physical register, e.g.
1076 // cl = EXTRACT_SUBREG reg1024, 1
1077 // then create and update the actual physical register allocated to RHS.
1079 // reg1024 = INSERT_SUBREG r1024, cl, 1
1080 if (CopyMI->getOperand(1).getSubReg()) {
1081 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
1082 << " of a super-class.\n";
1083 return false; // Not coalescable.
1085 const TargetRegisterClass *RC =
1086 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
1088 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
1089 assert(RealDstReg && "Invalid extract_subreg instruction!");
1091 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
1092 assert(RealSrcReg && "Invalid extract_subreg instruction!");
1095 // For this type of EXTRACT_SUBREG, conservatively
1096 // check if the live interval of the source register interfere with the
1097 // actual super physical register we are trying to coalesce with.
1098 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
1099 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
1100 if (li_->hasInterval(PhysReg) &&
1101 RHS.overlaps(li_->getInterval(PhysReg))) {
1102 DOUT << "Interfere with register ";
1103 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
1104 return false; // Not coalescable
1106 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
1107 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1108 DOUT << "Interfere with sub-register ";
1109 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1110 return false; // Not coalescable
1114 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
1115 : CopyMI->getOperand(2).getSubReg();
1117 if (OldSubIdx == SubIdx &&
1118 !differingRegisterClasses(SrcReg, DstReg, SubRC))
1119 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1120 // coalesced to a larger register so the subreg indices cancel out.
1121 // Also check if the other larger register is of the same register
1122 // class as the would be resulting register.
1125 DOUT << "\t Sub-register indices mismatch.\n";
1126 return false; // Not coalescable.
1130 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1131 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
1132 unsigned LargeRegSize =
1133 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1134 unsigned SmallRegSize =
1135 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
1136 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1137 unsigned Threshold = allocatableRCRegs_[RC].count();
1138 // Be conservative. If both sides are virtual registers, do not coalesce
1139 // if this will cause a high use density interval to target a smaller
1140 // set of registers.
1141 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
1142 if ((float)std::distance(mri_->use_begin(SmallReg),
1143 mri_->use_end()) / SmallRegSize <
1144 (float)std::distance(mri_->use_begin(LargeReg),
1145 mri_->use_end()) / LargeRegSize) {
1146 Again = true; // May be possible to coalesce later.
1152 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
1153 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1154 // with another? If it's the resulting destination register, then
1155 // the subidx must be propagated to uses (but only those defined
1156 // by the EXTRACT_SUBREG). If it's being coalesced into another
1157 // register, it should be safe because register is assumed to have
1158 // the register class of the super-register.
1160 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1161 // If they are not of the same register class, we cannot join them.
1162 DOUT << "\tSrc/Dest are different register classes.\n";
1163 // Allow the coalescer to try again in case either side gets coalesced to
1164 // a physical register that's compatible with the other side. e.g.
1165 // r1024 = MOV32to32_ r1025
1166 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1167 Again = true; // May be possible to coalesce later.
1172 // Will it create illegal extract_subreg / insert_subreg?
1173 if (SrcIsPhys && HasIncompatibleSubRegDefUse(CopyMI, DstReg, SrcReg))
1175 if (DstIsPhys && HasIncompatibleSubRegDefUse(CopyMI, SrcReg, DstReg))
1178 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1179 LiveInterval &DstInt = li_->getInterval(DstReg);
1180 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
1181 "Register mapping is horribly broken!");
1183 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1184 DOUT << " and "; DstInt.print(DOUT, tri_);
1187 // Check if it is necessary to propagate "isDead" property.
1188 if (!isExtSubReg && !isInsSubReg) {
1189 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1190 bool isDead = mopd->isDead();
1192 // We need to be careful about coalescing a source physical register with a
1193 // virtual register. Once the coalescing is done, it cannot be broken and
1194 // these are not spillable! If the destination interval uses are far away,
1195 // think twice about coalescing them!
1196 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1197 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1198 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1199 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1200 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1201 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1202 if (TheCopy.isBackEdge)
1203 Threshold *= 2; // Favors back edge copies.
1205 // If the virtual register live interval is long but it has low use desity,
1206 // do not join them, instead mark the physical register as its allocation
1208 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
1209 if (Length > Threshold &&
1210 (((float)std::distance(mri_->use_begin(JoinVReg),
1211 mri_->use_end()) / Length) < (1.0 / Threshold))) {
1212 JoinVInt.preference = JoinPReg;
1214 DOUT << "\tMay tie down a physical register, abort!\n";
1215 Again = true; // May be possible to coalesce later.
1221 // Okay, attempt to join these two intervals. On failure, this returns false.
1222 // Otherwise, if one of the intervals being joined is a physreg, this method
1223 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1224 // been modified, so we can use this information below to update aliases.
1225 bool Swapped = false;
1226 // If SrcInt is implicitly defined, it's safe to coalesce.
1227 bool isEmpty = SrcInt.empty();
1228 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
1229 // Only coalesce an empty interval (defined by implicit_def) with
1230 // another interval which has a valno defined by the CopyMI and the CopyMI
1231 // is a kill of the implicit def.
1232 DOUT << "Not profitable!\n";
1236 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
1237 // Coalescing failed.
1239 // If definition of source is defined by trivial computation, try
1240 // rematerializing it.
1241 if (!isExtSubReg && !isInsSubReg &&
1242 ReMaterializeTrivialDef(SrcInt, DstInt.reg, CopyMI))
1245 // If we can eliminate the copy without merging the live ranges, do so now.
1246 if (!isExtSubReg && !isInsSubReg &&
1247 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1248 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
1249 JoinedCopies.insert(CopyMI);
1253 // Otherwise, we are unable to join the intervals.
1254 DOUT << "Interference!\n";
1255 Again = true; // May be possible to coalesce later.
1259 LiveInterval *ResSrcInt = &SrcInt;
1260 LiveInterval *ResDstInt = &DstInt;
1262 std::swap(SrcReg, DstReg);
1263 std::swap(ResSrcInt, ResDstInt);
1265 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
1266 "LiveInterval::join didn't work right!");
1268 // If we're about to merge live ranges into a physical register live range,
1269 // we have to update any aliased register's live ranges to indicate that they
1270 // have clobbered values for this range.
1271 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1272 // If this is a extract_subreg where dst is a physical register, e.g.
1273 // cl = EXTRACT_SUBREG reg1024, 1
1274 // then create and update the actual physical register allocated to RHS.
1275 if (RealDstReg || RealSrcReg) {
1276 LiveInterval &RealInt =
1277 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
1278 SmallSet<const VNInfo*, 4> CopiedValNos;
1279 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1280 E = ResSrcInt->ranges.end(); I != E; ++I) {
1281 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1282 assert(DstLR && "Invalid joined interval!");
1283 const VNInfo *DstValNo = DstLR->valno;
1284 if (CopiedValNos.insert(DstValNo)) {
1285 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1286 li_->getVNInfoAllocator());
1287 ValNo->hasPHIKill = DstValNo->hasPHIKill;
1288 RealInt.addKills(ValNo, DstValNo->kills);
1289 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
1293 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
1296 // Update the liveintervals of sub-registers.
1297 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
1298 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
1299 li_->getVNInfoAllocator());
1302 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1303 // larger super-register.
1304 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1305 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
1306 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
1307 std::swap(SrcReg, DstReg);
1308 std::swap(ResSrcInt, ResDstInt);
1312 // Coalescing to a virtual register that is of a sub-register class of the
1313 // other. Make sure the resulting register is set to the right register class.
1315 mri_->setRegClass(DstReg, SubRC);
1320 // Add all copies that define val# in the source interval into the queue.
1321 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1322 e = ResSrcInt->vni_end(); i != e; ++i) {
1323 const VNInfo *vni = *i;
1324 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1326 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1327 unsigned NewSrcReg, NewDstReg;
1329 JoinedCopies.count(CopyMI) == 0 &&
1330 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1331 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
1332 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1333 isBackEdgeCopy(CopyMI, DstReg)));
1338 // Remember to delete the copy instruction.
1339 JoinedCopies.insert(CopyMI);
1341 // Some live range has been lengthened due to colaescing, eliminate the
1342 // unnecessary kills.
1343 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1344 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1345 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1350 // r1024 = implicit_def
1353 RemoveDeadImpDef(DstReg, *ResDstInt);
1354 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1356 // SrcReg is guarateed to be the register whose live interval that is
1358 li_->removeInterval(SrcReg);
1361 // Now the copy is being coalesced away, the val# previously defined
1362 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1363 // length interval. Remove the val#.
1364 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1365 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
1366 VNInfo *ImpVal = LR->valno;
1367 assert(ImpVal->def == CopyIdx);
1368 unsigned NextDef = LR->end;
1369 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
1370 ResDstInt->removeValNo(ImpVal);
1371 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1372 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1373 // Special case: vr1024 = implicit_def
1374 // vr1024 = insert_subreg vr1024, vr1025, c
1375 // The insert_subreg becomes a "copy" that defines a val# which can itself
1376 // be coalesced away.
1377 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1378 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1379 LR->valno->copy = DefMI;
1383 // If resulting interval has a preference that no longer fits because of subreg
1384 // coalescing, just clear the preference.
1385 if (ResDstInt->preference && (isExtSubReg || isInsSubReg) &&
1386 TargetRegisterInfo::isVirtualRegister(ResDstInt->reg)) {
1387 const TargetRegisterClass *RC = mri_->getRegClass(ResDstInt->reg);
1388 if (!RC->contains(ResDstInt->preference))
1389 ResDstInt->preference = 0;
1392 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1399 /// ComputeUltimateVN - Assuming we are going to join two live intervals,
1400 /// compute what the resultant value numbers for each value in the input two
1401 /// ranges will be. This is complicated by copies between the two which can
1402 /// and will commonly cause multiple value numbers to be merged into one.
1404 /// VN is the value number that we're trying to resolve. InstDefiningValue
1405 /// keeps track of the new InstDefiningValue assignment for the result
1406 /// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1407 /// whether a value in this or other is a copy from the opposite set.
1408 /// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1409 /// already been assigned.
1411 /// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1412 /// contains the value number the copy is from.
1414 static unsigned ComputeUltimateVN(VNInfo *VNI,
1415 SmallVector<VNInfo*, 16> &NewVNInfo,
1416 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1417 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
1418 SmallVector<int, 16> &ThisValNoAssignments,
1419 SmallVector<int, 16> &OtherValNoAssignments) {
1420 unsigned VN = VNI->id;
1422 // If the VN has already been computed, just return it.
1423 if (ThisValNoAssignments[VN] >= 0)
1424 return ThisValNoAssignments[VN];
1425 // assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
1427 // If this val is not a copy from the other val, then it must be a new value
1428 // number in the destination.
1429 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
1430 if (I == ThisFromOther.end()) {
1431 NewVNInfo.push_back(VNI);
1432 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
1434 VNInfo *OtherValNo = I->second;
1436 // Otherwise, this *is* a copy from the RHS. If the other side has already
1437 // been computed, return it.
1438 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1439 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
1441 // Mark this value number as currently being computed, then ask what the
1442 // ultimate value # of the other value is.
1443 ThisValNoAssignments[VN] = -2;
1444 unsigned UltimateVN =
1445 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1446 OtherValNoAssignments, ThisValNoAssignments);
1447 return ThisValNoAssignments[VN] = UltimateVN;
1450 static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
1451 return std::find(V.begin(), V.end(), Val) != V.end();
1454 /// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1455 /// the specified live interval is defined by a copy from the specified
1457 bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1460 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1463 if (LR->valno->def == ~0U &&
1464 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1465 *tri_->getSuperRegisters(li.reg)) {
1466 // It's a sub-register live interval, we may not have precise information.
1468 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1469 unsigned SrcReg, DstReg;
1470 if (DefMI && tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1471 DstReg == li.reg && SrcReg == Reg) {
1472 // Cache computed info.
1473 LR->valno->def = LR->start;
1474 LR->valno->copy = DefMI;
1481 /// SimpleJoin - Attempt to joint the specified interval into this one. The
1482 /// caller of this method must guarantee that the RHS only contains a single
1483 /// value number and that the RHS is not defined by a copy from this
1484 /// interval. This returns false if the intervals are not joinable, or it
1485 /// joins them and returns true.
1486 bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
1487 assert(RHS.containsOneValue());
1489 // Some number (potentially more than one) value numbers in the current
1490 // interval may be defined as copies from the RHS. Scan the overlapping
1491 // portions of the LHS and RHS, keeping track of this and looking for
1492 // overlapping live ranges that are NOT defined as copies. If these exist, we
1495 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1496 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1498 if (LHSIt->start < RHSIt->start) {
1499 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1500 if (LHSIt != LHS.begin()) --LHSIt;
1501 } else if (RHSIt->start < LHSIt->start) {
1502 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1503 if (RHSIt != RHS.begin()) --RHSIt;
1506 SmallVector<VNInfo*, 8> EliminatedLHSVals;
1509 // Determine if these live intervals overlap.
1510 bool Overlaps = false;
1511 if (LHSIt->start <= RHSIt->start)
1512 Overlaps = LHSIt->end > RHSIt->start;
1514 Overlaps = RHSIt->end > LHSIt->start;
1516 // If the live intervals overlap, there are two interesting cases: if the
1517 // LHS interval is defined by a copy from the RHS, it's ok and we record
1518 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1519 // coalesce these live ranges and we bail out.
1521 // If we haven't already recorded that this value # is safe, check it.
1522 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
1523 // Copy from the RHS?
1524 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
1525 return false; // Nope, bail out.
1527 if (LHSIt->contains(RHSIt->valno->def))
1528 // Here is an interesting situation:
1530 // vr1025 = copy vr1024
1535 // Even though vr1025 is copied from vr1024, it's not safe to
1536 // coalesced them since live range of vr1025 intersects the
1537 // def of vr1024. This happens because vr1025 is assigned the
1538 // value of the previous iteration of vr1024.
1540 EliminatedLHSVals.push_back(LHSIt->valno);
1543 // We know this entire LHS live range is okay, so skip it now.
1544 if (++LHSIt == LHSEnd) break;
1548 if (LHSIt->end < RHSIt->end) {
1549 if (++LHSIt == LHSEnd) break;
1551 // One interesting case to check here. It's possible that we have
1552 // something like "X3 = Y" which defines a new value number in the LHS,
1553 // and is the last use of this liverange of the RHS. In this case, we
1554 // want to notice this copy (so that it gets coalesced away) even though
1555 // the live ranges don't actually overlap.
1556 if (LHSIt->start == RHSIt->end) {
1557 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
1558 // We already know that this value number is going to be merged in
1559 // if coalescing succeeds. Just skip the liverange.
1560 if (++LHSIt == LHSEnd) break;
1562 // Otherwise, if this is a copy from the RHS, mark it as being merged
1564 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
1565 if (LHSIt->contains(RHSIt->valno->def))
1566 // Here is an interesting situation:
1568 // vr1025 = copy vr1024
1573 // Even though vr1025 is copied from vr1024, it's not safe to
1574 // coalesced them since live range of vr1025 intersects the
1575 // def of vr1024. This happens because vr1025 is assigned the
1576 // value of the previous iteration of vr1024.
1578 EliminatedLHSVals.push_back(LHSIt->valno);
1580 // We know this entire LHS live range is okay, so skip it now.
1581 if (++LHSIt == LHSEnd) break;
1586 if (++RHSIt == RHSEnd) break;
1590 // If we got here, we know that the coalescing will be successful and that
1591 // the value numbers in EliminatedLHSVals will all be merged together. Since
1592 // the most common case is that EliminatedLHSVals has a single number, we
1593 // optimize for it: if there is more than one value, we merge them all into
1594 // the lowest numbered one, then handle the interval as if we were merging
1595 // with one value number.
1597 if (EliminatedLHSVals.size() > 1) {
1598 // Loop through all the equal value numbers merging them into the smallest
1600 VNInfo *Smallest = EliminatedLHSVals[0];
1601 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1602 if (EliminatedLHSVals[i]->id < Smallest->id) {
1603 // Merge the current notion of the smallest into the smaller one.
1604 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1605 Smallest = EliminatedLHSVals[i];
1607 // Merge into the smallest.
1608 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1611 LHSValNo = Smallest;
1612 } else if (EliminatedLHSVals.empty()) {
1613 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1614 *tri_->getSuperRegisters(LHS.reg))
1615 // Imprecise sub-register information. Can't handle it.
1617 assert(0 && "No copies from the RHS?");
1619 LHSValNo = EliminatedLHSVals[0];
1622 // Okay, now that there is a single LHS value number that we're merging the
1623 // RHS into, update the value number info for the LHS to indicate that the
1624 // value number is defined where the RHS value number was.
1625 const VNInfo *VNI = RHS.getValNumInfo(0);
1626 LHSValNo->def = VNI->def;
1627 LHSValNo->copy = VNI->copy;
1629 // Okay, the final step is to loop over the RHS live intervals, adding them to
1631 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
1632 LHS.addKills(LHSValNo, VNI->kills);
1633 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1634 LHS.weight += RHS.weight;
1635 if (RHS.preference && !LHS.preference)
1636 LHS.preference = RHS.preference;
1641 /// JoinIntervals - Attempt to join these two intervals. On failure, this
1642 /// returns false. Otherwise, if one of the intervals being joined is a
1643 /// physreg, this method always canonicalizes LHS to be it. The output
1644 /// "RHS" will not have been modified, so we can use this information
1645 /// below to update aliases.
1646 bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1647 LiveInterval &RHS, bool &Swapped) {
1648 // Compute the final value assignment, assuming that the live ranges can be
1650 SmallVector<int, 16> LHSValNoAssignments;
1651 SmallVector<int, 16> RHSValNoAssignments;
1652 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1653 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
1654 SmallVector<VNInfo*, 16> NewVNInfo;
1656 // If a live interval is a physical register, conservatively check if any
1657 // of its sub-registers is overlapping the live interval of the virtual
1658 // register. If so, do not coalesce.
1659 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1660 *tri_->getSubRegisters(LHS.reg)) {
1661 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
1662 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1663 DOUT << "Interfere with sub-register ";
1664 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1667 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1668 *tri_->getSubRegisters(RHS.reg)) {
1669 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
1670 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1671 DOUT << "Interfere with sub-register ";
1672 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
1677 // Compute ultimate value numbers for the LHS and RHS values.
1678 if (RHS.containsOneValue()) {
1679 // Copies from a liveinterval with a single value are simple to handle and
1680 // very common, handle the special case here. This is important, because
1681 // often RHS is small and LHS is large (e.g. a physreg).
1683 // Find out if the RHS is defined as a copy from some value in the LHS.
1684 int RHSVal0DefinedFromLHS = -1;
1686 VNInfo *RHSValNoInfo = NULL;
1687 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
1688 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1689 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
1690 // If RHS is not defined as a copy from the LHS, we can use simpler and
1691 // faster checks to see if the live ranges are coalescable. This joiner
1692 // can't swap the LHS/RHS intervals though.
1693 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1694 return SimpleJoin(LHS, RHS);
1696 RHSValNoInfo = RHSValNoInfo0;
1699 // It was defined as a copy from the LHS, find out what value # it is.
1700 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
1701 RHSValID = RHSValNoInfo->id;
1702 RHSVal0DefinedFromLHS = RHSValID;
1705 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1706 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1707 NewVNInfo.resize(LHS.getNumValNums(), NULL);
1709 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1710 // should now get updated.
1711 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1714 unsigned VN = VNI->id;
1715 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1716 if (LHSSrcReg != RHS.reg) {
1717 // If this is not a copy from the RHS, its value number will be
1718 // unmodified by the coalescing.
1719 NewVNInfo[VN] = VNI;
1720 LHSValNoAssignments[VN] = VN;
1721 } else if (RHSValID == -1) {
1722 // Otherwise, it is a copy from the RHS, and we don't already have a
1723 // value# for it. Keep the current value number, but remember it.
1724 LHSValNoAssignments[VN] = RHSValID = VN;
1725 NewVNInfo[VN] = RHSValNoInfo;
1726 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1728 // Otherwise, use the specified value #.
1729 LHSValNoAssignments[VN] = RHSValID;
1730 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1731 NewVNInfo[VN] = RHSValNoInfo;
1732 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
1736 NewVNInfo[VN] = VNI;
1737 LHSValNoAssignments[VN] = VN;
1741 assert(RHSValID != -1 && "Didn't find value #?");
1742 RHSValNoAssignments[0] = RHSValID;
1743 if (RHSVal0DefinedFromLHS != -1) {
1744 // This path doesn't go through ComputeUltimateVN so just set
1746 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
1749 // Loop over the value numbers of the LHS, seeing if any are defined from
1751 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1754 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1757 // DstReg is known to be a register in the LHS interval. If the src is
1758 // from the RHS interval, we can use its value #.
1759 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
1762 // Figure out the value # from the RHS.
1763 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
1766 // Loop over the value numbers of the RHS, seeing if any are defined from
1768 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1771 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
1774 // DstReg is known to be a register in the RHS interval. If the src is
1775 // from the LHS interval, we can use its value #.
1776 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
1779 // Figure out the value # from the LHS.
1780 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
1783 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1784 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1785 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1787 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1790 unsigned VN = VNI->id;
1791 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1793 ComputeUltimateVN(VNI, NewVNInfo,
1794 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1795 LHSValNoAssignments, RHSValNoAssignments);
1797 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1800 unsigned VN = VNI->id;
1801 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
1803 // If this value number isn't a copy from the LHS, it's a new number.
1804 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
1805 NewVNInfo.push_back(VNI);
1806 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
1810 ComputeUltimateVN(VNI, NewVNInfo,
1811 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1812 RHSValNoAssignments, LHSValNoAssignments);
1816 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1817 // interval lists to see if these intervals are coalescable.
1818 LiveInterval::const_iterator I = LHS.begin();
1819 LiveInterval::const_iterator IE = LHS.end();
1820 LiveInterval::const_iterator J = RHS.begin();
1821 LiveInterval::const_iterator JE = RHS.end();
1823 // Skip ahead until the first place of potential sharing.
1824 if (I->start < J->start) {
1825 I = std::upper_bound(I, IE, J->start);
1826 if (I != LHS.begin()) --I;
1827 } else if (J->start < I->start) {
1828 J = std::upper_bound(J, JE, I->start);
1829 if (J != RHS.begin()) --J;
1833 // Determine if these two live ranges overlap.
1835 if (I->start < J->start) {
1836 Overlaps = I->end > J->start;
1838 Overlaps = J->end > I->start;
1841 // If so, check value # info to determine if they are really different.
1843 // If the live range overlap will map to the same value number in the
1844 // result liverange, we can still coalesce them. If not, we can't.
1845 if (LHSValNoAssignments[I->valno->id] !=
1846 RHSValNoAssignments[J->valno->id])
1850 if (I->end < J->end) {
1859 // Update kill info. Some live ranges are extended due to copy coalescing.
1860 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1861 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1862 VNInfo *VNI = I->first;
1863 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1864 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
1865 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
1866 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1869 // Update kill info. Some live ranges are extended due to copy coalescing.
1870 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1871 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1872 VNInfo *VNI = I->first;
1873 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1874 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
1875 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
1876 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1879 // If we get here, we know that we can coalesce the live ranges. Ask the
1880 // intervals to coalesce themselves now.
1881 if ((RHS.ranges.size() > LHS.ranges.size() &&
1882 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1883 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
1884 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
1887 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
1894 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1895 // depth of the basic block (the unsigned), and then on the MBB number.
1896 struct DepthMBBCompare {
1897 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1898 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1899 if (LHS.first > RHS.first) return true; // Deeper loops first
1900 return LHS.first == RHS.first &&
1901 LHS.second->getNumber() < RHS.second->getNumber();
1906 /// getRepIntervalSize - Returns the size of the interval that represents the
1907 /// specified register.
1909 unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1910 return Rc->getRepIntervalSize(Reg);
1913 /// CopyRecSort::operator - Join priority queue sorting function.
1915 bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1916 // Inner loops first.
1917 if (left.LoopDepth > right.LoopDepth)
1919 else if (left.LoopDepth == right.LoopDepth)
1920 if (left.isBackEdge && !right.isBackEdge)
1925 void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
1926 std::vector<CopyRec> &TryAgain) {
1927 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
1929 std::vector<CopyRec> VirtCopies;
1930 std::vector<CopyRec> PhysCopies;
1931 std::vector<CopyRec> ImpDefCopies;
1932 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
1933 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1935 MachineInstr *Inst = MII++;
1937 // If this isn't a copy nor a extract_subreg, we can't join intervals.
1938 unsigned SrcReg, DstReg;
1939 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1940 DstReg = Inst->getOperand(0).getReg();
1941 SrcReg = Inst->getOperand(1).getReg();
1942 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1943 DstReg = Inst->getOperand(0).getReg();
1944 SrcReg = Inst->getOperand(2).getReg();
1945 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1948 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1949 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1951 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
1953 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1954 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1955 else if (SrcIsPhys || DstIsPhys)
1956 PhysCopies.push_back(CopyRec(Inst, 0, false));
1958 VirtCopies.push_back(CopyRec(Inst, 0, false));
1965 // Try coalescing implicit copies first, followed by copies to / from
1966 // physical registers, then finally copies from virtual registers to
1967 // virtual registers.
1968 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1969 CopyRec &TheCopy = ImpDefCopies[i];
1971 if (!JoinCopy(TheCopy, Again))
1973 TryAgain.push_back(TheCopy);
1975 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1976 CopyRec &TheCopy = PhysCopies[i];
1978 if (!JoinCopy(TheCopy, Again))
1980 TryAgain.push_back(TheCopy);
1982 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1983 CopyRec &TheCopy = VirtCopies[i];
1985 if (!JoinCopy(TheCopy, Again))
1987 TryAgain.push_back(TheCopy);
1991 void SimpleRegisterCoalescing::joinIntervals() {
1992 DOUT << "********** JOINING INTERVALS ***********\n";
1995 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1997 std::vector<CopyRec> TryAgainList;
1998 if (loopInfo->empty()) {
1999 // If there are no loops in the function, join intervals in function order.
2000 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
2002 CopyCoalesceInMBB(I, TryAgainList);
2004 // Otherwise, join intervals in inner loops before other intervals.
2005 // Unfortunately we can't just iterate over loop hierarchy here because
2006 // there may be more MBB's than BB's. Collect MBB's for sorting.
2008 // Join intervals in the function prolog first. We want to join physical
2009 // registers with virtual registers before the intervals got too long.
2010 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
2011 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
2012 MachineBasicBlock *MBB = I;
2013 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
2016 // Sort by loop depth.
2017 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
2019 // Finally, join intervals in loop nest order.
2020 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
2021 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
2024 // Joining intervals can allow other intervals to be joined. Iteratively join
2025 // until we make no progress.
2027 SmallVector<CopyRec, 16> TryAgain;
2028 bool ProgressMade = true;
2029 while (ProgressMade) {
2030 ProgressMade = false;
2031 while (!JoinQueue->empty()) {
2032 CopyRec R = JoinQueue->pop();
2034 bool Success = JoinCopy(R, Again);
2036 ProgressMade = true;
2038 TryAgain.push_back(R);
2042 while (!TryAgain.empty()) {
2043 JoinQueue->push(TryAgain.back());
2044 TryAgain.pop_back();
2049 bool ProgressMade = true;
2050 while (ProgressMade) {
2051 ProgressMade = false;
2053 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
2054 CopyRec &TheCopy = TryAgainList[i];
2057 bool Success = JoinCopy(TheCopy, Again);
2058 if (Success || !Again) {
2059 TheCopy.MI = 0; // Mark this one as done.
2060 ProgressMade = true;
2071 /// Return true if the two specified registers belong to different register
2072 /// classes. The registers may be either phys or virt regs. In the
2073 /// case where both registers are virtual registers, it would also returns
2074 /// true by reference the RegB register class in SubRC if it is a subset of
2075 /// RegA's register class.
2077 SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
2078 const TargetRegisterClass *&SubRC) const {
2080 // Get the register classes for the first reg.
2081 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
2082 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
2083 "Shouldn't consider two physregs!");
2084 return !mri_->getRegClass(RegB)->contains(RegA);
2087 // Compare against the regclass for the second reg.
2088 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
2089 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
2090 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
2091 if (RegClassA == RegClassB)
2093 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
2096 return !RegClassA->contains(RegB);
2099 /// lastRegisterUse - Returns the last use of the specific register between
2100 /// cycles Start and End or NULL if there are no uses.
2102 SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
2103 unsigned Reg, unsigned &UseIdx) const{
2105 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
2106 MachineOperand *LastUse = NULL;
2107 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
2108 E = mri_->use_end(); I != E; ++I) {
2109 MachineOperand &Use = I.getOperand();
2110 MachineInstr *UseMI = Use.getParent();
2111 unsigned SrcReg, DstReg;
2112 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
2113 // Ignore identity copies.
2115 unsigned Idx = li_->getInstructionIndex(UseMI);
2116 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
2124 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
2127 // Skip deleted instructions
2128 MachineInstr *MI = li_->getInstructionFromIndex(e);
2129 while ((e - InstrSlots::NUM) >= s && !MI) {
2130 e -= InstrSlots::NUM;
2131 MI = li_->getInstructionFromIndex(e);
2133 if (e < s || MI == NULL)
2136 // Ignore identity copies.
2137 unsigned SrcReg, DstReg;
2138 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
2139 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2140 MachineOperand &Use = MI->getOperand(i);
2141 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
2142 tri_->regsOverlap(Use.getReg(), Reg)) {
2148 e -= InstrSlots::NUM;
2155 void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
2156 if (TargetRegisterInfo::isPhysicalRegister(reg))
2157 cerr << tri_->getName(reg);
2159 cerr << "%reg" << reg;
2162 void SimpleRegisterCoalescing::releaseMemory() {
2163 JoinedCopies.clear();
2164 ReMatCopies.clear();
2167 static bool isZeroLengthInterval(LiveInterval *li) {
2168 for (LiveInterval::Ranges::const_iterator
2169 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2170 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2175 /// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2176 /// turn the copy into an implicit def.
2178 SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2179 MachineBasicBlock *MBB,
2180 unsigned DstReg, unsigned SrcReg) {
2181 MachineInstr *CopyMI = &*I;
2182 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2183 if (!li_->hasInterval(SrcReg))
2185 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2186 if (!SrcInt.empty())
2188 if (!li_->hasInterval(DstReg))
2190 LiveInterval &DstInt = li_->getInterval(DstReg);
2191 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
2192 DstInt.removeValNo(DstLR->valno);
2193 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2194 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2195 CopyMI->RemoveOperand(i);
2196 bool NoUse = mri_->use_empty(SrcReg);
2198 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2199 E = mri_->reg_end(); I != E; ) {
2200 assert(I.getOperand().isDef());
2201 MachineInstr *DefMI = &*I;
2203 // The implicit_def source has no other uses, delete it.
2204 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2205 li_->RemoveMachineInstrFromMaps(DefMI);
2206 DefMI->eraseFromParent();
2214 bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2216 mri_ = &fn.getRegInfo();
2217 tm_ = &fn.getTarget();
2218 tri_ = tm_->getRegisterInfo();
2219 tii_ = tm_->getInstrInfo();
2220 li_ = &getAnalysis<LiveIntervals>();
2221 loopInfo = &getAnalysis<MachineLoopInfo>();
2223 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2224 << "********** Function: "
2225 << ((Value*)mf_->getFunction())->getName() << '\n';
2227 allocatableRegs_ = tri_->getAllocatableSet(fn);
2228 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2229 E = tri_->regclass_end(); I != E; ++I)
2230 allocatableRCRegs_.insert(std::make_pair(*I,
2231 tri_->getAllocatableSet(fn, *I)));
2233 // Join (coalesce) intervals if requested.
2234 if (EnableJoining) {
2236 DOUT << "********** INTERVALS POST JOINING **********\n";
2237 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
2238 I->second->print(DOUT, tri_);
2243 // Perform a final pass over the instructions and compute spill weights
2244 // and remove identity moves.
2245 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2246 mbbi != mbbe; ++mbbi) {
2247 MachineBasicBlock* mbb = mbbi;
2248 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
2250 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2252 MachineInstr *MI = mii;
2253 unsigned SrcReg, DstReg;
2254 if (JoinedCopies.count(MI)) {
2255 // Delete all coalesced copies.
2256 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2257 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2258 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2259 "Unrecognized copy instruction");
2260 DstReg = MI->getOperand(0).getReg();
2262 if (MI->registerDefIsDead(DstReg)) {
2263 LiveInterval &li = li_->getInterval(DstReg);
2264 if (!ShortenDeadCopySrcLiveRange(li, MI))
2265 ShortenDeadCopyLiveRange(li, MI);
2267 li_->RemoveMachineInstrFromMaps(MI);
2268 mii = mbbi->erase(mii);
2273 // If the move will be an identity move delete it
2274 bool isMove = tii_->isMoveInstr(*mii, SrcReg, DstReg);
2275 if (isMove && SrcReg == DstReg) {
2276 if (li_->hasInterval(SrcReg)) {
2277 LiveInterval &RegInt = li_->getInterval(SrcReg);
2278 // If def of this move instruction is dead, remove its live range
2279 // from the dstination register's live interval.
2280 if (mii->registerDefIsDead(DstReg)) {
2281 if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2282 ShortenDeadCopyLiveRange(RegInt, mii);
2285 li_->RemoveMachineInstrFromMaps(mii);
2286 mii = mbbi->erase(mii);
2288 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
2289 SmallSet<unsigned, 4> UniqueUses;
2290 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2291 const MachineOperand &mop = mii->getOperand(i);
2292 if (mop.isRegister() && mop.getReg() &&
2293 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
2294 unsigned reg = mop.getReg();
2295 // Multiple uses of reg by the same instruction. It should not
2296 // contribute to spill weight again.
2297 if (UniqueUses.count(reg) != 0)
2299 LiveInterval &RegInt = li_->getInterval(reg);
2301 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
2302 UniqueUses.insert(reg);
2310 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2311 LiveInterval &LI = *I->second;
2312 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
2313 // If the live interval length is essentially zero, i.e. in every live
2314 // range the use follows def immediately, it doesn't make sense to spill
2315 // it and hope it will be easier to allocate for this li.
2316 if (isZeroLengthInterval(&LI))
2317 LI.weight = HUGE_VALF;
2319 bool isLoad = false;
2320 if (li_->isReMaterializable(LI, isLoad)) {
2321 // If all of the definitions of the interval are re-materializable,
2322 // it is a preferred candidate for spilling. If non of the defs are
2323 // loads, then it's potentially very cheap to re-materialize.
2324 // FIXME: this gets much more complicated once we support non-trivial
2325 // re-materialization.
2333 // Slightly prefer live interval that has been assigned a preferred reg.
2337 // Divide the weight of the interval by its size. This encourages
2338 // spilling of intervals that are large and have few uses, and
2339 // discourages spilling of small intervals with many uses.
2340 LI.weight /= li_->getApproximateInstructionCount(LI) * InstrSlots::NUM;
2348 /// print - Implement the dump method.
2349 void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2353 RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2354 return new SimpleRegisterCoalescing();
2357 // Make sure that anything that uses RegisterCoalescer pulls in this file...
2358 DEFINING_FILE_FOR(SimpleRegisterCoalescing)